brackt/app/components/AutodraftSettings.tsx
Chris Parsons 4bbcac1949
fix: resolve all 48 WCAG 2.2 AA accessibility issues (#439)
* fix: resolve all 48 WCAG 2.2 AA accessibility issues

Critical fixes:
- Add aria-label to all unlabeled inputs/selects in draft dialogs (ParticipantSelectionDialog, TimeBankAdjustmentDialog, AvailableParticipantsSection)
- Add role="dialog" + aria-modal + focus trap to ConnectionOverlay and AuthRecoveryOverlay
- Add aria-live region and connection status announcement to ConnectionOverlay

Serious fixes:
- Add skip-to-content link in root.tsx with id="main-content" on <main>
- Add aria-label to UserMenu trigger button
- Add aria-describedby + role="alert" to all auth form error messages (login, register, onboarding, forgot-password, reset-password)
- Replace emoji column headers in StandingsTable with aria-label + aria-hidden spans
- Add aria-live="assertive" to "It's your turn" desktop and mobile on-clock indicators
- Add aria-live="polite" to draft room countdown timer
- Add pause button to SportTicker (WCAG 2.2.2); add aria-hidden to ticker content
- Fix Footer text contrast (changed from 28% to text-muted-foreground)
- Fix OvernightPauseSettings: add htmlFor/id pairs and role="radiogroup"+aria-checked to mode buttons
- Fix DraftSetupSection: replace broken htmlFor with aria-label on date picker button
- Add aria-label to PeopleSection owner and commissioner selects
- Add labels to ScoringPresetPicker score inputs; add role="radiogroup"+aria-checked to preset buttons
- Add role="radiogroup"+aria-checked to AutodraftSettings option buttons
- Add accessible names, aria-current="step", and <ol> list semantics to WizardStepper

Moderate fixes:
- Add aria-controls to RecentPicksFeed toggle button; wrap picks list in aria-live region
- Add role="tab"+aria-selected+aria-controls to mobile board sub-tabs + role="tabpanel"
- Add role="radiogroup"+aria-checked to TimerModeSelector
- Add aria-current="page" + aria-label to SettingsDesktopNav
- Add aria-label="Admin navigation" to admin sidebar nav
- Add scope="col" + <caption> to StandingsTable and ScoringTables
- Add ARIA table roles (role="table/rowgroup/row/columnheader/rowheader/cell") to DraftSummaryView CSS grid

Minor fixes:
- Add aria-hidden="true" to decorative trend icons in StandingsTable
- Add aria-hidden="true" to desktop column header labels row in AvailableParticipantsSection
- Replace title with aria-label on all icon-only buttons (watchlist, queue) in AvailableParticipantsSection
- Add aria-label to NotificationSettings switchOnly Switch
- Add prefers-reduced-motion check to SlotMachineHeadline JS animation
- Bump --muted-foreground from 55% to 62% opacity for improved contrast margin

https://claude.ai/code/session_01JXajpFxhqLf8aPCncP81k3

* Fix code review findings from WCAG compliance pass

- Add Arrow key navigation + roving tabindex to all role=radiogroup
  components (AutodraftSettings x2, TimerModeSelector,
  OvernightPauseSettings, ScoringPresetPicker) per ARIA radio pattern
- Extract shared focus-trap logic into useFocusTrap hook; update
  ConnectionOverlay and AuthRecoveryOverlay to use it
- Add tabIndex={-1} to ConnectionOverlay Card so focus can land in
  spinner-only state (no interactive children)
- Replace aria-live on loading dots container with sr-only span so
  status changes are announced by text content, not aria-label
- Remove contradictory aria-hidden+role=columnheader from
  AvailableParticipantsSection visual-only header row
- Remove invalid scope="col" from div[role=columnheader] in
  DraftSummaryView (scope is only valid on <th>)
- Remove redundant aria-label from ParticipantSelectionDialog sport
  select (htmlFor label is sufficient)
- Change WizardStepper connector <li> to role=presentation
- Revert muted-foreground from 62% to 55% (original already passes
  contrast; footer was fixed separately via text-muted-foreground)

https://claude.ai/code/session_01JXajpFxhqLf8aPCncP81k3

* Fix lint error and update tests for WCAG role changes

- Replace el! non-null assertion with optional chaining in useFocusTrap
- Update AutodraftSettings tests to query role="radio" instead of
  role="button" (buttons have an explicit radio role since the WCAG pass)
- Update AvailableParticipantsSection watchlist tests to use
  getByRole/getAllByRole instead of getByTitle/getAllByTitle (watchlist
  buttons now use aria-label instead of title)

https://claude.ai/code/session_01JXajpFxhqLf8aPCncP81k3

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-17 20:11:38 -07:00

492 lines
16 KiB
TypeScript

import { useState, useEffect, useRef } from "react";
import { Check, Info, ChevronDown } from "lucide-react";
import { toast } from "sonner";
import { Label } from "~/components/ui/label";
import { Popover, PopoverContent, PopoverTrigger } from "~/components/ui/popover";
type AutodraftMode = "next_pick" | "while_on";
// 4 visible states map to isEnabled + mode + queueOnly:
// "off" → isEnabled: false
// "next_queue" → isEnabled: true, mode: "next_pick", queueOnly: true
// "all_queue" → isEnabled: true, mode: "while_on", queueOnly: true
// "all_picks" → isEnabled: true, mode: "while_on", queueOnly: false
type AutodraftState = "off" | "next_queue" | "all_queue" | "all_picks";
type OptionConfig = {
label: string;
desc: string;
isEnabled: boolean;
mode: AutodraftMode;
queueOnly: boolean;
};
// Record ensures all AutodraftState values are covered — no runtime find() needed
const OPTIONS: Record<AutodraftState, OptionConfig> = {
off: {
label: "Off",
desc: "You pick manually every round.",
isEnabled: false,
mode: "next_pick",
queueOnly: false,
},
next_queue: {
label: "Next in Queue",
desc: "Autodrafts your next pick from your queue, then turns off.",
isEnabled: true,
mode: "next_pick",
queueOnly: true,
},
all_queue: {
label: "All in Queue",
desc: "Keeps autodrafting from your queue until it runs out, then turns off automatically.",
isEnabled: true,
mode: "while_on",
queueOnly: true,
},
all_picks: {
label: "All Picks",
desc: "Keeps autodrafting all your picks. Uses your queue first, then falls back to the highest-ranked undrafted player.",
isEnabled: true,
mode: "while_on",
queueOnly: false,
},
};
const OPTION_ORDER: AutodraftState[] = ["off", "next_queue", "all_queue", "all_picks"];
// border-l-[3px] is applied to ALL options (transparent when inactive) so the
// content never shifts when the active border color is applied.
function getButtonClassName(state: AutodraftState, isActive: boolean): string {
if (!isActive) {
return "border-l-[3px] border-l-transparent text-muted-foreground hover:bg-muted/40";
}
if (state === "off") {
return "border-l-[3px] border-l-muted-foreground/50 text-foreground";
}
return "border-l-[3px] border-l-electric bg-electric text-background";
}
function getCheckClassName(state: AutodraftState): string {
if (state === "off") return "text-muted-foreground";
return "text-background";
}
function toAutodraftState(
isEnabled: boolean,
mode: AutodraftMode,
queueOnly: boolean
): AutodraftState {
if (!isEnabled) return "off";
if (mode === "next_pick") return "next_queue";
return queueOnly ? "all_queue" : "all_picks";
}
export function getAutodraftLabel(
isEnabled: boolean,
mode: AutodraftMode,
queueOnly: boolean
): string {
return OPTIONS[toAutodraftState(isEnabled, mode, queueOnly)].label;
}
interface CompactAutodraftBadgeProps {
isEnabled: boolean;
mode: AutodraftMode;
queueOnly: boolean;
showChevron?: boolean;
}
export function CompactAutodraftBadge({
isEnabled,
mode,
queueOnly,
showChevron = false,
}: CompactAutodraftBadgeProps) {
const state = toAutodraftState(isEnabled, mode, queueOnly);
const { label } = OPTIONS[state];
const isOff = state === "off";
return (
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">Autodraft:</span>
<span
className={`text-xs font-medium px-2 py-1 rounded flex items-center gap-1 ${
isOff
? "bg-muted text-muted-foreground border border-border"
: "bg-electric/20 text-electric border border-electric/30"
}`}
>
{label}
{showChevron && <ChevronDown className="h-3 w-3" />}
</span>
</div>
);
}
interface AutodraftBadgeWithPopoverProps {
seasonId: string;
teamId: string;
isEnabled: boolean;
mode: AutodraftMode;
queueOnly: boolean;
isMyTurn: boolean;
onUpdate: (isEnabled: boolean, mode: AutodraftMode, queueOnly: boolean) => void;
showOvernightNote?: boolean;
}
function AutodraftOptions({
seasonId,
teamId,
isEnabled,
mode,
queueOnly,
isMyTurn,
onUpdate,
}: Omit<AutodraftBadgeWithPopoverProps, "seasonId" | "teamId"> & {
seasonId: string;
teamId: string;
}) {
const [localState, setLocalState] = useState<AutodraftState>(
toAutodraftState(isEnabled, mode, queueOnly)
);
const abortRef = useRef<AbortController | null>(null);
useEffect(() => {
setLocalState(toAutodraftState(isEnabled, mode, queueOnly));
}, [isEnabled, mode, queueOnly]);
const sendUpdate = async (newState: AutodraftState) => {
abortRef.current?.abort();
abortRef.current = new AbortController();
const option = OPTIONS[newState];
try {
const formData = new FormData();
formData.append("seasonId", seasonId);
formData.append("teamId", teamId);
formData.append("isEnabled", option.isEnabled.toString());
formData.append("mode", option.mode);
formData.append("queueOnly", option.queueOnly.toString());
const response = await fetch("/api/autodraft/update", {
method: "POST",
body: formData,
signal: abortRef.current.signal,
});
if (response.ok) {
onUpdate(option.isEnabled, option.mode, option.queueOnly);
toast.success(
option.isEnabled ? `Autodraft set to "${option.label}"` : "Autodraft turned off"
);
} else {
setLocalState(toAutodraftState(isEnabled, mode, queueOnly));
toast.error("Failed to save autodraft settings");
}
} catch (error) {
if (error instanceof Error && error.name === "AbortError") return;
setLocalState(toAutodraftState(isEnabled, mode, queueOnly));
toast.error("Failed to save autodraft settings");
}
};
const handleStateChange = (newState: AutodraftState) => {
if (newState === localState || isMyTurn) return;
setLocalState(newState);
sendUpdate(newState);
};
const isDisabled = isMyTurn;
function handleGroupKeyDown(e: React.KeyboardEvent<HTMLDivElement>) {
if (isDisabled) return;
if (!["ArrowDown", "ArrowRight", "ArrowUp", "ArrowLeft"].includes(e.key)) return;
e.preventDefault();
const idx = OPTION_ORDER.indexOf(localState);
const next = e.key === "ArrowDown" || e.key === "ArrowRight"
? (idx + 1) % OPTION_ORDER.length
: (idx - 1 + OPTION_ORDER.length) % OPTION_ORDER.length;
const nextState = OPTION_ORDER[next];
handleStateChange(nextState);
e.currentTarget.querySelector<HTMLElement>(`[data-radio-value="${nextState}"]`)?.focus();
}
return (
<div
role="radiogroup"
aria-label="Autodraft setting"
onKeyDown={handleGroupKeyDown}
className="flex flex-col rounded-lg border overflow-hidden"
>
{OPTION_ORDER.map((state) => {
const { label } = OPTIONS[state];
const isActive = localState === state;
return (
<button
key={state}
type="button"
role="radio"
aria-checked={isActive}
tabIndex={isActive ? 0 : -1}
data-radio-value={state}
disabled={isDisabled}
onClick={() => handleStateChange(state)}
className={`w-full py-2.5 px-3 text-left transition-colors border-b last:border-b-0 flex items-center justify-between gap-2 ${getButtonClassName(state, isActive)} ${
isDisabled ? "opacity-50 cursor-not-allowed" : "cursor-pointer"
}`}
>
<span className="text-xs font-medium">{label}</span>
{isActive && (
<Check className={`h-3.5 w-3.5 shrink-0 ${getCheckClassName(state)}`} aria-hidden="true" />
)}
</button>
);
})}
{isMyTurn && (
<p className="text-xs text-muted-foreground mt-2 text-center px-3 py-2">
You're on the clock!
</p>
)}
</div>
);
}
export function AutodraftBadgeWithPopover({
seasonId,
teamId,
isEnabled,
mode,
queueOnly,
isMyTurn,
onUpdate,
showOvernightNote = false,
}: AutodraftBadgeWithPopoverProps) {
const [open, setOpen] = useState(false);
return (
<div className="flex items-center gap-2">
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<button
type="button"
className="hover:bg-muted/40 rounded px-2 py-1 -mx-2 -my-1 transition-colors"
>
<CompactAutodraftBadge
isEnabled={isEnabled}
mode={mode}
queueOnly={queueOnly}
showChevron
/>
</button>
</PopoverTrigger>
<PopoverContent className="w-72 p-0" align="end">
<AutodraftOptions
seasonId={seasonId}
teamId={teamId}
isEnabled={isEnabled}
mode={mode}
queueOnly={queueOnly}
isMyTurn={isMyTurn}
onUpdate={onUpdate}
/>
</PopoverContent>
</Popover>
<Popover>
<PopoverTrigger asChild>
<button
type="button"
className="text-muted-foreground hover:text-foreground transition-colors"
aria-label="Autodraft options explained"
>
<Info className="h-3.5 w-3.5" />
</button>
</PopoverTrigger>
<PopoverContent className="w-72" align="end">
<p className="text-sm font-semibold mb-2.5">Autodraft Options</p>
<div className="space-y-2.5">
{OPTION_ORDER.map((state) => {
const { label, desc } = OPTIONS[state];
return (
<div key={state}>
<p className="text-xs font-medium">{label}</p>
<p className="text-xs text-muted-foreground">{desc}</p>
</div>
);
})}
</div>
{showOvernightNote && (
<p className="text-xs text-muted-foreground mt-3 pt-3 border-t leading-relaxed">
Autodraft picks still fire during the overnight pause — the pause only freezes the timer if autodraft is off.
</p>
)}
</PopoverContent>
</Popover>
</div>
);
}
interface AutodraftSettingsProps {
seasonId: string;
teamId: string;
isEnabled: boolean;
mode: AutodraftMode;
queueOnly: boolean;
isMyTurn: boolean;
onUpdate: (isEnabled: boolean, mode: AutodraftMode, queueOnly: boolean) => void;
showOvernightNote?: boolean;
}
export function AutodraftSettings({
seasonId,
teamId,
isEnabled,
mode,
queueOnly,
isMyTurn,
onUpdate,
showOvernightNote,
}: AutodraftSettingsProps) {
const [localState, setLocalState] = useState<AutodraftState>(
toAutodraftState(isEnabled, mode, queueOnly)
);
// Holds the abort controller for any in-flight save so rapid selections
// cancel the previous request rather than racing to update the server.
const abortRef = useRef<AbortController | null>(null);
// Sync local state with props when they change (from socket events)
useEffect(() => {
setLocalState(toAutodraftState(isEnabled, mode, queueOnly));
}, [isEnabled, mode, queueOnly]);
const sendUpdate = async (newState: AutodraftState) => {
// Cancel any in-flight request before starting a new one
abortRef.current?.abort();
abortRef.current = new AbortController();
const option = OPTIONS[newState];
try {
const formData = new FormData();
formData.append("seasonId", seasonId);
formData.append("teamId", teamId);
formData.append("isEnabled", option.isEnabled.toString());
formData.append("mode", option.mode);
formData.append("queueOnly", option.queueOnly.toString());
const response = await fetch("/api/autodraft/update", {
method: "POST",
body: formData,
signal: abortRef.current.signal,
});
if (response.ok) {
onUpdate(option.isEnabled, option.mode, option.queueOnly);
toast.success(
option.isEnabled ? `Autodraft set to "${option.label}"` : "Autodraft turned off"
);
} else {
setLocalState(toAutodraftState(isEnabled, mode, queueOnly));
toast.error("Failed to save autodraft settings");
}
} catch (error) {
// Ignore cancellations — a newer selection has already taken over
if (error instanceof Error && error.name === "AbortError") return;
setLocalState(toAutodraftState(isEnabled, mode, queueOnly));
toast.error("Failed to save autodraft settings");
}
};
const handleStateChange = (newState: AutodraftState) => {
if (newState === localState || isMyTurn) return;
setLocalState(newState);
sendUpdate(newState);
};
const isDisabled = isMyTurn;
function handleGroupKeyDown(e: React.KeyboardEvent<HTMLDivElement>) {
if (isDisabled) return;
if (!["ArrowDown", "ArrowRight", "ArrowUp", "ArrowLeft"].includes(e.key)) return;
e.preventDefault();
const idx = OPTION_ORDER.indexOf(localState);
const next = e.key === "ArrowDown" || e.key === "ArrowRight"
? (idx + 1) % OPTION_ORDER.length
: (idx - 1 + OPTION_ORDER.length) % OPTION_ORDER.length;
const nextState = OPTION_ORDER[next];
handleStateChange(nextState);
e.currentTarget.querySelector<HTMLElement>(`[data-radio-value="${nextState}"]`)?.focus();
}
return (
<div className="border-t pt-4 mt-4">
{/* Header with info icon inline */}
<div className="flex items-center gap-1.5 mb-3">
<Label className="text-sm font-semibold">Autodraft</Label>
<Popover>
<PopoverTrigger asChild>
<button
type="button"
className="text-muted-foreground hover:text-foreground transition-colors"
aria-label="Autodraft options explained"
>
<Info className="h-3.5 w-3.5" />
</button>
</PopoverTrigger>
<PopoverContent className="w-72" align="start">
<p className="text-sm font-semibold mb-2.5">Autodraft Options</p>
<div className="space-y-2.5">
{OPTION_ORDER.map((state) => {
const { label, desc } = OPTIONS[state];
return (
<div key={state}>
<p className="text-xs font-medium">{label}</p>
<p className="text-xs text-muted-foreground">{desc}</p>
</div>
);
})}
</div>
</PopoverContent>
</Popover>
</div>
<div role="radiogroup" aria-label="Autodraft setting" onKeyDown={handleGroupKeyDown} className="flex flex-col rounded-lg border overflow-hidden">
{OPTION_ORDER.map((state) => {
const { label } = OPTIONS[state];
const isActive = localState === state;
return (
<button
key={state}
type="button"
role="radio"
aria-checked={isActive}
tabIndex={isActive ? 0 : -1}
data-radio-value={state}
disabled={isDisabled}
onClick={() => handleStateChange(state)}
className={`w-full py-2.5 px-3 text-left transition-colors border-b last:border-b-0 flex items-center justify-between gap-2 ${getButtonClassName(state, isActive)} ${
isDisabled ? "opacity-50 cursor-not-allowed" : "cursor-pointer"
}`}
>
<span className="text-xs font-medium">{label}</span>
{isActive && (
<Check className={`h-3.5 w-3.5 shrink-0 ${getCheckClassName(state)}`} aria-hidden="true" />
)}
</button>
);
})}
</div>
{isMyTurn && (
<p className="text-xs text-muted-foreground mt-2">You're on the clock!</p>
)}
{showOvernightNote && (
<p className="text-xs text-muted-foreground mt-3 leading-relaxed">
If overnight pause is enabled, autodraft picks still fire during your overnight window the pause only protects your timer if autodraft is off.
</p>
)}
</div>
);
}