Phase 7: judges — links, phone page, open link, judged control room
- Setup: nominate judges, copy personal links, QR codes (generated on demand in the browser), revoke/restore, and an open-link toggle. - GET /api/judge/[token] returns only that judge's own scores; PUT .../scores runs every check from ARCHITECTURE.md in checkJudgeWrite (pure, unit-tested) after one parallel lookup, plus a rate limit. - /j/[token]: mobile cards per team, spotlight pinned first, autosave with per-card status, read-only when locked/done, link-off when revoked. - /jo/[token]: name form -> personal link, remembered in localStorage so a re-scan doesn't create a second judge. - Control room: averages with on-request overrides, judge progress matrix, per-judge breakdown, spotlight select and lock toggle. - usePendingEdits shares the optimistic autosave logic between the admin grid and the judge page. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,23 +1,18 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import { saveAdminScore } from "@/app/admin/live-actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { BlockInput, NumberStepper } from "@/components/ui/score-inputs";
|
||||
import { formatScore } from "@/lib/criteria";
|
||||
import { usePendingEdits } from "@/lib/hooks/use-pending-edits";
|
||||
import type { LiveGame, LiveView } from "@/lib/live-view";
|
||||
|
||||
import { ErrorText } from "./error-text";
|
||||
|
||||
// An edit the server hasn't echoed back yet. Shown instead of the server's value so
|
||||
// taps feel instant (optimistic UI).
|
||||
type PendingEdit = { value: number | null; version: number; savedAt: number | null };
|
||||
|
||||
const cellKey = (teamId: string, criterionId: string) => `${teamId}|${criterionId}`;
|
||||
// A saved edit normally disappears when the refreshed data matches it. If it never
|
||||
// matches (someone else changed the cell), stop masking the server's value after this long.
|
||||
const STALE_MS = 5000;
|
||||
|
||||
export function ScoringGrid({
|
||||
eventId,
|
||||
@@ -29,59 +24,30 @@ export function ScoringGrid({
|
||||
teams: LiveView["teams"];
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [pending, setPending] = useState<Record<string, PendingEdit>>({});
|
||||
const [savingCount, setSavingCount] = useState(0);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const versions = useRef(0);
|
||||
|
||||
// Drop optimistic edits once the server data has caught up with them.
|
||||
useEffect(() => {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- reconciling local edits with fresh server props
|
||||
setPending((current) => {
|
||||
const now = Date.now();
|
||||
const kept = Object.entries(current).filter(([key, edit]) => {
|
||||
if (edit.savedAt === null) return true;
|
||||
const [teamId, criterionId] = key.split("|");
|
||||
const serverValue = game.cells[teamId]?.[criterionId]?.adminValue ?? null;
|
||||
return serverValue !== edit.value && now - edit.savedAt < STALE_MS;
|
||||
});
|
||||
return kept.length === Object.keys(current).length ? current : Object.fromEntries(kept);
|
||||
});
|
||||
}, [game]);
|
||||
// The admin's own rows: the scores in a direct game, the overrides in a judged game.
|
||||
const adminValues = useMemo(() => {
|
||||
const values: Record<string, number> = {};
|
||||
for (const [teamId, cells] of Object.entries(game.cells)) {
|
||||
for (const [criterionId, cell] of Object.entries(cells)) {
|
||||
if (cell.adminValue !== null) values[cellKey(teamId, criterionId)] = cell.adminValue;
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}, [game.cells]);
|
||||
|
||||
const save = (teamId: string, criterionId: string, value: number | null) => {
|
||||
const key = cellKey(teamId, criterionId);
|
||||
const version = ++versions.current;
|
||||
setPending((current) => ({ ...current, [key]: { value, version, savedAt: null } }));
|
||||
setSavingCount((count) => count + 1);
|
||||
setError(null);
|
||||
|
||||
// Only the newest edit of a cell may update or clear its pending state.
|
||||
const settle = (savedAt: number | null) =>
|
||||
setPending((current) => {
|
||||
if (current[key]?.version !== version) return current;
|
||||
if (savedAt === null) {
|
||||
return Object.fromEntries(Object.entries(current).filter(([other]) => other !== key));
|
||||
}
|
||||
return { ...current, [key]: { ...current[key], savedAt } };
|
||||
});
|
||||
|
||||
saveAdminScore(eventId, game.id, teamId, criterionId, value)
|
||||
.then((result) => {
|
||||
if (result.ok) {
|
||||
settle(Date.now());
|
||||
router.refresh();
|
||||
} else {
|
||||
settle(null);
|
||||
setError(result.error);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
settle(null);
|
||||
setError("That score wasn't saved — couldn't reach the server. Check your connection and enter it again.");
|
||||
})
|
||||
.finally(() => setSavingCount((count) => count - 1));
|
||||
};
|
||||
const save = useCallback(
|
||||
(key: string, value: number | null) => {
|
||||
const [teamId, criterionId] = key.split("|");
|
||||
return saveAdminScore(eventId, game.id, teamId, criterionId, value);
|
||||
},
|
||||
[eventId, game.id],
|
||||
);
|
||||
const refresh = useCallback(() => router.refresh(), [router]);
|
||||
const { edit, valueOf, isSaving, errorFor } = usePendingEdits(adminValues, save, refresh);
|
||||
// Judged games show averages; the override input for a cell only opens on request,
|
||||
// which keeps a 5-criteria grid on screen without sideways scrolling.
|
||||
const [overriding, setOverriding] = useState<string | null>(null);
|
||||
|
||||
if (game.criteria.length === 0) {
|
||||
return <p>This game has no criteria yet. Add some on the setup page.</p>;
|
||||
@@ -91,6 +57,7 @@ export function ScoringGrid({
|
||||
}
|
||||
|
||||
const judged = game.scoringMode === "judged";
|
||||
const error = errorFor();
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
@@ -120,8 +87,9 @@ export function ScoringGrid({
|
||||
<tbody>
|
||||
{teams.map((team) => {
|
||||
const result = game.results[team.id];
|
||||
const spotlit = game.spotlightTeamId === team.id;
|
||||
return (
|
||||
<tr key={team.id} className="bg-chalk">
|
||||
<tr key={team.id} className={spotlit ? "bg-floodlight/25" : "bg-chalk"}>
|
||||
<th scope="row" className="rounded-l-md py-2 pr-3 pl-2 font-bold whitespace-nowrap">
|
||||
<span
|
||||
aria-hidden
|
||||
@@ -129,32 +97,57 @@ export function ScoringGrid({
|
||||
style={{ backgroundColor: team.color }}
|
||||
/>
|
||||
{team.name}
|
||||
{spotlit && <span className="block text-sm font-normal">★ Now performing</span>}
|
||||
</th>
|
||||
{game.criteria.map((criterion) => {
|
||||
const cell = game.cells[team.id]?.[criterion.id];
|
||||
const edit = pending[cellKey(team.id, criterion.id)];
|
||||
const value = edit ? edit.value : (cell?.adminValue ?? null);
|
||||
const key = cellKey(team.id, criterion.id);
|
||||
const value = valueOf(key);
|
||||
const inputProps = {
|
||||
range: criterion,
|
||||
value,
|
||||
label: `${criterion.label} for ${team.name}`,
|
||||
onChange: (next: number | null) => save(team.id, criterion.id, next),
|
||||
label: `${judged ? "Override value: " : ""}${criterion.label} for ${team.name}`,
|
||||
onChange: (next: number | null) => edit(key, next),
|
||||
};
|
||||
return (
|
||||
<td key={criterion.id} className="px-2 py-2 align-top">
|
||||
{criterion.inputType === "blocks" ? (
|
||||
{judged && (
|
||||
<span className="mb-1 block text-sm">
|
||||
{cell?.judgeAverage == null ? (
|
||||
<span className="text-ink/70">No judge scores yet</span>
|
||||
) : (
|
||||
<>
|
||||
<strong
|
||||
className={`text-lg tabular-nums ${value !== null ? "text-ink/50 line-through" : ""}`}
|
||||
>
|
||||
{formatScore(cell.judgeAverage)}
|
||||
</strong>{" "}
|
||||
<span className="text-ink/70">
|
||||
avg of {cell.judgeCount} {cell.judgeCount === 1 ? "judge" : "judges"}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
{value !== null && (
|
||||
<strong className="ml-1 rounded bg-alert px-1.5 text-white">
|
||||
Override {formatScore(value)}
|
||||
</strong>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
{judged && value === null && overriding !== key ? (
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
aria-label={`Override ${criterion.label} for ${team.name}`}
|
||||
onClick={() => setOverriding(key)}
|
||||
>
|
||||
Override
|
||||
</Button>
|
||||
) : criterion.inputType === "blocks" ? (
|
||||
<BlockInput compact color={team.color} {...inputProps} />
|
||||
) : (
|
||||
<NumberStepper {...inputProps} />
|
||||
)}
|
||||
{judged && (
|
||||
<span className="mt-1 block text-sm text-ink/70">
|
||||
{cell?.judgeAverage == null
|
||||
? "No judge scores"
|
||||
: `Judges: ${formatScore(cell.judgeAverage)} (${cell.judgeCount})`}
|
||||
{value !== null && " · overridden"}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
@@ -174,13 +167,13 @@ export function ScoringGrid({
|
||||
</table>
|
||||
</div>
|
||||
<p role="status" className="text-sm font-bold">
|
||||
{savingCount > 0 ? "Saving…" : error ? "" : "All scores saved ✓"}
|
||||
{isSaving() ? "Saving…" : error ? "" : "All scores saved ✓"}
|
||||
</p>
|
||||
<ErrorText>{error}</ErrorText>
|
||||
{judged && (
|
||||
<p className="text-sm text-ink/70">
|
||||
This is a judged game. A value you enter here overrides the judges' average for that
|
||||
cell; clear it to use the judges again.
|
||||
“Override” replaces the judges' average for that cell until you clear it
|
||||
(tap the selected block again, or empty the number).
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user