- Timer: one per event, set from the control room (duration, presets, start/pause/resume/reset, show/hide, T shortcut). Rules are pure functions in src/lib/timer.ts; the server's clock sets the end time and each screen counts down locally, corrected for its own clock. Needs supabase/migrations/0002_timer.sql. - Sound effects on the scoreboard, synthesised with Web Audio (no files): drum-roll + crash per revealed team, fanfare for first place, a chime on game change, ticks for the last 10 seconds and a buzzer at zero. Triggers are pure functions comparing consecutive payloads. - 'Turn sound on' button on the scoreboard, since browsers block audio until a click; the choice is remembered across reloads. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
284 lines
12 KiB
TypeScript
284 lines
12 KiB
TypeScript
"use client";
|
||
|
||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
|
||
|
||
import { readableTextColor } from "@/lib/color";
|
||
import { useRefreshChannel } from "@/lib/hooks/use-refresh-channel";
|
||
import { useSound } from "@/lib/hooks/use-sound";
|
||
import { channelNames } from "@/lib/realtime-channels";
|
||
import type { ScoreboardPayload, ScoreboardTeam } from "@/lib/scoreboard";
|
||
import { soundsForUpdate } from "@/lib/scoreboard-sounds";
|
||
|
||
import { CountUp } from "./count-up";
|
||
import { ScoreboardTimer } from "./scoreboard-timer";
|
||
|
||
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";
|
||
|
||
// Teams already revealed when this page loaded appear at once; only teams revealed
|
||
// while watching get the drum-roll.
|
||
const [revealedOnLoad] = useState(
|
||
() => new Set(initial.teams.filter((team) => team.rank !== undefined).map((team) => team.id)),
|
||
);
|
||
|
||
// Sound effects for what just changed: a new game, a team being revealed.
|
||
const sound = useSound();
|
||
const { play } = sound;
|
||
const previousPayload = useRef(initial);
|
||
useEffect(() => {
|
||
const before = previousPayload.current;
|
||
previousPayload.current = payload;
|
||
if (before === payload) return;
|
||
soundsForUpdate(before, payload, { reducedMotion: prefersReducedMotion() }).forEach(play);
|
||
}, [payload, play]);
|
||
|
||
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>
|
||
|
||
{payload.timer && <ScoreboardTimer timer={payload.timer} serverNow={payload.updatedAt} play={play} />}
|
||
|
||
{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}
|
||
drumRoll={revealing && !revealedOnLoad.has(team.id)}
|
||
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-70" : ""}`}
|
||
>
|
||
{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>
|
||
{/* Stays visible while sound is off or waiting, so the host can't miss that it's silent. */}
|
||
<button
|
||
type="button"
|
||
aria-pressed={sound.state === "on"}
|
||
onClick={sound.state === "on" ? sound.turnOff : () => void sound.turnOn()}
|
||
className={`min-h-11 rounded-md border px-4 font-bold hover:bg-white/10 focus-visible:outline-floodlight ${
|
||
sound.state === "on" ? "border-white/30" : "border-floodlight text-floodlight"
|
||
} ${idle && sound.state === "on" ? "invisible" : ""}`}
|
||
>
|
||
{sound.state === "on" ? "Sound on" : sound.state === "waiting" ? "Click anywhere for sound" : "Turn sound on"}
|
||
</button>
|
||
<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,
|
||
drumRoll,
|
||
register,
|
||
}: {
|
||
team: ScoreboardTeam;
|
||
showScore: boolean;
|
||
/** Play the reveal build-up when this row first appears. */
|
||
drumRoll: 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={`relative 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" : ""
|
||
} ${drumRoll ? "animate-reveal-in" : ""}`}
|
||
>
|
||
{drumRoll && (
|
||
// Visual drum-roll: a shaking "?" covers the row for a beat before the team appears.
|
||
<div
|
||
aria-hidden
|
||
className="reveal-cover absolute inset-0 z-10 flex items-center justify-center rounded-[1vh] border-2 border-dashed border-floodlight bg-stage font-display text-[60cqh] font-bold text-floodlight"
|
||
>
|
||
<span className="reveal-shake">?</span>
|
||
</div>
|
||
)}
|
||
<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 };
|
||
}
|