87 lines
2.6 KiB
TypeScript
87 lines
2.6 KiB
TypeScript
"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<StoryReaction, typeof ThumbsUp> = {
|
|
like: ThumbsUp,
|
|
heart: Heart,
|
|
salute: Flag,
|
|
};
|
|
|
|
type ReactionCounts = Record<StoryReaction, number>;
|
|
|
|
export function BeatReactions({
|
|
beatId,
|
|
initialReaction,
|
|
initialCounts,
|
|
}: {
|
|
beatId: number;
|
|
initialReaction: StoryReaction | null;
|
|
initialCounts: ReactionCounts;
|
|
}) {
|
|
const [current, setCurrent] = useState<StoryReaction | null>(initialReaction);
|
|
const [counts, setCounts] = useState<ReactionCounts>(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 (
|
|
<div className="mt-5 flex flex-wrap items-center gap-2">
|
|
{STORY_REACTIONS.map((reaction) => {
|
|
const Icon = REACTION_ICONS[reaction];
|
|
const active = current === reaction;
|
|
return (
|
|
<Button
|
|
key={reaction}
|
|
type="button"
|
|
variant="outline"
|
|
size="sm"
|
|
disabled={pending}
|
|
aria-pressed={active}
|
|
aria-label={`${REACTION_LABELS[reaction]} (${counts[reaction]})`}
|
|
onClick={() => toggle(reaction)}
|
|
className={cn(
|
|
"h-8 gap-1.5 text-xs",
|
|
active && "border-primary bg-primary/10 text-primary",
|
|
)}
|
|
>
|
|
<Icon className="size-3.5" />
|
|
<span>{counts[reaction]}</span>
|
|
</Button>
|
|
);
|
|
})}
|
|
</div>
|
|
);
|
|
}
|