Files
arr/web/src/ui.tsx
T
Miguel PalhasandClaude Opus 5.5 6c183c5d98 refactor(web): chips and type roles as utilities
A chip's look is read off the data attributes it already carries, in
the order the board always resolved them. Lamps stay in CSS: the glow
and the power-up are effects, not layout.

Refs #280

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-11 18:03:23 +00:00

773 lines
21 KiB
TypeScript

// The shared control and row vocabulary (Master Control, revision 2). Every
// list in the app is one row primitive with a fixed action column, and every
// button is one of five controls. A view that cannot fit them grows a variant
// here; it does not keep a private copy.
import {
type ComponentProps,
createContext,
type HTMLAttributes,
type KeyboardEvent,
type MouseEvent,
type ReactNode,
type Ref,
useCallback,
useContext,
useState,
} from "react";
import { Icon, type IconName, useArmed } from "./icons";
import { type ControlLook, chip, control, cx, toggle, toggleLamp, toggleState, type } from "./look";
export type Tone = "fault" | "warn";
export { cx } from "./look";
/** A boolean data attribute: present (empty) or absent. */
export function flag(on: boolean | undefined): "" | undefined {
return on ? "" : undefined;
}
/* ---- controls ------------------------------------------------------------ */
export interface ControlProps extends ComponentProps<"button"> {
/** The word on the plate. */
text: string;
/** Secondary actions: ink on a hairline, never a toggle. */
quiet?: boolean;
/** A leading glyph beside the word. */
glyph?: IconName;
/** Fixed width, so a label that changes (GRAB → SENDING → SENT) never moves the row. */
fixed?: boolean;
/** Full width, content at the start: a phone tray or a settings panel. */
fill?: boolean;
danger?: boolean;
state?: ControlLook["state"];
busy?: boolean;
done?: boolean;
failed?: boolean;
}
/** A word control: the primary action of a header or panel, or a quiet secondary one. */
export function Control({
text,
quiet,
glyph,
fixed,
fill,
danger,
state,
busy,
done,
failed,
className,
...rest
}: ControlProps) {
return (
<button
type="button"
className={cx(
control({
look: quiet ? "quiet" : "primary",
shape: fixed ? "fixed" : "word",
fill,
danger,
state,
}),
className,
)}
data-busy={flag(busy)}
data-done={flag(done)}
data-failed={flag(failed)}
{...rest}
>
{glyph && <Icon name={glyph} className={fill ? "mr-1" : undefined} />}
<span>{text}</span>
</button>
);
}
/** A 44px square glyph control. The label is the accessible name and nothing else. */
export function IconControl({
glyph,
label,
look,
shape = "icon",
className,
...rest
}: ComponentProps<"button"> & {
glyph: IconName;
label: string;
look?: ControlLook["look"];
shape?: "icon" | "chip";
}) {
return (
<button
type="button"
className={cx(control({ look, shape }), className)}
aria-label={label}
{...rest}
>
<Icon name={glyph} />
</button>
);
}
/** An external link wearing the icon control's skin. */
export function IconLink({
label,
href,
shape = "icon",
children,
}: {
label: string;
href: string;
shape?: "icon" | "trailer";
children: ReactNode;
}) {
return (
<a
className={control({ shape })}
href={href}
target="_blank"
rel="noreferrer"
aria-label={label}
>
{children}
</a>
);
}
/**
* A rule that is on or off: a lamp plus the word, never a border colour
* alone (the Word-Beside-The-Lamp rule). The state word has a fixed width,
* so flipping it never moves anything.
*/
export function LampToggle({
label,
pressed,
fill = false,
...rest
}: ComponentProps<"button"> & {
label: string;
pressed: boolean;
/** Full width, content at the start: a phone tray or a settings panel. */
fill?: boolean;
"data-focus-id"?: string;
}) {
return (
<button type="button" className={toggle(pressed, fill)} aria-pressed={pressed} {...rest}>
<span className={toggleLamp(pressed)} aria-hidden="true" />
<span>{label}</span>
<span className={toggleState(pressed)} aria-hidden="true">
{pressed ? "on" : "off"}
</span>
</button>
);
}
/**
* Show / hide at full control height. The verb swaps but the plate keeps
* one width, and the count is tabular, so opening never moves the head.
*/
export function Disclosure({
noun = "",
count,
open,
onToggle,
}: {
noun?: string;
count: number;
open: boolean;
onToggle: () => void;
}) {
return (
<button
type="button"
className={cx(control({ look: "quiet", shape: "disclose" }), "ml-auto")}
aria-expanded={open}
onClick={onToggle}
>
<span>{`${open ? "hide" : "show"} ${count}${noun === "" ? "" : ` ${noun}`}`}</span>
<Icon
name="chevronDown"
className={cx(
"[transition:transform_200ms_var(--ease-out)]",
open && "[transform:rotate(180deg)]",
)}
/>
</button>
);
}
/**
* The arm-then-confirm as a labelled control, for the ⋯ tray where a phone
* spells the action out. Full width there, so the armed label can be longer.
*/
export function ArmedDeleteWord({
label,
execute,
}: {
label: string;
execute: () => Promise<boolean | undefined> | undefined;
}) {
const { armed, spent, click, disarm } = useArmed(execute);
return (
<Control
text={armed ? `tap again to ${label}` : label}
glyph={armed ? "check" : "trash"}
quiet
fill
danger
state={armed ? "armed" : null}
data-kind="delete"
data-armed={armed ? "true" : undefined}
disabled={spent}
onClick={click}
onBlur={() => {
if (armed) {
disarm();
}
}}
/>
);
}
/* ---- status -------------------------------------------------------------- */
export interface Status {
text: string;
tone?: Tone;
busy?: boolean;
/** A way out carried by the sentence itself (a quiet control after it). */
action?: { label: string; run: () => void };
}
/**
* A status slot. The slot is always laid out — an empty one keeps its line —
* so a message arriving or leaving never pushes the content below it.
*/
const SLOT = {
// a page bar's one line, ellipsised: a message never pushes the page down
head: "flex-1 min-w-0 m-0 overflow-hidden whitespace-nowrap text-ellipsis",
// a section's line: reserved, and wraps only when the sentence must
deck: "flex items-center flex-wrap gap-y-2 gap-x-3 min-h-chip-h mb-3",
} as const;
export function StatusSlot({
status,
variant,
}: {
status: Status | null;
variant: keyof typeof SLOT;
}) {
return (
<p
className={cx(
"readout text-xs text-ink-muted data-[tone=fault]:text-signal-fault",
SLOT[variant],
)}
role="status"
data-empty={String(status === null)}
data-tone={status?.tone}
data-action={flag(status?.action !== undefined)}
>
{status?.busy && (
<span className="lamp inline-block mr-2" data-state="probing" aria-hidden="true" />
)}
{status?.text ?? ""}
{status?.action && <Control text={status.action.label} quiet onClick={status.action.run} />}
</p>
);
}
/** A status setter for one slot, with the same signature everywhere. */
export function useStatus(): [
Status | null,
(text: string | null, tone?: Tone, busy?: boolean) => void,
] {
const [status, setStatus] = useState<Status | null>(null);
const set = useCallback((text: string | null, tone?: Tone, busy = false) => {
setStatus(text === null ? null : { text, tone, busy });
}, []);
return [status, set];
}
/* ---- the row's note ---------------------------------------------------------- */
export interface Note {
text: string;
tone?: Tone;
}
export type Say = (text: string | null, tone?: Tone) => void;
/** The row's status slot, in the tray. Null clears it. */
export function useNote(): [Note | null, Say] {
const [note, setNote] = useState<Note | null>(null);
const say = useCallback<Say>((text, tone) => {
setNote(text === null ? null : { text, tone });
}, []);
return [note, say];
}
/** A note line outside a row, written the way a row's own slot is. */
export function NoteLine({ note, className }: { note: Note | null; className: string }) {
return (
<p className={className} role="status" hidden={note === null} data-tone={note?.tone}>
{note?.text ?? ""}
</p>
);
}
/* ---- chips ------------------------------------------------------------------- */
export interface Explain {
text: string;
say: Say;
tone?: Tone;
}
/**
* A chip whose meaning would otherwise live in a tooltip. Touch has no hover,
* so the chip becomes a button that writes its sentence into the row's own
* status slot, and a second tap takes it away.
*/
function useExplain(explain: Explain | undefined) {
const [open, setOpen] = useState(false);
if (!explain) {
return {};
}
const toggle = (event: MouseEvent | KeyboardEvent) => {
event.stopPropagation();
event.preventDefault();
const next = !open;
setOpen(next);
explain.say(next ? explain.text : null, explain.tone);
};
return {
role: "button",
tabIndex: 0,
"data-explain": "",
"aria-expanded": open,
onClick: toggle,
onKeyDown: (event: KeyboardEvent) => {
if (event.key === "Enter" || event.key === " ") {
toggle(event);
}
},
};
}
export interface ChipProps extends HTMLAttributes<HTMLSpanElement> {
/** The whole label is a glyph. */
glyph?: boolean;
/** A live download's chip. */
download?: boolean;
explain?: Explain;
[data: `data-${string}`]: string | undefined;
}
/** A chip, the §9.3 column unit. Its look is read off its own data attributes. */
export function Chip({ glyph, download, className, explain, children, ...rest }: ChipProps) {
const explainProps = useExplain(explain);
return (
<span
className={cx(
chip({
verdict: rest["data-verdict"],
blacklist: rest["data-blacklist"],
movieState: rest["data-movie-state"],
wanted: rest["data-wanted"],
dlPhase: rest["data-dl-phase"],
status: rest["data-status"],
counts: rest["data-counts"],
flag: rest["data-flag"],
mt: rest["data-mt"],
tone: rest["data-tone"],
secondary: rest["data-pri"] === "2",
interactive: explain !== undefined || rest.role === "button",
explain: explain !== undefined,
glyph,
download,
cell: rest["data-cell"] !== undefined,
}),
className,
)}
{...rest}
{...explainProps}
>
{children}
</span>
);
}
/* ---- the row --------------------------------------------------------------- */
/** One cell in a row's action column. An empty cell still takes its width. */
export interface ActionSlot {
node: ReactNode | null;
/** The width class: a glyph square, a lamp toggle, or a fixed word control. */
width: "icon" | "toggle" | "word";
/** Shown from 40rem up; on a phone this action lives in the ⋯ tray instead. */
wide?: boolean;
/** Shown below 40rem only — an empty cell that keeps a phone column aligned. */
narrow?: boolean;
/** A word or toggle control fills its column; an input keeps its own width. */
fill?: boolean;
}
export interface RowProps {
/** `data-row`: which kind of row, for the few rules that differ by kind. */
kind: string;
lead?: ReactNode;
title?: ReactNode;
titleClassName?: string;
/** The chip line. */
meta?: ReactNode;
sub?: ReactNode;
/** The sub line opens to its full string on a tap. */
subExpands?: boolean;
/** Body content between the chip line and the sub line. */
beforeSub?: ReactNode;
/** Body content after the sub line. */
afterSub?: ReactNode;
bodyClassName?: string;
onBodyClick?: (event: MouseEvent<HTMLDivElement>) => void;
actions?: ActionSlot[];
/** The phone tray: labelled, full-width versions of the wide-only actions. */
more?: ReactNode;
/** The whole row opens something: a stretched button under the controls. */
open?: {
label: string;
run: (origin: HTMLElement) => void;
chevron?: boolean;
className?: string;
expanded?: boolean;
disabled?: boolean;
};
note?: Note | null;
/** Full-width area under the line: inline panels after the note. */
tray?: ReactNode;
}
/** A sub line that opens to its full string on a tap. */
export function Expandable({ className, children }: { className: string; children: ReactNode }) {
const [full, setFull] = useState(false);
return (
// biome-ignore lint/a11y/noStaticElementInteractions: a reading aid, the text is already all there for a screen reader
// biome-ignore lint/a11y/useKeyWithClickEvents: same
<div className={className} data-full={flag(full)} onClick={() => setFull(!full)}>
{children}
</div>
);
}
/**
* The one row: `lead | body | actions`, plus a full-width tray. The body is
* `minmax(0, 1fr)`, so a long title or a run of chips is clipped inside it
* and can never push the actions onto a second line.
*/
export function Row(props: RowProps) {
const [moreOpen, setMoreOpen] = useState(false);
const { open, actions = [] } = props;
return (
<li className="r" data-row={props.kind} data-nolead={flag(!props.lead)}>
{open && (
<button
type="button"
className={cx("r-link", open.className)}
aria-label={open.label}
aria-expanded={open.expanded}
aria-disabled={open.disabled ? "true" : undefined}
onClick={(event) => open.run(event.currentTarget)}
/>
)}
{props.lead && <div className="r-lead">{props.lead}</div>}
{/* biome-ignore lint/a11y/noStaticElementInteractions: the season name expands it too — the chevron stays the accessible control */}
{/* biome-ignore lint/a11y/useKeyWithClickEvents: same */}
<div className={cx("r-body", props.bodyClassName)} onClick={props.onBodyClick}>
{props.title !== undefined && props.title !== null && (
<div className={cx("r-title", props.titleClassName)}>{props.title}</div>
)}
<div className="r-meta">{props.meta}</div>
{props.beforeSub}
{props.sub !== undefined &&
props.sub !== null &&
(props.subExpands ? (
<Expandable className="r-sub readout">{props.sub}</Expandable>
) : (
<div className="r-sub readout">{props.sub}</div>
))}
{props.afterSub}
</div>
<div className="r-act">
{actions.map((slot, index) => (
<span
// the column is positional: a slot is its index
// biome-ignore lint/suspicious/noArrayIndexKey: see above
key={index}
// a word or a toggle fills its column, so every row's plates line up
className={cx("r-slot", slot.width !== "icon" && slot.fill !== false && "*:w-full")}
data-width={slot.width}
data-wide={flag(slot.wide)}
data-narrow={flag(slot.narrow)}
>
{slot.node}
</span>
))}
{props.more && (
<span className="r-slot" data-width="icon" data-narrow="">
<IconControl
glyph="more"
label="more actions"
aria-expanded={moreOpen}
onClick={() => setMoreOpen(!moreOpen)}
/>
</span>
)}
{open && open.chevron !== false && actions.length === 0 && (
<span className="r-slot r-chevron" data-width="icon" aria-hidden="true">
<Icon name="chevronRight" />
</span>
)}
</div>
<div className="r-tray">
<NoteLine note={props.note ?? null} className="r-note readout" />
{props.more && (
<div className="r-morepanel" hidden={!moreOpen}>
{props.more}
</div>
)}
{props.tray}
</div>
</li>
);
}
/** A row-shaped placeholder: same height and columns as the row it stands for. */
export function SkeletonRows({ count, withLead = true }: { count: number; withLead?: boolean }) {
return Array.from({ length: count }, (_, index) => (
// biome-ignore lint/suspicious/noArrayIndexKey: placeholders have no identity
<li key={index} className="r r-skel" aria-hidden="true" data-nolead={flag(!withLead)}>
{withLead && (
<div className="r-lead">
<span className="skel skel-lead" />
</div>
)}
<div className="r-body">
<span className="skel skel-line" />
<span className="skel skel-line skel-short" />
</div>
<div className="r-act" />
</li>
));
}
/** A list's one-line empty or error state, at row height. */
export function EmptyRow({
text,
tone,
children,
}: {
text: string;
tone?: "fault";
children?: ReactNode;
}) {
return (
<li className="r-empty readout" data-tone={tone}>
{text}
{children}
</li>
);
}
/* ---- page skeleton ------------------------------------------------------- */
/**
* A page: the one centred column, and a container, so a row answers to the
* page's width rather than the window's. The gutter belongs to the content;
* a child marked `data-bleed` (the detail hero) reaches both edges.
*/
export function Deck({
label,
detail = false,
hidden,
id,
ref,
onKeyDown,
children,
}: {
label: string;
/** A detail page opens on its hero, so the page drops its top padding. */
detail?: boolean;
hidden?: boolean;
id?: string;
ref?: Ref<HTMLElement>;
onKeyDown?: (event: KeyboardEvent<HTMLElement>) => void;
children: ReactNode;
}) {
return (
<main
className={cx(
"@container w-full max-w-deck mx-auto pb-12 flex-1 *:not-data-bleed:mx-gutter",
detail ? "pt-0" : "pt-4",
)}
aria-label={label}
hidden={hidden}
id={id}
ref={ref}
onKeyDown={onKeyDown}
>
{children}
</main>
);
}
/** A page's line: title, count, a one-line status slot, the page's controls. */
export function PageBar({
title,
count,
status,
children,
}: {
title: string;
/** Absent leaves the count's slot out entirely. */
count?: string;
status: Status | null;
children?: ReactNode;
}) {
return (
<header className="flex items-center gap-3 min-h-control-h mb-4">
<h2 className={cx(type.pageTitle, "capitalize")}>{title}</h2>
{count !== undefined && <span className={cx(type.count, "flex-none")}>{count}</span>}
<StatusSlot status={status} variant="head" />
{children}
</header>
);
}
/** Whether a section sits inside another: its head is then a quieter group label. */
const Nested = createContext(false);
const InnerSection = createContext(false);
/** A section of a page; `spacing` replaces the default gap after it. */
export function Section({
spacing = "mb-8",
hidden,
labelledBy,
ref,
className,
children,
}: {
spacing?: string;
hidden?: boolean;
labelledBy?: string;
ref?: Ref<HTMLElement>;
/** A marker other rules still key on, such as `subs-lane`. */
className?: string;
children: ReactNode;
}) {
const outer = useContext(Nested);
return (
<section
className={cx(spacing, className)}
hidden={hidden}
aria-labelledby={labelledBy}
ref={ref}
>
<InnerSection.Provider value={outer}>
<Nested.Provider value={true}>{children}</Nested.Provider>
</InnerSection.Provider>
</section>
);
}
/** A section head: the engraved label, a count, then whatever acts on it. */
export function DeckHead({
label,
labelId,
as: Heading = "h3",
titled = "label",
count,
children,
}: {
label: string;
labelId?: string;
as?: "h3" | "h4";
/** A page's section title, or a group's engraved label. */
titled?: "section" | "label";
count?: string | number | null;
children?: ReactNode;
}) {
// nested heads inside a section are group labels, one step quieter
const nested = useContext(InnerSection);
return (
<header
className={cx(
"flex items-center gap-3 pb-1 border-b border-b-line",
nested ? "min-h-chip-h pt-3" : "min-h-control-h",
)}
>
<Heading
className={titled === "section" ? type.sectionTitle : cx(type.label, "text-ink-muted")}
id={labelId}
>
{label}
</Heading>
{count !== undefined && <span className={type.count}>{count ?? ""}</span>}
{children}
</header>
);
}
/** A list of rows, or of poster cards. */
export function Rows({
grid = false,
className,
hidden,
children,
}: {
grid?: boolean;
/** A marker other rules still key on, such as `seasons`. */
className?: string;
hidden?: boolean;
children?: ReactNode;
}) {
return (
<ul
className={cx("m-0 list-none", grid ? "grid-rows px-0 pb-0" : "p-0", className)}
aria-hidden={hidden}
>
{children}
</ul>
);
}
/** A group's one plain sentence, which opens to the long form on a tap. */
export function GroupNote({ short, more }: { short: string; more?: string }) {
const [open, setOpen] = useState(false);
return (
<div
className="flex flex-wrap items-center gap-y-1 gap-x-2 pt-2 text-sm text-ink-muted"
data-explain-group={more === undefined ? undefined : ""}
>
<p className="m-0">{short}</p>
{more !== undefined && (
<>
<IconControl
glyph="info"
label="more about this list"
aria-expanded={open}
onClick={() => setOpen(!open)}
look="faint"
shape="chip"
/>
<p className="m-0 basis-full max-w-measure text-xs" hidden={!open}>
{more}
</p>
</>
)}
</div>
);
}