import { useCallback, useEffect, useRef, useState, type KeyboardEvent } from "react"; import { readStoredView, writeStoredView, type ViewOption } from "@/lib/responsibility-views"; import { cn } from "@/lib/utils"; /** * The view a page shows, remembered per page in local storage. Starts from * the stored choice (or `fallback`, else the first option) and works without storage. * `requested` (a view a link asked for, such as `?view=`) wins and is remembered. */ export function useStoredView( key: string, options: readonly ViewOption[], fallback?: T, requested?: T | null, ): [T, (view: T) => void] { const [view, setView] = useState(() => requested ?? readStoredView(key, options, fallback)); const choose = useCallback((next: T) => { setView(next); writeStoredView(key, next); }, [key]); useEffect(() => { if (requested) choose(requested); }, [requested, choose]); return [view, choose]; } /** * A small segmented switch between a page's views: one radio group, arrow * keys move the choice, and only the chosen option is in the tab order. */ export function ViewSwitcher({ label, options, value, onChange, className, }: { label: string; options: readonly ViewOption[]; value: T; onChange: (value: T) => void; className?: string; }) { const buttons = useRef<(HTMLButtonElement | null)[]>([]); const select = (index: number) => { const wrapped = (index + options.length) % options.length; onChange(options[wrapped]!.value); buttons.current[wrapped]?.focus(); }; const onKeyDown = (event: KeyboardEvent, index: number) => { const next = event.key === "ArrowRight" || event.key === "ArrowDown" ? index + 1 : event.key === "ArrowLeft" || event.key === "ArrowUp" ? index - 1 : event.key === "Home" ? 0 : event.key === "End" ? options.length - 1 : null; if (next === null) return; event.preventDefault(); select(next); }; return (
{options.map((option, index) => { const checked = option.value === value; return ( ); })}
); }