Phase 3: admin magic-link auth and event setup screens
- /login sends a Supabase magic link (admin emails only); /auth/confirm completes sign-in; proxy.ts guards /admin and every server action re-checks with requireAdmin(), since actions are plain POST endpoints. - /admin lists, creates, duplicates and deletes events. - /admin/events/[eventId] edits teams (colour, order) and games with criteria, presets and notes. All input goes through zod schemas that mirror the database constraints so errors read as plain sentences. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
"use client";
|
||||
|
||||
import { useActionState } from "react";
|
||||
|
||||
import { createEvent } from "@/app/admin/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Field, inputClass } from "@/components/ui/field";
|
||||
|
||||
import { ErrorText } from "./error-text";
|
||||
|
||||
export function CreateEventForm() {
|
||||
const [state, formAction, pending] = useActionState(createEvent, null);
|
||||
|
||||
return (
|
||||
<form action={formAction} className="mt-3 flex flex-wrap items-end gap-3">
|
||||
<Field label="Name" className="min-w-56 flex-1">
|
||||
<input name="name" required maxLength={120} className={inputClass} placeholder="Worship Game Night" />
|
||||
</Field>
|
||||
<Field label="Date (optional)">
|
||||
<input name="eventDate" type="date" className={inputClass} />
|
||||
</Field>
|
||||
<Button type="submit" disabled={pending}>
|
||||
{pending ? "Creating…" : "Create game night"}
|
||||
</Button>
|
||||
<div className="basis-full">
|
||||
<ErrorText>{state && !state.ok ? state.error : null}</ErrorText>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export function ErrorText({ children }: { children: string | null }) {
|
||||
return (
|
||||
<p role="alert" className="font-bold text-alert empty:hidden">
|
||||
{children}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
import { updateEvent } from "@/app/admin/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Field, inputClass } from "@/components/ui/field";
|
||||
|
||||
import { ErrorText } from "./error-text";
|
||||
import { useAction } from "./use-action";
|
||||
|
||||
export function EventDetailsForm(props: { eventId: string; name: string; eventDate: string }) {
|
||||
const [name, setName] = useState(props.name);
|
||||
const [eventDate, setEventDate] = useState(props.eventDate);
|
||||
const { pending, error, run } = useAction();
|
||||
const dirty = name !== props.name || eventDate !== props.eventDate;
|
||||
|
||||
return (
|
||||
<form
|
||||
className="mt-3 flex flex-wrap items-end gap-3"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
run(() => updateEvent(props.eventId, { name, eventDate }));
|
||||
}}
|
||||
>
|
||||
<Field label="Name" className="min-w-56 flex-1">
|
||||
<input
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
required
|
||||
maxLength={120}
|
||||
className={inputClass}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Date (optional)">
|
||||
<input
|
||||
type="date"
|
||||
value={eventDate}
|
||||
onChange={(event) => setEventDate(event.target.value)}
|
||||
className={inputClass}
|
||||
/>
|
||||
</Field>
|
||||
<Button type="submit" variant="secondary" disabled={pending || !dirty}>
|
||||
{pending ? "Saving…" : dirty ? "Save details" : "Saved"}
|
||||
</Button>
|
||||
<div className="basis-full">
|
||||
<ErrorText>{error}</ErrorText>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
"use client";
|
||||
|
||||
import { deleteEvent, duplicateEvent } from "@/app/admin/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
import { ErrorText } from "./error-text";
|
||||
import { useAction } from "./use-action";
|
||||
|
||||
export function EventRowActions({ eventId, eventName }: { eventId: string; eventName: string }) {
|
||||
const { pending, error, run } = useAction();
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
disabled={pending}
|
||||
onClick={() => run(() => duplicateEvent(eventId))}
|
||||
>
|
||||
Duplicate
|
||||
</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
size="sm"
|
||||
disabled={pending}
|
||||
onClick={() => {
|
||||
if (window.confirm(`Delete "${eventName}" and all its teams, games and scores? This can't be undone.`)) {
|
||||
run(() => deleteEvent(eventId));
|
||||
}
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
<ErrorText>{error}</ErrorText>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
import { saveGame } from "@/app/admin/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Field, inputClass, textareaClass } from "@/components/ui/field";
|
||||
import { criteriaPresets, type PresetKey } from "@/lib/presets";
|
||||
import type { GameWithCriteria } from "@/lib/queries/event";
|
||||
import { parsePlacementPoints, type CriterionDraft, type GameDraft } from "@/lib/validation/admin";
|
||||
|
||||
import { ErrorText } from "./error-text";
|
||||
import { useAction } from "./use-action";
|
||||
|
||||
// A stable React key per criterion row, including rows that aren't saved yet.
|
||||
type CriterionRow = CriterionDraft & { key: string };
|
||||
type Draft = Omit<GameDraft, "criteria" | "placementPoints"> & {
|
||||
placementPoints: string;
|
||||
criteria: CriterionRow[];
|
||||
};
|
||||
|
||||
let nextKey = 0;
|
||||
const newKey = () => `new-${nextKey++}`;
|
||||
|
||||
const blankCriterion = (): CriterionRow => ({
|
||||
key: newKey(),
|
||||
label: "",
|
||||
description: "",
|
||||
inputType: "blocks",
|
||||
min: 1,
|
||||
max: 5,
|
||||
step: 1,
|
||||
weight: 1,
|
||||
});
|
||||
|
||||
function toDraft(game: GameWithCriteria): Draft {
|
||||
return {
|
||||
title: game.title,
|
||||
description: game.description ?? "",
|
||||
scoringMode: game.scoring_mode,
|
||||
pointsMode: game.points_mode,
|
||||
multiplier: game.multiplier,
|
||||
placementPoints: game.placement_points.join(", "),
|
||||
adminNotes: game.admin_notes ?? "",
|
||||
judgeNotes: game.judge_notes ?? "",
|
||||
criteria: game.criteria.map((criterion) => ({
|
||||
key: criterion.id,
|
||||
id: criterion.id,
|
||||
label: criterion.label,
|
||||
description: criterion.description ?? "",
|
||||
inputType: criterion.input_type,
|
||||
min: criterion.min_value,
|
||||
max: criterion.max_value,
|
||||
step: criterion.step,
|
||||
weight: criterion.weight,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
const presetKeys = Object.keys(criteriaPresets) as PresetKey[];
|
||||
|
||||
export function GameForm({ eventId, game }: { eventId: string; game: GameWithCriteria }) {
|
||||
const [draft, setDraft] = useState(() => toDraft(game));
|
||||
const [dirty, setDirty] = useState(false);
|
||||
const { pending, error, run } = useAction();
|
||||
|
||||
const change = (patch: Partial<Draft>) => {
|
||||
setDraft((current) => ({ ...current, ...patch }));
|
||||
setDirty(true);
|
||||
};
|
||||
const changeCriterion = (key: string, patch: Partial<CriterionDraft>) =>
|
||||
change({
|
||||
criteria: draft.criteria.map((criterion) =>
|
||||
criterion.key === key ? { ...criterion, ...patch } : criterion,
|
||||
),
|
||||
});
|
||||
const moveCriterion = (index: number, offset: -1 | 1) => {
|
||||
const criteria = [...draft.criteria];
|
||||
[criteria[index], criteria[index + offset]] = [criteria[index + offset], criteria[index]];
|
||||
change({ criteria });
|
||||
};
|
||||
|
||||
const applyPreset = (key: PresetKey) => {
|
||||
const hasSaved = draft.criteria.some((criterion) => criterion.id);
|
||||
if (
|
||||
hasSaved &&
|
||||
!window.confirm("Replace this game's criteria with the preset? Scores for the old criteria are deleted when you save.")
|
||||
) {
|
||||
return;
|
||||
}
|
||||
change({
|
||||
criteria: criteriaPresets[key].criteria.map((criterion) => ({ ...criterion, key: newKey() })),
|
||||
});
|
||||
};
|
||||
|
||||
const save = () =>
|
||||
run(
|
||||
() =>
|
||||
saveGame(eventId, game.id, {
|
||||
...draft,
|
||||
placementPoints: parsePlacementPoints(draft.placementPoints),
|
||||
criteria: draft.criteria.map((row) => {
|
||||
const criterion: CriterionDraft & { key?: string } = { ...row };
|
||||
delete criterion.key;
|
||||
return criterion;
|
||||
}),
|
||||
}),
|
||||
() => setDirty(false),
|
||||
);
|
||||
|
||||
return (
|
||||
<form
|
||||
className="flex flex-col gap-5"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
save();
|
||||
}}
|
||||
>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<Field label="Title">
|
||||
<input
|
||||
value={draft.title}
|
||||
onChange={(event) => change({ title: event.target.value })}
|
||||
required
|
||||
maxLength={120}
|
||||
className={inputClass}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Description (optional)">
|
||||
<input
|
||||
value={draft.description}
|
||||
onChange={(event) => change({ description: event.target.value })}
|
||||
className={inputClass}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label="Who scores"
|
||||
hint={draft.scoringMode === "judged" ? "Judges score from their phones via links." : "You enter the scores yourself."}
|
||||
>
|
||||
<select
|
||||
value={draft.scoringMode}
|
||||
onChange={(event) => change({ scoringMode: event.target.value as Draft["scoringMode"] })}
|
||||
className={inputClass}
|
||||
>
|
||||
<option value="direct">Direct — host enters scores</option>
|
||||
<option value="judged">Judged — judges score via links</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field
|
||||
label="Leaderboard points"
|
||||
hint={
|
||||
draft.pointsMode === "placement"
|
||||
? "Teams are ranked, then get the placement points below."
|
||||
: "Teams get their criteria total as points."
|
||||
}
|
||||
>
|
||||
<select
|
||||
value={draft.pointsMode}
|
||||
onChange={(event) => change({ pointsMode: event.target.value as Draft["pointsMode"] })}
|
||||
className={inputClass}
|
||||
>
|
||||
<option value="raw">Raw — criteria total</option>
|
||||
<option value="placement">Placement — points by rank</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Multiplier" hint="Points are multiplied by this. Use 2 for a double-points game.">
|
||||
<NumberInput value={draft.multiplier} min={0} step="any" onChange={(multiplier) => change({ multiplier })} />
|
||||
</Field>
|
||||
{draft.pointsMode === "placement" && (
|
||||
<Field label="Placement points" hint="1st, 2nd, 3rd… separated by commas. Teams beyond the list get 0.">
|
||||
<input
|
||||
value={draft.placementPoints}
|
||||
onChange={(event) => change({ placementPoints: event.target.value })}
|
||||
className={inputClass}
|
||||
placeholder="10, 7, 5, 3"
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<fieldset className="flex flex-col gap-3">
|
||||
<legend className="text-lg font-bold">Criteria</legend>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="text-sm font-bold">Replace with preset:</span>
|
||||
{presetKeys.map((key) => (
|
||||
<Button key={key} variant="secondary" size="sm" onClick={() => applyPreset(key)}>
|
||||
{criteriaPresets[key].label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<ol className="flex flex-col gap-3">
|
||||
{draft.criteria.map((criterion, index) => (
|
||||
<li key={criterion.key} className="rounded-md border border-ink/15 bg-chalk p-3">
|
||||
<div className="grid gap-3 sm:grid-cols-[2fr_3fr]">
|
||||
<Field label="Label">
|
||||
<input
|
||||
value={criterion.label}
|
||||
onChange={(event) => changeCriterion(criterion.key, { label: event.target.value })}
|
||||
required
|
||||
maxLength={60}
|
||||
className={inputClass}
|
||||
placeholder="Pitch"
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Description (shown to whoever scores)">
|
||||
<input
|
||||
value={criterion.description}
|
||||
onChange={(event) => changeCriterion(criterion.key, { description: event.target.value })}
|
||||
maxLength={300}
|
||||
className={inputClass}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap items-end gap-3">
|
||||
<Field label="Input">
|
||||
<select
|
||||
value={criterion.inputType}
|
||||
onChange={(event) =>
|
||||
changeCriterion(criterion.key, {
|
||||
inputType: event.target.value as CriterionDraft["inputType"],
|
||||
})
|
||||
}
|
||||
className={inputClass}
|
||||
>
|
||||
<option value="blocks">Blocks (tap a number)</option>
|
||||
<option value="number">Number (type or +/−)</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Min" className="w-20">
|
||||
<NumberInput value={criterion.min} step="any" onChange={(min) => changeCriterion(criterion.key, { min })} />
|
||||
</Field>
|
||||
<Field label="Max" className="w-20">
|
||||
<NumberInput value={criterion.max} step="any" onChange={(max) => changeCriterion(criterion.key, { max })} />
|
||||
</Field>
|
||||
<Field label="Step" className="w-20">
|
||||
<NumberInput value={criterion.step} step="any" onChange={(step) => changeCriterion(criterion.key, { step })} />
|
||||
</Field>
|
||||
<Field label="Weight" className="w-20">
|
||||
<NumberInput value={criterion.weight} min={0} step="any" onChange={(weight) => changeCriterion(criterion.key, { weight })} />
|
||||
</Field>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
aria-label={`Move ${criterion.label || "criterion"} up`}
|
||||
disabled={index === 0}
|
||||
onClick={() => moveCriterion(index, -1)}
|
||||
>
|
||||
↑
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
aria-label={`Move ${criterion.label || "criterion"} down`}
|
||||
disabled={index === draft.criteria.length - 1}
|
||||
onClick={() => moveCriterion(index, 1)}
|
||||
>
|
||||
↓
|
||||
</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
size="sm"
|
||||
disabled={draft.criteria.length === 1}
|
||||
onClick={() =>
|
||||
change({ criteria: draft.criteria.filter((other) => other.key !== criterion.key) })
|
||||
}
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
<div>
|
||||
<Button
|
||||
variant="secondary"
|
||||
disabled={draft.criteria.length >= 20}
|
||||
onClick={() => change({ criteria: [...draft.criteria, blankCriterion()] })}
|
||||
>
|
||||
Add criterion
|
||||
</Button>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<Field label="Notes for judges" hint="Judges see this on their page.">
|
||||
<textarea
|
||||
value={draft.judgeNotes}
|
||||
onChange={(event) => change({ judgeNotes: event.target.value })}
|
||||
rows={3}
|
||||
className={textareaClass}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Notes for you" hint="Only you see this, in the control room.">
|
||||
<textarea
|
||||
value={draft.adminNotes}
|
||||
onChange={(event) => change({ adminNotes: event.target.value })}
|
||||
rows={3}
|
||||
className={textareaClass}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Button type="submit" disabled={pending || !dirty}>
|
||||
{pending ? "Saving…" : "Save game"}
|
||||
</Button>
|
||||
<span role="status" className="text-sm font-bold">
|
||||
{dirty ? "Unsaved changes" : "Saved ✓"}
|
||||
</span>
|
||||
<ErrorText>{error}</ErrorText>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
/** Numeric input that reports NaN while empty, so validation can say "must be a number". */
|
||||
function NumberInput({
|
||||
value,
|
||||
onChange,
|
||||
...props
|
||||
}: {
|
||||
value: number;
|
||||
onChange: (value: number) => void;
|
||||
min?: number;
|
||||
step?: number | "any";
|
||||
}) {
|
||||
return (
|
||||
<input
|
||||
type="number"
|
||||
inputMode="decimal"
|
||||
value={Number.isNaN(value) ? "" : value}
|
||||
onChange={(event) => onChange(event.target.value === "" ? Number.NaN : Number(event.target.value))}
|
||||
className={inputClass}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
import { addGame, deleteGame, duplicateGame, moveGame } from "@/app/admin/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { inputClass } from "@/components/ui/field";
|
||||
import { criteriaPresets, type PresetKey } from "@/lib/presets";
|
||||
import type { GameWithCriteria } from "@/lib/queries/event";
|
||||
|
||||
import { ErrorText } from "./error-text";
|
||||
import { GameForm } from "./game-form";
|
||||
import { useAction } from "./use-action";
|
||||
|
||||
const presetKeys = Object.keys(criteriaPresets) as PresetKey[];
|
||||
|
||||
export function GamesEditor({ eventId, games }: { eventId: string; games: GameWithCriteria[] }) {
|
||||
const [preset, setPreset] = useState<PresetKey>("karaoke");
|
||||
const { pending, error, run } = useAction();
|
||||
|
||||
return (
|
||||
<div className="mt-3 flex flex-col gap-3">
|
||||
{games.length === 0 && <p>No games yet. Pick a starting point below and add one.</p>}
|
||||
<ol className="flex flex-col gap-3">
|
||||
{games.map((game, index) => (
|
||||
<GameCard
|
||||
key={game.id}
|
||||
eventId={eventId}
|
||||
game={game}
|
||||
number={index + 1}
|
||||
isFirst={index === 0}
|
||||
isLast={index === games.length - 1}
|
||||
/>
|
||||
))}
|
||||
</ol>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2 rounded-lg border border-ink/15 bg-white p-4">
|
||||
<label className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-bold">Start from</span>
|
||||
<select
|
||||
value={preset}
|
||||
onChange={(event) => setPreset(event.target.value as PresetKey)}
|
||||
className={`${inputClass} w-auto`}
|
||||
>
|
||||
{presetKeys.map((key) => (
|
||||
<option key={key} value={key}>
|
||||
{criteriaPresets[key].label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<Button disabled={pending} onClick={() => run(() => addGame(eventId, preset))}>
|
||||
Add game
|
||||
</Button>
|
||||
<ErrorText>{error}</ErrorText>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function GameCard({
|
||||
eventId,
|
||||
game,
|
||||
number,
|
||||
isFirst,
|
||||
isLast,
|
||||
}: {
|
||||
eventId: string;
|
||||
game: GameWithCriteria;
|
||||
number: number;
|
||||
isFirst: boolean;
|
||||
isLast: boolean;
|
||||
}) {
|
||||
const { pending, error, run } = useAction();
|
||||
const criteriaCount = game.criteria.length;
|
||||
|
||||
return (
|
||||
<li className="rounded-lg border border-ink/15 bg-white">
|
||||
<details>
|
||||
<summary className="flex min-h-11 cursor-pointer flex-wrap items-center gap-x-3 gap-y-1 p-4">
|
||||
<span className="text-xl font-bold">
|
||||
{number}. {game.title}
|
||||
</span>
|
||||
<span className="text-sm text-ink/70">
|
||||
{game.scoring_mode === "judged" ? "Judged" : "Direct"} ·{" "}
|
||||
{game.points_mode === "placement" ? "placement points" : "raw points"} · {criteriaCount}{" "}
|
||||
{criteriaCount === 1 ? "criterion" : "criteria"}
|
||||
</span>
|
||||
</summary>
|
||||
|
||||
<div className="flex flex-col gap-4 border-t border-ink/15 p-4">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
disabled={pending || isFirst}
|
||||
onClick={() => run(() => moveGame(eventId, game.id, "up"))}
|
||||
>
|
||||
↑ Move up
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
disabled={pending || isLast}
|
||||
onClick={() => run(() => moveGame(eventId, game.id, "down"))}
|
||||
>
|
||||
↓ Move down
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
disabled={pending}
|
||||
onClick={() => run(() => duplicateGame(eventId, game.id))}
|
||||
>
|
||||
Duplicate
|
||||
</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
size="sm"
|
||||
disabled={pending}
|
||||
onClick={() => {
|
||||
if (window.confirm(`Delete "${game.title}" and its scores? This can't be undone.`)) {
|
||||
run(() => deleteGame(eventId, game.id));
|
||||
}
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
<ErrorText>{error}</ErrorText>
|
||||
</div>
|
||||
|
||||
{/* Re-mount after each save so the form picks up ids of newly created criteria. */}
|
||||
<GameForm key={game.updated_at} eventId={eventId} game={game} />
|
||||
</div>
|
||||
</details>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
import { addTeam, deleteTeam, moveTeam, updateTeam } from "@/app/admin/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { inputClass } from "@/components/ui/field";
|
||||
import type { Tables } from "@/lib/database.types";
|
||||
|
||||
import { ErrorText } from "./error-text";
|
||||
import { useAction } from "./use-action";
|
||||
|
||||
type Team = Tables<"teams">;
|
||||
|
||||
export function TeamsEditor({ eventId, teams }: { eventId: string; teams: Team[] }) {
|
||||
const [newName, setNewName] = useState("");
|
||||
const { pending, error, run } = useAction();
|
||||
|
||||
return (
|
||||
<div className="mt-3 flex flex-col gap-3">
|
||||
{teams.length === 0 && <p>No teams yet. Add the first one below.</p>}
|
||||
<ul className="flex flex-col gap-2">
|
||||
{teams.map((team, index) => (
|
||||
<TeamRow
|
||||
// Re-mount when saved values change so local edits reset to the server's copy.
|
||||
key={`${team.id}:${team.name}:${team.color}`}
|
||||
eventId={eventId}
|
||||
team={team}
|
||||
isFirst={index === 0}
|
||||
isLast={index === teams.length - 1}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
<form
|
||||
className="flex flex-wrap items-center gap-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
run(() => addTeam(eventId, newName), () => setNewName(""));
|
||||
}}
|
||||
>
|
||||
<input
|
||||
aria-label="New team name"
|
||||
value={newName}
|
||||
onChange={(event) => setNewName(event.target.value)}
|
||||
required
|
||||
maxLength={60}
|
||||
placeholder="Team name"
|
||||
className={`${inputClass} max-w-xs`}
|
||||
/>
|
||||
<Button type="submit" disabled={pending}>
|
||||
Add team
|
||||
</Button>
|
||||
</form>
|
||||
<ErrorText>{error}</ErrorText>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TeamRow({
|
||||
eventId,
|
||||
team,
|
||||
isFirst,
|
||||
isLast,
|
||||
}: {
|
||||
eventId: string;
|
||||
team: Team;
|
||||
isFirst: boolean;
|
||||
isLast: boolean;
|
||||
}) {
|
||||
const [name, setName] = useState(team.name);
|
||||
const [color, setColor] = useState(team.color);
|
||||
const { pending, error, run } = useAction();
|
||||
|
||||
// Saves on blur rather than per keystroke: one request per edit.
|
||||
const save = () => {
|
||||
if (name === team.name && color === team.color) return;
|
||||
run(() => updateTeam(eventId, team.id, { name, color }));
|
||||
};
|
||||
|
||||
return (
|
||||
<li className="flex flex-col gap-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
aria-label={`Colour for ${team.name}`}
|
||||
value={color}
|
||||
onChange={(event) => setColor(event.target.value)}
|
||||
onBlur={save}
|
||||
className="h-11 w-14 cursor-pointer rounded-md border border-ink/25 bg-white p-1"
|
||||
/>
|
||||
<input
|
||||
aria-label="Team name"
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
onBlur={save}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter") event.currentTarget.blur();
|
||||
}}
|
||||
maxLength={60}
|
||||
className={`${inputClass} min-w-40 flex-1`}
|
||||
/>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
aria-label={`Move ${team.name} up`}
|
||||
disabled={pending || isFirst}
|
||||
onClick={() => run(() => moveTeam(eventId, team.id, "up"))}
|
||||
>
|
||||
↑
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
aria-label={`Move ${team.name} down`}
|
||||
disabled={pending || isLast}
|
||||
onClick={() => run(() => moveTeam(eventId, team.id, "down"))}
|
||||
>
|
||||
↓
|
||||
</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
size="sm"
|
||||
disabled={pending}
|
||||
onClick={() => {
|
||||
if (window.confirm(`Delete team "${team.name}" and its scores?`)) {
|
||||
run(() => deleteTeam(eventId, team.id));
|
||||
}
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
</div>
|
||||
<ErrorText>{error}</ErrorText>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useState, useTransition } from "react";
|
||||
|
||||
import type { ActionResult } from "@/app/admin/actions";
|
||||
|
||||
/** Runs a server action, tracking pending state and the last error message. */
|
||||
export function useAction() {
|
||||
const [pending, startTransition] = useTransition();
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const run = useCallback((action: () => Promise<ActionResult>, onSuccess?: () => void) => {
|
||||
startTransition(async () => {
|
||||
try {
|
||||
const result = await action();
|
||||
if (result.ok) {
|
||||
setError(null);
|
||||
onSuccess?.();
|
||||
} else {
|
||||
setError(result.error);
|
||||
}
|
||||
} catch {
|
||||
setError("Couldn't reach the server. Check your connection and try again.");
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
return { pending, error, run };
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { ButtonHTMLAttributes } from "react";
|
||||
|
||||
const variants = {
|
||||
primary: "bg-ink text-white hover:bg-ink/90",
|
||||
secondary: "border border-ink/25 bg-white text-ink hover:bg-ink/5",
|
||||
danger: "border border-alert/50 bg-white text-alert hover:bg-alert/10",
|
||||
} as const;
|
||||
|
||||
const sizes = {
|
||||
// min-h-11 = 44px tap target
|
||||
md: "min-h-11 px-4 text-base",
|
||||
sm: "min-h-11 min-w-11 px-3 text-sm",
|
||||
} as const;
|
||||
|
||||
export type ButtonVariant = keyof typeof variants;
|
||||
|
||||
export function buttonClass(variant: ButtonVariant = "primary", size: keyof typeof sizes = "md") {
|
||||
return `inline-flex items-center justify-center gap-2 rounded-md font-bold transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${variants[variant]} ${sizes[size]}`;
|
||||
}
|
||||
|
||||
type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
|
||||
variant?: ButtonVariant;
|
||||
size?: keyof typeof sizes;
|
||||
};
|
||||
|
||||
export function Button({ variant, size, className = "", type = "button", ...props }: ButtonProps) {
|
||||
return <button type={type} className={`${buttonClass(variant, size)} ${className}`} {...props} />;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
export const inputClass =
|
||||
"min-h-11 w-full rounded-md border border-ink/25 bg-white px-3 text-base text-ink placeholder:text-ink/40";
|
||||
|
||||
export const textareaClass = `${inputClass} py-2`;
|
||||
|
||||
/** Label wrapping its control, so the whole thing is one tap target and needs no ids. */
|
||||
export function Field({
|
||||
label,
|
||||
hint,
|
||||
className = "",
|
||||
children,
|
||||
}: {
|
||||
label: string;
|
||||
hint?: string;
|
||||
className?: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<label className={`flex flex-col gap-1 ${className}`}>
|
||||
<span className="text-sm font-bold">{label}</span>
|
||||
{children}
|
||||
{hint && <span className="text-sm text-ink/70">{hint}</span>}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user