feat(polls): add the polls page with live tallies and tie decisions
`/polls` lists live polls first, then ones waiting on a decision, then closed history; `/polls/[id]` is the vote surface. Both under Operations. - Voting, the live tally and the superuser tie decision live in one client panel so the pages stay server components. - The tally refreshes on a scoped 10s timer instead of joining the app-wide SSE bus: every game event currently makes each client re-render its whole layout, and a poll page does not need to be part of that fan-out. - Anonymity is applied in the read model, not the view: counts always render, identities only for a public poll or a superuser. - A pending tie shows its deadline and one Decide button per tied option; the service refuses a key outside the frozen tie set. - The outcome line renders only for a settled poll, so a tied poll does not claim a decision it has not made.
This commit is contained in:
parent
dee3dbea09
commit
d9d4ef1c08
5 changed files with 720 additions and 0 deletions
56
src/app/(frontend)/polls/[id]/page.tsx
Normal file
56
src/app/(frontend)/polls/[id]/page.tsx
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import config from "@payload-config";
|
||||
import { getPayload } from "payload";
|
||||
import { headers as nextHeaders } from "next/headers";
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { ArrowLeft } from "lucide-react";
|
||||
|
||||
import { PollVotePanel } from "@/components/frontend/polls/PollVotePanel";
|
||||
import { loadUserPermissions } from "@/utils/access-control/loadUserPermissions";
|
||||
import { advancePoll } from "@/lib/polls/service";
|
||||
import { buildPollView } from "@/lib/polls/surface";
|
||||
import type { Poll } from "@/payload-types";
|
||||
|
||||
export const metadata = {
|
||||
title: "Poll: Polaris Task Force",
|
||||
};
|
||||
|
||||
export default async function PollPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
const pollId = Number(id);
|
||||
if (!Number.isInteger(pollId)) notFound();
|
||||
|
||||
const headers = await nextHeaders();
|
||||
const payload = await getPayload({ config });
|
||||
const { user } = await payload.auth({ headers, canSetHeaders: false });
|
||||
|
||||
// The (frontend) layout renders LandingPage for guests; this only guards the
|
||||
// authed render path's types.
|
||||
if (!user || user.collection !== "users") return null;
|
||||
|
||||
// Opening the page settles anything that is due, so a poll closes on time
|
||||
// even when the bot is down.
|
||||
const poll = (await advancePoll(payload, { pollId })) as Poll | null;
|
||||
if (!poll || !poll.id) notFound();
|
||||
|
||||
const { isSuperuser } = await loadUserPermissions(payload, user);
|
||||
const roleDocs = (user as { roleDocs?: (number | { id: number })[] | null }).roleDocs ?? [];
|
||||
const view = await buildPollView(payload, poll, {
|
||||
userId: Number(user.id),
|
||||
isSuperuser,
|
||||
roleIds: roleDocs.map((ref) => (typeof ref === "number" ? ref : ref.id)),
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-3xl flex-col gap-4 p-5">
|
||||
<Link
|
||||
href="/polls"
|
||||
className="flex items-center gap-1 text-xs text-muted-foreground underline-offset-4 hover:underline"
|
||||
>
|
||||
<ArrowLeft className="size-3.5" />
|
||||
All polls
|
||||
</Link>
|
||||
<PollVotePanel initialView={view} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
180
src/app/(frontend)/polls/actions.ts
Normal file
180
src/app/(frontend)/polls/actions.ts
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
"use server";
|
||||
|
||||
import config from "@payload-config";
|
||||
import { getPayload } from "payload";
|
||||
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
||||
import { hasPermission } from "@/utils/access-control/hasPermission";
|
||||
import { loadUserPermissions } from "@/utils/access-control/loadUserPermissions";
|
||||
import {
|
||||
advancePoll,
|
||||
castPollVote,
|
||||
resolveTie,
|
||||
tallyPollNow,
|
||||
type CastPollVoteResult,
|
||||
} from "@/lib/polls/service";
|
||||
import { buildPollView, type PollView, type PollViewer } from "@/lib/polls/surface";
|
||||
import type { Poll } from "@/payload-types";
|
||||
|
||||
interface ActionResult<T = undefined> {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
data?: T;
|
||||
}
|
||||
|
||||
async function authenticate() {
|
||||
const payloadConfig = await config;
|
||||
const payload = await getPayload({ config: payloadConfig });
|
||||
const { headers } = await import("next/headers");
|
||||
const hdrs = await headers();
|
||||
const { user } = await payload.auth({ headers: hdrs, canSetHeaders: false });
|
||||
|
||||
if (!isPayloadUser(user)) {
|
||||
throw new Error("Unauthorized");
|
||||
}
|
||||
|
||||
return { payload, user };
|
||||
}
|
||||
|
||||
/** The viewer's roles and superuser flag, in one cached permission load. */
|
||||
async function loadViewer(
|
||||
payload: Awaited<ReturnType<typeof getPayload>>,
|
||||
user: { id: number | string; roleDocs?: unknown },
|
||||
): Promise<PollViewer> {
|
||||
const { isSuperuser } = await loadUserPermissions(payload, user);
|
||||
const roleDocs = (user as { roleDocs?: (number | { id: number })[] | null }).roleDocs ?? [];
|
||||
return {
|
||||
userId: Number(user.id),
|
||||
isSuperuser,
|
||||
roleIds: roleDocs.map((ref) => (typeof ref === "number" ? ref : ref.id)),
|
||||
};
|
||||
}
|
||||
|
||||
const failure = (result: Extract<CastPollVoteResult, { ok: false }>): string => {
|
||||
switch (result.reason) {
|
||||
case "not-found":
|
||||
return "That poll no longer exists.";
|
||||
case "closed":
|
||||
return "This poll has closed.";
|
||||
case "ineligible":
|
||||
return "You are not eligible to vote in this poll.";
|
||||
case "invalid-answer":
|
||||
return "That answer is not on this poll.";
|
||||
case "too-many":
|
||||
return "This poll takes one answer.";
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Cast, change, or retract a vote. Empty `answers` retracts. Returns the
|
||||
* rebuilt view so the caller can render the new tally without a round trip.
|
||||
*/
|
||||
export async function castPollVoteAction(
|
||||
pollId: number,
|
||||
answers: string[],
|
||||
): Promise<ActionResult<PollView>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
const viewer = await loadViewer(payload, user);
|
||||
|
||||
// Close anything that is due before deciding the vote is refused: a poll
|
||||
// whose time ran out should not answer "closed" without being resolved.
|
||||
await advancePoll(payload, { pollId });
|
||||
|
||||
const result = await castPollVote(payload, {
|
||||
pollId,
|
||||
userId: viewer.userId,
|
||||
answers,
|
||||
});
|
||||
if (!result.ok) return { success: false, error: failure(result) };
|
||||
|
||||
const poll = await payload.findByID({
|
||||
collection: "polls",
|
||||
id: pollId,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
return { success: true, data: await buildPollView(payload, poll as Poll, viewer) };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
if (message === "Unauthorized") return { success: false, error: "You must be logged in." };
|
||||
return { success: false, error: message };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A superuser settles a tied poll. Permission is the superuser tier, which is
|
||||
* the same tier that may read vote identities.
|
||||
*/
|
||||
export async function resolvePollTieAction(
|
||||
pollId: number,
|
||||
winnerKey: string,
|
||||
): Promise<ActionResult<PollView>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
if (!(await hasPermission(payload, user, "system:admin-access"))) {
|
||||
return { success: false, error: "Only a superuser can settle a tied poll." };
|
||||
}
|
||||
const viewer = await loadViewer(payload, user);
|
||||
|
||||
await resolveTie(payload, { pollId, winnerKey, decidedBy: viewer.userId });
|
||||
|
||||
const poll = await payload.findByID({
|
||||
collection: "polls",
|
||||
id: pollId,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
return { success: true, data: await buildPollView(payload, poll as Poll, viewer) };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
if (message === "Unauthorized") return { success: false, error: "You must be logged in." };
|
||||
return { success: false, error: message };
|
||||
}
|
||||
}
|
||||
|
||||
/** Close a poll early. Staff only: polls:update. */
|
||||
export async function closePollAction(pollId: number): Promise<ActionResult<PollView>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
if (!(await hasPermission(payload, user, "polls:update"))) {
|
||||
return { success: false, error: "You do not have permission to close this poll." };
|
||||
}
|
||||
const viewer = await loadViewer(payload, user);
|
||||
|
||||
await advancePoll(payload, { pollId, now: Date.now() + 1 });
|
||||
|
||||
const poll = await payload.findByID({
|
||||
collection: "polls",
|
||||
id: pollId,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
return { success: true, data: await buildPollView(payload, poll as Poll, viewer) };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
if (message === "Unauthorized") return { success: false, error: "You must be logged in." };
|
||||
return { success: false, error: message };
|
||||
}
|
||||
}
|
||||
|
||||
/** Lightweight refresh for the live tally, so open pages converge without SSE. */
|
||||
export async function getPollViewAction(pollId: number): Promise<ActionResult<PollView>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
const viewer = await loadViewer(payload, user);
|
||||
|
||||
await advancePoll(payload, { pollId });
|
||||
|
||||
const poll = await payload.findByID({
|
||||
collection: "polls",
|
||||
id: pollId,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
return { success: true, data: await buildPollView(payload, poll as Poll, viewer) };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
if (message === "Unauthorized") return { success: false, error: "You must be logged in." };
|
||||
return { success: false, error: message };
|
||||
}
|
||||
}
|
||||
150
src/app/(frontend)/polls/page.tsx
Normal file
150
src/app/(frontend)/polls/page.tsx
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
import config from "@payload-config";
|
||||
import { getPayload } from "payload";
|
||||
import { headers as nextHeaders } from "next/headers";
|
||||
import Link from "next/link";
|
||||
import { Vote } from "lucide-react";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { loadUserPermissions } from "@/utils/access-control/loadUserPermissions";
|
||||
import { listPolls, type PollView } from "@/lib/polls/surface";
|
||||
|
||||
export const metadata = {
|
||||
title: "Polls: Polaris Task Force",
|
||||
};
|
||||
|
||||
const statusLabel = (view: PollView): string => {
|
||||
if (view.awaitingDecision) return "Tied";
|
||||
if (view.closed) return "Closed";
|
||||
return "Open";
|
||||
};
|
||||
|
||||
const statusClass = (view: PollView): string => {
|
||||
if (view.awaitingDecision) return "border-amber-500/50 text-amber-300";
|
||||
if (view.closed) return "border-white/20 text-muted-foreground";
|
||||
return "border-emerald-500/50 text-emerald-300";
|
||||
};
|
||||
|
||||
function PollCard({ view }: { view: PollView }) {
|
||||
const leading = [...view.options].sort((a, b) => b.weighted - a.weighted)[0];
|
||||
return (
|
||||
<Link href={`/polls/${view.id}`} className="block">
|
||||
<Card className="transition-colors hover:border-white/25">
|
||||
<CardHeader className="gap-2">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge variant="outline" className={statusClass(view)}>
|
||||
{statusLabel(view)}
|
||||
</Badge>
|
||||
<Badge variant="outline" className="border-white/20 text-muted-foreground">
|
||||
{view.multiSelect ? "Multiple answers" : "One answer"}
|
||||
</Badge>
|
||||
<Badge variant="outline" className="border-white/20 text-muted-foreground">
|
||||
{view.anonymity === "anonymous" ? "Anonymous" : "Public"}
|
||||
</Badge>
|
||||
{view.initiated && (
|
||||
<Badge variant="outline" className="border-sky-500/50 text-sky-300">
|
||||
You opened this
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<CardTitle className="text-base">{view.title}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-2">
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground">
|
||||
<span>
|
||||
{view.totalVotes} voter{view.totalVotes === 1 ? "" : "s"}
|
||||
</span>
|
||||
<span>
|
||||
{view.closed
|
||||
? `Closed ${new Date(view.closesAt).toLocaleDateString()}`
|
||||
: `Closes ${new Date(view.closesAt).toLocaleString()}`}
|
||||
</span>
|
||||
{view.closed && view.winnerLabel && <span>Outcome: {view.winnerLabel}</span>}
|
||||
</div>
|
||||
|
||||
{leading && (
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex items-center justify-between text-xs">
|
||||
<span className="truncate">
|
||||
{leading.emoji ? `${leading.emoji} ` : ""}
|
||||
{leading.label}
|
||||
</span>
|
||||
<span className="font-mono text-muted-foreground">
|
||||
{leading.raw} · weight {Number.isInteger(leading.weighted) ? leading.weighted : leading.weighted.toFixed(2)}
|
||||
</span>
|
||||
</div>
|
||||
<Progress value={leading.share} className="h-1.5" />
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
export default async function PollsPage() {
|
||||
const headers = await nextHeaders();
|
||||
const payload = await getPayload({ config });
|
||||
const { user } = await payload.auth({ headers, canSetHeaders: false });
|
||||
|
||||
// The (frontend) layout renders LandingPage for guests; this only guards the
|
||||
// authed render path's types.
|
||||
if (!user || user.collection !== "users") return null;
|
||||
|
||||
const { isSuperuser } = await loadUserPermissions(payload, user);
|
||||
const roleDocs = (user as { roleDocs?: (number | { id: number })[] | null }).roleDocs ?? [];
|
||||
const polls = await listPolls(payload, {
|
||||
userId: Number(user.id),
|
||||
isSuperuser,
|
||||
roleIds: roleDocs.map((ref) => (typeof ref === "number" ? ref : ref.id)),
|
||||
});
|
||||
|
||||
const live = polls.filter((poll) => !poll.closed || poll.awaitingDecision);
|
||||
const past = polls.filter((poll) => poll.closed && !poll.awaitingDecision);
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-4xl flex-col gap-6 p-5">
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<Vote className="size-5 text-muted-foreground" />
|
||||
<h1 className="text-lg font-semibold">Unit polls</h1>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Questions the unit answers together. A conversation with an NPC can raise one; your vote
|
||||
here and on Discord are the same vote.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{live.length === 0 && past.length === 0 && (
|
||||
<Card>
|
||||
<CardContent className="py-8 text-center text-sm text-muted-foreground">
|
||||
No polls yet. They appear here when a conversation raises one.
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{live.length > 0 && (
|
||||
<section className="flex flex-col gap-3">
|
||||
<h2 className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
||||
Live
|
||||
</h2>
|
||||
{live.map((view) => (
|
||||
<PollCard key={view.id} view={view} />
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{past.length > 0 && (
|
||||
<section className="flex flex-col gap-3">
|
||||
<h2 className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
||||
Closed
|
||||
</h2>
|
||||
{past.map((view) => (
|
||||
<PollCard key={view.id} view={view} />
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -29,6 +29,7 @@ import {
|
|||
Truck,
|
||||
UserCog,
|
||||
Users,
|
||||
Vote,
|
||||
} from "lucide-react";
|
||||
|
||||
export const sidebarData = {
|
||||
|
|
@ -109,6 +110,11 @@ export const sidebarData = {
|
|||
url: "/operations/extractions",
|
||||
icon: ClipboardCheck,
|
||||
},
|
||||
{
|
||||
title: "Unit Polls",
|
||||
url: "/polls",
|
||||
icon: Vote,
|
||||
},
|
||||
],
|
||||
navLogistics: [
|
||||
{
|
||||
|
|
|
|||
328
src/components/frontend/polls/PollVotePanel.tsx
Normal file
328
src/components/frontend/polls/PollVotePanel.tsx
Normal file
|
|
@ -0,0 +1,328 @@
|
|||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState, useTransition } from "react";
|
||||
import Link from "next/link";
|
||||
import { Check, Clock, Gavel, ShieldQuestion, Users } from "lucide-react";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { PollView } from "@/lib/polls/surface";
|
||||
import { castPollVoteAction, getPollViewAction, resolvePollTieAction } from "@/app/(frontend)/polls/actions";
|
||||
|
||||
const REFRESH_MS = 10_000;
|
||||
|
||||
const formatWeight = (value: number): string =>
|
||||
Number.isInteger(value) ? String(value) : value.toFixed(2);
|
||||
|
||||
const formatWhen = (iso: string | null): string => {
|
||||
if (!iso) return "n/a";
|
||||
const date = new Date(iso);
|
||||
return Number.isNaN(date.getTime()) ? "n/a" : date.toLocaleString();
|
||||
};
|
||||
|
||||
const relative = (iso: string | null): string => {
|
||||
if (!iso) return "";
|
||||
const ms = new Date(iso).getTime() - Date.now();
|
||||
if (Number.isNaN(ms)) return "";
|
||||
const abs = Math.abs(ms);
|
||||
const minutes = Math.round(abs / 60_000);
|
||||
const hours = Math.round(abs / 3_600_000);
|
||||
const days = Math.round(abs / 86_400_000);
|
||||
const span =
|
||||
minutes < 60 ? `${minutes}m` : hours < 48 ? `${hours}h` : `${days}d`;
|
||||
return ms >= 0 ? `in ${span}` : `${span} ago`;
|
||||
};
|
||||
|
||||
function StatusBadge({ view }: { view: PollView }) {
|
||||
if (view.awaitingDecision) {
|
||||
return <Badge variant="outline" className="border-amber-500/50 text-amber-300">Tied</Badge>;
|
||||
}
|
||||
if (view.closed) {
|
||||
return <Badge variant="outline" className="border-white/20 text-muted-foreground">Closed</Badge>;
|
||||
}
|
||||
return <Badge variant="outline" className="border-emerald-500/50 text-emerald-300">Open</Badge>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vote panel for one poll. Voting, the live tally, and the superuser tie
|
||||
* decision all live here so the page itself stays a server component.
|
||||
*
|
||||
* The tally refreshes on a scoped timer instead of the app-wide SSE bus: every
|
||||
* game event makes each client re-render its whole layout, and a poll page
|
||||
* does not need to join that fan-out.
|
||||
*/
|
||||
export function PollVotePanel({ initialView }: { initialView: PollView }) {
|
||||
const [view, setView] = useState<PollView>(initialView);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [notice, setNotice] = useState<string | null>(null);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const busy = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
setView(initialView);
|
||||
}, [initialView]);
|
||||
|
||||
const refresh = useCallback(() => {
|
||||
if (busy.current || document.visibilityState !== "visible") return;
|
||||
startTransition(async () => {
|
||||
const result = await getPollViewAction(initialView.id);
|
||||
if (result.success && result.data) setView(result.data);
|
||||
});
|
||||
}, [initialView.id]);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setInterval(refresh, REFRESH_MS);
|
||||
return () => clearInterval(timer);
|
||||
}, [refresh]);
|
||||
|
||||
const applyAnswers = (answers: string[]) => {
|
||||
setError(null);
|
||||
setNotice(null);
|
||||
busy.current = true;
|
||||
startTransition(async () => {
|
||||
const result = await castPollVoteAction(view.id, answers);
|
||||
busy.current = false;
|
||||
if (!result.success || !result.data) {
|
||||
setError(result.error ?? "Your vote could not be recorded.");
|
||||
return;
|
||||
}
|
||||
setView(result.data);
|
||||
setNotice(answers.length === 0 ? "Vote withdrawn." : "Vote recorded.");
|
||||
});
|
||||
};
|
||||
|
||||
const toggleOption = (key: string) => {
|
||||
if (!view.canVote) return;
|
||||
if (view.multiSelect) {
|
||||
const next = view.yourAnswers.includes(key)
|
||||
? view.yourAnswers.filter((answer) => answer !== key)
|
||||
: [...view.yourAnswers, key];
|
||||
applyAnswers(next);
|
||||
return;
|
||||
}
|
||||
// Single answer: pressing the chosen option again retracts it.
|
||||
applyAnswers(view.yourAnswers.includes(key) ? [] : [key]);
|
||||
};
|
||||
|
||||
const settleTie = (winnerKey: string) => {
|
||||
setError(null);
|
||||
setNotice(null);
|
||||
busy.current = true;
|
||||
startTransition(async () => {
|
||||
const result = await resolvePollTieAction(view.id, winnerKey);
|
||||
busy.current = false;
|
||||
if (!result.success || !result.data) {
|
||||
setError(result.error ?? "The decision could not be recorded.");
|
||||
return;
|
||||
}
|
||||
setView(result.data);
|
||||
setNotice("Tie settled.");
|
||||
});
|
||||
};
|
||||
|
||||
const tiedOptions = view.options.filter((option) => view.tiedKeys.includes(option.key));
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<Card>
|
||||
<CardHeader className="gap-2">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<StatusBadge view={view} />
|
||||
<Badge variant="outline" className="border-white/20 text-muted-foreground">
|
||||
{view.multiSelect ? "Multiple answers" : "One answer"}
|
||||
</Badge>
|
||||
<Badge variant="outline" className="border-white/20 text-muted-foreground">
|
||||
{view.anonymity === "anonymous" ? "Anonymous" : "Public"}
|
||||
</Badge>
|
||||
{view.eligibleRoleCount > 0 && (
|
||||
<Badge variant="outline" className="border-white/20 text-muted-foreground">
|
||||
{view.eligibleRoleCount} eligible role{view.eligibleRoleCount === 1 ? "" : "s"}
|
||||
</Badge>
|
||||
)}
|
||||
{view.initiated && (
|
||||
<Badge variant="outline" className="border-sky-500/50 text-sky-300">
|
||||
You opened this
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<CardTitle className="text-xl">{view.title}</CardTitle>
|
||||
{view.body && <p className="text-sm text-muted-foreground">{view.body}</p>}
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground">
|
||||
<span className="flex items-center gap-1">
|
||||
<Clock className="size-3.5" />
|
||||
{view.closed
|
||||
? `Closed ${formatWhen(view.closesAt)}`
|
||||
: `Closes ${formatWhen(view.closesAt)} (${relative(view.closesAt)})`}
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<Users className="size-3.5" />
|
||||
{view.totalVotes} voter{view.totalVotes === 1 ? "" : "s"} · weight{" "}
|
||||
{formatWeight(view.totalWeight)}
|
||||
</span>
|
||||
{view.anonymity === "anonymous" && (
|
||||
<span className="flex items-center gap-1">
|
||||
<ShieldQuestion className="size-3.5" />
|
||||
{view.showsVoters
|
||||
? "Anonymous to members; you can see voters"
|
||||
: "Voter identities are hidden"}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
{view.options.map((option) => {
|
||||
const chosen = option.chosen;
|
||||
const selectable = view.canVote;
|
||||
return (
|
||||
<div
|
||||
key={option.key}
|
||||
className={cn(
|
||||
"rounded-lg border p-3 transition-colors",
|
||||
chosen ? "border-emerald-500/50 bg-emerald-500/5" : "border-white/10",
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2 text-sm font-medium">
|
||||
{option.emoji && <span>{option.emoji}</span>}
|
||||
<span className="truncate">{option.label}</span>
|
||||
{chosen && <Check className="size-4 shrink-0 text-emerald-400" />}
|
||||
</div>
|
||||
{option.description && (
|
||||
<p className="mt-0.5 text-xs text-muted-foreground">{option.description}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="shrink-0 text-right font-mono text-xs text-muted-foreground">
|
||||
<div>{option.raw}</div>
|
||||
<div className="text-[10px]">weight {formatWeight(option.weighted)}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Progress value={option.share} className="mt-2 h-1.5" />
|
||||
|
||||
{option.voters.length > 0 && (
|
||||
<p className="mt-1.5 text-[11px] text-muted-foreground">
|
||||
{option.voters.join(", ")}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{selectable && (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant={chosen ? "secondary" : "outline"}
|
||||
className="mt-2"
|
||||
disabled={isPending}
|
||||
onClick={() => toggleOption(option.key)}
|
||||
>
|
||||
{chosen
|
||||
? view.multiSelect
|
||||
? "Remove my answer"
|
||||
: "Withdraw my vote"
|
||||
: view.multiSelect
|
||||
? "Add my answer"
|
||||
: "Vote for this"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||
{notice && !error && <p className="text-sm text-emerald-400">{notice}</p>}
|
||||
|
||||
{!view.canVote && !view.closed && view.eligibleRoleCount > 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Only members holding one of this poll's eligible roles may vote.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{view.resolved && (
|
||||
<p className="text-sm">
|
||||
{view.winnerKey ? (
|
||||
<>
|
||||
<span className="text-muted-foreground">Outcome: </span>
|
||||
<span className="font-medium">{view.winnerLabel}</span>
|
||||
<span className="text-muted-foreground">
|
||||
{" "}
|
||||
({view.resolutionMethod?.replace("_", " ")})
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-muted-foreground">
|
||||
{view.totalVotes === 0
|
||||
? "No decision: nobody voted, so no result flag was written."
|
||||
: "No decision: no option carried a weighted score, so no result flag was written."}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{view.awaitingDecision && (
|
||||
<Card className="border-amber-500/30">
|
||||
<CardHeader className="gap-1">
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<Gavel className="size-4 text-amber-300" />
|
||||
Tied vote
|
||||
</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
The top options scored the same and the initiator's vote could not break it.
|
||||
{view.decisionDeadline
|
||||
? ` If nobody decides by ${formatWhen(view.decisionDeadline)} (${relative(
|
||||
view.decisionDeadline,
|
||||
)}), a random tied option wins.`
|
||||
: ""}
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-2">
|
||||
{tiedOptions.map((option) => (
|
||||
<div key={option.key} className="flex items-center justify-between gap-3">
|
||||
<span className="text-sm">
|
||||
{option.emoji ? `${option.emoji} ` : ""}
|
||||
{option.label}
|
||||
<span className="ml-2 text-xs text-muted-foreground">
|
||||
weight {formatWeight(option.weighted)}
|
||||
</span>
|
||||
</span>
|
||||
{view.canResolve ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={isPending}
|
||||
onClick={() => settleTie(option.key)}
|
||||
>
|
||||
Decide
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
{!view.canResolve && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
A superuser will settle this.
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<Link href="/polls" className="underline-offset-4 hover:underline">
|
||||
All polls
|
||||
</Link>
|
||||
<span>{isPending ? "Updating..." : `Refreshes every ${REFRESH_MS / 1000}s`}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Loading…
Reference in a new issue