Phase 4: scoreboard page, public API and realtime refresh
- buildScoreboardPayload is the single place deciding what the public may see: visible, frozen (snapshot scores, live current game), hidden (no scores, alphabetical) and reveal (unrevealed teams carry no score/order). - GET /api/public/scoreboard/[token] validates the token, then loads the event with the service client in one parallel round trip. - notify() pings sb/admin/game channels over Realtime's REST endpoint with no data; useRefreshChannel refetches immediately on a ping, throttles bursts, and falls back to a 10s poll, focus and reconnect. - /s/[token]: FLIP rank animation, count-up totals, reduced motion, fullscreen, cursor hide and a connection indicator. - Admin setup actions now notify, so renames and reorders show up live. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
/** Decimals needed to show `value` exactly, capped at 2 (totals are rounded to 2dp). */
|
||||
const decimalsOf = (value: number) => {
|
||||
const [, fraction = ""] = value.toFixed(2).replace(/0+$/, "").split(".");
|
||||
return fraction.length;
|
||||
};
|
||||
|
||||
/** Shows a number, counting up (or down) to each new value. Instant with reduced motion. */
|
||||
export function CountUp({ value, durationMs }: { value: number; durationMs: number }) {
|
||||
const [shown, setShown] = useState(value);
|
||||
// Where the display currently is, so an update mid-count continues from there.
|
||||
const shownRef = useRef(value);
|
||||
|
||||
useEffect(() => {
|
||||
const from = shownRef.current;
|
||||
if (from === value) return;
|
||||
|
||||
const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
const start = performance.now();
|
||||
let frame = requestAnimationFrame(function tick(now) {
|
||||
const progress = reduced ? 1 : Math.min(1, (now - start) / durationMs);
|
||||
const eased = 1 - (1 - progress) ** 3;
|
||||
const next = progress === 1 ? value : from + (value - from) * eased;
|
||||
shownRef.current = next;
|
||||
setShown(next);
|
||||
if (progress < 1) frame = requestAnimationFrame(tick);
|
||||
});
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [value, durationMs]);
|
||||
|
||||
// Count in whole numbers when the target is whole, so digits don't flicker with decimals.
|
||||
return <>{shown.toFixed(decimalsOf(value))}</>;
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
|
||||
import { readableTextColor } from "@/lib/color";
|
||||
import { useRefreshChannel } from "@/lib/hooks/use-refresh-channel";
|
||||
import { channelNames } from "@/lib/realtime-channels";
|
||||
import type { ScoreboardPayload, ScoreboardTeam } from "@/lib/scoreboard";
|
||||
|
||||
import { CountUp } from "./count-up";
|
||||
|
||||
const MOVE_MS = 600;
|
||||
const IDLE_MS = 3000;
|
||||
|
||||
const connectionDot = { live: "bg-signal", connecting: "bg-white/40", offline: "bg-alert" };
|
||||
const connectionLabel = { live: "live", connecting: "connecting…", offline: "offline — reconnecting" };
|
||||
|
||||
const prefersReducedMotion = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
|
||||
export function Scoreboard({ token, initial }: { token: string; initial: ScoreboardPayload }) {
|
||||
const [payload, setPayload] = useState(initial);
|
||||
const [fetchFailed, setFetchFailed] = useState(false);
|
||||
|
||||
const refetch = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(`/api/public/scoreboard/${token}`, { cache: "no-store" });
|
||||
if (!response.ok) throw new Error(String(response.status));
|
||||
setPayload((await response.json()) as ScoreboardPayload);
|
||||
setFetchFailed(false);
|
||||
} catch {
|
||||
// Keep showing the last good scores; the dot tells the host something is wrong.
|
||||
setFetchFailed(true);
|
||||
}
|
||||
}, [token]);
|
||||
|
||||
const socket = useRefreshChannel(channelNames.scoreboard(token), refetch);
|
||||
const connection = fetchFailed || socket === "disconnected" ? "offline" : socket === "connected" ? "live" : "connecting";
|
||||
|
||||
const rowElements = useRef(new Map<string, HTMLElement>());
|
||||
const lastTops = useRef(new Map<string, number>());
|
||||
|
||||
// FLIP: rows are re-ordered in the DOM, then slid from where they were to where they are.
|
||||
useLayoutEffect(() => {
|
||||
const animate = !prefersReducedMotion();
|
||||
rowElements.current.forEach((element, id) => {
|
||||
// offsetTop ignores transforms, so a move that interrupts another still measures correctly.
|
||||
const top = element.offsetTop;
|
||||
const previous = lastTops.current.get(id);
|
||||
if (animate && previous !== undefined && previous !== top) {
|
||||
element.animate(
|
||||
[{ transform: `translateY(${previous - top}px)` }, { transform: "translateY(0)" }],
|
||||
{ duration: MOVE_MS, easing: "cubic-bezier(0.2, 0.8, 0.2, 1)" },
|
||||
);
|
||||
// The one bold moment: a team that climbs gets a floodlight flash.
|
||||
if (top < previous) {
|
||||
element.animate(
|
||||
[
|
||||
{ boxShadow: "0 0 0 0 var(--floodlight)" },
|
||||
{ boxShadow: "0 0 0 0.6vh var(--floodlight)", offset: 0.35 },
|
||||
{ boxShadow: "0 0 0 0 transparent" },
|
||||
],
|
||||
{ duration: MOVE_MS * 1.5, easing: "ease-out" },
|
||||
);
|
||||
}
|
||||
}
|
||||
lastTops.current.set(id, top);
|
||||
});
|
||||
for (const id of lastTops.current.keys()) {
|
||||
if (!rowElements.current.has(id)) lastTops.current.delete(id);
|
||||
}
|
||||
}, [payload]);
|
||||
|
||||
// A resize moves every row; re-measure so the next update doesn't animate from stale positions.
|
||||
useEffect(() => {
|
||||
const remeasure = () =>
|
||||
rowElements.current.forEach((element, id) => lastTops.current.set(id, element.offsetTop));
|
||||
window.addEventListener("resize", remeasure);
|
||||
return () => window.removeEventListener("resize", remeasure);
|
||||
}, []);
|
||||
|
||||
const idle = useIdle(IDLE_MS);
|
||||
const { isFullscreen, toggleFullscreen } = useFullscreen();
|
||||
|
||||
const revealing = payload.reveal?.active ?? false;
|
||||
const hidden = payload.visibility === "hidden" && !revealing;
|
||||
const { currentGame } = payload;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`flex h-dvh flex-col gap-[2.5vh] overflow-hidden bg-stage px-[4vw] py-[3.5vh] text-white ${idle ? "cursor-none" : ""}`}
|
||||
>
|
||||
<header className="flex items-baseline justify-between gap-[3vw] font-display text-[clamp(1.25rem,5vh,4.5rem)] leading-none font-bold">
|
||||
<h1 className="truncate">{payload.eventName}</h1>
|
||||
{currentGame && (
|
||||
<p className="shrink-0 text-floodlight">
|
||||
<span className="text-white/70">
|
||||
Game {currentGame.index} of {currentGame.total}:
|
||||
</span>{" "}
|
||||
{currentGame.title}
|
||||
</p>
|
||||
)}
|
||||
</header>
|
||||
|
||||
{hidden && (
|
||||
<p className="self-center rounded-full border-2 border-alert px-[2.5vw] py-[1vh] text-[clamp(1rem,3.2vh,2.5rem)] font-bold">
|
||||
Scores are hidden — final reveal soon
|
||||
</p>
|
||||
)}
|
||||
|
||||
<ol className="flex min-h-0 flex-1 flex-col justify-center gap-[1.2vh]">
|
||||
{payload.teams.length === 0 && (
|
||||
<li className="self-center text-[clamp(1rem,3.2vh,2.5rem)] text-white/70">No teams yet</li>
|
||||
)}
|
||||
{payload.teams.map((team, index) =>
|
||||
revealing && team.rank === undefined ? (
|
||||
// Keyed by slot, not team: a mystery row must say nothing about who is in it.
|
||||
<li
|
||||
key={`slot-${index}`}
|
||||
aria-label="Not revealed yet"
|
||||
className="flex max-h-[20vh] min-h-0 flex-1 basis-0 items-center justify-center rounded-[1vh] border-2 border-dashed border-white/25 font-display text-[4vh] text-white/40"
|
||||
>
|
||||
?
|
||||
</li>
|
||||
) : (
|
||||
<TeamRow
|
||||
key={team.id}
|
||||
team={team}
|
||||
showScore={!hidden}
|
||||
justRevealed={revealing}
|
||||
register={(element) => {
|
||||
if (element) rowElements.current.set(team.id, element);
|
||||
else rowElements.current.delete(team.id);
|
||||
}}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
</ol>
|
||||
|
||||
<footer
|
||||
className={`flex items-center justify-end gap-[2vw] text-[clamp(0.875rem,2.2vh,1.5rem)] transition-opacity duration-500 ${idle ? "opacity-40" : ""}`}
|
||||
>
|
||||
{payload.visibility === "frozen" && !revealing && (
|
||||
<span className="mr-auto text-white/70">Scores frozen</span>
|
||||
)}
|
||||
<span role="status" className="flex items-center gap-[0.6em]">
|
||||
<span
|
||||
aria-hidden
|
||||
className={`inline-block size-[0.7em] rounded-full ${connectionDot[connection]}`}
|
||||
/>
|
||||
{connectionLabel[connection]}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleFullscreen}
|
||||
className={`min-h-11 rounded-md border border-white/30 px-4 font-bold hover:bg-white/10 focus-visible:outline-floodlight ${idle ? "invisible" : ""}`}
|
||||
>
|
||||
{isFullscreen ? "Exit fullscreen" : "Fullscreen"}
|
||||
</button>
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TeamRow({
|
||||
team,
|
||||
showScore,
|
||||
justRevealed,
|
||||
register,
|
||||
}: {
|
||||
team: ScoreboardTeam;
|
||||
showScore: boolean;
|
||||
justRevealed: boolean;
|
||||
register: (element: HTMLLIElement | null) => void;
|
||||
}) {
|
||||
const isLeader = showScore && team.rank === 1 && (team.total ?? 0) > 0;
|
||||
|
||||
return (
|
||||
<li
|
||||
ref={register}
|
||||
// Container units (cqh/cqw) size the text from the row itself, so rows fill the
|
||||
// screen whether there are 3 teams or 12.
|
||||
className={`flex max-h-[20vh] min-h-0 flex-1 basis-0 items-stretch overflow-hidden rounded-[1vh] bg-white/10 [container-type:size] ${
|
||||
isLeader ? "outline-[0.5vh] outline-floodlight outline-solid" : ""
|
||||
} ${justRevealed ? "animate-reveal-in" : ""}`}
|
||||
>
|
||||
<div
|
||||
className="flex aspect-square h-full shrink-0 items-center justify-center font-display text-[62cqh] leading-none font-bold tabular-nums"
|
||||
style={{ backgroundColor: team.color, color: readableTextColor(team.color) }}
|
||||
>
|
||||
{showScore && team.rank !== undefined ? team.rank : ""}
|
||||
</div>
|
||||
<div className="flex min-w-0 flex-1 items-center px-[3cqw] font-display text-[min(58cqh,7cqw)] leading-none font-bold">
|
||||
<span className="truncate">{team.name}</span>
|
||||
</div>
|
||||
{showScore && (
|
||||
<div className="flex shrink-0 items-center pr-[3cqw] font-display text-[min(72cqh,9cqw)] leading-none font-bold tabular-nums">
|
||||
{team.total !== undefined ? <CountUp value={team.total} durationMs={MOVE_MS} /> : "–"}
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
/** True after `ms` without mouse or keyboard activity (hides the cursor on the projector). */
|
||||
function useIdle(ms: number) {
|
||||
const [idle, setIdle] = useState(false);
|
||||
useEffect(() => {
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
const wake = () => {
|
||||
setIdle(false);
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => setIdle(true), ms);
|
||||
};
|
||||
const events = ["mousemove", "mousedown", "keydown", "touchstart"] as const;
|
||||
events.forEach((name) => window.addEventListener(name, wake));
|
||||
timer = setTimeout(() => setIdle(true), ms);
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
events.forEach((name) => window.removeEventListener(name, wake));
|
||||
};
|
||||
}, [ms]);
|
||||
return idle;
|
||||
}
|
||||
|
||||
function useFullscreen() {
|
||||
const [isFullscreen, setIsFullscreen] = useState(false);
|
||||
useEffect(() => {
|
||||
const onChange = () => setIsFullscreen(document.fullscreenElement !== null);
|
||||
document.addEventListener("fullscreenchange", onChange);
|
||||
return () => document.removeEventListener("fullscreenchange", onChange);
|
||||
}, []);
|
||||
|
||||
const toggleFullscreen = useCallback(() => {
|
||||
// Rejections (e.g. the browser blocking fullscreen) are harmless; the button just does nothing.
|
||||
if (document.fullscreenElement) void document.exitFullscreen().catch(() => {});
|
||||
else void document.documentElement.requestFullscreen().catch(() => {});
|
||||
}, []);
|
||||
|
||||
return { isFullscreen, toggleFullscreen };
|
||||
}
|
||||
Reference in New Issue
Block a user