Archived
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
62 lines
2.6 KiB
TypeScript
62 lines
2.6 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useState } from "react";
|
|
import { Bell, BellOff } from "lucide-react";
|
|
import { useAuth } from "@/hooks/useAuth";
|
|
import { errorMessage } from "@/lib/utils";
|
|
import { apiV2Data } from "@/lib/apiV2";
|
|
|
|
/** Follow / unfollow a series. Signed out, it links to the login page and back. */
|
|
export function FollowSeriesButton({ slug }: { slug: string }) {
|
|
const { user, token, loading } = useAuth();
|
|
const [following, setFollowing] = useState<boolean | null>(null);
|
|
const [seriesId, setSeriesId] = useState<string | null>(null);
|
|
const [busy, setBusy] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
// The page itself is cached for everyone, so whether this person follows (and the series as it
|
|
// is now) is asked separately.
|
|
useEffect(() => {
|
|
if (!token) return;
|
|
(apiV2Data("get", "/series/by-slug/{slug}", { params: { slug }, authToken: token }) as Promise<{ id: string; following: boolean }>)
|
|
.then(s => { setSeriesId(s.id); setFollowing(!!s.following); })
|
|
.catch(() => setFollowing(null));
|
|
}, [slug, token]);
|
|
|
|
if (loading) return null;
|
|
if (!user) {
|
|
return (
|
|
<a href={`/login?redirect=/series/${slug}`} className="inline-flex items-center gap-1.5 px-4 py-2 text-sm rounded-lg border bg-white hover:bg-gray-50">
|
|
<Bell className="w-4 h-4" /> Log in to follow
|
|
</a>
|
|
);
|
|
}
|
|
|
|
const toggle = async () => {
|
|
setBusy(true); setError(null);
|
|
try {
|
|
const res = await (apiV2Data(following ? "delete" : "put", "/series/{id}/follow", { params: { id: seriesId! }, authToken: token }) as Promise<{ following: boolean }>);
|
|
setFollowing(res.following);
|
|
} catch (e) {
|
|
setError(errorMessage(e) || "Couldn't change that");
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<div>
|
|
<button type="button" onClick={toggle} disabled={busy || following === null || !seriesId}
|
|
className={`inline-flex items-center gap-1.5 px-4 py-2 text-sm rounded-lg font-medium disabled:opacity-50 ${following ? "border bg-white text-gray-700 hover:bg-gray-50" : "bg-brand-600 text-white hover:bg-brand-700"}`}>
|
|
{following ? <><BellOff className="w-4 h-4" /> Unfollow</> : <><Bell className="w-4 h-4" /> Follow this series</>}
|
|
</button>
|
|
<p className="text-xs text-gray-500 mt-1.5" role="status">
|
|
{following
|
|
? "You'll get an email when a new event in this series is out (if you get news and announcements from us)."
|
|
: "Get an email when the next one is out."}
|
|
</p>
|
|
{error && <p className="text-xs text-red-600 mt-1">{error}</p>}
|
|
</div>
|
|
);
|
|
}
|