import { router, useHttp, usePage } from '@inertiajs/react'; import { Check } from 'lucide-react'; import { useEffect, useEffectEvent, useId, useRef, useState } from 'react'; import { toast } from 'sonner'; import CommitPollController from '@/actions/App/Http/Controllers/CommitPollController'; import CommitPollVoteController from '@/actions/App/Http/Controllers/CommitPollVoteController'; import { BodySegments } from '@/components/commit-body'; import { StableLabel } from '@/components/stable-label'; import { Button } from '@/components/ui/button'; import { useCommitNotFound } from '@/hooks/use-deleted-resources'; import { useNow } from '@/hooks/use-now'; import { useOwnsCommit } from '@/hooks/use-owns-commit'; import { bodySegments } from '@/lib/code'; import { changesSince, readAt } from '@/lib/commit-changes'; import { exactCountTitle, formatCount, formatExactCount } from '@/lib/numbers'; import { coalesce, commitChannel, listen } from '@/lib/realtime'; import { cn } from '@/lib/utils'; import type { Commit, Poll } from '@/types'; import type { GuildMentions } from '@/types/guild'; function timeLeft(closesAt: string, now: Date): string { const minutes = Math.ceil( (new Date(closesAt).getTime() - now.getTime()) / 60_000, ); if (minutes >= 1440) { return `${Math.floor(minutes / 1440)}d left`; } if (minutes >= 60) { return `${Math.floor(minutes / 60)}h left`; } return `${Math.max(minutes, 1)}m left`; } const failedVoteMessage = 'Could not record your vote. Try again.'; function votesLabel(count: number, format = formatExactCount): string { return `${format(count)} ${count === 1 ? 'vote' : 'votes'}`; } function percentage(votes: number, total: number): number { return total === 0 ? 0 : Math.round((votes / total) * 100); } // Only mentions the body also makes are linked, since those are the people the commit notifies. function OptionLabel({ label, mentions, guildMentions, isStatic, }: { label: string; mentions: Commit['mentions']; guildMentions?: GuildMentions; isStatic: boolean; }) { return ( ); } export function CommitPoll({ commit, poll: initialPoll, isStatic = false, }: { commit: Pick & { author: Pick; } & Partial>; poll: Poll; isStatic?: boolean; }) { const { auth, now: serverNow } = usePage().props; const ownsCommit = useOwnsCommit(); const commitNotFound = useCommitNotFound(); const now = useNow(); const id = useId(); const [snapshot, setSnapshot] = useState({ source: initialPoll, poll: initialPoll, }); // Parent refreshes update option badges, but unchanged props must not replace a newer read or vote. const poll = snapshot.source === initialPoll ? snapshot.poll : { ...snapshot.poll, options: snapshot.poll.options.map((option) => ({ ...option, guild_mentions: initialPoll.options.find( (fresh) => fresh.id === option.id, )?.guild_mentions, })), }; const request = useHttp<{ option: string }, { poll: Poll }>({ option: '', }); const choice = request.data.option; // A read started before a vote went out may come back without it, so only the latest of either one counts. const latest = useRef(0); // When the poll shown was read, on the server's clock, to ask whether votes came in since after missing updates. const readSince = useRef(Math.min(serverNow - 5_000, readAt())); const read = useEffectEvent(async (signal: AbortSignal) => { if (request.processing) { return; } const started = ++latest.current; const startedAt = readAt(); const response = await fetch(CommitPollController.show.url(commit), { headers: { Accept: 'application/json' }, cache: 'no-store', signal, }); if (response.ok && started === latest.current && !request.processing) { readSince.current = startedAt; setSnapshot({ source: initialPoll, poll: ((await response.json()) as { poll: Poll }).poll, }); } }); const isApproved = commit.status === 'approved'; const closesAt = poll.is_closed ? null : poll.closes_at; // Someone else voting changes the results the viewer may see, and closing shows the final ones to everyone, even // when nobody votes again. Choosing an option and not voting yet is kept either way. useEffect(() => { if (!isApproved) { return; } const controller = new AbortController(); const refresh = coalesce(() => read(controller.signal), 500); const stop = listen( commitChannel(commit.id), { poll: refresh.request }, () => void changesSince(commit.id, readSince.current).then( (change) => (change === null || change.changed) && refresh.request(), ), ); const closing = closesAt === null ? undefined : window.setTimeout( refresh.request, Math.max(new Date(closesAt).getTime() - Date.now(), 0) + 1_000, ); return () => { stop(); refresh.cancel(); window.clearTimeout(closing); controller.abort(); }; }, [commit.id, isApproved, closesAt]); const hasExpired = poll.is_closed || (poll.closes_at !== null && new Date(poll.closes_at) <= now); const canVote = auth.user !== null && commit.status === 'approved' && !ownsCommit(commit) && poll.closes_at !== null && !poll.has_voted && !hasExpired; const status = poll.closes_at === null ? 'Voting opens once approved' : hasExpired ? poll.total_votes === null ? 'Poll closed' : 'Final results' : timeLeft(poll.closes_at, now); const vote = async () => { if (choice === '' || request.processing) { return; } let isNotFound = false; try { const response = await request.submit( CommitPollVoteController.store(commit), { onHttpException: (response) => { isNotFound = commitNotFound(commit.id, response); }, onError: (errors) => toast.error( Object.values(errors)[0] ?? failedVoteMessage, ), }, ); if (response === undefined) { return; } latest.current++; setSnapshot({ source: initialPoll, poll: response.poll }); router.flushAll(); } catch { if (!isNotFound) { toast.error(failedVoteMessage); } } }; return (
{poll.total_votes === null && isStatic ? (
    {poll.options.map((option) => (
  • ))}

{status}

) : poll.total_votes === null ? (
Poll options
{poll.options.map((option) => ( ))}

{status}

{canVote && ( )}
) : (
    {poll.options.map((option) => { const share = percentage( option.votes_count ?? 0, poll.total_votes ?? 0, ); return (
  • {option.voted && ( <> , your vote )} {share}% ,{' '} {votesLabel( option.votes_count ?? 0, )}
  • ); })}

{votesLabel(poll.total_votes, formatCount)} {votesLabel(poll.total_votes)} · {status}

)}
); }