"use client"; import { useState, useTransition } from "react"; import { Flag, Heart, ThumbsUp } from "lucide-react"; import { Button } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import { setStoryBeatReaction } from "@/app/(frontend)/story/actions"; import { REACTION_LABELS, STORY_REACTIONS, type StoryReaction, } from "@/lib/story/reactions"; const REACTION_ICONS: Record = { like: ThumbsUp, heart: Heart, salute: Flag, }; type ReactionCounts = Record; export function BeatReactions({ beatId, initialReaction, initialCounts, }: { beatId: number; initialReaction: StoryReaction | null; initialCounts: ReactionCounts; }) { const [current, setCurrent] = useState(initialReaction); const [counts, setCounts] = useState(initialCounts); const [pending, startTransition] = useTransition(); function toggle(reaction: StoryReaction) { if (pending) return; const next: StoryReaction | null = current === reaction ? null : reaction; const previous = current; startTransition(async () => { setCounts((prev) => { const nextCounts = { ...prev }; if (previous) nextCounts[previous] = Math.max(0, nextCounts[previous] - 1); if (next) nextCounts[next] = nextCounts[next] + 1; return nextCounts; }); setCurrent(next); const result = await setStoryBeatReaction(beatId, next); if (!result.success || !result.data) { setCounts((prev) => { const reverted = { ...prev }; if (next) reverted[next] = Math.max(0, reverted[next] - 1); if (previous) reverted[previous] = reverted[previous] + 1; return reverted; }); setCurrent(previous); } }); } return (
{STORY_REACTIONS.map((reaction) => { const Icon = REACTION_ICONS[reaction]; const active = current === reaction; return ( ); })}
); }