strata-react 1.0.3 → 1.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/UPGRADING.md +1 -0
- package/dist/components/compare.d.ts +42 -0
- package/dist/components/fullscreen-frame.d.ts +16 -0
- package/dist/components/viewport.d.ts +41 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +579 -18
- package/dist/index.js.map +1 -1
- package/dist/lib/viewport.d.ts +29 -0
- package/dist/{query-gC6I6Cen.js → query-CXlmWmrY.js} +4 -4
- package/dist/query-CXlmWmrY.js.map +1 -0
- package/dist/strata.css +8 -0
- package/dist/testing.js +1 -1
- package/package.json +3 -2
- package/dist/query-gC6I6Cen.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["AriaButton","_Fragment","AriaPopover","AriaMenu","AriaDialog","AriaInput","AriaToolbar","sizes","_Fragment","AriaToggleButton","AriaSwitch","AriaDialog","_Fragment","AriaPopover","Dialog","AriaCheckbox","_Fragment","_Fragment","tones","_Fragment","_Fragment","AriaNumberField","AriaInput","AriaSlider","_Fragment","ToastQueue","ToastRegion","AriaToast","ToastContent","AriaButton","_Fragment","defaultFormat","format","AriaCheckbox","_Fragment","AriaTabs","_Fragment"],"sources":["../src/lib/format.ts","../src/lib/in-view.ts","../src/components/button.tsx","../src/lib/overlay.ts","../src/lib/chords.ts","../src/components/hotkeys.tsx","../src/components/commands.tsx","../src/components/toolbar.tsx","../src/components/toggle.tsx","../src/components/switch.tsx","../src/components/dialog.tsx","../src/components/popover.tsx","../src/components/checkbox.tsx","../src/components/async-button.tsx","../src/components/status.tsx","../src/components/metric.tsx","../src/components/meter.tsx","../src/components/composition.tsx","../src/components/link-card.tsx","../src/components/data-view.tsx","../src/lib/number-input.ts","../src/components/value-controls.tsx","../src/components/alert.tsx","../src/components/toast.tsx","../src/lib/client-work.ts","../src/components/job-status.tsx","../src/components/thumbnail.tsx","../src/components/disclosure.tsx","../src/components/selection.tsx","../src/components/data-table.tsx","../src/components/selectable-grid.tsx","../src/components/virtual-list.tsx","../src/components/infinite-list.tsx","../src/components/line-chart.tsx","../src/components/page-header.tsx","../src/components/undo.tsx","../src/components/done.tsx","../src/components/app-shell.tsx","../src/components/tabs.tsx","../src/components/active-list.tsx","../src/query/infinite.ts","../src/query/job.ts"],"sourcesContent":["// Every number and date on screen goes through Intl, once, here. Units are joined with a\n// non-breaking space so \"212 °C\" never wraps between figure and unit. A product that is not\n// en-GB calls createFormat with its locale once and exports the result from its own lib.\n//\n// The number formatters are callable (`format.integer(n)`) because that is the form people reach\n// for (strata-react issue #12), and they keep Intl's methods (`format.integer.format(n)`,\n// `formatToParts`, `resolvedOptions`) so existing calls and Intl knowledge still work.\n//\n// Dates follow the same shape. Every date formatter is callable with a Date, an ISO string or\n// epoch milliseconds (`format.dateTime(row.at)`), because rows arrive from an API as ISO strings\n// and an app that has to wrap each one in `new Date(...)` soon builds its own Intl.DateTimeFormat\n// beside it instead (strata-react issue #31, from the Bright Horizons History screen). An invalid\n// date throws a RangeError naming the input rather than printing \"Invalid Date\" into a row.\n// `date` and `dateTime` use Intl's medium/short styles, so the locale decides the order\n// (\"8 Nov 2026, 06:05\" in en-GB, \"Nov 8, 2026, 6:05 AM\" in en-US) and nobody hand-writes a\n// pattern. `timeZone` is optional: left out, times are the viewer's; a product that shows a place's\n// times (a kiln in one room, a shop's opening hours) passes that place's zone once.\n//\n// Tests: the non-breaking space is a real character in the DOM. Testing Library's text matchers\n// (`getByText`, `toHaveTextContent`) collapse whitespace and match \"6 pieces\", but accessible-name\n// matching (`getByRole(\"heading\", { name: \"6 pieces\" })`) compares the name exactly and does not.\n// Build the expected string with the same formatter (`{ name: format.count(6, \"piece\") }`), or\n// use a regex with `\\s` (`/6\\spieces/`), which matches U+00A0.\n//\n// A value that is not known (`null` or `undefined`: a count the source does not give, a date for\n// something never synced) prints as the placeholder, an en dash unless `createFormat`'s `missing`\n// says otherwise, from every number and date formatter (strata-react issue #47). Each screen used\n// to pick its own (\"–\", \"Never\", blank), so tables and cards disagreed. An invalid date still\n// throws: that is a bug, not a missing value.\n//\n// Three formatters came from the Tubes viewer, which wrote its own (strata-react issue #52): `ago`\n// (\"3 weeks ago\", from Intl.RelativeTimeFormat, with `now` passed in by tests), `compact` (\"1.2k\"\n// in en-GB, and `count`'s `{ compact: true }` for \"1.2k views\") and `runningTime` (\"4:05\", \"1:02:09\"), the\n// m:ss of a media player, which Intl.DurationFormat's long form is not. `share` is `percent` for a\n// part of a whole (strata-react issue #43): a part that is there never prints as \"0%\", nor a part\n// short of the whole as \"100%\".\n\nexport const NBSP = \" \";\n\n/** The placeholder printed for a value that is not known: an en dash. */\nexport const MISSING = \"–\";\n\n/** The decimal byte units `format.bytes` writes. */\nexport type ByteUnit = \"B\" | \"kB\" | \"MB\" | \"GB\" | \"TB\" | \"PB\";\nconst BYTE_UNITS: readonly ByteUnit[] = [\"B\", \"kB\", \"MB\", \"GB\", \"TB\", \"PB\"];\nconst BYTE_SIZE = Object.fromEntries(BYTE_UNITS.map((u, i) => [u, 1000 ** i])) as Record<ByteUnit, number>;\n\n/** An `Intl.NumberFormat` that can also be called directly: `f(n)` is `f.format(n)`. `null` or `undefined` prints the placeholder. */\nexport type NumberFormatter = ((value: number | bigint | Intl.StringNumericLiteral | null | undefined) => string) & {\n format: (value: number | bigint | Intl.StringNumericLiteral | null | undefined) => string;\n} & Pick<Intl.NumberFormat, \"formatToParts\" | \"resolvedOptions\">;\n\n/** What a date formatter accepts: a Date, an ISO 8601 string, or epoch milliseconds. */\nexport type DateInput = Date | string | number;\n\n/** An `Intl.DateTimeFormat` that can also be called directly, with a Date, an ISO string or epoch milliseconds. */\nexport type DateFormatter = ((value: DateInput | null | undefined) => string) & {\n format: (value: DateInput | null | undefined) => string;\n formatToParts: (value: DateInput) => Intl.DateTimeFormatPart[];\n formatRange: (start: DateInput, end: DateInput) => string;\n} & Pick<Intl.DateTimeFormat, \"resolvedOptions\">;\n\n/** Options shared by every date formatter one `createFormat` call makes. */\nexport interface FormatOptions {\n /** An IANA zone (\"Europe/London\", \"UTC\") to show times in. Left out, times are the viewer's own. */\n timeZone?: string;\n /** What a missing value (`null`, `undefined`) prints as. Default an en dash (`MISSING`). */\n missing?: string;\n}\n\n/** Options for `format.count`. */\nexport interface CountOptions {\n /** Write the figure compactly: \"1.2k views\". The noun still agrees with the exact count. */\n compact?: boolean;\n}\n\n/** A Date from a Date, an ISO string or epoch milliseconds; throws a RangeError naming the input when it is not a date. */\nexport function toDate(value: DateInput): Date {\n const date = value instanceof Date ? value : new Date(value);\n if (Number.isNaN(date.getTime())) throw new RangeError(`Not a date: ${JSON.stringify(String(value))}`);\n return date;\n}\n\nfunction callableDate(df: Intl.DateTimeFormat, missing: string): DateFormatter {\n const format = (value: DateInput | null | undefined) => (value == null ? missing : df.format(toDate(value)));\n return Object.assign(format, {\n format,\n formatToParts: (value: DateInput) => df.formatToParts(toDate(value)),\n formatRange: (start: DateInput, end: DateInput) => df.formatRange(toDate(start), toDate(end)),\n resolvedOptions: () => df.resolvedOptions(),\n });\n}\n\nfunction callable(nf: Intl.NumberFormat, missing: string): NumberFormatter {\n const format = (value: number | bigint | Intl.StringNumericLiteral | null | undefined) => (value == null ? missing : nf.format(value));\n return Object.assign(format, {\n format,\n formatToParts: (value: number | bigint) => nf.formatToParts(value),\n resolvedOptions: () => nf.resolvedOptions(),\n });\n}\n\n// Largest first: `ago` says a span in the largest unit it fills at least once, rounded down, so\n// 13 days is \"last week\" and 20 days \"2 weeks ago\", never \"3 weeks\" too early.\nconst DAY = 86_400_000;\nconst AGO_STEPS: readonly [Intl.RelativeTimeFormatUnit, number][] = [\n [\"year\", 365 * DAY],\n [\"month\", 30 * DAY],\n [\"week\", 7 * DAY],\n [\"day\", DAY],\n [\"hour\", 3_600_000],\n [\"minute\", 60_000],\n];\n\n/** Intl formatters for one locale (and optionally one time zone): integers, decimals, percent, dates, times, units with a non-breaking space, byte sizes, and counted nouns. */\nexport function createFormat(locale: string, options: FormatOptions = {}) {\n const { timeZone, missing = MISSING } = options;\n const dates = (opts: Intl.DateTimeFormatOptions) => callableDate(new Intl.DateTimeFormat(locale, { ...opts, timeZone }), missing);\n const integer = callable(new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }), missing);\n const decimal = callable(new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }), missing);\n const percent = callable(new Intl.NumberFormat(locale, { style: \"percent\", maximumFractionDigits: 0 }), missing);\n const compact = callable(new Intl.NumberFormat(locale, { notation: \"compact\", maximumFractionDigits: 1 }), missing);\n const relative = new Intl.RelativeTimeFormat(locale, { numeric: \"auto\" });\n const plurals = new Intl.PluralRules(locale);\n const clock = dates({ hour: \"2-digit\", minute: \"2-digit\" });\n const day = dates({ weekday: \"long\", day: \"numeric\", month: \"long\" });\n const shortDay = dates({ weekday: \"short\", hour: \"2-digit\", minute: \"2-digit\" });\n const date = dates({ dateStyle: \"medium\" });\n const dateTime = dates({ dateStyle: \"medium\", timeStyle: \"short\" });\n const withUnit = (value: number, unit: string, fmt: Pick<Intl.NumberFormat, \"format\"> = integer) =>\n `${fmt.format(value)}${NBSP}${unit}`;\n return {\n locale,\n /** The zone times are shown in, or `undefined` for the viewer's own. */\n timeZone,\n /** Whole numbers with grouping: `format.integer(1222)` is \"1,222\". */\n integer,\n /** One decimal place at most: `format.decimal(3.14)` is \"3.1\". */\n decimal,\n /** A ratio as a whole percent: `format.percent(0.42)` is \"42%\". */\n percent,\n /**\n * A part's share of a whole, as `percent` but never misleading at the ends: a part above 0 that\n * rounds to 0 is \"<1%\", and one short of the whole that rounds to 100 is \">99%\".\n * `format.share(2.4 / 512)` is \"<1%\".\n */\n share: (value: number | null | undefined) => {\n if (value == null || Number.isNaN(value)) return missing;\n if (value > 0 && value < 0.005) return `<${percent.format(0.01)}`;\n if (value >= 0.995 && value < 1) return `>${percent.format(0.99)}`;\n return percent.format(value);\n },\n /** A figure in short form for counts that run to thousands: `format.compact(1234)` is \"1.2k\" in en-GB, \"1.2K\" in en-US. */\n compact,\n /**\n * How long ago (or how far ahead) a time is, in the largest unit it reaches:\n * \"3 weeks ago\", \"yesterday\", \"in 2 hours\", \"now\" under a minute. Pass `now` in tests.\n */\n ago: (value: DateInput | null | undefined, now: DateInput = new Date()) => {\n if (value == null) return missing;\n const diff = toDate(value).getTime() - toDate(now).getTime();\n const span = Math.abs(diff);\n for (const [unit, size] of AGO_STEPS) {\n if (span >= size) return relative.format(Math.sign(diff) * Math.floor(span / size), unit);\n }\n return relative.format(0, \"second\");\n },\n /**\n * A media running time from seconds, as a player shows it: \"4:05\", \"1:02:09\". Unknown\n * (null, negative, not finite) prints the placeholder. Set it in `tabular-nums`.\n */\n runningTime: (seconds: number | null | undefined) => {\n if (seconds == null || !Number.isFinite(seconds) || seconds < 0) return missing;\n const s = Math.floor(seconds);\n const two = (n: number) => String(n).padStart(2, \"0\");\n const [h, m] = [Math.floor(s / 3600), Math.floor((s % 3600) / 60)];\n return h > 0 ? `${h}:${two(m)}:${two(s % 60)}` : `${m}:${two(s % 60)}`;\n },\n /** What a missing value prints as: an en dash unless `createFormat`'s `missing` says otherwise. */\n missing,\n /** A time of day: `format.clock(at)` is \"06:05\". */\n clock,\n /** A day without its year, for this week's things: `format.day(at)` is \"Sunday 8 November\". */\n day,\n /** A weekday and time, for chart axes and recent rows: `format.shortDay(at)` is \"Sun 06:05\". */\n shortDay,\n /** A date with its year, for a record or a deadline: `format.date(at)` is \"8 Nov 2026\". */\n date,\n /** A date and time, for a log or history row: `format.dateTime(at)` is \"8 Nov 2026, 06:05\". */\n dateTime,\n /** A figure and its unit joined by a non-breaking space (`NBSP`), so they never wrap apart. */\n withUnit,\n /** A temperature in °C, joined by a non-breaking space. */\n celsius: (value: number) => withUnit(value, \"°C\"),\n /**\n * A size in bytes in the largest decimal unit it reaches (kB, MB, GB, TB, as disks and\n * networks are sold): one decimal below 10 (\"5.2 GB\"), whole above (\"431 GB\"). Pass `unit`\n * to fix the unit, so figures compared side by side (\"431 of 466 GB\") share one.\n */\n bytes: (value: number, unit?: ByteUnit) => {\n const chosen = unit ?? [...BYTE_UNITS].reverse().find((u) => Math.abs(value) >= BYTE_SIZE[u]) ?? \"B\";\n const scaled = value / BYTE_SIZE[chosen];\n return withUnit(scaled, chosen, Math.abs(scaled) < 10 && chosen !== \"B\" ? decimal : integer);\n },\n /** The unit `bytes` would choose for a value, to share it across a set of figures. */\n byteUnit: (value: number): ByteUnit => [...BYTE_UNITS].reverse().find((u) => Math.abs(value) >= BYTE_SIZE[u]) ?? \"B\",\n /**\n * \"1 piece\", \"6 pieces\": the count and its noun, so copy never reads \"1 pieces\". They are\n * joined by a non-breaking space (`NBSP`), not a plain one: in a test, match with the same\n * call or a `\\s` regex, not a typed \"6 pieces\" string in a role's `name`.\n */\n count: (value: number | null | undefined, one: string, many = `${one}s`, { compact: short = false }: CountOptions = {}) =>\n value == null\n ? missing\n : `${(short ? compact : integer).format(value)}${NBSP}${plurals.select(value) === \"one\" ? one : many}`,\n };\n}\n\nexport type Format = ReturnType<typeof createFormat>;\n\n/** The en-GB formatters. */\nexport const format = createFormat(\"en-GB\");\n","import * as React from \"react\";\n\n// One IntersectionObserver hook for everything that waits until it is near the screen: the\n// sentinel at the end of an InfiniteList and an image in a Thumbnail. Both watch from the nearest\n// `[data-strata-scroll]` region (a VirtualList's) or else the viewport, with a root\n// margin so the work starts before the element is reached. They differ in two ways, which are\n// options rather than two hooks:\n//\n// - `once`: an image, once asked for, stays asked for; scrolling it away again must not unload it.\n// A sentinel reports in and out of view every time.\n// - `unsupported`: where there is no IntersectionObserver (an old browser, a test without the\n// fake), an image loads at once, because a photo that never loads is worse than one loaded\n// early. A sentinel reports out of view, because InfiniteList's Show more button is the path\n// that always works.\n\n/** Options for {@link useInView}. */\nexport type InViewOptions = {\n /** Watch only while this is true. Default true. */\n active?: boolean;\n /** How far outside the scroll region still counts as in view (IntersectionObserver `rootMargin`). */\n rootMargin?: string;\n /** Stay in view after the first time, and stop watching. */\n once?: boolean;\n /** What to report where `IntersectionObserver` does not exist. Default false. */\n unsupported?: boolean;\n};\n\n/**\n * Whether an element is within `rootMargin` of its scroll region (the nearest\n * `[data-strata-scroll]` ancestor, else the viewport). Returns a callback ref, so it follows the\n * element as it mounts and unmounts.\n */\nexport function useInView({ active = true, rootMargin = \"0px\", once = false, unsupported = false }: InViewOptions = {}) {\n const [inView, setInView] = React.useState(false);\n const [el, setEl] = React.useState<Element | null>(null);\n const seen = once && inView;\n React.useEffect(() => {\n if (seen) return;\n if (!active || !el) {\n setInView(false);\n return;\n }\n if (typeof IntersectionObserver === \"undefined\") {\n setInView(unsupported);\n return;\n }\n const root = el.parentElement?.closest<HTMLElement>(\"[data-strata-scroll]\") ?? null;\n const observer = new IntersectionObserver((entries) => setInView(entries[entries.length - 1].isIntersecting), { root, rootMargin });\n observer.observe(el);\n return () => observer.disconnect();\n }, [active, el, rootMargin, seen, unsupported]);\n return { ref: setEl, inView };\n}\n","import * as React from \"react\";\nimport { Button as AriaButton, type PressEvent } from \"react-aria-components\";\nimport { cva, type VariantProps } from \"class-variance-authority\";\nimport type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\nimport { Tooltip } from \"./tooltip\";\n\n// Variant names are shadcn's, so copied code and agents' prior knowledge still work. Two things\n// differ on purpose:\n// 1. The default variant is `outline`, not the filled accent. A bare <Button> is the restrained\n// one; the accent (`variant=\"default\"`) has to be asked for, once per view. Generated app screens\n// put the accent on every button; 12 of 23 real product screens had no filled primary at all.\n// 2. Heights come from --control-h, shared with Input and NativeSelect, so density changes move\n// every control together.\n// 3. React Aria is the primitives layer (CLAUDE.md, \"The stack\"): behaviour and accessibility come\n// from it, the look from our tokens. `asChild`/`Slot` is gone; a button that navigates is a link.\n// 4. `press`: the button gives 2% under a click or a finger, over 100ms. Buttons are used tens of\n// times a day, so that is all the motion they get (character.md, the frequency budget).\nexport const buttonVariants = cva(\n \"inline-flex shrink-0 cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-control type-label transition-state press disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0\",\n {\n variants: {\n variant: {\n default: \"bg-primary text-primary-foreground hover:bg-primary-10\",\n outline: \"border border-input bg-background text-foreground hover:bg-muted\",\n secondary: \"bg-muted text-foreground hover:bg-neutral-4\",\n ghost: \"text-foreground hover:bg-muted\",\n destructive: \"bg-destructive text-destructive-foreground hover:bg-danger\",\n link: \"h-auto px-0 text-primary-11 underline underline-offset-4 hover:text-primary-12\",\n },\n size: {\n default: \"h-(--control-h) px-4\",\n sm: \"h-(--control-h-sm) px-3\",\n icon: \"size-(--control-h)\",\n },\n },\n defaultVariants: { variant: \"outline\", size: \"default\" },\n },\n);\n\nexport type ButtonProps = Omit<React.ComponentProps<\"button\">, \"className\" | \"style\"> &\n VariantProps<typeof buttonVariants> & {\n className?: string;\n /** React Aria's press event (mouse, touch, pen and keyboard alike). `onClick` also works. */\n onPress?: (event: PressEvent) => void;\n };\n\n/**\n * A button with shadcn's variant names, built on React Aria's `Button` (press handling that behaves\n * the same for mouse, touch, pen and keyboard, focus-visible and hover state). The default variant is\n * `outline`; ask for the filled accent (`variant=\"default\"`) once per view. `type` defaults to `button`.\n * `onClick` and `disabled` are the DOM names and keep working; `onPress` is also accepted.\n */\nexport function Button({ className, variant, size, type = \"button\", disabled, ...props }: ButtonProps) {\n // data-variant says which variant was drawn, so a test can check \"one filled button per view\"\n // without reading class names (strata-react issue #48, `filledButtons` in strata-react/testing).\n return (\n <AriaButton\n type={type}\n isDisabled={disabled}\n data-variant={variant ?? \"outline\"}\n className={cn(buttonVariants({ variant, size }), className)}\n {...(props as object)}\n />\n );\n}\n\n// An icon-only button cannot be written without a name: `label` is required by the type, becomes\n// the accessible name and is shown as a `Tooltip` on hover and keyboard focus, so the name and the\n// visible hint come from one string and cannot drift. This makes the most common generated\n// accessibility defect (an unlabelled icon button) a compile error instead of an audit finding.\nexport type IconButtonProps = Omit<ButtonProps, \"size\" | \"children\" | \"aria-label\"> & {\n icon: IconComponent;\n label: string;\n /** Shown after the label in its tooltip, muted: \"Ctrl+Z\". */\n hint?: React.ReactNode;\n};\n\n/** An icon-only button. `label` is required and becomes the accessible name and the tooltip (hover and keyboard focus); `hint` adds a muted aside to it, such as a shortcut. */\nexport function IconButton({ icon: Icon, label, hint, variant = \"ghost\", ...props }: IconButtonProps) {\n return (\n <Tooltip label={label} hint={hint}>\n <Button size=\"icon\" variant={variant} aria-label={label} {...props}>\n <Icon aria-hidden />\n </Button>\n </Tooltip>\n );\n}\n\n// A row action says what it does in the row (\"Withdraw\") and whom it does it to in its name\n// (\"Withdraw Tom Ellery\"): a table of eight \"Withdraw\" buttons is eight identical names in a\n// screen reader's list of controls. The name is an aria-label that starts with the visible verb,\n// so it meets WCAG 2.5.3 (label in name) and voice control still finds it by \"Withdraw\". Visually\n// hidden suffix text is not used: a hidden span joined to the verb did not form a name with its\n// space in dom-testing-library (strata-react issue #11). Ghost and small, one per row, shown only\n// on the rows where it applies; an icon-only row action is an `IconButton` whose `label` names the\n// row the same way. It keeps the row's pitch: rows with and without the action are the same height.\nexport type RowActionProps = Omit<ButtonProps, \"children\" | \"aria-label\"> & {\n /** The visible verb, sentence case: \"Withdraw\", \"Remove\". */\n label: string;\n /** What the row is, as a person would say it: \"Tom Ellery\", \"Moonbeam\". Completes the accessible name. */\n subject: string;\n icon?: IconComponent;\n};\n\n/** A small ghost action for one table row: shows `label`, and is named \"`label` `subject`\" so every row's action has its own name. */\nexport function RowAction({ label, subject, icon: Icon, variant = \"ghost\", size = \"sm\", className, ...props }: RowActionProps) {\n // -my-1.5 lets the 32px button sit in the 20px line of a table row, inside the row's padding, so\n // rows with an action keep the same pitch as rows without one.\n return (\n <Button variant={variant} size={size} aria-label={`${label} ${subject}`} className={cn(\"-my-1.5\", className)} {...props}>\n {Icon && <Icon aria-hidden />}\n {label}\n </Button>\n );\n}\n","// The look every floating surface shares (Dialog, Popover, and later Menu and Toast): the popover\n// role pair, an overlay radius, one hairline and the one shadow that exists for what floats\n// (components.md §3.11). One string, so a menu and a popover cannot drift apart.\nexport const overlaySurface =\n \"rounded-overlay border border-border bg-popover text-popover-foreground shadow-overlay enter-overlay\";\n","// Chords: a shortcut written once (\"Mod+Shift+Z\") and shown per platform (⌘⇧Z on macOS, Ctrl+Shift+Z\n// elsewhere). `Mod` is the platform's command key: Meta on macOS, Ctrl everywhere else. The other\n// modifiers are Ctrl, Meta, Alt and Shift. The key is a `KeyboardEvent.key` value, compared without\n// case (\"z\" and \"Z\" are the same key; Shift is part of the chord when written).\n//\n// Matching is exact on the modifiers: \"Mod+Z\" is not \"Mod+Shift+Z\", so Undo and Redo cannot both\n// fire. Shift is ignored for a symbol key (\"?\" is typed with Shift on most layouts), and Alt is\n// matched on the physical key for letters, since Alt+Z types \"Ω\" on a Mac.\n\n/** `\"mac\"` or `\"other\"`: which modifier glyphs to draw and what `Mod` means. */\nexport type Platform = \"mac\" | \"other\";\n\n/** The platform this page runs on, read from the browser (`mac` for macOS and iOS). Server and test default: `other`. */\nexport function detectPlatform(): Platform {\n if (typeof navigator === \"undefined\") return \"other\";\n const nav = navigator as Navigator & { userAgentData?: { platform?: string } };\n const text = nav.userAgentData?.platform ?? nav.platform ?? \"\";\n return /mac|iphone|ipad|ipod/i.test(text) ? \"mac\" : \"other\";\n}\n\ntype Parsed = { ctrl: boolean; meta: boolean; alt: boolean; shift: boolean; key: string };\n\n/** Splits \"Mod+Shift+Z\" into modifiers and key for a platform. A bare \"+\" key is written \"Mod++\". */\nexport function parseChord(chord: string, platform: Platform = detectPlatform()): Parsed {\n const parts = chord.endsWith(\"++\") ? [...chord.slice(0, -2).split(\"+\").filter(Boolean), \"+\"] : chord.split(\"+\");\n const key = parts.pop() ?? \"\";\n const mods = new Set(parts.map((p) => p.toLowerCase()));\n const mod = mods.has(\"mod\");\n return {\n ctrl: mods.has(\"ctrl\") || (mod && platform !== \"mac\"),\n meta: mods.has(\"meta\") || (mod && platform === \"mac\"),\n alt: mods.has(\"alt\"),\n shift: mods.has(\"shift\"),\n key,\n };\n}\n\nconst symbol = (key: string) => key.length === 1 && key.toUpperCase() === key.toLowerCase();\n\n/** Whether a key event is this chord. Exact on Ctrl, Meta and Alt; Shift is exact for letters and named keys. */\nexport function matchesChord(e: Pick<KeyboardEvent, \"key\" | \"code\" | \"ctrlKey\" | \"metaKey\" | \"altKey\" | \"shiftKey\">, chord: string, platform: Platform = detectPlatform()): boolean {\n const c = parseChord(chord, platform);\n if (e.ctrlKey !== c.ctrl || e.metaKey !== c.meta || e.altKey !== c.alt) return false;\n if (!symbol(c.key) && e.shiftKey !== c.shift) return false;\n if (symbol(c.key) && c.shift && !e.shiftKey) return false;\n if (e.key.toLowerCase() === c.key.toLowerCase()) return true;\n return c.alt && /^[a-z]$/i.test(c.key) && e.code === `Key${c.key.toUpperCase()}`;\n}\n\nconst NAMES: Record<string, { mac: string; other: string }> = {\n ArrowUp: { mac: \"↑\", other: \"↑\" },\n ArrowDown: { mac: \"↓\", other: \"↓\" },\n ArrowLeft: { mac: \"←\", other: \"←\" },\n ArrowRight: { mac: \"→\", other: \"→\" },\n Escape: { mac: \"⎋\", other: \"Esc\" },\n Enter: { mac: \"↩\", other: \"Enter\" },\n Backspace: { mac: \"⌫\", other: \"Backspace\" },\n Delete: { mac: \"⌦\", other: \"Delete\" },\n \" \": { mac: \"Space\", other: \"Space\" },\n Tab: { mac: \"⇥\", other: \"Tab\" },\n Home: { mac: \"↖\", other: \"Home\" },\n End: { mac: \"↘\", other: \"End\" },\n};\n\n/** A chord as a person reads it on this platform: \"⌘⇧Z\" on macOS, \"Ctrl+Shift+Z\" elsewhere. */\nexport function formatChord(chord: string, platform: Platform = detectPlatform()): string {\n const c = parseChord(chord, platform);\n const key = NAMES[c.key]?.[platform] ?? (c.key.length === 1 ? c.key.toUpperCase() : c.key);\n if (platform === \"mac\") return `${c.ctrl ? \"⌃\" : \"\"}${c.alt ? \"⌥\" : \"\"}${c.shift ? \"⇧\" : \"\"}${c.meta ? \"⌘\" : \"\"}${key}`;\n return [c.ctrl && \"Ctrl\", c.meta && \"Meta\", c.alt && \"Alt\", c.shift && \"Shift\", key].filter(Boolean).join(\"+\");\n}\n\n// Chords the browser or the OS uses for itself. An app takes one over only on purpose (`claim` on\n// the command): silently stealing Ctrl+S from a person who wanted the browser's own is a choice.\nconst RESERVED = [\n \"Mod+S\", \"Mod+P\", \"Mod+F\", \"Mod+G\", \"Mod+O\", \"Mod+N\", \"Mod+T\", \"Mod+W\", \"Mod+R\", \"Mod+L\", \"Mod+D\", \"Mod+Q\", \"Mod+H\",\n \"Mod+J\", \"Mod+U\", \"Mod+Shift+T\", \"Mod+Shift+N\", \"Mod+Shift+W\", \"Alt+ArrowLeft\", \"Alt+ArrowRight\", \"F5\", \"F11\", \"F12\",\n];\n\n/** Whether the browser uses this chord for itself, so a command may take it only with `claim`. */\nexport function isReservedChord(chord: string, platform: Platform = detectPlatform()): boolean {\n const c = parseChord(chord, platform);\n return RESERVED.some((r) => {\n const p = parseChord(r, platform);\n return p.ctrl === c.ctrl && p.meta === c.meta && p.alt === c.alt && p.shift === c.shift && p.key.toLowerCase() === c.key.toLowerCase();\n });\n}\n","import * as React from \"react\";\nimport { cn } from \"../lib/utils\";\n\n// Single-key shortcuts for Operate screens that clear a queue (accept, reject, next). A person\n// doing the same answer a hundred times a day wants one key, no pointer and no motion\n// (ux-research `ux-character.md`: 100+ a day gets nothing but an instant change). Three rules\n// keep single keys from hurting anyone:\n// 1. They never fire while the person is typing: not in an input, textarea, select or\n// contenteditable (WCAG 2.1.4 Character Key Shortcuts), and not mid-composition (IME).\n// 2. They never take a chord: with Ctrl, Meta or Alt held the browser and the OS keep the key.\n// Shift is part of the key itself, so \"?\" works and \"A\" is not \"a\".\n// 3. Holding a key does not repeat an answer; only shortcuts marked `repeat` (moving) repeat.\n// The same list drives the handler and the legend, so a shortcut cannot exist without being\n// shown, and the legend cannot advertise a key that does nothing.\n\n/** One shortcut: the keys that run it (as `KeyboardEvent.key`), what it does in the product's words, and the action. */\nexport type Shortcut = {\n /** `KeyboardEvent.key` values, e.g. `[\"j\", \"ArrowDown\"]`. The first is the one the legend leads with. */\n keys: string[];\n /** What it does, in the product's words: \"Accept booking\", not \"Action 1\". */\n label: string;\n run: () => void;\n /** Fire again while the key is held. On for moving through a list, off (the default) for answers. */\n repeat?: boolean;\n /** Ignore the key for now, and show it muted in the legend (nothing is active, say). */\n disabled?: boolean;\n};\n\nconst TEXT_INPUTS_EXEMPT = new Set([\"checkbox\", \"radio\", \"button\", \"submit\", \"reset\", \"range\", \"color\", \"file\"]);\n\n/** True when a key pressed on this element is the person typing, so single-key shortcuts must leave it alone. */\nexport function isTypingTarget(target: EventTarget | null): boolean {\n if (!(target instanceof HTMLElement)) return false;\n if (target.isContentEditable || target.closest(\"[contenteditable=''],[contenteditable='true']\")) return true;\n if (target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement) return true;\n if (target instanceof HTMLInputElement) return !TEXT_INPUTS_EXEMPT.has(target.type);\n return false;\n}\n\nfunction toShortcuts(input: Shortcut[] | Record<string, () => void>): Shortcut[] {\n return Array.isArray(input) ? input : Object.entries(input).map(([key, run]) => ({ keys: [key], label: key, run }));\n}\n\n/**\n * Binds single-key shortcuts on the window, ignoring keys typed into fields, chords with Ctrl, Meta\n * or Alt, IME composition and (unless `repeat`) held keys. Pass the same list to `KeysLegend`.\n */\nexport function useHotkeys(shortcuts: Shortcut[] | Record<string, () => void>, { enabled = true }: { enabled?: boolean } = {}) {\n // The listener is bound once; it reads the latest list, so handlers can close over fresh state.\n const latest = React.useRef<Shortcut[]>([]);\n latest.current = toShortcuts(shortcuts);\n\n React.useEffect(() => {\n if (!enabled) return;\n const onKeyDown = (e: KeyboardEvent) => {\n if (e.defaultPrevented || e.isComposing || e.ctrlKey || e.metaKey || e.altKey) return;\n if (isTypingTarget(e.target)) return;\n const hit = latest.current.find((s) => !s.disabled && s.keys.includes(e.key));\n if (!hit || (e.repeat && !hit.repeat)) return;\n e.preventDefault();\n hit.run();\n };\n window.addEventListener(\"keydown\", onKeyDown);\n return () => window.removeEventListener(\"keydown\", onKeyDown);\n }, [enabled]);\n}\n\nconst KEY_NAMES: Record<string, string> = {\n ArrowDown: \"↓\",\n ArrowUp: \"↑\",\n ArrowLeft: \"←\",\n ArrowRight: \"→\",\n Escape: \"Esc\",\n Enter: \"Enter\",\n Backspace: \"Backspace\",\n Delete: \"Delete\",\n \" \": \"Space\",\n};\n\n// The legend is quiet, caption-sized and muted: it is there to be found, not read every time.\n// It hides on coarse pointers (phones, tablets without a keyboard), where the keys do not exist.\n// Each key is a <kbd>; alternatives are read as \"j or down arrow\".\n/** A quiet legend of the screen's shortcuts, from the same list `useHotkeys` binds. Hidden on touch screens. */\nexport function KeysLegend({\n shortcuts,\n label = \"Keyboard shortcuts\",\n className,\n}: {\n shortcuts: Pick<Shortcut, \"keys\" | \"label\" | \"disabled\">[];\n /** Names the legend for screen readers. */\n label?: string;\n className?: string;\n}) {\n return (\n <dl aria-label={label} className={cn(\"flex flex-wrap gap-x-4 gap-y-1 type-caption text-muted-foreground pointer-coarse:hidden\", className)}>\n {shortcuts.map((s) => (\n <div key={s.keys.join(\" \")} className={cn(\"flex items-center gap-1.5\", s.disabled && \"opacity-50\")}>\n <dt className=\"flex items-center gap-1\">\n {s.keys.map((k, i) => (\n <React.Fragment key={k}>\n {i > 0 && <span className=\"sr-only\"> or </span>}\n <kbd className=\"min-w-5 rounded-control border border-border bg-surface-sunken px-1 text-center font-mono text-foreground\">\n {KEY_NAMES[k] ?? k}\n </kbd>\n </React.Fragment>\n ))}\n </dt>\n <dd>{s.label}</dd>\n </div>\n ))}\n </dl>\n );\n}\n","import * as React from \"react\";\nimport {\n Autocomplete,\n Dialog as AriaDialog,\n Header,\n Heading,\n Keyboard,\n Menu as AriaMenu,\n MenuItem,\n MenuSection,\n MenuTrigger,\n Modal,\n ModalOverlay,\n Popover as AriaPopover,\n SearchField,\n Input as AriaInput,\n Separator,\n SubmenuTrigger,\n Text,\n useFilter,\n} from \"react-aria-components\";\nimport { Check, ChevronRight, Search, Trash2 } from \"lucide-react\";\nimport type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\nimport { overlaySurface } from \"../lib/overlay\";\nimport { formatChord, detectPlatform, isReservedChord, matchesChord, type Platform } from \"../lib/chords\";\nimport { isTypingTarget } from \"./hotkeys\";\n\n// One command, declared once, used everywhere a person can reach it: a dropdown or menu-bar menu,\n// a context menu, the command menu, the key handler and the legend. Each of those reads the same\n// object, so the label, the enabled state and the shortcut text cannot disagree (components.md\n// §3.16 and §3.11; strata-react issue #71). This is the single-key `Shortcut` idea of `useHotkeys`\n// carried to menus and chords: `useHotkeys` is unchanged for a queue worked with single keys.\n//\n// - A label is a string or a function, so Undo can say \"Undo move clip\" and follow the history.\n// - `keys` are chords written once (\"Mod+Z\"), shown per platform (⌘Z or Ctrl+Z). They never fire\n// while the person is typing (a field's own Ctrl+Z is the field's) unless the command says\n// `inFields`, never during IME composition, and a chord the browser uses (Ctrl+S, Ctrl+P, ...)\n// is taken only with `claim: true`, an explicit choice.\n// - `disabled` is `true` or a sentence saying why (\"Nothing to undo\"); a disabled command's chord\n// does nothing, and every menu shows the item as unavailable, with the reason.\n// - Menus use React Aria's menu: roles, arrows, Home and End, typeahead, Escape back to the\n// trigger, submenus. A destructive item carries an icon as well as its colour, since colour\n// alone is not a signal (components.md §3.4). A group whose commands all have `checked` is a\n// group of checkable items.\n// Motion: shortcuts and the command menu are used 100+ times a day, so they appear at once.\n\n/** A command: what it is called, how it is run, and everything the menus need to draw it. */\nexport type Command = {\n /** Stable key for the command. */\n id: string;\n /** The verb phrase, sentence case, in the product's words (\"Split clip\"); a function when it follows state (\"Undo move clip\"). */\n label: string | (() => string);\n run: () => void;\n /** Chords that run it, written once (\"Mod+Z\", \"Delete\", \"Shift+?\"); the first is the one shown. */\n keys?: string[];\n /** Cannot run now. A sentence says why (\"Nothing to undo\") and is shown in menus. */\n disabled?: boolean | string;\n /** Cannot be undone or removes something: drawn with an icon and the danger colour. */\n destructive?: boolean;\n /** Makes a menu item checkable: whether it is on now. `run` toggles it. */\n checked?: boolean;\n icon?: IconComponent;\n /** Fire again while the key is held (for moving). Default false. */\n repeat?: boolean;\n /** Run from inside a text field too. Default false: a field keeps its own keys. */\n inFields?: boolean;\n /** Take over a chord the browser uses (Ctrl+S, Ctrl+P). Required for those; otherwise the command is not bound. */\n claim?: boolean;\n};\n\n/** What goes in a menu: a command, a separator, a titled group, or a submenu. */\nexport type MenuEntry = Command | \"separator\" | { group: string; items: Command[] } | { submenu: string; items: MenuEntry[] };\n\n/** The text of a command's label, whether it is a string or a function. */\nexport const labelOf = (c: Command) => (typeof c.label === \"function\" ? c.label() : c.label);\nconst isDisabled = (c: Command) => Boolean(c.disabled);\nconst reasonOf = (c: Command) => (typeof c.disabled === \"string\" ? c.disabled : undefined);\nconst isCommand = (e: MenuEntry): e is Command => typeof e === \"object\" && \"run\" in e;\n\n/** Options for `useCommands`. */\nexport type CommandsOptions = {\n enabled?: boolean;\n /** Which platform's `Mod` to use; read from the browser when left out. */\n platform?: Platform;\n};\n\n/**\n * Binds every command's chords on the window. Never while typing (unless the command says\n * `inFields`), never during IME composition, not on a held key (unless `repeat`), not for a disabled\n * command, and not for a chord the browser uses unless the command `claim`s it. A command's chord\n * that clashes with another's is a mistake: the first in the list wins, and a dev warning names both.\n */\nexport function useCommands(commands: readonly Command[], { enabled = true, platform }: CommandsOptions = {}) {\n const latest = React.useRef<readonly Command[]>([]);\n latest.current = commands;\n const where = platform ?? detectPlatform();\n\n React.useEffect(() => {\n if (!enabled) return;\n const onKeyDown = (e: KeyboardEvent) => {\n if (e.defaultPrevented || e.isComposing) return;\n for (const c of latest.current) {\n const chord = c.keys?.find((k) => matchesChord(e, k, where));\n if (!chord) continue;\n if (isReservedChord(chord, where) && !c.claim) continue;\n if (isTypingTarget(e.target) && !c.inFields) continue;\n if (isDisabled(c) || (e.repeat && !c.repeat)) return;\n e.preventDefault();\n c.run();\n return;\n }\n };\n window.addEventListener(\"keydown\", onKeyDown);\n return () => window.removeEventListener(\"keydown\", onKeyDown);\n }, [enabled, where]);\n\n if (import.meta.env?.DEV) warnOnClashes(commands, where);\n}\n\nfunction warnOnClashes(commands: readonly Command[], platform: Platform) {\n const seen = new Map<string, string>();\n for (const c of commands) {\n for (const k of c.keys ?? []) {\n const shown = formatChord(k, platform);\n const other = seen.get(shown);\n if (other && other !== c.id) console.warn(`strata-react: \"${shown}\" is bound to both \"${other}\" and \"${c.id}\"; the first wins.`);\n else seen.set(shown, c.id);\n }\n if (c.keys?.some((k) => isReservedChord(k, platform)) && !c.claim) {\n console.warn(`strata-react: \"${c.id}\" uses a chord the browser keeps for itself; add \\`claim: true\\` to take it over.`);\n }\n }\n}\n\n/** The shortcut a command shows in menus and legends (\"⌘Z\", \"Ctrl+Z\"), or undefined. */\nexport function commandShortcut(c: Command, platform: Platform = detectPlatform()): string | undefined {\n return c.keys?.[0] ? formatChord(c.keys[0], platform) : undefined;\n}\n\n/** A quiet legend built from the same commands the key handler runs: only commands with keys, disabled ones muted. */\nexport function CommandLegend({\n commands,\n platform,\n label = \"Keyboard shortcuts\",\n className,\n}: {\n commands: readonly Command[];\n platform?: Platform;\n label?: string;\n className?: string;\n}) {\n const where = platform ?? detectPlatform();\n const shown = commands.filter((c) => c.keys?.length);\n return (\n <dl aria-label={label} className={cn(\"flex flex-wrap gap-x-4 gap-y-1 type-caption text-muted-foreground pointer-coarse:hidden\", className)}>\n {shown.map((c) => (\n <div key={c.id} className={cn(\"flex items-center gap-1.5\", isDisabled(c) && \"opacity-50\")}>\n <dt>\n <kbd className=\"min-w-5 rounded-control border border-border bg-surface-sunken px-1 text-center font-mono text-foreground\">\n {commandShortcut(c, where)}\n </kbd>\n </dt>\n <dd>{labelOf(c)}</dd>\n </div>\n ))}\n </dl>\n );\n}\n\nconst itemClass = cn(\n \"flex min-h-(--control-h-sm) cursor-pointer items-center gap-2 rounded-control px-2 type-body-sm outline-none\",\n \"data-[focused]:bg-muted data-[disabled]:cursor-not-allowed data-[disabled]:text-muted-foreground data-[disabled]:opacity-70\",\n \"data-[open]:bg-muted\",\n);\n\nfunction Item({ command, platform }: { command: Command; platform: Platform }) {\n const Icon = command.icon ?? (command.destructive ? Trash2 : undefined);\n const shortcut = commandShortcut(command, platform);\n const reason = reasonOf(command);\n return (\n <MenuItem\n id={command.id}\n textValue={labelOf(command)}\n isDisabled={isDisabled(command)}\n onAction={command.run}\n className={cn(itemClass, command.destructive && !isDisabled(command) && \"text-danger\", \"flex-wrap\")}\n >\n {({ isSelected, selectionMode }) => (\n <>\n {selectionMode !== \"none\" ? (\n <span aria-hidden className=\"grid size-4 shrink-0 place-items-center\">{isSelected && <Check className=\"size-4\" />}</span>\n ) : (\n Icon && <Icon aria-hidden className=\"size-4 shrink-0\" />\n )}\n <Text slot=\"label\" className=\"min-w-0 flex-1 truncate\">{labelOf(command)}</Text>\n {shortcut && <Keyboard className=\"ml-6 shrink-0 font-mono type-caption text-muted-foreground\">{shortcut}</Keyboard>}\n {reason && <Text slot=\"description\" className=\"w-full pl-6 type-caption text-muted-foreground\">{reason}</Text>}\n </>\n )}\n </MenuItem>\n );\n}\n\nfunction Entries({ entries, platform }: { entries: readonly MenuEntry[]; platform: Platform }) {\n return (\n <>\n {entries.map((entry, i) => {\n if (entry === \"separator\") return <Separator key={`sep-${i}`} className=\"my-1 h-px border-0 bg-border\" />;\n if (isCommand(entry)) return <Item key={entry.id} command={entry} platform={platform} />;\n if (\"group\" in entry) {\n const checkable = entry.items.length > 0 && entry.items.every((c) => c.checked !== undefined);\n return (\n <MenuSection\n key={`group-${entry.group}`}\n selectionMode={checkable ? \"multiple\" : undefined}\n selectedKeys={checkable ? entry.items.filter((c) => c.checked).map((c) => c.id) : undefined}\n >\n <Header className=\"px-2 pt-1 type-caption text-muted-foreground\">{entry.group}</Header>\n {entry.items.map((c) => <Item key={c.id} command={c} platform={platform} />)}\n </MenuSection>\n );\n }\n return (\n <SubmenuTrigger key={`sub-${entry.submenu}`}>\n <MenuItem textValue={entry.submenu} className={itemClass}>\n <Text slot=\"label\" className=\"min-w-0 flex-1 truncate\">{entry.submenu}</Text>\n <ChevronRight aria-hidden className=\"size-4 shrink-0 text-muted-foreground\" />\n </MenuItem>\n <AriaPopover offset={0} crossOffset={-4} className={cn(\"layer-overlay min-w-48 p-1\", overlaySurface)}>\n <AriaMenu aria-label={entry.submenu} className=\"outline-none\">\n <Entries entries={entry.items} platform={platform} />\n </AriaMenu>\n </AriaPopover>\n </SubmenuTrigger>\n );\n })}\n </>\n );\n}\n\nconst surface = cn(\"layer-overlay min-w-48 p-1\", overlaySurface);\n\n/** Props for `Menu`. */\nexport type MenuProps = {\n /** Names the menu: \"File\", \"Edit\". Required. */\n label: string;\n /** The control that opens it. */\n trigger: React.ReactElement;\n items: readonly MenuEntry[];\n /** Controlled open state, for a story or a test that needs it shown. */\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n platform?: Platform;\n className?: string;\n};\n\n/** A dropdown menu of commands: the menu roles and keyboard model, shortcuts shown per platform, unavailable items with their reason, separators, groups, checkable groups and submenus. */\nexport function Menu({ label, trigger, items, open, onOpenChange, platform, className }: MenuProps) {\n const where = platform ?? detectPlatform();\n return (\n <MenuTrigger isOpen={open} onOpenChange={onOpenChange}>\n {trigger}\n <AriaPopover placement=\"bottom start\" offset={4} className={cn(surface, className)}>\n <AriaMenu aria-label={label} className=\"outline-none\">\n <Entries entries={items} platform={where} />\n </AriaMenu>\n </AriaPopover>\n </MenuTrigger>\n );\n}\n\n/** Props for `ContextMenu`. */\nexport type ContextMenuProps = {\n /** Names the menu: \"Clip actions\". Required. */\n label: string;\n items: readonly MenuEntry[];\n /** The object it belongs to. It becomes the thing the menu opens on: right-click, the context-menu key and Shift+F10. */\n children: React.ReactElement<React.HTMLAttributes<HTMLElement>>;\n platform?: Platform;\n disabled?: boolean;\n};\n\n/**\n * A context menu for an object: opens on right-click at the pointer, and from the keyboard (the\n * context-menu key or Shift+F10) beside the focused object, with the same items and shortcuts as\n * every other menu. The child gets the handlers, so it should be focusable (a row, a clip).\n */\nexport function ContextMenu({ label, items, children, platform, disabled }: ContextMenuProps) {\n const where = platform ?? detectPlatform();\n const [at, setAt] = React.useState<{ x: number; y: number } | null>(null);\n const anchor = React.useRef<HTMLSpanElement>(null);\n const open = (x: number, y: number) => setAt({ x, y });\n const child = React.Children.only(children);\n return (\n <>\n {React.cloneElement(child, {\n onContextMenu: (e: React.MouseEvent<HTMLElement>) => {\n child.props.onContextMenu?.(e);\n if (disabled || e.defaultPrevented) return;\n e.preventDefault();\n open(e.clientX, e.clientY);\n },\n onKeyDown: (e: React.KeyboardEvent<HTMLElement>) => {\n child.props.onKeyDown?.(e);\n if (disabled || e.defaultPrevented) return;\n if (e.key === \"ContextMenu\" || (e.key === \"F10\" && e.shiftKey)) {\n e.preventDefault();\n const r = e.currentTarget.getBoundingClientRect();\n open(r.left + 8, r.bottom);\n }\n },\n })}\n {at && (\n <span ref={anchor} aria-hidden style={{ position: \"fixed\", left: at.x, top: at.y, width: 0, height: 0 }} />\n )}\n <AriaPopover triggerRef={anchor} isOpen={at !== null} onOpenChange={(o) => !o && setAt(null)} placement=\"bottom start\" offset={0} className={surface}>\n <AriaMenu aria-label={label} autoFocus=\"first\" onAction={() => setAt(null)} className=\"outline-none\">\n <Entries entries={items} platform={where} />\n </AriaMenu>\n </AriaPopover>\n </>\n );\n}\n\n/** Props for `CommandMenu`. */\nexport type CommandMenuProps = {\n /** The commands to search, usually the same list given to `useCommands`. Entries may be grouped. */\n commands: readonly MenuEntry[];\n /** Controlled open state; otherwise it opens on `shortcut`. */\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n /** The chord that opens it. Default `Mod+K`. `null` for none. */\n shortcut?: string | null;\n /** The search field's name and placeholder. Default \"Search commands\". */\n label?: string;\n platform?: Platform;\n};\n\nfunction flatten(entries: readonly MenuEntry[]): Command[] {\n return entries.flatMap((e) => (e === \"separator\" ? [] : isCommand(e) ? [e] : flatten(e.items)));\n}\n\n/** A searchable list of every command, opened by a chord (default Mod+K). Choosing one closes it and runs it; an unavailable command is shown with its reason and does nothing. */\nexport function CommandMenu({ commands, open, onOpenChange, shortcut = \"Mod+K\", label = \"Search commands\", platform }: CommandMenuProps) {\n const where = platform ?? detectPlatform();\n const [own, setOwn] = React.useState(false);\n const isOpen = open ?? own;\n const set = (next: boolean) => {\n setOwn(next);\n onOpenChange?.(next);\n };\n React.useEffect(() => {\n if (!shortcut) return;\n const onKeyDown = (e: KeyboardEvent) => {\n if (e.defaultPrevented || e.isComposing || !matchesChord(e, shortcut, where)) return;\n e.preventDefault();\n // A held key repeats keydown; toggling on each would flicker the dialog open and shut.\n if (e.repeat) return;\n set(!isOpen);\n };\n window.addEventListener(\"keydown\", onKeyDown);\n return () => window.removeEventListener(\"keydown\", onKeyDown);\n });\n const { contains } = useFilter({ sensitivity: \"base\" });\n const all = flatten(commands);\n return (\n <ModalOverlay isOpen={isOpen} onOpenChange={set} isDismissable className=\"layer-overlay fixed inset-0 grid justify-items-center overflow-hidden bg-foreground/40 p-4 pt-24\">\n <Modal className={cn(\"flex max-h-full w-full max-w-lg flex-col self-start outline-none\", overlaySurface)}>\n <AriaDialog aria-label={label} className=\"flex min-h-0 flex-col outline-none\">\n <Autocomplete filter={contains}>\n <SearchField aria-label={label} autoFocus className=\"flex items-center gap-2 border-b border-border px-3\">\n <Search aria-hidden className=\"size-4 shrink-0 text-muted-foreground\" />\n <AriaInput placeholder={label} className=\"h-(--control-h) min-w-0 flex-1 bg-transparent type-body outline-none placeholder:text-muted-foreground\" />\n </SearchField>\n <AriaMenu\n aria-label=\"Commands\"\n className=\"min-h-0 overflow-y-auto overscroll-contain p-1 outline-none\"\n renderEmptyState={() => <p className=\"px-3 py-4 type-body-sm text-muted-foreground\">No command matches.</p>}\n onAction={() => set(false)}\n >\n {all.map((c) => <Item key={c.id} command={c} platform={where} />)}\n </AriaMenu>\n </Autocomplete>\n </AriaDialog>\n <Heading slot=\"title\" className=\"sr-only\">{label}</Heading>\n </Modal>\n </ModalOverlay>\n );\n}\n","import * as React from \"react\";\nimport { Toolbar as AriaToolbar, Separator } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\nimport { isTypingTarget } from \"./hotkeys\";\n\n// A toolbar groups controls that act on what is shown (a preview's grid and quality, a timeline's\n// snap, a table's density). React Aria gives it the WAI-ARIA toolbar keyboard model: one tab stop,\n// arrow keys (and Home and End) move inside it, Tab leaves it. It needs a `label`, as an unnamed\n// toolbar is announced as nothing. Groups inside it are separated by a hairline (`ToolbarSeparator`)\n// rather than by space alone, so a row of eight small controls reads as three groups. It lays out\n// as one wrapping row: when it runs out of width, controls wrap to the next line instead of being\n// hidden behind an overflow menu, which keeps every control reachable with no extra state\n// (an overflow menu is the later step, once the Menu exists).\n\n/** Props for `Toolbar`. */\nexport type ToolbarProps = {\n /** Names the toolbar for screen readers: \"Preview options\". Required. */\n label: string;\n orientation?: \"horizontal\" | \"vertical\";\n children: React.ReactNode;\n className?: string;\n};\n\n/** A group of controls with one tab stop and arrow-key movement (the WAI-ARIA toolbar pattern). Needs a `label`. */\nexport function Toolbar({ label, orientation = \"horizontal\", children, className }: ToolbarProps) {\n // React Aria's toolbar moves with the arrow keys; Home and End (to the first and last control) are\n // added here, as the WAI-ARIA toolbar pattern lists them. The capture phase runs before React\n // Aria's own handler, and a typing target (a number field inside the toolbar) keeps its Home and End.\n const jump = (e: React.KeyboardEvent<HTMLElement>) => {\n // Only events from inside the toolbar's own DOM: a Popover opened from a control here renders in\n // a portal, and its events still reach this handler through React's tree.\n if ((e.key !== \"Home\" && e.key !== \"End\") || isTypingTarget(e.target) || !e.currentTarget.contains(e.target as Node)) return;\n const items = [...e.currentTarget.querySelectorAll<HTMLElement>(\"button, input, select, textarea, a[href], [tabindex]\")].filter(\n (el) => !el.hasAttribute(\"disabled\") && el.getAttribute(\"aria-disabled\") !== \"true\" && el.tabIndex >= -1 && el.getAttribute(\"role\") !== \"separator\",\n );\n const target = e.key === \"Home\" ? items[0] : items[items.length - 1];\n if (!target) return;\n e.preventDefault();\n e.stopPropagation();\n target.focus();\n };\n return (\n <div className=\"contents\" onKeyDownCapture={jump}>\n <AriaToolbar\n aria-label={label}\n orientation={orientation}\n className={cn(\"flex flex-wrap items-center gap-1\", orientation === \"vertical\" && \"flex-col items-stretch\", className)}\n >\n {children}\n </AriaToolbar>\n </div>\n );\n}\n\n/** A hairline between groups of controls inside a `Toolbar`. */\nexport function ToolbarSeparator({ className }: { className?: string }) {\n return <Separator className={cn(\"mx-1 h-5 w-px self-center border-0 bg-border\", className)} />;\n}\n","import * as React from \"react\";\nimport { ToggleButton as AriaToggleButton, ToggleButtonGroup } from \"react-aria-components\";\nimport type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\nimport { Tooltip } from \"./tooltip\";\n\n// On/off and one-of-a-few controls for what acts on the view: grid, snap, quality, view mode,\n// density. `Toggle` is one pressed-or-not button (`aria-pressed`); `ToggleGroup` is a single-choice\n// set of them for 2 to 7 short options that switch a view (components.md §3.3; for 2 to 5 options\n// that each need a sentence use `ChoiceGroup`).\n//\n// The chosen state must be seen without colour and must not look like the view's one filled\n// primary button (patterns.md §2, the one-filled-button rule): chosen is an ink border on a\n// neutral tint, with the label unchanged in weight (no layout shift), never `bg-primary`. An\n// icon-only toggle cannot be written without its name: `label` is required, becomes the accessible\n// name and is shown as a tooltip, as for `IconButton`. Toggles are used tens of times a day, so\n// they get the press and colour transitions and nothing more (character.md §3).\n\nconst base =\n \"inline-flex shrink-0 cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-control border type-label transition-state press [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 \" +\n \"border-input bg-background text-muted-foreground data-[hovered]:bg-muted data-[hovered]:text-foreground \" +\n \"data-[selected]:border-foreground data-[selected]:bg-muted data-[selected]:text-foreground \" +\n \"data-[disabled]:pointer-events-none data-[disabled]:opacity-50\";\n\nconst sizes = { default: \"h-(--control-h)\", sm: \"h-(--control-h-sm)\" } as const;\ntype Size = keyof typeof sizes;\n\n/** Props for `Toggle`. */\nexport type ToggleProps = {\n /** The name, always. Shown as the text unless `icon` is given with `iconOnly`, then it is the accessible name and the tooltip. */\n label: string;\n icon?: IconComponent;\n /** Show only the icon; `label` stays the name and tooltip. */\n iconOnly?: boolean;\n pressed?: boolean;\n defaultPressed?: boolean;\n onChange?: (pressed: boolean) => void;\n disabled?: boolean;\n size?: Size;\n className?: string;\n};\n\nfunction Face({ label, icon: Icon, iconOnly, pad }: { label: string; icon?: IconComponent; iconOnly?: boolean; pad: string }) {\n return (\n <>\n {Icon && <Icon aria-hidden />}\n {!iconOnly && <span className={pad}>{label}</span>}\n </>\n );\n}\n\n/** A button that is pressed or not (`aria-pressed`). Chosen reads as an ink border on a tint, never as the filled primary. */\nexport function Toggle({ label, icon, iconOnly = false, pressed, defaultPressed, onChange, disabled, size = \"default\", className }: ToggleProps) {\n const button = (\n <AriaToggleButton\n isSelected={pressed}\n defaultSelected={defaultPressed}\n onChange={onChange}\n isDisabled={disabled}\n aria-label={icon && iconOnly ? label : undefined}\n className={cn(base, sizes[size], icon && iconOnly ? (size === \"sm\" ? \"size-(--control-h-sm)\" : \"size-(--control-h)\") : \"px-3\", className)}\n >\n <Face label={label} icon={icon} iconOnly={iconOnly && Boolean(icon)} pad=\"\" />\n </AriaToggleButton>\n );\n return icon && iconOnly ? <Tooltip label={label}>{button}</Tooltip> : button;\n}\n\n/** One option of a `ToggleGroup`. */\nexport type ToggleOption = { value: string; label: string; icon?: IconComponent; iconOnly?: boolean };\n\n/** Props for `ToggleGroup`. */\nexport type ToggleGroupProps = {\n /** Names the group for screen readers: \"Preview quality\". Required. */\n label: string;\n options: readonly ToggleOption[];\n value: string;\n onChange: (value: string) => void;\n size?: Size;\n className?: string;\n};\n\n/** A single-choice set of toggle buttons for 2 to 7 short options that switch a view. One is always chosen; arrow keys move between them. */\nexport function ToggleGroup({ label, options, value, onChange, size = \"default\", className }: ToggleGroupProps) {\n return (\n <ToggleButtonGroup\n aria-label={label}\n selectionMode=\"single\"\n disallowEmptySelection\n selectedKeys={[value]}\n onSelectionChange={(keys) => {\n const next = [...keys][0];\n if (next !== undefined) onChange(String(next));\n }}\n className={cn(\"inline-flex gap-0.5 rounded-surface border border-border bg-background p-0.5\", className)}\n >\n {options.map((o) => {\n const iconOnly = Boolean(o.icon && o.iconOnly);\n const item = (\n <AriaToggleButton\n id={o.value}\n aria-label={iconOnly ? o.label : undefined}\n className={cn(\n base,\n // Inside the group the segments are 4px, the outer 6px less its 2px padding; the group's own\n // hairline replaces each segment's, and the chosen one keeps the ink border.\n \"border-transparent bg-transparent data-[selected]:border-foreground\",\n sizes[size],\n iconOnly ? (size === \"sm\" ? \"size-(--control-h-sm)\" : \"size-(--control-h)\") : \"px-3\",\n )}\n >\n <Face label={o.label} icon={o.icon} iconOnly={iconOnly} pad=\"\" />\n </AriaToggleButton>\n );\n return iconOnly ? <Tooltip key={o.value} label={o.label}>{item}</Tooltip> : React.cloneElement(item, { key: o.value });\n })}\n </ToggleButtonGroup>\n );\n}\n","import { Switch as AriaSwitch } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\n\n// A switch is for a setting that applies the moment it is flipped (show the grid, enable the\n// heatmap), never for one that needs a Save: that is a Checkbox in a form (components.md §3.3).\n// The label and the control are one target. \"On\" is shown by position and by a tick in the thumb\n// as well as by colour, so it survives a colour-blind reading. `role=\"switch\"` and its on state\n// come from React Aria. Used many times a day, so only a short colour and position transition.\n\n/** Props for `Switch`. */\nexport type SwitchProps = {\n /** What it turns on, as the visible label: \"Show elevation profile\". Required. */\n label: string;\n /** A muted second line under the label. */\n detail?: string;\n on?: boolean;\n defaultOn?: boolean;\n onChange?: (on: boolean) => void;\n disabled?: boolean;\n className?: string;\n};\n\n/** An on/off setting that applies at once, its label and control one target. */\nexport function Switch({ label, detail, on, defaultOn, onChange, disabled, className }: SwitchProps) {\n return (\n <AriaSwitch\n isSelected={on}\n defaultSelected={defaultOn}\n onChange={onChange}\n isDisabled={disabled}\n className={cn(\"group inline-flex min-h-6 cursor-pointer items-start gap-3 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50\", className)}\n >\n <span\n aria-hidden\n className={cn(\n \"mt-0.5 flex h-5 w-9 shrink-0 items-center rounded-pill border border-input bg-muted p-0.5 transition-state\",\n \"group-data-[selected]:border-primary group-data-[selected]:bg-primary\",\n \"group-data-[focus-visible]:outline-2 group-data-[focus-visible]:outline-offset-2 group-data-[focus-visible]:outline-ring\",\n )}\n >\n <span className=\"grid size-3.5 place-items-center rounded-pill bg-background text-primary group-data-[selected]:translate-x-4\">\n <span className=\"hidden size-1.5 rounded-pill bg-primary group-data-[selected]:block\" />\n </span>\n </span>\n <span className=\"grid\">\n <span className=\"type-body\">{label}</span>\n {detail && <span className=\"type-body-sm text-muted-foreground\">{detail}</span>}\n </span>\n </AriaSwitch>\n );\n}\n","import * as React from \"react\";\nimport {\n Dialog as AriaDialog,\n DialogTrigger,\n Heading,\n Modal,\n ModalOverlay,\n} from \"react-aria-components\";\nimport { X } from \"lucide-react\";\nimport { Button, IconButton } from \"./button\";\nimport { describeActionError } from \"../lib/errors\";\nimport { cn } from \"../lib/utils\";\nimport { overlaySurface } from \"../lib/overlay\";\n\n// Dialog is for a task that needs its own space; \"a modal is never the first idea for a form that\n// fits on the page\" (components.md §3.11). AlertDialog is the only confirm in the library, for what\n// cannot be undone: a reversible removal uses `UndoBar` instead (patterns.md §7).\n//\n// What the types and the component settle, so an app cannot get them wrong:\n// - A title is required (visible, or `hideTitle` for a screen-reader-only one): an unnamed dialog is\n// announced as \"dialog\" and nothing else. An AlertDialog's `confirm` is required and is the verb,\n// \"Delete 3 firings\", never \"OK\".\n// - React Aria moves focus in on open and back to the trigger on close, makes the page behind inert\n// and stops it scrolling. Content scrolls inside the dialog when tall (`overscroll-contain`), and\n// everything is portalled onto `layer-overlay`, above panes, sticky headers and the undo bar.\n// - A dialog can be made not closable while work runs (`closable={false}`: no close control, no\n// Escape, no outside press), so an export cannot lose its Close button halfway, as strata-vid's did.\n// - An AlertDialog ignores outside presses, focuses its safe choice (Cancel) first, and stays open\n// with the reason when an async confirm fails, since closing would hide that it did not happen.\n// - The same surface is a Sheet with `placement=\"end\"`: a side panel for a long form or a detail.\n\ntype Common = {\n /** What it is for: \"Export video\", \"Delete 3 firings?\". Required. */\n title: string;\n /** Shown under the title when it is not enough alone. */\n description?: React.ReactNode;\n /** The control that opens it. Leave out and drive it with `open` and `onOpenChange`. */\n trigger?: React.ReactElement;\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n className?: string;\n};\n\n/** Props for `Dialog`. */\nexport type DialogProps = Common & {\n /** The body. It scrolls inside the dialog when it is taller than the window. */\n children?: React.ReactNode;\n /** The buttons along the bottom, built with `DialogActions`'s `close` render prop when one should close it. One filled button at most. */\n actions?: React.ReactNode | ((close: () => void) => React.ReactNode);\n /** Keep the title for screen readers only, when the body already says it. */\n hideTitle?: boolean;\n /** `false` while work cannot be interrupted: no close control, Escape or outside press. Default true. */\n closable?: boolean;\n /** `center` is a dialog; `end` is a sheet down the right edge. Default `center`. */\n placement?: \"center\" | \"end\";\n size?: \"sm\" | \"md\" | \"lg\";\n};\n\nconst sizes = { sm: \"max-w-sm\", md: \"max-w-lg\", lg: \"max-w-3xl\" } as const;\n\nconst overlayClass = \"layer-overlay fixed inset-0 grid overflow-hidden bg-foreground/40\";\n\n/** A modal dialog with a required title; focus goes in and returns, Escape and a close control dismiss it. `placement=\"end\"` makes it a sheet. */\nexport function Dialog({\n title, description, trigger, open, onOpenChange, className, children, actions,\n hideTitle, closable = true, placement = \"center\", size = \"md\",\n}: DialogProps) {\n const descriptionId = React.useId();\n return (\n <DialogTrigger isOpen={open} onOpenChange={onOpenChange}>\n {trigger}\n <ModalOverlay isDismissable={closable} isKeyboardDismissDisabled={!closable} className={cn(overlayClass, placement === \"end\" ? \"justify-items-end\" : \"place-items-center p-4\")}>\n <Modal\n className={cn(\n \"flex max-h-full min-h-0 w-full flex-col outline-none\",\n overlaySurface,\n placement === \"end\" ? \"h-full max-w-md rounded-r-none\" : sizes[size],\n className,\n )}\n >\n <AriaDialog aria-describedby={description != null ? descriptionId : undefined} className=\"flex min-h-0 flex-1 flex-col gap-4 p-4 outline-none\">\n {({ close }) => (\n <>\n <div className=\"flex items-start justify-between gap-4\">\n <div className=\"grid gap-1\">\n <Heading slot=\"title\" className={cn(\"type-heading\", hideTitle && \"sr-only\")}>\n {title}\n </Heading>\n {description != null && <p id={descriptionId} className=\"type-body-sm text-muted-foreground\">{description}</p>}\n </div>\n {closable && <IconButton icon={X} label=\"Close\" onPress={close} className=\"-mr-2 -mt-2 shrink-0\" />}\n </div>\n {children != null && <div className=\"min-h-0 flex-1 overflow-y-auto overscroll-contain\">{children}</div>}\n {actions != null && (\n <div className=\"flex flex-wrap justify-end gap-2\">{typeof actions === \"function\" ? actions(close) : actions}</div>\n )}\n </>\n )}\n </AriaDialog>\n </Modal>\n </ModalOverlay>\n </DialogTrigger>\n );\n}\n\n/** Props for `AlertDialog`. */\nexport type AlertDialogProps = Common & {\n /** The verb, repeating the action: \"Delete 3 firings\". Required; \"OK\" and \"Confirm\" are what this prevents. */\n confirm: string;\n /** Runs on confirm. When it returns a promise the dialog waits, shows the button busy, and stays open with the reason if it rejects. */\n onConfirm: () => void | Promise<unknown>;\n /** The safe choice, which has initial focus. Default \"Cancel\". */\n cancel?: string;\n /** `destructive` fills the confirm button with the destructive role. Default `destructive`. */\n tone?: \"destructive\" | \"default\";\n};\n\n/**\n * A confirm for what cannot be undone. Names the object and the consequence in `title`, repeats the\n * verb on the confirm button, focuses Cancel first and ignores outside presses.\n */\nexport function AlertDialog({\n title, description, trigger, open, onOpenChange, className, confirm, onConfirm, cancel = \"Cancel\", tone = \"destructive\",\n}: AlertDialogProps) {\n const [busy, setBusy] = React.useState(false);\n const [error, setError] = React.useState<string>();\n const [inner, setInner] = React.useState(false);\n const descriptionId = React.useId();\n const isOpen = open ?? inner;\n const change = (next: boolean) => {\n if (busy) return;\n setError(undefined);\n setInner(next);\n onOpenChange?.(next);\n };\n const run = async () => {\n try {\n const result = onConfirm();\n if (result && typeof (result as Promise<unknown>).then === \"function\") {\n setBusy(true);\n await result;\n }\n setBusy(false);\n change(false);\n } catch (thrown) {\n setBusy(false);\n setError(describeActionError(thrown) ?? \"That did not go through. Nothing was confirmed; try again.\");\n }\n };\n return (\n <DialogTrigger isOpen={isOpen} onOpenChange={change}>\n {trigger}\n <ModalOverlay isDismissable={false} isKeyboardDismissDisabled={busy} className={cn(overlayClass, \"place-items-center p-4\")}>\n <Modal className={cn(\"flex max-h-full w-full max-w-sm flex-col outline-none\", overlaySurface, className)}>\n <AriaDialog role=\"alertdialog\" aria-describedby={description != null ? descriptionId : undefined} className=\"flex min-h-0 flex-1 flex-col gap-4 p-4 outline-none\">\n {({ close }) => (\n <>\n {/* The message scrolls inside the dialog on a short window or with large text; the buttons stay in view. */}\n <div className=\"grid min-h-0 gap-3 overflow-y-auto overscroll-contain\">\n <div className=\"grid gap-1\">\n <Heading slot=\"title\" className=\"type-heading\">{title}</Heading>\n {description != null && <p id={descriptionId} className=\"type-body-sm text-muted-foreground\">{description}</p>}\n </div>\n {error && (\n <p role=\"alert\" className=\"rounded-control bg-danger-subtle px-3 py-2 type-body-sm text-danger\">\n {error}\n </p>\n )}\n </div>\n <div className=\"flex flex-wrap justify-end gap-2\">\n <Button autoFocus disabled={busy} onPress={close}>{cancel}</Button>\n <Button variant={tone === \"destructive\" ? \"destructive\" : \"default\"} disabled={busy} aria-busy={busy || undefined} onPress={run}>\n {busy ? `${confirm}…` : confirm}\n </Button>\n </div>\n </>\n )}\n </AriaDialog>\n </Modal>\n </ModalOverlay>\n </DialogTrigger>\n );\n}\n\n","import * as React from \"react\";\nimport { Dialog, DialogTrigger, Popover as AriaPopover } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\nimport { overlaySurface } from \"../lib/overlay\";\n\n// A popover holds a small form or a choice anchored to the control that opened it (a colour, a\n// sort, a few filters) where a dialog would take the whole screen. Unlike a tooltip it may hold\n// anything interactive. React Aria keeps it inside the viewport (flips and shifts at the edges),\n// closes it on Escape and on a press outside, and returns focus to the trigger. It is a labelled\n// `dialog`, so `label` is required: an unnamed floating region is the same defect as an unnamed\n// icon button. It is portalled to the body on `layer-overlay`, so panes and sticky headers cannot\n// clip or cover it.\n\n/** Props for `Popover`. */\nexport type PopoverProps = {\n /** What the popover is, as a screen reader names it: \"Line colour\", \"Filters\". Required. */\n label: string;\n /** The control that opens it (a `Button`); it gets `aria-expanded` and focus back on close. */\n trigger: React.ReactElement;\n children: React.ReactNode;\n side?: \"top\" | \"right\" | \"bottom\" | \"left\";\n /** Where along the trigger it lines up. Default `start`. */\n align?: \"start\" | \"center\" | \"end\";\n /** Controlled open state. */\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n /** Width of the surface. Default `md` (18rem). */\n size?: \"sm\" | \"md\" | \"lg\";\n className?: string;\n};\n\nconst widths = { sm: \"w-52\", md: \"w-72\", lg: \"w-96\" } as const;\n\n/** A floating panel anchored to its trigger, for a small form or choice. Requires a `label`; closes on Escape and outside press, and returns focus. */\nexport function Popover({ label, trigger, children, side = \"bottom\", align = \"start\", open, onOpenChange, size = \"md\", className }: PopoverProps) {\n const placement = (align === \"center\" ? side : `${side} ${align}`) as React.ComponentProps<typeof AriaPopover>[\"placement\"];\n return (\n <DialogTrigger isOpen={open} onOpenChange={onOpenChange}>\n {trigger}\n <AriaPopover placement={placement} offset={6} className={cn(\"layer-overlay p-3\", widths[size], overlaySurface, className)}>\n <Dialog aria-label={label} className=\"outline-none\">\n {children}\n </Dialog>\n </AriaPopover>\n </DialogTrigger>\n );\n}\n","import * as React from \"react\";\nimport { Checkbox as AriaCheckbox } from \"react-aria-components\";\nimport { Check, Minus } from \"lucide-react\";\nimport { cn } from \"../lib/utils\";\n\n// A checkbox cannot be written without a name: `label` is required, as `IconButton`'s is. Shown,\n// it sits beside the box inside one <label>, so the label and the control are a single target\n// with no dead zone between them (Vercel's interface guidelines; ux-design audit.md). Hidden\n// (`hideLabel`, for a table cell where the row already says what it is), it becomes the\n// accessible name through aria-label, never through visually hidden text: a hidden span inside a\n// label joined to a neighbour did not form a name with its space in dom-testing-library (strata-\n// react issue #11), and an aria-label leaves no room for that.\n//\n// It is React Aria's Checkbox (a visually hidden native input inside the label), so keyboard,\n// forms, `aria-checked=\"mixed\"` and press handling are the library's, and the 18px box is drawn\n// from our tokens (it is no longer the platform's `accent-primary` control: that one could not show\n// a tick and a dash in the theme's own roles). `checked=\"mixed\"` is the indeterminate state a\n// select-all needs. It used to be native; the visual baselines changed for it (CHANGELOG).\n//\n// `onCheckedChange` also says whether Shift was held, which is how a list of checkboxes extends a\n// range (strata-react issue #32). A change event carries no modifier keys, so the label notes Shift\n// on the press that leads to it: a mouse press anywhere on the target, or Space on the box.\n\n/** A checkbox with its label as one target. `label` is required; `checked=\"mixed\"` is indeterminate. */\nexport type CheckboxProps = Omit<React.ComponentProps<\"input\">, \"type\" | \"checked\" | \"onChange\" | \"aria-label\" | \"children\" | \"style\"> & {\n /** Names the checkbox. Shown beside it unless `hideLabel`. */\n label: string;\n /** Keep the label as the accessible name only, for a cell or toolbar where the context shows what it is. */\n hideLabel?: boolean;\n /** A muted second line under a shown label. */\n detail?: string;\n checked: boolean | \"mixed\";\n /** Called with the new state, and whether Shift was held (a range click or Shift+Space). */\n onCheckedChange: (checked: boolean, gesture: CheckboxGesture) => void;\n};\n\n/** How a checkbox was changed: `shiftKey` is true for Shift+click and Shift+Space, which extend a range in a list. */\nexport type CheckboxGesture = { shiftKey: boolean };\n\n/** A checkbox and its label as one target. `label` is required; `hideLabel` keeps it as the accessible name only. */\nexport function Checkbox({ label, hideLabel = false, detail, checked, onCheckedChange, className, disabled, required, ...props }: CheckboxProps) {\n const shift = useShiftNote();\n // Shift is noted in the capture phase on a wrapper, because React Aria's press handling stops the\n // events it uses before they bubble. `contents` keeps the wrapper out of layout.\n return (\n <span className=\"contents\" onMouseDownCapture={shift.handlers.onMouseDown} onKeyDownCapture={shift.handlers.onKeyDown}>\n <AriaCheckbox\n isSelected={checked === true}\n isIndeterminate={checked === \"mixed\"}\n isDisabled={disabled}\n isRequired={required}\n onChange={(selected) => onCheckedChange(selected, shift.take())}\n aria-label={hideLabel ? label : undefined}\n {...(props as object)}\n className={cn(\n \"group inline-flex min-h-6 min-w-6 items-start gap-3\",\n hideLabel && \"items-center justify-center\",\n disabled ? \"cursor-not-allowed opacity-50\" : \"cursor-pointer\",\n className,\n )}\n >\n {({ isSelected, isIndeterminate }) => (\n <>\n <span\n aria-hidden\n className={cn(\n \"grid size-4.5 shrink-0 place-items-center rounded-control border border-input bg-background transition-state\",\n \"group-data-[focus-visible]:outline-2 group-data-[focus-visible]:outline-offset-2 group-data-[focus-visible]:outline-ring\",\n (isSelected || isIndeterminate) && \"border-primary bg-primary text-primary-foreground\",\n !hideLabel && \"mt-0.5\",\n )}\n >\n {isIndeterminate ? <Minus className=\"size-3.5\" strokeWidth={3} /> : isSelected ? <Check className=\"size-3.5\" strokeWidth={3} /> : null}\n </span>\n {!hideLabel && (\n <span className=\"grid\">\n <span className=\"type-body\">{label}</span>\n {detail && <span className=\"type-body-sm text-muted-foreground\">{detail}</span>}\n </span>\n )}\n </>\n )}\n </AriaCheckbox>\n </span>\n );\n}\n\n/** Notes Shift on the press that leads to a checkbox's change event, which has no modifier keys of its own. */\nexport function useShiftNote() {\n const held = React.useRef(false);\n return React.useMemo(\n () => ({\n handlers: {\n onMouseDown: (e: React.MouseEvent) => void (held.current = e.shiftKey),\n onKeyDown: (e: React.KeyboardEvent) => void (held.current = e.shiftKey),\n },\n take: (): CheckboxGesture => {\n const shiftKey = held.current;\n held.current = false;\n return { shiftKey };\n },\n }),\n [],\n );\n}\n","import * as React from \"react\";\nimport { Check, CircleAlert, LoaderCircle } from \"lucide-react\";\nimport { Button, type ButtonProps } from \"./button\";\nimport { describeActionError, fieldErrorsOf } from \"../lib/errors\";\n\n// One object through its states: \"Book firing\" becomes \"Booking…\" becomes \"Booked\", in the same\n// button, rather than the button being swapped for a spinner. The labels are stacked in one grid\n// cell so the button is always as wide as its longest label and nothing around it shifts. The\n// button stays enabled until the request starts (so a person can always try), and the outcome is\n// announced politely for screen readers. When the action fails, the announcement carries what\n// went wrong in the product's words before the retry label (\"Kiln 2 is already booked. Try\n// again\"), because \"Try again\" alone does not say whether trying again can help.\n//\n// The button carries `data-phase` (and Button's `data-variant`), so a test reads which phase it is\n// in without matching four stacked labels in its text (strata-react issue #48); `asyncButtonPhase`\n// in strata-react/testing reads it.\n//\n// `useAsyncAction` also owns a form's field messages (strata-react issues #42 and #46). `validate`\n// runs before the action, and messages it returns stop the run and land on `fieldErrors`, keyed by\n// field; a server's per-field messages (an HttpError's `fieldErrors`, from a 422) land there too.\n// A screen passes `fieldErrors.link` to `Field error=` and keeps no `problem` state of its own.\n// Failing validation leaves the button idle, not \"Try again\": nothing was tried. `onInvalid` runs\n// once the messages are on screen, to move focus to the first field named.\n\nexport type Phase = \"idle\" | \"pending\" | \"done\" | \"error\";\n\nexport type AsyncLabels = {\n idle: string;\n /** Ends in an ellipsis: \"Saving…\", \"Booking…\". */\n pending: string;\n /** The same verb, finished: \"Saved\", \"Booked\". */\n done: string;\n error?: string;\n};\n\n/** One button through idle, pending, done and error, with the label changing in place and its width fixed by the longest label. The outcome is announced politely, with the error's own words when `error` is given. */\nexport function AsyncButton({\n phase,\n labels,\n error,\n disabled,\n ...props\n}: Omit<ButtonProps, \"children\"> & {\n phase: Phase;\n labels: AsyncLabels;\n /** What went wrong, in the product's words (`useAsyncAction`'s `error`). Announced with the error label when `phase` is `error`. */\n error?: string;\n}) {\n const errorLabel = labels.error ?? \"Try again\";\n const current = { idle: labels.idle, pending: labels.pending, done: labels.done, error: errorLabel }[phase];\n const Icon = { idle: null, pending: LoaderCircle, done: Check, error: CircleAlert }[phase];\n const announcement = phase === \"done\" ? labels.done : phase === \"error\" ? (error ? `${error} ${errorLabel}` : errorLabel) : \"\";\n\n return (\n <>\n <Button {...props} data-phase={phase} disabled={disabled || phase === \"pending\"} aria-disabled={phase === \"pending\" || undefined}>\n {Icon && <Icon aria-hidden className={phase === \"pending\" ? \"motion-safe:animate-spin\" : undefined} />}\n <span className=\"grid\">\n {[labels.idle, labels.pending, labels.done, errorLabel].map((l) => (\n <span key={l} aria-hidden={l !== current} className={l === current ? \"[grid-area:1/1]\" : \"invisible [grid-area:1/1]\"}>\n {l}\n </span>\n ))}\n </span>\n </Button>\n <span role=\"status\" className=\"sr-only\">\n {announcement}\n </span>\n </>\n );\n}\n\n/** Messages for a form's fields, keyed by field name. */\nexport type FieldErrors = Readonly<Record<string, string>>;\n\n/** Options for `useAsyncAction`. */\nexport type AsyncActionOptions<A extends unknown[] = unknown[]> = {\n /** How long `done` shows before returning to `idle`. Default 2000ms. */\n settleMs?: number;\n /** Called with whatever the action threw, once the `error` render has committed: for logging, or to move focus to the retry button or an error message. */\n onError?: (error: unknown) => void;\n /** Turns what was thrown into `error`'s sentence, in the product's words. Default `describeActionError`: HTTP status sentences for `fetchJson`'s `HttpError`, else the Error's message. */\n describeError?: (error: unknown) => string | undefined;\n /** Checks the arguments before the action runs. A message for any field stops the run and is put on `fieldErrors`; the button stays idle. */\n validate?: (...args: A) => Record<string, string | undefined> | undefined;\n /** Called once validation's messages are on screen: to move focus to the first field named. */\n onInvalid?: (fieldErrors: FieldErrors) => void;\n};\n\n/** What `useAsyncAction` returns: the phase for `AsyncButton`, a stable `run`, and what went wrong while `phase` is `error`. */\nexport type AsyncAction<A extends unknown[]> = {\n phase: Phase;\n run: (...args: A) => Promise<void>;\n /** What went wrong, from `describeError`, while `phase` is `error`; otherwise undefined. Pass it to `AsyncButton`'s `error`. */\n error: string | undefined;\n /** What the action threw, while `phase` is `error`: to read more than the sentence (an HttpError's `status` or `body`). */\n thrown: unknown;\n /** Messages per field, from `validate` or from the server (an HttpError's `fieldErrors`). Pass each to its `Field`'s `error`. Cleared by the next run. */\n fieldErrors: FieldErrors;\n /** Clears one field's message (as the person edits it), or all of them. */\n clearFieldError: (field?: string) => void;\n};\n\n// The action and its options are read through a ref so `run` keeps one identity for the\n// component's life: a caller can pass an inline arrow without re-rendering every child that takes\n// `run`, and without the try/catch and error state each caller used to write to reach the phase.\n\n/** Runs an async action and reports its phase, its error and any field messages. `done` returns to `idle` after `settleMs`; `run` never changes identity. */\nexport function useAsyncAction<A extends unknown[]>(\n action: (...args: A) => Promise<unknown>,\n { settleMs = 2000, onError, describeError = describeActionError, validate, onInvalid }: AsyncActionOptions<A> = {},\n): AsyncAction<A> {\n const [state, setState] = React.useState<ActionState>(idle);\n const timer = React.useRef<number | undefined>(undefined);\n const unreported = React.useRef<{ thrown: unknown } | { invalid: FieldErrors } | undefined>(undefined);\n const latest = React.useRef({ action, onError, settleMs, describeError, validate, onInvalid });\n React.useLayoutEffect(() => {\n latest.current = { action, onError, settleMs, describeError, validate, onInvalid };\n });\n React.useEffect(() => () => window.clearTimeout(timer.current), []);\n const run = React.useCallback(async (...args: A) => {\n window.clearTimeout(timer.current);\n const invalid = messages(latest.current.validate?.(...args));\n if (invalid) {\n unreported.current = { invalid };\n setState({ ...idle, fieldErrors: invalid });\n return;\n }\n setState({ ...idle, phase: \"pending\" });\n try {\n await latest.current.action(...args);\n setState({ ...idle, phase: \"done\" });\n timer.current = window.setTimeout(() => setState(idle), latest.current.settleMs);\n } catch (thrown) {\n unreported.current = { thrown };\n setState({ phase: \"error\", error: latest.current.describeError(thrown), thrown, fieldErrors: fieldErrorsOf(thrown) });\n }\n }, []);\n // onError and onInvalid run after their render commits, not inside run: there the button is\n // still disabled from `pending` and a message rendered on `error` does not exist yet, so a\n // callback that moves focus to either would find nothing to focus.\n React.useEffect(() => {\n const note = unreported.current;\n if (!note) return;\n if (\"thrown\" in note && state.phase === \"error\") latest.current.onError?.(note.thrown);\n else if (\"invalid\" in note) latest.current.onInvalid?.(note.invalid);\n else return;\n unreported.current = undefined;\n }, [state]);\n const clearFieldError = React.useCallback(\n (field?: string) =>\n setState((s) => {\n if (field === undefined) return Object.keys(s.fieldErrors).length ? { ...s, fieldErrors: {} } : s;\n if (!(field in s.fieldErrors)) return s;\n const { [field]: _gone, ...rest } = s.fieldErrors;\n return { ...s, fieldErrors: rest };\n }),\n [],\n );\n return { phase: state.phase, run, error: state.error, thrown: state.thrown, fieldErrors: state.fieldErrors, clearFieldError };\n}\n\ntype ActionState = { phase: Phase; error: string | undefined; thrown: unknown; fieldErrors: FieldErrors };\nconst idle: ActionState = { phase: \"idle\", error: undefined, thrown: undefined, fieldErrors: {} };\n\n/** The messages `validate` returned, without the empty ones; undefined when there are none. */\nfunction messages(found: Record<string, string | undefined> | undefined): FieldErrors | undefined {\n if (!found) return undefined;\n const kept = Object.fromEntries(Object.entries(found).filter((e): e is [string, string] => Boolean(e[1])));\n return Object.keys(kept).length ? kept : undefined;\n}\n","import type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\n\n// Status is a word first. `children` is required and must be a string, so a status can never be a\n// bare coloured dot. The tint and ink come from the fixed status roles, which are kept apart from\n// the brand accent: pale tint, dark ink of the same hue, never a saturated chip with white text.\n// No pulsing variant exists; nothing on a status mark moves unless the data behind it is live.\n\nexport type Tone = \"neutral\" | \"info\" | \"success\" | \"warning\" | \"danger\";\n\nconst tones: Record<Tone, string> = {\n neutral: \"bg-muted text-muted-foreground\",\n info: \"bg-info-subtle text-info\",\n success: \"bg-success-subtle text-success\",\n warning: \"bg-warning-subtle text-warning\",\n danger: \"bg-danger-subtle text-danger\",\n};\n\n/** A status as a word on a pale tint of its tone, with an optional icon. Never colour alone. */\nexport function Status({\n tone,\n icon: Icon,\n children,\n className,\n}: {\n tone: Tone;\n icon?: IconComponent;\n children: string;\n className?: string;\n}) {\n return (\n <span\n className={cn(\n \"inline-flex items-center gap-1.5 whitespace-nowrap rounded-pill py-0.5 pr-2.5 pl-2 type-caption font-medium\",\n tones[tone],\n className,\n )}\n >\n {Icon && <Icon aria-hidden className=\"size-3.5 shrink-0\" />}\n {children}\n </span>\n );\n}\n","import * as React from \"react\";\nimport { cn } from \"../lib/utils\";\n\n// Headline figures as one container split by hairlines, label over value: what real product screens\n// do, instead of four cards each with an icon in a tinted circle. There is deliberately no `icon`,\n// `sparkline` or `trend` prop. A change is written in words with its window (\"4 more than last\n// Thursday\"), because a green \"+12.5%\" pill says neither what changed nor since when, and the trend\n// gets its own chart.\n\n/** Headline figures as one description list split by hairlines. Holds `Metric`s. */\nexport function MetricStrip({ label, children, className }: { label: string; children: React.ReactNode; className?: string }) {\n return (\n <dl\n aria-label={label}\n className={cn(\n \"grid grid-cols-1 border-y border-border sm:auto-cols-fr sm:grid-flow-col sm:divide-x sm:divide-border\",\n className,\n )}\n >\n {children}\n </dl>\n );\n}\n\nexport type MetricProps = {\n label: string;\n /** Already formatted. Ink colour, 28px, tabular figures: never the brand colour, never 48px. */\n value: string;\n unit?: string;\n /** One sentence: the change in words with its window, or what the figure means right now. */\n note?: React.ReactNode;\n};\n\n/** One figure: label over value, an optional muted unit and a note that states any change in words with its window. */\nexport function Metric({ label, value, unit, note }: MetricProps) {\n return (\n <div className=\"grid content-start gap-0.5 border-border py-3 not-first:border-t sm:px-5 sm:not-first:border-t-0 sm:first:pl-0\">\n <dt className=\"type-label text-muted-foreground\">{label}</dt>\n <dd className=\"type-figure text-foreground\">\n {value}\n {unit && <span className=\"type-body text-muted-foreground\">{\" \" + unit}</span>}\n </dd>\n {note && <dd className=\"type-body-sm text-muted-foreground\">{note}</dd>}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { format } from \"../lib/format\";\nimport { cn } from \"../lib/utils\";\nimport { Status } from \"./status\";\n\n// A usage bar: how full one thing is (a disk, a quota, a kiln's shelves), for status dashboards\n// that otherwise hand-roll a div with a width (strata-react issue #25, from jburnhams/homepage).\n// The rules it encodes, from ux-research ui-library/components.md §3.8 and patterns.md §5:\n// - It is a `meter`, not a `progressbar`: a progress bar is a task moving to done, a meter is a\n// level that can go up or down. Its accessible name is what is measured (\"Disk /\") and its\n// value text says the reading in words (\"72% used\"), so a screen reader hears \"Disk /, meter,\n// 72% used\" rather than a bare 72.\n// - The figure is always printed beside the bar. A bar alone is read to ±10% at best.\n// - Thresholds are what the person compares against, so they are drawn on the track as notches,\n// like LineChart's `band`. Each threshold must name its state (\"Filling up\", \"Nearly full\"):\n// when the reading crosses one, the fill takes the status ink and the word is shown as a\n// `Status`, so colour is never the only cue. Thresholds are shares of `max` (0.8 is 80%),\n// because a dashboard of disks of different sizes shares one set of them.\n// - `worseWhen=\"lower\"` turns the thresholds round for levels where empty is the problem (a\n// battery, credit left): a threshold then applies at or below its share.\n// - Below every threshold the fill is one chart hue (`--chart-1` unless `colour` says otherwise),\n// the same default as LineChart, never the brand accent and never a status colour, since\n// \"fine\" needs no colour of its own.\n// - `hideLabel` is for a meter in a table row, where the row already says what it measures; the\n// label stays as the meter's accessible name.\n// - No animation on the fill: a dashboard re-renders readings, and a bar that slides on each one\n// draws the eye to nothing.\n\n/** A level on a `Meter` at which the reading changes state, with the word for that state. */\nexport type MeterThreshold = {\n /** A share of `max`, from 0 to 1: 0.8 is 80%. */\n at: number;\n tone: \"warning\" | \"danger\";\n /** What the state is called, in the product's words: \"Filling up\", \"Nearly full\". */\n label: string;\n};\n\nexport type MeterProps = {\n /** What is measured, such as \"Disk /\". The meter's accessible name. */\n label: string;\n value: number;\n /** The full scale, in the same units as `value`. Defaults to 1, so a share can be passed as is. */\n max?: number;\n /** The reading in words, shown beside the bar and used as `aria-valuetext`. Defaults to \"72% used\". */\n valueText?: string;\n /** A second line of fact, such as \"36 of 50 GB\". */\n detail?: React.ReactNode;\n thresholds?: MeterThreshold[];\n /** \"lower\" when an emptier reading is the worse one (a battery, credit left). */\n worseWhen?: \"higher\" | \"lower\";\n /** Keeps the label as the accessible name only, for a meter in a table row that names it. */\n hideLabel?: boolean;\n /** CSS colour for the fill below every threshold. Defaults to the first chart token. */\n colour?: string;\n className?: string;\n};\n\n/** The threshold a share has crossed, if any: the most severe one reached in the worse direction. */\nexport function crossedThreshold(\n share: number,\n thresholds: readonly MeterThreshold[] = [],\n worseWhen: \"higher\" | \"lower\" = \"higher\",\n): MeterThreshold | undefined {\n const reached = thresholds.filter((t) => (worseWhen === \"higher\" ? share >= t.at : share <= t.at));\n // The one furthest in the worse direction wins, so danger beats warning when both are reached.\n return reached.sort((a, b) => (worseWhen === \"higher\" ? b.at - a.at : a.at - b.at))[0];\n}\n\nconst fills = { warning: \"var(--warning)\", danger: \"var(--danger)\" } as const;\n\n/** How full one thing is: a labelled `meter` with its reading in words, threshold notches, and a status word once a threshold is crossed. */\nexport function Meter({\n label,\n value,\n max = 1,\n valueText,\n detail,\n thresholds,\n worseWhen = \"higher\",\n hideLabel = false,\n colour = \"var(--chart-1)\",\n className,\n}: MeterProps) {\n const labelId = React.useId();\n const statusId = React.useId();\n const detailId = React.useId();\n const share = max > 0 ? Math.min(1, Math.max(0, value / max)) : 0;\n const crossed = crossedThreshold(share, thresholds, worseWhen);\n // `share`, not `percent`: a disk with a little on it reads \"<1% used\", never \"0% used\".\n const text = valueText ?? `${format.share(share)} used`;\n const hasNote = Boolean(crossed || detail);\n // Two ids rather than one wrapper, so the description reads \"Nearly full, 431 GB of 466 GB\"\n // with a break between the parts instead of running them together.\n const describedBy = [crossed && statusId, detail && detailId].filter(Boolean).join(\" \") || undefined;\n\n const bar = (\n <div\n role=\"meter\"\n aria-labelledby={hideLabel ? undefined : labelId}\n aria-label={hideLabel ? label : undefined}\n aria-valuemin={0}\n aria-valuemax={max}\n aria-valuenow={Math.min(max, Math.max(0, value))}\n aria-valuetext={text}\n aria-describedby={describedBy}\n className=\"relative h-2 min-w-16 flex-1 overflow-hidden rounded-pill bg-muted\"\n >\n <div\n className=\"absolute inset-y-0 left-0\"\n style={{ width: `${share * 100}%`, background: crossed ? fills[crossed.tone] : colour }}\n />\n {/* Notches in the ground colour: the levels the reading is judged against. */}\n {thresholds?.map((t) => (\n <div\n key={t.at}\n className=\"absolute inset-y-0 w-0.5 -translate-x-1/2 bg-background\"\n style={{ left: `${Math.min(1, Math.max(0, t.at)) * 100}%` }}\n />\n ))}\n </div>\n );\n\n // The visible figure is the meter's value text, so it is hidden from the accessibility tree\n // rather than read twice.\n const figure = (\n <span aria-hidden className=\"shrink-0 type-body-sm tabular-nums text-foreground\">\n {text}\n </span>\n );\n\n const note = hasNote && (\n <div className=\"flex flex-wrap items-center gap-x-3 gap-y-1\">\n {crossed && (\n <span id={statusId} className=\"contents\">\n <Status tone={crossed.tone}>{crossed.label}</Status>\n </span>\n )}\n {detail && (\n <span id={detailId} className=\"type-body-sm text-muted-foreground tabular-nums\">\n {detail}\n </span>\n )}\n </div>\n );\n\n if (hideLabel) {\n return (\n <div className={cn(\"grid min-w-0 gap-1.5\", className)}>\n <div className=\"flex items-center gap-3\">\n {bar}\n {figure}\n </div>\n {note}\n </div>\n );\n }\n\n return (\n <div className={cn(\"grid min-w-0 gap-1.5\", className)}>\n <div className=\"flex items-baseline justify-between gap-3\">\n <span id={labelId} className=\"min-w-0 truncate type-label text-foreground\">\n {label}\n </span>\n {figure}\n </div>\n <div className=\"flex\">{bar}</div>\n {note}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { format } from \"../lib/format\";\nimport { cn } from \"../lib/utils\";\n\n// What a whole is made of (memory: used, cached, buffers, free; a kiln load: bisque, glaze, empty\n// shelves), as one stacked bar over a table. strata-react issue #25 asked for it after\n// jburnhams/homepage hand-rolled one. The rules, from ux-research ui-library/components.md §3.8\n// and patterns.md §5:\n// - Colour is never the only cue. The bar shows proportion at a glance; the table under it says\n// every part's name, amount and share in words, with a swatch that ties the row to its\n// segment. The bar is hidden from screen readers because the table already carries all of it.\n// - The parts stay in the order given, in the bar and the table, so the order is the caller's\n// meaning (used before cached before free), not sorted by size.\n// - Categorical colours come from `--chart-1…5` in order, which palette.mjs checks are told apart\n// by colour-blind readers. A sixth part has no token to take, so it must bring its own colour;\n// more than five parts usually means the small ones belong in an \"Other\" part.\n// - Segments are split by a 2px gap in the ground colour, so two neighbours of similar lightness\n// still read as two.\n// - When the parts do not fill the whole (`total` is larger than their sum), the remainder is the\n// empty track, and it must be named (`restLabel`, such as \"Free\"), so the table can say what the\n// gap is. Neither the remainder nor a part is ever left unlabelled.\n// - Values are formatted by the caller (`formatValue`), as LineChart's `formatY` is, so units stay\n// the product's; shares go through `format.share` unless `formatShare` says otherwise.\n// - A part that is there is never shown as nothing (strata-react issue #43: 2.4 GB of a 512 GB\n// disk read \"0%\"). Its share prints \"<1%\" (`format.share`), and its segment keeps a 4px sliver\n// however small it is; the table carries the exact figure.\n\n/** One part of a `CompositionBar`'s whole. */\nexport type CompositionPart = {\n /** Stable key for the part. */\n key: string;\n label: string;\n value: number;\n /** CSS colour for the segment and swatch. Defaults to the chart token for its position. */\n colour?: string;\n};\n\nexport type CompositionBarProps = {\n /** What the whole is, such as \"Memory\". Shown above the bar and names the table. */\n label: string;\n parts: CompositionPart[];\n formatValue: (value: number) => string;\n /** Formats a part's share of the whole (0 to 1). Defaults to `format.share` (\"<1%\" for a part that rounds to 0). */\n formatShare?: (share: number) => string;\n /** Header of the parts column, for screen readers and over the table. Defaults to \"Part\". */\n partHeader?: string;\n /** Header of the amounts column. Defaults to \"Amount\". */\n valueHeader?: string;\n /** Header of the shares column. Defaults to \"Share\". */\n shareHeader?: string;\n className?: string;\n} & (\n | {\n /** The size of the whole, when the parts do not fill it. The remainder is the empty track. */\n total: number;\n /** What the remainder is called (\"Free\", \"Empty shelves\"). Required with `total`. */\n restLabel: string;\n }\n | { total?: undefined; restLabel?: undefined }\n);\n\nconst MAX_TOKENS = 5;\n\n/** A part's colour: its own, or the chart token for its position. Throws past the fifth token. */\nfunction colourFor(part: CompositionPart, index: number) {\n if (part.colour) return part.colour;\n if (index >= MAX_TOKENS) {\n throw new Error(\n `CompositionBar: part \"${part.label}\" is number ${index + 1}, and there are only ${MAX_TOKENS} chart colours. ` +\n `Combine the smallest parts into one \"Other\" part, or give this part a colour.`,\n );\n }\n return `var(--chart-${index + 1})`;\n}\n\n/** What a whole is made of: a stacked bar for proportion and a table that names every part, its amount and its share, so colour is never the only cue. */\nexport function CompositionBar({\n label,\n parts,\n formatValue,\n formatShare = format.share,\n partHeader = \"Part\",\n valueHeader = \"Amount\",\n shareHeader = \"Share\",\n className,\n ...whole\n}: CompositionBarProps) {\n const captionId = React.useId();\n const sum = parts.reduce((n, p) => n + Math.max(0, p.value), 0);\n const total = Math.max(whole.total ?? sum, sum);\n const rest = whole.total !== undefined ? total - sum : 0;\n const shareOf = (value: number) => (total > 0 ? Math.max(0, value) / total : 0);\n const rows = parts.map((p, i) => ({ ...p, colour: colourFor(p, i), share: shareOf(p.value) }));\n\n return (\n <figure className={cn(\"grid min-w-0 gap-3\", className)}>\n <figcaption id={captionId} className=\"type-label text-foreground\">\n {label}\n </figcaption>\n <div aria-hidden className=\"flex h-3 gap-0.5 overflow-hidden rounded-pill bg-muted\">\n {rows\n .filter((r) => r.value > 0)\n .map((r) => (\n // Grow by share from a zero basis, so the gaps come out of every segment fairly and the\n // parts fill the track exactly. Shares, not raw values: flex-grow factors that sum to\n // less than 1 fill only that fraction of the track (found in review).\n <div key={r.key} className=\"h-full min-w-1\" style={{ flex: `${r.share} 1 0`, background: r.colour }} />\n ))}\n {rest > 0 && <div className=\"h-full min-w-0\" style={{ flex: `${shareOf(rest)} 1 0` }} />}\n </div>\n <table aria-labelledby={captionId} className=\"w-full border-collapse type-body-sm\">\n <thead className=\"sr-only\">\n <tr>\n <th scope=\"col\">{partHeader}</th>\n <th scope=\"col\">{valueHeader}</th>\n <th scope=\"col\">{shareHeader}</th>\n </tr>\n </thead>\n <tbody>\n {rows.map((r) => (\n <tr key={r.key} className=\"border-t border-border first:border-t-0\">\n <th scope=\"row\" className=\"py-1.5 pr-4 text-left font-normal\">\n <span className=\"inline-flex items-center gap-2\">\n <span aria-hidden className=\"size-3 shrink-0 rounded-control\" style={{ background: r.colour }} />\n {r.label}\n </span>\n </th>\n <td className=\"py-1.5 pr-4 text-right tabular-nums\">{formatValue(r.value)}</td>\n <td className=\"w-px py-1.5 text-right whitespace-nowrap text-muted-foreground tabular-nums\">\n {formatShare(r.share)}\n </td>\n </tr>\n ))}\n {whole.total !== undefined && (\n <tr className=\"border-t border-border\">\n <th scope=\"row\" className=\"py-1.5 pr-4 text-left font-normal\">\n <span className=\"inline-flex items-center gap-2\">\n {/* The empty track's colour with a hairline, so the swatch reads as \"nothing here\". */}\n <span aria-hidden className=\"size-3 shrink-0 rounded-control border border-border bg-muted\" />\n {whole.restLabel}\n </span>\n </th>\n <td className=\"py-1.5 pr-4 text-right tabular-nums\">{formatValue(rest)}</td>\n <td className=\"w-px py-1.5 text-right whitespace-nowrap text-muted-foreground tabular-nums\">\n {formatShare(shareOf(rest))}\n </td>\n </tr>\n )}\n </tbody>\n </table>\n </figure>\n );\n}\n","import * as React from \"react\";\nimport { Link, type To } from \"react-router\";\nimport { ArrowUpRight } from \"lucide-react\";\nimport { cn } from \"../lib/utils\";\n\n// A card that is a way to somewhere: an app on a homepage, a project in a list of projects.\n// strata-react issue #25 asked for it after jburnhams/homepage built `AppCard` by hand. A card is\n// right here because each destination *is* a separate object a person picks (ux-research\n// ui-library/patterns.md §3); a section of a screen is not, and gets space and hairlines instead.\n// - The whole card is the target, but it is one link with a short name. The link sits on the\n// title and its `::after` covers the card, so a pointer can press anywhere while a screen reader\n// hears \"Kiln log, link\" and then the description and status marks as its description, instead\n// of a link named with every word on the card. There is one tab stop per card.\n// - Because the whole card is one link, nothing else on it can be interactive (a button or a\n// second link inside a link is invalid and unreachable). `marks` is for `Status` words only.\n// - Status marks are words (`Status`), never a coloured dot in a corner.\n// - `to` is a route in this app (React Router's `Link`); `href` leaves it (a plain anchor) and is\n// marked with an arrow, so a person knows before pressing that they will leave.\n// - Hover and focus change the border and draw the ring around the card, not the title. There is\n// no lift, scale or shadow: elevation is for what floats above the page, and a card on a\n// homepage is pressed many times a day (ux-research ux-character.md, character by frequency).\n\n/** A destination card's props: `to` for a route in this app, or `href` for anywhere else, never both. */\nexport type LinkCardProps = (\n | {\n /** A route in this app, followed with React Router. */\n to: To;\n href?: undefined;\n }\n | {\n /** Somewhere outside this app; the card shows an arrow. */\n href: string;\n to?: undefined;\n }\n) & {\n /** The destination's name, and the link's accessible name. */\n title: string;\n /** One sentence on what is there. Read as the link's description. */\n description?: string;\n /** `Status` words about the destination (\"Running\", \"Updated today\"). Nothing interactive. */\n marks?: React.ReactNode;\n /** The title's element. h3 under a section heading; h2 when the cards are the page's sections. */\n as?: \"h2\" | \"h3\" | \"h4\";\n className?: string;\n};\n\n/** A destination as a card that is one link: its title is the link's name, the description and status marks are its description, and the whole card is the target. */\nexport function LinkCard({ title, description, marks, as: Heading = \"h3\", className, ...destination }: LinkCardProps) {\n const descriptionId = React.useId();\n const marksId = React.useId();\n const describedBy = [description && descriptionId, marks && marksId].filter(Boolean).join(\" \") || undefined;\n const linkClass =\n \"rounded-control outline-none after:absolute after:inset-0 after:rounded-surface\";\n\n return (\n <div\n className={cn(\n \"relative grid content-start gap-1.5 rounded-surface border border-border bg-background p-4 transition-state\",\n \"hover:border-muted-foreground has-focus-visible:outline-2 has-focus-visible:outline-offset-2 has-focus-visible:outline-ring\",\n className,\n )}\n >\n <Heading className=\"flex items-start justify-between gap-3 type-heading text-foreground\">\n {destination.href !== undefined ? (\n <>\n <a href={destination.href} aria-describedby={describedBy} className={linkClass}>\n {title}\n </a>\n <ArrowUpRight aria-hidden className=\"mt-0.5 size-4 shrink-0 text-muted-foreground\" />\n </>\n ) : (\n <Link to={destination.to} aria-describedby={describedBy} className={linkClass}>\n {title}\n </Link>\n )}\n </Heading>\n {description && (\n <p id={descriptionId} className=\"type-body-sm text-pretty text-muted-foreground\">\n {description}\n </p>\n )}\n {marks && (\n <div id={marksId} className=\"mt-1.5 flex flex-wrap gap-2\">\n {marks}\n </div>\n )}\n </div>\n );\n}\n\n/** A labelled list of `LinkCard`s in a grid: one column on a phone, up to three on a wide screen. */\nexport function LinkCardList({ label, children, className }: { label: string; children: React.ReactNode; className?: string }) {\n return (\n <ul aria-label={label} className={cn(\"grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3\", className)}>\n {React.Children.toArray(children).map((child, i) => (\n <li key={React.isValidElement(child) && child.key != null ? child.key : i} className=\"grid\">\n {child}\n </li>\n ))}\n </ul>\n );\n}\n","import * as React from \"react\";\nimport { CircleAlert, History, RotateCcw } from \"lucide-react\";\nimport { Button } from \"./button\";\nimport { format } from \"../lib/format\";\nimport { cn } from \"../lib/utils\";\n\n// Every view of remote data goes through DataView, and DataView will not type-check without a\n// skeleton and an empty state. Generated UI renders the happy path; this makes the other three\n// states part of the component's signature rather than a review comment.\n//\n// A failed refresh is not a failed read (strata-react issue #26). Once data has arrived, a later\n// refetch that fails (a poll while the server restarts, a Try again on a flaky link) leaves the\n// data on screen with `stale` set: a polite notice above it says what happened, when the data\n// shown was read, and offers Try again. Swapping a whole dashboard for an error panel throws away\n// readings the person was using, and a silent failure lets them act on old numbers as if live, so\n// the data stays and its age is said in words. Only a read that never produced data is an error.\n//\n// The failed read's look is replaceable (strata-react issue #50): an app with a second look (the\n// Tubes viewer, with its own tokens and pill buttons) passes `error`, a render function given the\n// message and the retry, and keeps the state machine (loading, error, ready, stale, empty) rather\n// than copying DataView to change one panel. Whatever it draws sits inside a `role=\"alert\"` box,\n// so the failure is still announced; the default is `LoadError`, exported for reuse.\n\n/** Data still shown after a refresh failed: why the refresh failed, when the data was read, and the Try again. */\nexport type Stale = {\n /** Why the refresh failed, for a person: the sentence an error panel would have shown. */\n message: string;\n /** When the data on screen was read. */\n readAt: Date;\n /** Fetch again. */\n retry: () => void;\n /** A fetch is on its way (a Try again or the next poll). */\n retrying?: boolean;\n};\n\n/** The state of one remote read, for `DataView`: loading, failed with no data, or ready (and `stale` when a later refresh failed). */\nexport type Load<T> =\n | { status: \"loading\" }\n | { status: \"error\"; message: string; retry: () => void }\n | { status: \"ready\"; data: T; stale?: Stale };\n\n/** What a failed read hands to an `error` renderer: the sentence for a person, and the Try again. */\nexport type LoadFailure = { message: string; retry: () => void };\n\n/** The default failed-read panel: the reason on the danger tint, with Try again. Its parent carries `role=\"alert\"`. */\nexport function LoadError({ message, retry, className }: LoadFailure & { className?: string }) {\n return (\n <div className={cn(\"flex flex-wrap items-start gap-3 rounded-surface bg-danger-subtle p-4 text-danger\", className)}>\n <CircleAlert aria-hidden className=\"mt-0.5 size-5 shrink-0\" />\n <p className=\"min-w-0 flex-1 type-body\">{message}</p>\n <Button size=\"sm\" onClick={retry}>\n <RotateCcw aria-hidden />\n Try again\n </Button>\n </div>\n );\n}\n\nconst defaultError = (failure: LoadFailure) => <LoadError {...failure} />;\n\n/** Every view of remote data: renders `skeleton` while loading, an alert with Try again on error, `empty` when `isEmpty`, else `children(data)`, under a `StaleNotice` when a refresh failed. The skeleton and empty state are required. */\nexport function DataView<T>({\n state,\n isEmpty,\n skeleton,\n empty,\n children,\n staleNotice = (stale) => <StaleNotice stale={stale} />,\n error = defaultError,\n className,\n}: {\n state: Load<T>;\n /** When the loaded data counts as empty. For arrays, `(rows) => rows.length === 0`. */\n isEmpty: (data: T) => boolean;\n /** Mirrors the final layout, so nothing jumps when data arrives. Not a centred spinner. */\n skeleton: React.ReactNode;\n /** What goes here and how to add it. An `EmptyState`, not an illustration. */\n empty: React.ReactNode;\n children: (data: T) => React.ReactNode;\n /** Shown above the data when a refresh failed. Defaults to a `StaleNotice`; pass one with the product's words for what is old (\"Readings from 13:50\"). */\n staleNotice?: (stale: Stale) => React.ReactNode;\n /** Draws a read that failed with no data, given the message and the retry. Defaults to `LoadError`. Rendered inside a `role=\"alert\"` box. */\n error?: (failure: LoadFailure) => React.ReactNode;\n className?: string;\n}) {\n return (\n <div className={cn(\"min-w-0\", className)} aria-busy={state.status === \"loading\" || undefined}>\n {state.status === \"loading\" && skeleton}\n {state.status === \"error\" && <div role=\"alert\">{error({ message: state.message, retry: state.retry })}</div>}\n {state.status === \"ready\" && (\n <>\n {state.stale && staleNotice(state.stale)}\n {isEmpty(state.data) ? empty : children(state.data)}\n </>\n )}\n </div>\n );\n}\n\n/** When `readAt` was, for a person: the clock time today, else the weekday and time. */\nfunction readTime(readAt: Date, now = new Date()) {\n return readAt.toDateString() === now.toDateString() ? format.clock.format(readAt) : format.shortDay.format(readAt);\n}\n\n/** The notice over data whose refresh failed: what happened, how old the data shown is, and Try again. A polite status, not an alert: nothing was lost. */\nexport function StaleNotice({\n stale,\n shown,\n className,\n}: {\n stale: Stale;\n /** What is old, in the product's words, given when it was read (\"13:50\", or \"Sat 13:50\" before today). Defaults to \"Showing data from 13:50.\" */\n shown?: (when: string) => React.ReactNode;\n className?: string;\n}) {\n return (\n <div role=\"status\" className={cn(\"mb-4 flex flex-wrap items-start gap-3 rounded-surface bg-warning-subtle p-3 text-warning\", className)}>\n <History aria-hidden className=\"mt-0.5 size-4 shrink-0\" />\n <p className=\"min-w-0 flex-1 type-body-sm\">\n {stale.message} {shown ? shown(readTime(stale.readAt)) : `Showing data from ${readTime(stale.readAt)}.`}\n </p>\n <Button size=\"sm\" onClick={stale.retry} disabled={stale.retrying}>\n <RotateCcw aria-hidden />\n {stale.retrying ? \"Trying again…\" : \"Try again\"}\n </Button>\n </div>\n );\n}\n\n// An empty state teaches the next action. No illustration slot exists, on purpose.\n/** An empty state that teaches the next action: a title, a sentence and an action. No illustration slot, on purpose. */\nexport function EmptyState({ title, children, action }: { title: string; children?: React.ReactNode; action?: React.ReactNode }) {\n return (\n <div className=\"grid justify-items-start gap-2 border-y border-border py-6\">\n <p className=\"type-heading\">{title}</p>\n {children && <p className=\"max-w-prose type-body text-muted-foreground\">{children}</p>}\n {action && <div className=\"mt-2\">{action}</div>}\n </div>\n );\n}\n\n/** A placeholder block for a loading layout. Size it with layout classes so it mirrors the final content. */\nexport function Skeleton({ className }: { className?: string }) {\n return <div aria-hidden className={cn(\"rounded-control bg-muted motion-safe:animate-pulse\", className)} />;\n}\n","// Colour rules for `ColorField` (issue #73): reading a typed hex, and the WCAG contrast ratio\n// against what the colour is drawn on, which a user-chosen colour (content, not theme) is checked\n// with. Number parsing and stepping are React Aria's.\n\n/** Reads `#rgb`, `#rrggbb` (with or without the #) as lower-case `#rrggbb`, or null. */\nexport function parseHex(text: string): string | null {\n const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(text.trim());\n if (!m) return null;\n const h = m[1].toLowerCase();\n return \"#\" + (h.length === 3 ? [...h].map((c) => c + c).join(\"\") : h);\n}\n\nfunction luminance(hex: string): number {\n const v = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255).map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));\n return 0.2126 * v[0] + 0.7152 * v[1] + 0.0722 * v[2];\n}\n\n/** WCAG contrast ratio between two `#rrggbb` colours, 1 to 21. */\nexport function contrastRatio(a: string, b: string): number {\n const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);\n return (hi + 0.05) / (lo + 0.05);\n}\n","import * as React from \"react\";\nimport {\n I18nProvider,\n Input as AriaInput,\n NumberField as AriaNumberField,\n Slider as AriaSlider,\n SliderOutput,\n SliderThumb,\n SliderTrack,\n} from \"react-aria-components\";\nimport { useFieldControl } from \"./field\";\nimport { NBSP, format } from \"../lib/format\";\nimport { contrastRatio, parseHex } from \"../lib/number-input\";\nimport { cn } from \"../lib/utils\";\n\n// Controls for setting a number or a colour precisely (strata-react issue #73, from moving\n// strata-vid onto Strata: opacity, rotation, volume, bitrate, a line colour). The native ones fail\n// in the same few ways, and each rule below answers one:\n//\n// - `parseFloat(e.target.value)` turns an empty field into NaN. Here a value that is not known is\n// `null`, stays `null`, and prints `format.missing`; a typed value outside the limits is NOT\n// clamped and NOT passed on: React Aria's field runs with `commitBehavior=\"validate\"` (it keeps\n// what was typed instead of snapping 600 to 500), and the control tells the surrounding `Field`\n// what is wrong (\"Enter a value from 0% to 500%.\"), the same place a server's 422 appears. The\n// callback only ever receives a number inside the limits, or null.\n// - The unit lives inside the control, muted. A slider's spoken value carries it (\"40%\", \"90°\")\n// when `Intl` knows the unit (percent, degree, millisecond, megabit-per-second and the like):\n// React Aria builds `aria-valuetext` from an `Intl.NumberFormat`, so \"px\" or \"steps\" are in the\n// printed value and the label but cannot be in the spoken one.\n// - Digits are the locale's: what is printed and what is read back go through `Intl` (React Aria's\n// `NumberParser`), so 12,5 works in a de-DE app, and the message is in the same digits.\n// - Behaviour is React Aria's: arrows step, PageUp/PageDown take ten steps, Home/End jump to the\n// limits, a field commits on Enter and blur. Nothing animates when a value changes: these are\n// dragged and stepped dozens of times a minute (character.md, the frequency budget).\n// - A colour a person picks for their own content (a route's line) is content, not theme, so it is\n// the one place a raw colour value is right; `against` checks it against what it is drawn on.\n// The colour field's text box is ours: React Aria's colour field puts the old colour back when\n// the text is not a colour, where this one says so under the control; the swatch opens the\n// platform picker.\n\nconst box =\n \"flex h-(--control-h) w-full min-w-0 items-center rounded-control border border-input bg-background px-3 type-body text-foreground transition-state data-[disabled]:cursor-not-allowed data-[disabled]:bg-muted data-[disabled]:opacity-70 has-[input:disabled]:cursor-not-allowed has-[input:disabled]:bg-muted has-[input:disabled]:opacity-70 aria-invalid:border-danger has-[input:focus-visible]:outline-2 has-[input:focus-visible]:outline-offset-2 has-[input:focus-visible]:outline-ring\";\n\n/** A number with its unit joined by a non-breaking space; `%` and `°` stay attached. */\nfunction withUnit(text: string, unit?: string) {\n if (!unit) return text;\n return unit === \"%\" || unit === \"°\" ? text + unit : text + NBSP + unit;\n}\n\n// Units `Intl` can speak, by the symbol an app prints. Anything else is printed but not spoken.\nconst intlUnits: Record<string, string> = {\n \"%\": \"percent\",\n \"°\": \"degree\",\n ms: \"millisecond\",\n s: \"second\",\n kB: \"kilobyte\",\n MB: \"megabyte\",\n GB: \"gigabyte\",\n kbps: \"kilobit-per-second\",\n Mbps: \"megabit-per-second\",\n};\n\nfunction decimalsOf(n: number): number {\n const s = String(n);\n if (s.includes(\"e-\")) return Number(s.split(\"e-\")[1]) + (s.split(\"e-\")[0].split(\".\")[1]?.length ?? 0);\n return s.split(\".\")[1]?.length ?? 0;\n}\n\nfunction useNumberText(locale: string, places: number) {\n return React.useMemo(() => {\n const f = new Intl.NumberFormat(locale, { maximumFractionDigits: places, minimumFractionDigits: 0 });\n return (n: number) => f.format(n);\n }, [locale, places]);\n}\n\nfunction formatOptionsFor(places: number, unit?: string): Intl.NumberFormatOptions {\n const base: Intl.NumberFormatOptions = { maximumFractionDigits: places, minimumFractionDigits: 0 };\n const known = unit ? intlUnits[unit] : undefined;\n return known ? { ...base, style: \"unit\", unit: known, unitDisplay: \"narrow\" } : base;\n}\n\n/** Props shared by the number field and the slider. */\nexport type RangeProps = {\n min?: number;\n max?: number;\n /** The size of one arrow-key step. Default 1. */\n step?: number;\n /** The unit shown with the value: \"%\", \"°\", \"Mbps\", \"px\". Spoken too when `Intl` has it (%, °, ms, s, kB, MB, GB, kbps, Mbps). */\n unit?: string;\n /** The locale for digits and the decimal mark. Default the app's `format` locale. */\n locale?: string;\n};\n\n/** Props for `NumberField`. */\nexport type NumberFieldProps = RangeProps & {\n /** The current value; `null` when it is not known (shown as an en dash, not 0). */\n value: number | null;\n /** Receives a number inside the limits, or `null` when the field is cleared. Never NaN, never out of range. */\n onChange: (value: number | null) => void;\n /** Decimal places to show and keep. Default the places in `step` (and `min`). */\n places?: number;\n /** An empty field is an error (\"Enter a value.\") rather than `null`. */\n required?: boolean;\n disabled?: boolean;\n /** Names the control when it is used without a `Field`. */\n \"aria-label\"?: string;\n id?: string;\n name?: string;\n className?: string;\n};\n\nfunction describeRange(min: number | undefined, max: number | undefined, show: (n: number) => string, unit?: string) {\n const a = min === undefined ? \"\" : withUnit(show(min), unit);\n const b = max === undefined ? \"\" : withUnit(show(max), unit);\n if (min !== undefined && max !== undefined) return `Enter a value from ${a} to ${b}.`;\n if (min !== undefined) return `Enter ${a} or more.`;\n if (max !== undefined) return `Enter ${b} or less.`;\n return \"Enter a number.\";\n}\n\n/** A number with a unit on React Aria's number field: typed input is validated, not clamped, so an out-of-range value is explained in the surrounding `Field` and never passed on; empty stays `null`. */\nexport function NumberField({\n value,\n onChange,\n min,\n max,\n step = 1,\n places,\n unit,\n locale = format.locale,\n required = false,\n disabled,\n id: idProp,\n name,\n className,\n \"aria-label\": ariaLabel,\n}: NumberFieldProps) {\n const { field, report } = useFieldControl();\n const digits = places ?? Math.max(decimalsOf(step), min === undefined ? 0 : decimalsOf(min));\n const show = useNumberText(locale, digits);\n const [own, setOwn] = React.useState(false); // invalid, when there is no Field to say so\n const unitId = React.useId();\n // What the field shows. It follows `value`, but also holds an entry we refused, so the person sees\n // (and can correct) what they typed instead of the field snapping back to the old value.\n const [local, setLocal] = React.useState<number>(value ?? Number.NaN);\n const [seen, setSeen] = React.useState(value);\n if (seen !== value) {\n setSeen(value);\n setLocal(value ?? Number.NaN);\n }\n\n const fail = (message: string) => {\n setOwn(true);\n report(message);\n };\n const ok = () => {\n setOwn(false);\n report(undefined);\n };\n\n const handle = (n: number) => {\n setLocal(n);\n if (Number.isNaN(n)) {\n if (required) return fail(\"Enter a value.\");\n ok();\n if (value !== null) onChange(null);\n return;\n }\n if ((min !== undefined && n < min) || (max !== undefined && n > max)) return fail(describeRange(min, max, show, unit));\n ok();\n if (n !== value) onChange(n);\n };\n\n const invalid = field?.invalid || own;\n return (\n <I18nProvider locale={locale}>\n <AriaNumberField\n value={local}\n onChange={handle}\n minValue={min}\n maxValue={max}\n step={step}\n formatOptions={{ maximumFractionDigits: digits, minimumFractionDigits: 0 }}\n commitBehavior=\"validate\"\n isDisabled={disabled}\n isInvalid={invalid || undefined}\n name={name}\n aria-label={ariaLabel ?? field?.label}\n className={cn(box, className)}\n >\n <AriaInput\n id={idProp ?? field?.id}\n placeholder={format.missing}\n aria-describedby={[field?.describedBy, unit ? unitId : undefined].filter(Boolean).join(\" \") || undefined}\n className=\"min-w-0 flex-1 bg-transparent tabular-nums outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed\"\n />\n {unit && (\n <span id={unitId} className=\"ml-2 shrink-0 type-body-sm text-muted-foreground\">\n <span aria-hidden>{unit}</span>\n <span className=\"sr-only\">{intlUnits[unit] ? intlUnits[unit].replace(/-/g, \" \") : unit}</span>\n </span>\n )}\n </AriaNumberField>\n </I18nProvider>\n );\n}\n\n/** Props for `Slider`. */\nexport type SliderProps = RangeProps & {\n value: number;\n onChange: (value: number) => void;\n /** Both limits are required: a slider with no ends is not a slider. */\n min: number;\n max: number;\n /** Replace the printed value with a `NumberField` beside the track, so an exact value can be typed. */\n editable?: boolean;\n /** Hide the printed value (when something else beside it already shows it). */\n hideValue?: boolean;\n /** Decimal places in the printed and spoken value. Default the places in `step`. */\n places?: number;\n disabled?: boolean;\n /** Names the slider when it is used without a `Field`. */\n \"aria-label\"?: string;\n className?: string;\n};\n\n/** A slider on React Aria with its current value always printed beside the track (and spoken with the unit when `Intl` knows it); `editable` adds a number field to type an exact value. */\nexport function Slider({\n value,\n onChange,\n min,\n max,\n step = 1,\n unit,\n locale = format.locale,\n editable = false,\n hideValue = false,\n places,\n disabled,\n className,\n \"aria-label\": ariaLabel,\n}: SliderProps) {\n const { field } = useFieldControl();\n const digits = places ?? Math.max(decimalsOf(step), decimalsOf(min));\n const show = useNumberText(locale, digits);\n const name = ariaLabel ?? field?.label ?? \"Value\";\n const text = withUnit(show(value), unit);\n return (\n <I18nProvider locale={locale}>\n <AriaSlider\n value={value}\n onChange={(v) => onChange(v as number)}\n minValue={min}\n maxValue={max}\n step={step}\n formatOptions={formatOptionsFor(digits, unit)}\n isDisabled={disabled}\n aria-label={name}\n aria-describedby={field?.describedBy}\n className={cn(\"flex min-w-0 items-center gap-3\", className)}\n >\n <SliderTrack className=\"relative flex h-(--control-h) min-w-0 flex-1 cursor-pointer items-center data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50\">\n {({ state }) => (\n <>\n <span aria-hidden className=\"absolute inset-x-0 h-1.5 rounded-pill bg-muted\" />\n <span aria-hidden className=\"absolute left-0 h-1.5 rounded-pill bg-primary\" style={{ width: `${state.getThumbPercent(0) * 100}%` }} />\n <SliderThumb className=\"top-1/2 size-5 rounded-pill border-2 border-primary bg-background data-[focus-visible]:outline-2 data-[focus-visible]:outline-offset-2 data-[focus-visible]:outline-ring\" />\n </>\n )}\n </SliderTrack>\n {editable ? (\n <NumberField className=\"w-28 shrink-0\" aria-label={`${name}, exact value`} value={value} onChange={(v) => v !== null && onChange(v)} min={min} max={max} step={step} unit={unit} locale={locale} places={digits} required disabled={disabled} />\n ) : (\n !hideValue && (\n <SliderOutput aria-hidden className=\"w-16 shrink-0 text-right type-body-sm tabular-nums text-foreground\">\n {text}\n </SliderOutput>\n )\n )}\n </AriaSlider>\n </I18nProvider>\n );\n}\n\n/** Props for `ColorField`. */\nexport type ColorFieldProps = {\n /** `#rrggbb`, or `null` when no colour is set. */\n value: string | null;\n /** Receives a valid `#rrggbb` (lower case) or `null` when cleared; never a half-typed value. */\n onChange: (value: string | null) => void;\n /** A short list the app suggests, as `#rrggbb`. Pressing one chooses it. */\n suggestions?: readonly string[];\n /** The colour this will be drawn on, `#rrggbb`: a note appears when the contrast would be low. */\n against?: string;\n /** What it is drawn on, in words: \"the map\". Completes the note. */\n againstLabel?: string;\n /** The lowest contrast ratio accepted before the note shows. Default 3, the WCAG minimum for graphics. */\n minContrast?: number;\n disabled?: boolean;\n \"aria-label\"?: string;\n id?: string;\n className?: string;\n};\n\n/** Choose a colour with the platform picker, see and type its hex value, pick from the app's suggestions, and get a note when it would be hard to see on `against`. A half-typed value is never passed on. */\nexport function ColorField({ value, onChange, suggestions, against, againstLabel = \"the background\", minContrast = 3, disabled, id: idProp, className, \"aria-label\": ariaLabel }: ColorFieldProps) {\n const { field, report } = useFieldControl();\n const [draft, setDraft] = React.useState<string | null>(null);\n const [own, setOwn] = React.useState(false);\n const text = draft ?? value ?? \"\";\n const ratio = value && against ? contrastRatio(value, against) : null;\n\n const commitText = (t: string): boolean => {\n if (t.trim() === \"\") {\n setOwn(false);\n report(undefined);\n if (value !== null) onChange(null);\n return true;\n }\n const hex = parseHex(t);\n if (!hex) {\n setOwn(true);\n report(\"Enter a colour like #1a7f64.\");\n return false;\n }\n setOwn(false);\n report(undefined);\n if (hex !== value) onChange(hex);\n return true;\n };\n\n const pick = (hex: string) => {\n setDraft(null);\n setOwn(false);\n report(undefined);\n if (hex !== value) onChange(hex);\n };\n\n const invalid = field?.invalid || own;\n return (\n <div className={cn(\"grid min-w-0 gap-2\", className)}>\n <div className={cn(box, \"gap-2 px-2\")} aria-invalid={invalid || undefined}>\n <span className=\"relative size-6 shrink-0 overflow-hidden rounded-control border border-input\">\n {/* The swatch is the chosen colour itself: user content, not a theme role. */}\n <span aria-hidden className={cn(\"absolute inset-0\", value === null && \"bg-muted\")} style={value ? { background: value } : undefined} />\n <input\n type=\"color\"\n aria-label={ariaLabel ? `${ariaLabel}, picker` : \"Colour picker\"}\n value={value ?? \"#000000\"}\n disabled={disabled}\n onChange={(e) => pick(e.target.value)}\n className=\"absolute inset-0 size-full cursor-pointer opacity-0 disabled:cursor-not-allowed\"\n />\n </span>\n <input\n id={idProp ?? field?.id}\n type=\"text\"\n autoComplete=\"off\"\n spellCheck={false}\n disabled={disabled}\n aria-label={ariaLabel}\n aria-describedby={field?.describedBy}\n aria-invalid={invalid || undefined}\n placeholder={format.missing}\n value={text}\n onChange={(e) => setDraft(e.target.value)}\n onBlur={() => {\n if (draft !== null && commitText(draft)) setDraft(null);\n }}\n onKeyDown={(e) => {\n if (e.key === \"Enter\" && draft !== null && commitText(draft)) setDraft(null);\n if (e.key === \"Escape\" && draft !== null) {\n setDraft(null);\n setOwn(false);\n report(undefined);\n }\n }}\n className=\"min-w-0 flex-1 bg-transparent tabular-nums outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed\"\n />\n </div>\n {suggestions && suggestions.length > 0 && (\n <div role=\"group\" aria-label=\"Suggested colours\" className=\"flex flex-wrap gap-1.5\">\n {suggestions.map((hex) => (\n <button\n key={hex}\n type=\"button\"\n disabled={disabled}\n aria-label={hex}\n aria-pressed={value === hex}\n onClick={() => pick(hex)}\n className=\"size-6 cursor-pointer rounded-control border border-input transition-state aria-pressed:outline-2 aria-pressed:outline-offset-2 aria-pressed:outline-foreground disabled:cursor-not-allowed disabled:opacity-50\"\n style={{ background: hex }}\n />\n ))}\n </div>\n )}\n {ratio !== null && ratio < minContrast && (\n <p className=\"type-body-sm text-warning\">\n Hard to see on {againstLabel}: contrast {format.decimal(ratio)}:1, aim for {format.decimal(minContrast)}:1 or more.\n </p>\n )}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { CircleAlert, CircleCheck, Info, TriangleAlert } from \"lucide-react\";\nimport type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\nimport type { Tone } from \"./status\";\n\n// An alert is one inline sentence about a problem or a fact, where it applies: a failed export\n// under the export, a stale reading above the chart. It is how an error a person must act on is\n// shown, with its recovery as `action`; a toast is not (components.md §3.13, patterns.md §7).\n//\n// Drawn as a pale tint of its tone with its icon and, for `title`, a heavier first line: never a\n// coloured stripe down one side of a rounded box (the tell in ux-slop-taxonomy), and never colour\n// alone, since the icon and the words carry the tone. `role=\"alert\"` interrupts a screen reader,\n// so it is on only when the alert appears in response to something the person just did\n// (`announce`); a banner that is simply there on load is a plain region the reader finds in order.\n\n/** Props for `Alert`. */\nexport type AlertProps = {\n tone: Exclude<Tone, \"neutral\">;\n /** A short first line, when the sentence needs one: \"Export failed\". */\n title?: string;\n /** The sentence, in the product's words: what happened and what to do. */\n children: React.ReactNode;\n /** One recovery, a `Button` (\"Try again\"). */\n action?: React.ReactNode;\n /** It appeared because of something the person just did (a failed submit): announce it at once (`role=\"alert\"`). */\n announce?: boolean;\n className?: string;\n};\n\nconst tones: Record<Exclude<Tone, \"neutral\">, { box: string; icon: IconComponent }> = {\n info: { box: \"bg-info-subtle text-info\", icon: Info },\n success: { box: \"bg-success-subtle text-success\", icon: CircleCheck },\n warning: { box: \"bg-warning-subtle text-warning\", icon: TriangleAlert },\n danger: { box: \"bg-danger-subtle text-danger\", icon: CircleAlert },\n};\n\n/** An inline sentence about a problem or a fact, in a tone with an icon, with one optional action. `announce` makes it `role=\"alert\"` for a result of the person's own action. */\nexport function Alert({ tone, title, children, action, announce = false, className }: AlertProps) {\n const { box, icon: Icon } = tones[tone];\n return (\n <div role={announce ? \"alert\" : \"region\"} aria-label={announce ? undefined : title ?? \"Notice\"} className={cn(\"flex items-start gap-3 rounded-surface px-3 py-2.5\", box, className)}>\n <Icon aria-hidden className=\"mt-0.5 size-4 shrink-0\" />\n <div className=\"grid min-w-0 flex-1 gap-0.5\">\n {title && <p className=\"type-label\">{title}</p>}\n <div className=\"type-body-sm\">{children}</div>\n </div>\n {action && <div className=\"shrink-0 self-center\">{action}</div>}\n </div>\n );\n}\n","import { UNSTABLE_Toast as AriaToast, UNSTABLE_ToastContent as ToastContent, UNSTABLE_ToastQueue as ToastQueue, UNSTABLE_ToastRegion as ToastRegion, Button as AriaButton, Text } from \"react-aria-components\";\nimport { CircleCheck, Info, TriangleAlert, X } from \"lucide-react\";\nimport { Button } from \"./button\";\nimport { cn } from \"../lib/utils\";\nimport { overlaySurface } from \"../lib/overlay\";\n\n// A toast confirms background work that finished (\"Export finished\", \"3 pieces synced\"). It is a\n// polite live region; it never carries an error a person must act on, which goes inline as an\n// `Alert` with its recovery (components.md §3.13, patterns.md §7), so there is no danger tone:\n// the type refuses it. `warning` is for a fact worth a glance (\"Kiln 2 is 40 min behind\").\n//\n// Rules the component owns so an app does not have to:\n// - One region, once, at the app root (`ToastRegion`), on the `layer-bar` layer: bottom end of the\n// window on a wide screen, the top on a phone, so it does not sit on the undo bar or cover the\n// focused control. It is a labelled landmark the keyboard reaches with F6 (React Aria).\n// - It stays long enough to read: 5 s plus 40 ms a character, up to 15 s, at least 8 s with an\n// action. The timer pauses while the pointer or focus is on it. There is always a dismiss control.\n// - At most one action, a button (\"Open file\"); content is words, not a form.\n// - Announcements are React Aria's: the toast's text is read when it appears and not again.\n// - The queue is module-level, so `toast.show()` works from a mutation's `onSuccess` outside any\n// component; `toast.clear()` empties it for a test. React Aria marks its toast API unstable; it\n// is used only here, behind this small surface, so a change upstream stays in this file.\n// Toasts are rare and brief, so they get the overlay entrance and nothing else (character.md §3).\n\n/** What a toast says. */\nexport type ToastContentProps = {\n /** What finished, past tense, in the product's words: \"Export finished\". */\n title: string;\n /** One more sentence: what and where (\"run.mp4, 2:31 at 1080p, in your Downloads folder.\"). */\n description?: string;\n /** `info` by default. There is no danger tone: an error the person must act on is an `Alert`. */\n tone?: \"info\" | \"success\" | \"warning\";\n /** One action beside the words. */\n action?: { label: string; onPress: () => void };\n /** Milliseconds before it goes. Defaults to enough to read the words. */\n timeout?: number;\n};\n\nconst queue = new ToastQueue<ToastContentProps>({ maxVisibleToasts: 3 });\n\n/** Milliseconds a toast stays: 5 s plus 40 ms a character, to at most 15 s, and at least 8 s with an action. */\nexport function toastTimeout(content: Pick<ToastContentProps, \"title\" | \"description\" | \"action\" | \"timeout\">): number {\n if (content.timeout !== undefined) return content.timeout;\n const chars = content.title.length + (content.description?.length ?? 0) + (content.action?.label.length ?? 0);\n return Math.max(content.action ? 8000 : 0, Math.min(15000, 5000 + 40 * chars));\n}\n\n/** The toast queue: `toast.show({ title })` from anywhere; `toast.close(key)`; `toast.clear()`. */\nexport const toast = {\n /** Shows a toast and returns its key. */\n show(content: ToastContentProps): string {\n return queue.add(content, { timeout: toastTimeout(content) });\n },\n close(key: string) {\n queue.close(key);\n },\n clear() {\n queue.clear();\n },\n};\n\nconst marks = { info: { icon: Info, color: \"text-info\" }, success: { icon: CircleCheck, color: \"text-success\" }, warning: { icon: TriangleAlert, color: \"text-warning\" } } as const;\n\n/** Props for `ToastRegion`. */\nexport type StrataToastRegionProps = {\n /** Names the landmark. Default \"Notifications\". */\n label?: string;\n className?: string;\n};\n\n/** The one place toasts appear. Render it once at the app root. A labelled landmark (F6), polite, above panes and the undo bar. */\nexport function StrataToastRegion({ label = \"Notifications\", className }: StrataToastRegionProps) {\n return (\n <ToastRegion\n queue={queue}\n aria-label={label}\n className={cn(\"layer-bar fixed inset-x-4 top-4 grid justify-items-end gap-2 outline-none sm:inset-x-auto sm:top-auto sm:right-4 sm:bottom-4\", className)}\n >\n {({ toast: t }) => (\n <AriaToast\n toast={t}\n className={cn(\"flex w-full max-w-sm items-start gap-3 p-3 outline-none data-[focus-visible]:outline-2 data-[focus-visible]:outline-ring\", overlaySurface)}\n >\n {(() => {\n const { icon: Icon, color } = marks[t.content.tone ?? \"info\"];\n return <Icon aria-hidden className={cn(\"mt-0.5 size-4 shrink-0\", color)} />;\n })()}\n <ToastContent className=\"grid min-w-0 flex-1 gap-0.5\">\n <Text slot=\"title\" className=\"type-label\">\n {t.content.title}\n </Text>\n {t.content.description && <Text slot=\"description\" className=\"type-body-sm text-muted-foreground\">{t.content.description}</Text>}\n </ToastContent>\n {t.content.action && (\n <Button size=\"sm\" onPress={() => { t.content.action?.onPress(); queue.close(t.key); }}>\n {t.content.action.label}\n </Button>\n )}\n <AriaButton slot=\"close\" aria-label=\"Dismiss\" className=\"grid size-6 shrink-0 cursor-pointer place-items-center rounded-control text-muted-foreground transition-state data-[hovered]:bg-muted data-[hovered]:text-foreground\">\n <X aria-hidden className=\"size-4\" />\n </AriaButton>\n </AriaToast>\n )}\n </ToastRegion>\n );\n}\n","import * as React from \"react\";\n\n// Work the browser does for a while (an export, an upload, a render) has the same shape as a\n// server job: it runs, reports how far it is, and ends finished, failed or cancelled (issue #72).\n// `useClientWork` holds that shape so a screen hands it straight to `JobStatus` and a toast,\n// instead of each screen keeping its own booleans. Cancelling aborts the `signal` the work was\n// given (pass it to `fetch`, or check it between steps) and ends as `cancelled`, never as a\n// failure: an abort is the person's decision, and its error is not reported. Starting again while\n// running is ignored, so a double click does not run the work twice. A stale run (cancelled, then\n// restarted) cannot write over the newer one.\n\n/** What the work is given: a signal that aborts on cancel, and a way to report progress. */\nexport type WorkContext = {\n signal: AbortSignal;\n /** Report items done, and the total when it is known. */\n progress: (current: number, total?: number) => void;\n};\n\n/** Where client work is. */\nexport type WorkPhase = \"idle\" | \"running\" | \"finished\" | \"failed\" | \"cancelled\";\n\n/** The state `useClientWork` returns. */\nexport type ClientWork<T> = {\n phase: WorkPhase;\n current?: number;\n total?: number;\n result?: T;\n error?: unknown;\n /** Runs the work. Ignored while it is already running. */\n start: () => Promise<void>;\n /** Aborts the work's signal; the phase becomes `cancelled`. */\n cancel: () => void;\n /** Back to `idle`, forgetting the result. */\n dismiss: () => void;\n};\n\ntype State<T> = { phase: WorkPhase; current?: number; total?: number; result?: T; error?: unknown };\n\n/** Runs browser-side work with progress, cancel and a clear end state, ready for `JobStatus`. */\nexport function useClientWork<T>(run: (ctx: WorkContext) => Promise<T>): ClientWork<T> {\n const [state, setState] = React.useState<State<T>>({ phase: \"idle\" });\n const controller = React.useRef<AbortController | null>(null);\n const runRef = React.useRef(run);\n runRef.current = run;\n\n const start = React.useCallback(async () => {\n if (controller.current) return;\n const mine = new AbortController();\n controller.current = mine;\n const live = () => controller.current === mine;\n setState({ phase: \"running\" });\n try {\n const result = await runRef.current({\n signal: mine.signal,\n progress: (current, total) => live() && setState((s) => ({ ...s, current, total: total ?? s.total })),\n });\n if (!live()) return;\n setState(mine.signal.aborted ? { phase: \"cancelled\" } : { phase: \"finished\", result });\n } catch (error) {\n if (!live()) return;\n setState(mine.signal.aborted ? { phase: \"cancelled\" } : { phase: \"failed\", error });\n } finally {\n if (live()) controller.current = null;\n }\n }, []);\n\n const cancel = React.useCallback(() => {\n const c = controller.current;\n if (!c) return;\n c.abort();\n controller.current = null;\n setState({ phase: \"cancelled\" });\n }, []);\n\n const dismiss = React.useCallback(() => {\n if (!controller.current) setState({ phase: \"idle\" });\n }, []);\n\n // Unmounting aborts the run and forgets it, so a remount (Strict Mode's setup, cleanup, setup) can\n // start again and the aborted run can no longer write state.\n React.useEffect(\n () => () => {\n controller.current?.abort();\n controller.current = null;\n },\n [],\n );\n\n return { ...state, start, cancel, dismiss };\n}\n","import * as React from \"react\";\nimport { Check, CircleAlert, LoaderCircle, TriangleAlert, Ban } from \"lucide-react\";\nimport { format } from \"../lib/format\";\nimport type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\nimport { Button } from \"./button\";\nimport { Status, type Tone } from \"./status\";\n\n// A job the server runs for a while (syncing sources one after another, an import, a re-index),\n// as the screen that started it shows it (strata-react issue #45, from the Tubes Library screen,\n// which built each part by hand). Three things are true of every such job, and the props make\n// each one impossible to leave out:\n//\n// - Its state is a word, as `Status` is: `words` names running, finished and failed in the\n// product's terms (\"Syncing\", \"Finished\", \"Finished with failures\"), all three required, so a\n// screen cannot forget the end it did not test. Beside the word, `summary` is the app's own\n// sentence (\"Syncing 2 of 3: Night Sky. 42 new videos so far.\").\n// - How far it has got is a bar only when the total is known (`current` of `total`), a\n// `progressbar`, not a `meter`: this is a task moving to done. Without a total there is no bar,\n// because a bar that guesses is worse than the sentence.\n// - When it ends, each item that failed is named with its reason (`failures`), because \"3\n// failed\" alone sends the person hunting. A job that failed as a whole (`failed`, the summary\n// saying why) names no item.\n//\n// It is announced, politely, only when something a person waits for happens: the item changes\n// (`current`) or the job ends. A poll every two seconds that rewrites \"42 new videos so far\" in\n// a live region would talk over everything else, so the visible sentence is not the live region;\n// a separate one carries the word and the sentence at those moments.\n//\n// Work the browser does (an export, an upload, a render; issue #72) uses the same component, so one\n// idea of \"a job\" covers both: `onCancel` shows a Cancel button while it runs (work the person can\n// stop is stoppable), `cancelled` is a fourth ending in neutral (\"Cancelled\": not a failure, nothing\n// to retry), and `onDismiss` shows Dismiss once it has ended so the result does not linger. With no\n// `total` there is no bar, only the turning mark and the sentence, which is the indeterminate case. The spinner turns only\n// while running, the one case where a status mark's data is live. Polling and re-reading what\n// the job changed is `useJob`'s.\n\n/** An item a job could not do, and why, in the product's words. */\nexport type JobFailure = { key: string; label: string; reason: string };\n\n/** A job's three states as words, all required: \"Syncing\", \"Finished\", \"Finished with failures\". */\nexport type JobWords = { running: string; finished: string; failed: string; /** Shown when `cancelled`. Default \"Cancelled\". */ cancelled?: string };\n\n/** The job status's props. */\nexport type JobStatusProps = {\n /** What the job is (\"Library sync\"): names the section and the progress bar. */\n label: string;\n /** The job is still going. */\n running: boolean;\n words: JobWords;\n /** The app's sentence for where the job is or how it went: \"Syncing 2 of 3: Night Sky.\" */\n summary: string;\n /** Items done or being done, with `total`, for the bar. */\n current?: number;\n /** Items in all, when known. No bar without it. */\n total?: number;\n /** Each item that failed, with its reason. Any failure makes a finished job `failed`'s word. */\n failures?: JobFailure[];\n /** The job failed as a whole, for a reason that names no item (the summary says it). */\n failed?: boolean;\n /** Names the list of failures for screen readers. Default \"Failures\". */\n failuresLabel?: string;\n /** The person stopped it. A neutral ending, not a failure. */\n cancelled?: boolean;\n /** Stops the job. Shows a Cancel button while it runs. */\n onCancel?: () => void;\n /** Label of the cancel button. Default \"Cancel\". */\n cancelLabel?: string;\n /** Clears the result. Shows a Dismiss button once the job has ended. */\n onDismiss?: () => void;\n className?: string;\n};\n\nconst Spinner: IconComponent = ({ className, ...props }) => (\n <LoaderCircle {...props} className={cn(className, \"motion-safe:animate-spin\")} />\n);\n\n/** A long-running server job: its state as a required word beside the app's sentence, a progress bar when the total is known, each failure named with its reason, and a polite announcement only when the item changes or the job ends. */\nexport function JobStatus({\n label,\n running,\n words,\n summary,\n current,\n total,\n failures = [],\n failed = false,\n failuresLabel = \"Failures\",\n cancelled = false,\n onCancel,\n cancelLabel = \"Cancel\",\n onDismiss,\n className,\n}: JobStatusProps) {\n const ended: { tone: Tone; icon: IconComponent; word: string } = cancelled\n ? { tone: \"neutral\", icon: Ban, word: words.cancelled ?? \"Cancelled\" }\n : failed\n ? { tone: \"danger\", icon: CircleAlert, word: words.failed }\n : failures.length\n ? { tone: \"warning\", icon: TriangleAlert, word: words.failed }\n : { tone: \"success\", icon: Check, word: words.finished };\n const { tone, icon, word } = running ? { tone: \"info\" as const, icon: Spinner, word: words.running } : ended;\n\n // What is announced changes only with the item or the end, not with every poll's sentence.\n const moment = running ? `running:${current ?? \"\"}` : `ended:${word}`;\n const [said, setSaid] = React.useState({ moment, text: \"\" });\n if (said.moment !== moment) setSaid({ moment, text: `${word}. ${summary}` });\n\n const bar = running && total !== undefined && total > 0 && current !== undefined;\n const done = Math.min(total ?? 0, Math.max(0, current ?? 0));\n\n return (\n <section aria-label={label} className={cn(\"grid min-w-0 gap-3\", className)}>\n <div className=\"flex flex-wrap items-center gap-x-3 gap-y-1\">\n <Status tone={tone} icon={icon}>\n {word}\n </Status>\n <p className=\"min-w-0 flex-1 type-body-sm text-foreground\">{summary}</p>\n {running && onCancel && (\n <Button size=\"sm\" onPress={onCancel}>\n {cancelLabel}\n </Button>\n )}\n {!running && onDismiss && (\n <Button size=\"sm\" variant=\"ghost\" onPress={onDismiss}>\n Dismiss\n </Button>\n )}\n </div>\n {bar && (\n <div\n role=\"progressbar\"\n aria-label={label}\n aria-valuemin={0}\n aria-valuemax={total}\n aria-valuenow={done}\n aria-valuetext={`${format.integer(done)} of ${format.integer(total)}`}\n className=\"relative h-2 overflow-hidden rounded-pill bg-muted\"\n >\n <div className=\"absolute inset-y-0 left-0\" style={{ width: `${(done / total) * 100}%`, background: \"var(--chart-1)\" }} />\n </div>\n )}\n {!running && failures.length > 0 && (\n <ul aria-label={failuresLabel} className=\"grid gap-1 border-l-2 border-warning pl-3 type-body-sm\">\n {failures.map((f) => (\n <li key={f.key}>\n <span className=\"type-label\">{f.label}</span>\n <span className=\"text-muted-foreground\">: {f.reason}</span>\n </li>\n ))}\n </ul>\n )}\n <p role=\"status\" className=\"sr-only\">\n {said.text}\n </p>\n </section>\n );\n}\n","import * as React from \"react\";\nimport { ImageOff } from \"lucide-react\";\nimport { Skeleton } from \"./data-view\";\nimport { useInView } from \"../lib/in-view\";\nimport { cn } from \"../lib/utils\";\n\n// A photo or crop from an API, in a list, a table cell or a grid (strata-react issue #33, from\n// the Bright Horizons review app, where some crops 404 because the file is missing on disk). A\n// plain <img> gets three things wrong there, and each is a state generated UI leaves out:\n//\n// - it has no size until it loads, so the rows below jump as each one arrives. The box here has\n// its aspect ratio before anything is fetched, and the image is cropped (`cover`) or fitted\n// (`contain`) into it, so nothing moves.\n// - while it loads it is a blank, and on a slow connection a blank reads as \"no photo\". Here it\n// is a `Skeleton`, the same placeholder DataView's loading layouts are made of.\n// - when it fails it is the browser's broken-image icon and the alt text crammed into the box.\n// Here it says what happened in the product's words: `missing` is required (\"Photo not\n// found\"), for the same reason DataView requires `empty`. A record with no photo at all\n// (`src={null}`) shows the same words without a request.\n//\n// `alt` is required too; pass \"\" only when the name beside the thumbnail already says everything\n// it shows. The missing state is an `img` named \"<alt>: <missing>\", so a screen reader hears\n// which photo is gone. Thumbnails come in dozens, so the request waits until the box is near the\n// screen (`useInView`, the hook InfiniteList's sentinel uses, with the same scroll region and a\n// root margin), and once asked for it is not unloaded. `eager` is for the first few on screen.\n// There is no fade-in: a list of thumbnails is seen many times a day (ux-character.md, character\n// by frequency), so the photo simply replaces its skeleton.\n//\n// Two more uses from the Tubes viewer (strata-react issue #51), which drew plain <img>s and lost\n// all of the above:\n//\n// - `children` are drawn above the image in the same positioned box: a video's running time in\n// one corner, \"Saved\" in another. They keep their place while the image loads, fails or is\n// missing, because the box, not the image, holds them. Position them yourself (`absolute\n// bottom-1 right-1`); they are not part of the image's name.\n// - `fallback` replaces the icon and words with the product's own drawing, such as a channel's\n// first letter on a disc for an avatar with no picture. The missing state is still one `img`,\n// named `alt` (with `missing` after it, when given, as \"Night Sky: No picture\"), so a person\n// using a screen reader hears whose picture it is either way. A round avatar is `aspect={1}`\n// with `className=\"rounded-pill\"`.\n\n/** A width-over-height ratio: a number (`1.5`) or a fraction (`\"4/3\"`). */\nexport type AspectRatio = number | `${number}/${number}`;\n\n/** The thumbnail's props. Either `missing` (the words shown when there is no image) or a `fallback` drawing is required. */\nexport type ThumbnailProps = {\n /** The image URL. `null` when the record has no photo: the `missing` words show without a request. */\n src: string | null;\n /** What the photo shows (\"Celadon bowl, front\"). `\"\"` only when the text beside it already says it. */\n alt: string;\n /** Width over height. The box has this shape before the image loads. Default `1`. */\n aspect?: AspectRatio;\n /** `cover` crops to fill the box (default); `contain` fits the whole image in it. */\n fit?: \"cover\" | \"contain\";\n srcSet?: string;\n sizes?: string;\n /** Load at once rather than when near the screen: for the first few above the fold. */\n eager?: boolean;\n /** How far outside the scroll region the request starts (IntersectionObserver `rootMargin`). */\n rootMargin?: string;\n /** Layout at the call site: a width (`w-24`, `w-full`), or `rounded-pill` for an avatar. The height follows from `aspect`. */\n className?: string;\n /** Overlays drawn above the image in the same box (a running time, a \"Saved\" badge), in place whether the image has loaded, failed or is missing. */\n children?: React.ReactNode;\n} & (\n | {\n /** What to show when there is no photo or it cannot be loaded, in the product's words: \"Photo not found\". */\n missing: string;\n /** Drawn instead of the icon and `missing` words when there is no image: a letter on a disc for an avatar. */\n fallback?: React.ReactNode;\n }\n | {\n /** Added to the missing state's name after `alt` (\"Night Sky: No picture\"), when given. */\n missing?: string;\n /** Drawn when there is no image or it cannot be loaded: a letter on a disc for an avatar. */\n fallback: React.ReactNode;\n }\n);\n\ntype Phase = \"loading\" | \"loaded\" | \"missing\";\n\nconst ratio = (aspect: AspectRatio) => (typeof aspect === \"number\" ? String(aspect) : aspect.replace(\"/\", \" / \"));\n\n/** A box of fixed aspect ratio for a remote image: a skeleton until it loads, the `missing` words (or a `fallback`) if it cannot, a request only when it nears the screen, and `children` overlaid in its corners. `alt` and `missing` or `fallback` are required. */\nexport function Thumbnail({\n src,\n alt,\n missing,\n aspect = 1,\n fit = \"cover\",\n srcSet,\n sizes,\n eager = false,\n rootMargin = \"200px\",\n className,\n fallback,\n children,\n}: ThumbnailProps) {\n // The outcome is kept with the request it belongs to (`src` and `srcSet`, since the browser may\n // have loaded a candidate from either), so a new request starts loading again without an effect\n // to reset it, and a late event from the old image cannot mark the new one.\n const request = src ? `${src} ${srcSet ?? \"\"}` : null;\n const [result, setResult] = React.useState<{ request: string; ok: boolean } | null>(null);\n const phase: Phase = !request ? \"missing\" : result?.request === request ? (result.ok ? \"loaded\" : \"missing\") : \"loading\";\n const near = useInView({ active: !eager && !!src, rootMargin, once: true, unsupported: true });\n const requested = eager || near.inView;\n\n return (\n <div\n ref={near.ref}\n className={cn(\"relative overflow-hidden rounded-control bg-muted\", className)}\n style={{ aspectRatio: ratio(aspect) }}\n aria-busy={phase === \"loading\" || undefined}\n >\n {phase === \"loading\" && <Skeleton className=\"absolute inset-0\" />}\n {src && request && phase !== \"missing\" && requested && (\n <img\n key={request}\n src={src}\n srcSet={srcSet}\n sizes={sizes}\n alt={alt}\n decoding=\"async\"\n onLoad={() => setResult({ request, ok: true })}\n onError={() => setResult({ request, ok: false })}\n className={cn(\"absolute inset-0 size-full\", fit === \"cover\" ? \"object-cover\" : \"object-contain\", phase === \"loading\" && \"opacity-0\")}\n />\n )}\n {phase === \"missing\" && (\n <div\n role=\"img\"\n aria-label={[alt, missing].filter(Boolean).join(\": \")}\n className={cn(\n \"absolute inset-0 grid\",\n fallback === undefined && \"content-center justify-items-center gap-0.5 p-1 text-center text-muted-foreground\",\n )}\n >\n {fallback === undefined ? (\n <>\n <ImageOff aria-hidden className=\"size-4 shrink-0\" />\n <span className=\"type-caption text-balance\">{missing}</span>\n </>\n ) : (\n <div aria-hidden className=\"grid size-full min-h-0 min-w-0\">\n {fallback}\n </div>\n )}\n </div>\n )}\n {children}\n </div>\n );\n}\n\n/** The loading shape of a `Thumbnail`, for a `DataView` skeleton: the same box and aspect ratio, so nothing moves when the list arrives. */\nexport function ThumbnailSkeleton({ aspect = 1, className }: { aspect?: AspectRatio; className?: string }) {\n return (\n <div aria-hidden className={cn(\"relative overflow-hidden rounded-control bg-muted\", className)} style={{ aspectRatio: ratio(aspect) }}>\n <Skeleton className=\"absolute inset-0\" />\n </div>\n );\n}\n","import * as React from \"react\";\nimport { ChevronRight } from \"lucide-react\";\nimport { useSearchParams } from \"react-router\";\nimport { cn } from \"../lib/utils\";\n\n// Show more of one thing in place: a batch's faces under its row in a history list, a firing's\n// pieces under its line in the log. Strata issue #34, from an app that wrote its own <details>.\n//\n// Not <details>. A closed <details> still mounts its content, so every row's detail component\n// runs, and a list of forty batches makes forty requests on load for bodies nobody opened. Here\n// the body is mounted only while it is open: a `useLoad` inside it runs on the first open, and on\n// a later open the query cache answers at once. Closed, nothing of the body is in the DOM.\n//\n// The trigger is a native button (Enter and Space, focus outline from the base layer) with\n// `aria-expanded`, and `aria-controls` naming the body while it exists (the WAI-ARIA disclosure\n// pattern). Focus stays on the button through open and close, so a keyboard user walks a list of\n// rows with Tab and opens each in place. The summary is the button's name, so it holds text and\n// marks (a Status, a count), never controls; actions for the row go in `actions`, beside it.\n//\n// No height animation: people open rows in a list many times a session, and character by\n// frequency (ux-research ux-character.md) gives frequent actions no motion. The chevron turns\n// with the state, which is the only signal besides the body itself.\n//\n// Many disclosures over one list share their state through `useExpanded`, which can keep it in\n// the URL (`?open=f-0412`), so an opened row survives a reload and can be linked. `DataTable`'s\n// `expansion` prop draws the same thing as a detail row under a table row.\n\n/** Open and closed disclosure state: controlled with `open` and `onOpenChange`, or uncontrolled from `defaultOpen`. */\nexport type DisclosureOpenProps =\n | { open: boolean; onOpenChange: (open: boolean) => void; defaultOpen?: never }\n | { open?: never; onOpenChange?: (open: boolean) => void; defaultOpen?: boolean };\n\nexport type DisclosureProps = DisclosureOpenProps & {\n /** The always-visible line, and the button's accessible name: text and marks, no controls. */\n summary: React.ReactNode;\n /** Mounted only while open, so a request inside runs when the person opens it. */\n children: React.ReactNode;\n /** Controls for the row (a `RowAction`), beside the summary and outside its button. */\n actions?: React.ReactNode;\n className?: string;\n};\n\n/** Shows more of one thing in place: a button with `aria-expanded` around `summary`, and a body mounted only while open (so a request inside it runs on first open). Controlled with `open`/`onOpenChange` or `useExpanded`, or uncontrolled with `defaultOpen`. */\nexport function Disclosure({ summary, children, actions, open, defaultOpen = false, onOpenChange, className }: DisclosureProps) {\n const [own, setOwn] = React.useState(defaultOpen);\n const isOpen = open ?? own;\n const bodyId = React.useId();\n const toggle = () => {\n if (open === undefined) setOwn(!isOpen);\n onOpenChange?.(!isOpen);\n };\n return (\n <div className={cn(\"min-w-0\", className)}>\n <div className=\"flex items-center gap-3\">\n <button\n type=\"button\"\n aria-expanded={isOpen}\n aria-controls={isOpen ? bodyId : undefined}\n onClick={toggle}\n className=\"-mx-1 flex min-h-(--control-h-sm) min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-control px-1 text-left hover:bg-muted\"\n >\n <Chevron open={isOpen} />\n <span className=\"min-w-0 flex-1\">{summary}</span>\n </button>\n {actions && <div className=\"flex shrink-0 items-center gap-2\">{actions}</div>}\n </div>\n {isOpen && (\n <div id={bodyId} className=\"pt-2 pb-3 pl-6\">\n {children}\n </div>\n )}\n </div>\n );\n}\n\n/** The disclosure chevron: points right when closed, down when open. Shared with `DataTable`'s row toggle. */\nexport function Chevron({ open, className }: { open: boolean; className?: string }) {\n return <ChevronRight aria-hidden className={cn(\"size-4 shrink-0 text-muted-foreground\", open && \"rotate-90\", className)} />;\n}\n\n/** Which of many disclosures are open, by key: spread into `DataTable`'s `expansion`, or read with `isOpen`/`setOpen` for a list of `Disclosure`s. */\nexport type Expanded = {\n /** Keys of the open items. */\n expanded: ReadonlySet<string>;\n /** Replaces the open set. `DataTable` calls this. */\n onChange: (next: Set<string>) => void;\n isOpen: (key: string) => boolean;\n setOpen: (key: string, open: boolean) => void;\n collapseAll: () => void;\n};\n\nexport type ExpandedOptions = {\n /** Keep the open keys in this URL search parameter (`?open=a&open=b`), so an opened row can be linked and survives a reload. Needs a React Router context. */\n param?: string;\n /** Keys open at first. Ignored with `param`: there the URL says what is open, so a link that opens a row carries it. */\n initial?: Iterable<string>;\n /** Opening one closes the others (an accordion). Default false: people compare two rows. */\n single?: boolean;\n};\n\n/** Shared open state for the disclosures of one list or table, optionally kept in the URL (`param`). */\nexport function useExpanded(options: ExpandedOptions = {}): Expanded {\n // One of two hooks, chosen by whether `param` is given; a screen does not switch between the two\n // while mounted (as with DataTable's `sortParam`), so the hook order is stable.\n return options.param ? useUrlExpanded(options.param, options) : useLocalExpanded(options);\n}\n\nfunction api(expanded: ReadonlySet<string>, set: (next: Set<string>) => void, single?: boolean): Expanded {\n return {\n expanded,\n // With `single`, a change that opens a key keeps only that key, so `DataTable` (which calls\n // onChange with the whole set) gets the accordion too, not only `setOpen`.\n onChange: (next) => {\n const opened = single ? [...next].filter((k) => !expanded.has(k)) : [];\n set(opened.length ? new Set([opened[opened.length - 1]]) : next);\n },\n isOpen: (key) => expanded.has(key),\n setOpen: (key, open) => {\n const next = single ? new Set<string>() : new Set(expanded);\n if (open) next.add(key);\n else next.delete(key);\n set(next);\n },\n collapseAll: () => set(new Set()),\n };\n}\n\nfunction useLocalExpanded({ initial = [], single }: ExpandedOptions): Expanded {\n const [expanded, setExpanded] = React.useState<ReadonlySet<string>>(() => new Set(initial));\n return React.useMemo(() => api(expanded, setExpanded, single), [expanded, single]);\n}\n\nfunction useUrlExpanded(param: string, { single }: ExpandedOptions): Expanded {\n const [params, setParams] = useSearchParams();\n const fromUrl = params.getAll(param);\n const joined = fromUrl.join(\"\\u0000\");\n // `fromUrl` is a new array each render; its joined form is the dependency.\n const expanded = React.useMemo<ReadonlySet<string>>(() => new Set(fromUrl), [joined]);\n const set = React.useCallback(\n (next: Set<string>) =>\n setParams(\n (p) => {\n const out = new URLSearchParams(p);\n out.delete(param);\n for (const k of next) out.append(param, k);\n return out;\n },\n { replace: true },\n ),\n [param, setParams],\n );\n return React.useMemo(() => api(expanded, set, single), [expanded, set, single]);\n}\n","import * as React from \"react\";\nimport { X } from \"lucide-react\";\nimport { format as defaultFormat, type Format } from \"../lib/format\";\nimport { cn } from \"../lib/utils\";\nimport { Button } from \"./button\";\n\n// Select many, then act: the state (`useSelection`), and the bar that says how many are chosen and\n// holds what can be done to them (`BulkBar`). `DataTable`'s `selection` prop draws the checkboxes.\n//\n// The selection is pruned to the rows that exist. After a bulk removal, a refetch or a new filter,\n// a key whose row is gone is not counted and not acted on: the bar never says \"3 selected\" over\n// two visible rows, and an action never reaches a row the person cannot see. (Gmail and Linear\n// both drop a selection a filter hides; acting on hidden rows is how a bulk delete surprises.)\n//\n// Shift extends a range from the last row clicked, on every surface (`useSelectRows`), and\n// `initial` chooses a row when it first appears rather than only on mount, so a selection seeded\n// from data still applies once the data arrives (both from strata-react issue #32, a review screen\n// of face crops with the likely matches pre-chosen).\n//\n// The count is the bar's live region, and only the count: it is always mounted, so a screen reader\n// hears \"2 bookings selected\" on each change, and the buttons are outside it, so their names are\n// not read again with every tick. The actions are a labelled group. Per the research, at most one\n// of them is filled (`variant=\"default\"`), named with its verb and count (\"Withdraw 3\"), and a\n// reversible bulk removal goes through `useUndoable` like a single one, not through a confirm.\n\n/** Which rows start chosen: their keys, or a test on each row. Either applies to a row the first time it appears. */\nexport type InitialSelection<T> = Iterable<string> | ((row: T) => boolean);\n\ntype SelectionState = { keys: readonly string[]; seen: ReadonlySet<string>; raw: ReadonlySet<string> };\n\n// Bring the state up to the rows now shown: drop keys whose row has gone, and choose the rows seen\n// for the first time that `initial` names. A row seen before keeps the person's choice, even if it\n// left and came back (it returns unchosen, as it was forgotten when it left).\nfunction reconcile<T>(prev: SelectionState, rows: readonly T[], keys: readonly string[], initial: (row: T, key: string) => boolean): SelectionState {\n const present = new Set(keys);\n const raw = new Set([...prev.raw].filter((k) => present.has(k)));\n const seen = new Set(prev.seen);\n rows.forEach((row, i) => {\n const key = keys[i];\n if (seen.has(key)) return;\n seen.add(key);\n if (initial(row, key)) raw.add(key);\n });\n return { keys, seen, raw };\n}\n\nconst sameKeys = (a: readonly string[], b: readonly string[]) => a.length === b.length && a.every((k, i) => k === b[i]);\n\n/**\n * Chosen row keys, pruned to the rows that exist, and the calls that change them. Spread into\n * `DataTable`'s or `SelectableGrid`'s `selection` with a `rowLabel`. `initial` (keys, or a test on\n * the row) chooses each row the first time it appears, so a selection seeded from data that loads\n * later, or a next page, still starts right.\n */\nexport function useSelection<T>(rows: readonly T[], rowKey: (row: T) => string, initial: InitialSelection<T> = []) {\n // `initial` is read when a row first appears, so a new function each render is fine.\n const initialRef = React.useRef(initial);\n initialRef.current = initial;\n // Keys are read into a set once per `initial` value, not once per row: a single-use iterable (a\n // generator, `set.values()`) would otherwise be used up by the first row, and an array rebuilt\n // for every row. The set is kept for rows that arrive later.\n const initialKeys = React.useRef<{ source: InitialSelection<T>; keys: ReadonlySet<string> } | undefined>(undefined);\n const test = (row: T, key: string) => {\n const init = initialRef.current;\n if (typeof init === \"function\") return init(row);\n if (initialKeys.current?.source !== init) initialKeys.current = { source: init, keys: new Set(init) };\n return initialKeys.current.keys.has(key);\n };\n const keys = rows.map(rowKey);\n const [state, setState] = React.useState<SelectionState>(() =>\n reconcile({ keys: [], seen: new Set(), raw: new Set() }, rows, keys, test),\n );\n // Adjusted while rendering (React's pattern for state derived from props), not in an effect, so\n // the first paint of new rows already shows them chosen. Compared by key, not by array identity,\n // so `rows={data ?? []}` does not loop.\n let current = state;\n if (!sameKeys(state.keys, keys)) {\n current = reconcile(state, rows, keys, test);\n setState(current);\n }\n const selected = current.raw;\n // rowKey is usually an inline arrow, so it is left out of the dependencies: the rows change.\n const selectedRows = React.useMemo(() => rows.filter((r) => selected.has(rowKey(r))), [rows, selected]);\n // A key with no row is never kept, so an action never reaches a row the person cannot see.\n const onChange = React.useCallback(\n (next: Set<string>) =>\n setState((s) => {\n const present = new Set(s.keys);\n return { ...s, raw: new Set([...next].filter((k) => present.has(k))) };\n }),\n [],\n );\n const clear = React.useCallback(() => setState((s) => ({ ...s, raw: new Set() })), []);\n return { selected, selectedRows, count: selected.size, onChange, clear };\n}\n\n/** The part of a selection the surfaces drawing it (`DataTable`, `SelectableGrid`) need. */\ntype SelectionLike<T> = {\n selected: ReadonlySet<string>;\n onChange: (next: Set<string>) => void;\n isSelectable?: (row: T) => boolean;\n};\n\n/**\n * Selecting rows of a surface in the order it shows them: one row, a range with Shift, and all\n * shown. Shared by `DataTable` and `SelectableGrid`, so a range and select-all behave the same on\n * both. `rows` are in display order (after sorting) and include rows a virtualised surface has not\n * rendered.\n *\n * A range runs from the last row clicked (the anchor) to this one, over the selectable rows\n * between, and sets them all to this row's new state, as Gmail and Finder do: Shift-clicking an\n * unchosen row chooses the run, Shift-clicking a chosen one clears it. Every click moves the\n * anchor. An anchor that has left the rows (filtered, removed) makes the next Shift-click a plain\n * one.\n * @internal\n */\nexport function useSelectRows<T>(rows: readonly T[], rowKey: (row: T) => string, selection?: SelectionLike<T>) {\n const anchor = React.useRef<string | undefined>(undefined);\n const keys = selection ? rows.filter((r) => selection.isSelectable?.(r) ?? true).map(rowKey) : [];\n const chosen = selection ? keys.filter((k) => selection.selected.has(k)).length : 0;\n const allChecked: boolean | \"mixed\" = chosen === 0 ? false : chosen === keys.length ? true : \"mixed\";\n\n const toggle = (key: string, on: boolean, { shiftKey }: { shiftKey: boolean }) => {\n if (!selection) return;\n const next = new Set(selection.selected);\n const from = shiftKey && anchor.current !== undefined ? keys.indexOf(anchor.current) : -1;\n const to = keys.indexOf(key);\n if (from >= 0 && to >= 0) {\n const [a, b] = from < to ? [from, to] : [to, from];\n for (const k of keys.slice(a, b + 1)) {\n if (on) next.add(k);\n else next.delete(k);\n }\n } else if (on) next.add(key);\n else next.delete(key);\n anchor.current = key;\n selection.onChange(next);\n };\n\n // A full or mixed box clears what is shown; an empty one selects every selectable row shown.\n // Keys outside `rows` (filtered away) are left as they are.\n const toggleAll = () => {\n if (!selection) return;\n const next = new Set(selection.selected);\n if (allChecked === false) keys.forEach((k) => next.add(k));\n else keys.forEach((k) => next.delete(k));\n selection.onChange(next);\n };\n\n return { toggle, all: { checked: allChecked, toggle: toggleAll, disabled: keys.length === 0 } };\n}\n\n/** The bar for a selection: a polite live count (\"2 bookings selected\"), the bulk actions, and Clear selection. Renders only the live region while nothing is chosen. */\nexport function BulkBar({\n count,\n noun,\n onClear,\n children,\n format = defaultFormat,\n className,\n}: {\n count: number;\n /** What is chosen, singular, or singular and plural: `\"booking\"`, `[\"person\", \"people\"]`. */\n noun: string | [one: string, many: string];\n onClear: () => void;\n /** The actions. At most one filled button, named with its verb and count; while the bar is up it is the view's only filled button, so the screen's own primary goes to `outline`. */\n children: React.ReactNode;\n /** The product's formatters, for the count's figures and plural. Default en-GB. */\n format?: Format;\n className?: string;\n}) {\n const [one, many] = typeof noun === \"string\" ? [noun, `${noun}s`] : noun;\n const label = `${format.count(count, one, many)} selected`;\n return (\n <div\n className={cn(\n count > 0 && \"flex flex-wrap items-center gap-x-4 gap-y-2 rounded-surface bg-surface-sunken py-1.5 pr-1.5 pl-3\",\n className,\n )}\n >\n <p aria-live=\"polite\" className={count > 0 ? \"type-label tabular-nums\" : \"sr-only\"}>\n {count > 0 ? label : `No ${many} selected`}\n </p>\n {count > 0 && (\n <div role=\"group\" aria-label={`Actions for the selected ${many}`} className=\"flex flex-1 flex-wrap items-center gap-2\">\n {children}\n <Button size=\"sm\" variant=\"ghost\" className=\"ml-auto\" onClick={onClear}>\n <X aria-hidden />\n Clear selection\n </Button>\n </div>\n )}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { ArrowDown, ArrowUp, ArrowUpDown } from \"lucide-react\";\nimport {\n createSortedRowModel,\n flexRender,\n rowSortingFeature,\n tableFeatures,\n useTable,\n type ColumnDef,\n type SortingState,\n} from \"@tanstack/react-table\";\nimport { useVirtualizer } from \"@tanstack/react-virtual\";\nimport { useSearchParams } from \"react-router\";\nimport { format } from \"../lib/format\";\nimport { cn } from \"../lib/utils\";\nimport { Checkbox } from \"./checkbox\";\nimport { Chevron } from \"./disclosure\";\nimport { useSelectRows } from \"./selection\";\n\n// The table real product screens use: 12px muted sentence-case headers, row rules (no zebra),\n// numbers right-aligned in tabular figures, one status mark and at most one action per row.\n// Sortable headers are buttons and look sortable; aria-sort says which way. The scroll container is\n// a labelled, focusable region so keyboard users can scroll a wide table.\n//\n// Underneath: TanStack Table for the row model and sorting, TanStack Virtual once a table passes\n// `virtualizeFrom` rows (only the visible rows are in the DOM; the header sticks). The column API\n// stays small on purpose (key, header, cell, numeric, sort), so a screen reads as a list of\n// decisions about columns, not as table plumbing. `sortParam` keeps the sort in the URL\n// (?sort=when.desc) so a sorted view can be linked and survives a reload.\n//\n// Selection is opt-in (`selection`), because checkboxes belong only where a bulk action exists\n// (one of 23 real product screens had them; a checkbox on every row is a generated-UI tell). When\n// it is on, the first column is a checkbox per row, named from the row (`rowLabel` is required),\n// disabled where `isSelectable` says no; the header's \"Select all shown\" covers the selectable rows\n// in `rows` (all of them, not only the rendered ones of a virtualised table) and is mixed when some\n// are chosen. Shift-click (or Shift+Space) chooses or clears the run from the last row clicked, in\n// the sorted order shown (`useSelectRows`, shared with `SelectableGrid`). Selected rows take the sunken fill, not a ring, so a selection never reads as focus.\n// The table only draws the selection; the state is the caller's, usually `useSelection`, and the\n// actions live in a `BulkBar`.\n//\n// Expansion is opt-in too (`expansion`): a row opens a detail row under it, for what belongs to\n// the row but would crowd the table (a firing's pieces, a batch's faces). It follows `Disclosure`:\n// the toggle is a button with `aria-expanded`, named for what it shows (`rowLabel`, \"Pieces in\n// firing 412\"), and the detail is mounted only while open, so a `useLoad` inside it runs on the\n// first open and not for every row on load. The detail row spans the data columns, starts under\n// the first of them, and has no rule between it and its row, so the two read as one. State is the\n// caller's, usually `useExpanded` (which can keep it in the URL). A virtualised table measures\n// each detail row, so details of any height scroll correctly.\n//\n// Missing values (strata-react issue #47, from the Tubes Library table): a column that gives\n// `value` gets a typed sort (numbers, then text in the locale's order with numbers in it read as\n// numbers, then dates) and a placeholder for a row whose value is `null` or `undefined`: an en\n// dash in the muted ink, named \"No value\" for a screen reader, or the column's `missing` word\n// where the word carries meaning (\"Never\"). Missing rows sort after every real value in both\n// directions, because \"not known\" is not \"smallest\"; a column's own `sort` still decides the\n// order among the rows that have a value. Without `value` a column works as before.\n\n/** What a column's `value` may be: a number, text or a date, or `null`/`undefined` when the row has none. */\nexport type CellValue = number | string | Date | null | undefined;\n\nexport type Column<T> = {\n key: string;\n header: string;\n /** Right-aligns and sets tabular figures. Use for every quantity. */\n numeric?: boolean;\n /** Orders two rows. With `value`, it orders only rows that have one (missing ones go last); `false` turns off `value`'s default sort. */\n sort?: ((a: T, b: T) => number) | false;\n /** What the cell shows when the row's `value` is missing, where the word carries meaning (\"Never\"). Default an en dash. */\n missing?: string;\n /** Cells that may hold long text get truncated rather than stretching the table. */\n truncate?: boolean;\n /** Keep the header for screen readers only, as for a column of row actions. `header` still names it. */\n hideHeader?: boolean;\n className?: string;\n} & (\n | {\n cell: (row: T) => React.ReactNode;\n /** The row's value for this column: gives a typed default sort with missing values last, and the missing placeholder. */\n value?: (row: T) => CellValue;\n }\n | {\n /** How a row with a value is drawn. Default: numbers through `format.decimal`, dates through `format.date`, text as it is. */\n cell?: (row: T) => React.ReactNode;\n /** The row's value for this column: gives a typed default sort with missing values last, and the missing placeholder. */\n value: (row: T) => CellValue;\n }\n);\n\nconst collator = new Intl.Collator(undefined, { numeric: true, sensitivity: \"base\" });\nconst kind = (v: number | string | Date) => (typeof v === \"number\" ? 0 : typeof v === \"string\" ? 1 : 2);\n\n/** Orders two present values: numbers, then text (locale order, numbers in text read as numbers), then dates. */\nfunction compareValues(a: number | string | Date, b: number | string | Date) {\n if (kind(a) !== kind(b)) return kind(a) - kind(b);\n if (typeof a === \"string\") return collator.compare(a, b as string);\n return Number(a) - Number(b);\n}\n\n/** A cell with no value: the column's word, or an en dash named \"No value\" for a screen reader. */\nfunction Missing({ word }: { word?: string }) {\n return word ? (\n <span className=\"text-muted-foreground\">{word}</span>\n ) : (\n <span className=\"text-muted-foreground\">\n <span aria-hidden>{format.missing}</span>\n <span className=\"sr-only\">No value</span>\n </span>\n );\n}\n\nfunction drawValue(v: number | string | Date) {\n return typeof v === \"number\" ? format.decimal(v) : v instanceof Date ? format.date(v) : v;\n}\n\n/** Row selection for a `DataTable`: the chosen row keys, how to change them, and how to name each row's checkbox. */\nexport type RowSelection<T> = {\n /** Keys (from `rowKey`) of the chosen rows. */\n selected: ReadonlySet<string>;\n onChange: (next: Set<string>) => void;\n /** Names the row in its checkbox (\"Select <rowLabel>\"). Required: an unnamed checkbox is a column of \"checkbox, not checked\". */\n rowLabel: (row: T) => string;\n /** Rows that cannot be chosen get a disabled checkbox and are left out of select-all. Default: every row. */\n isSelectable?: (row: T) => boolean;\n};\n\n/** Row expansion for a `DataTable`: the open row keys, how to change them, how to name each toggle, and the detail to show. */\nexport type RowExpansion<T> = {\n /** Keys (from `rowKey`) of the open rows. */\n expanded: ReadonlySet<string>;\n onChange: (next: Set<string>) => void;\n /** Names the row's toggle by what it shows: \"Pieces in firing 412\". Its state is `aria-expanded`, so the name stays the same open or closed. */\n rowLabel: (row: T) => string;\n /** The row's detail, mounted only while it is open. Return an element whose component makes any request, so the request runs on open. */\n detail: (row: T) => React.ReactNode;\n /** Rows with nothing to show get no toggle. Default: every row. */\n isExpandable?: (row: T) => boolean;\n};\n\nexport type Sort = { key: string; dir: \"ascending\" | \"descending\" };\n\nexport type DataTableProps<T> = {\n /** Names the table for screen readers and labels the scroll region. */\n caption: string;\n columns: Column<T>[];\n rows: T[];\n rowKey: (row: T) => string;\n initialSort?: Sort;\n /** Keep the sort in this URL search parameter. Needs a React Router context. */\n sortParam?: string;\n /** Row count from which only the visible rows render. Default 100. */\n virtualizeFrom?: number;\n /** Height of the scroll region once virtualised, in px. Default 480. */\n maxHeight?: number;\n /** Adds a checkbox column and \"Select all shown\". Use only where a `BulkBar` acts on the selection. */\n selection?: RowSelection<T>;\n /** Adds a toggle per row that opens a detail row under it. Spread `useExpanded()` in with a `rowLabel` and `detail`. */\n expansion?: RowExpansion<T>;\n className?: string;\n};\n\ntype SortState = [Sort | undefined, (next: Sort) => void];\n\nfunction useLocalSort(initial?: Sort): SortState {\n const [sort, setSort] = React.useState(initial);\n return [sort, setSort];\n}\n\n/** Reads a sort from its URL form (`pieces.desc`). */\nexport function parseSort(value: string | null): Sort | undefined {\n if (!value) return undefined;\n const [key, dir] = value.split(\".\");\n if (!key) return undefined;\n return { key, dir: dir === \"desc\" ? \"descending\" : \"ascending\" };\n}\n\n/** Writes a sort in its URL form (`pieces.desc`). */\nexport function serialiseSort(sort: Sort) {\n return `${sort.key}.${sort.dir === \"descending\" ? \"desc\" : \"asc\"}`;\n}\n\nfunction useUrlSort(param: string, initial?: Sort): SortState {\n const [params, setParams] = useSearchParams();\n const sort = parseSort(params.get(param)) ?? initial;\n const set = React.useCallback(\n (next: Sort) =>\n setParams(\n (p) => {\n const out = new URLSearchParams(p);\n out.set(param, serialiseSort(next));\n return out;\n },\n { replace: true },\n ),\n [param, setParams],\n );\n return [sort, set];\n}\n\n/** A table on TanStack Table: muted headers, row rules, right-aligned tabular numbers, sortable headers with `aria-sort`, virtualised from `virtualizeFrom` rows, sort optionally kept in the URL (`sortParam`). */\nexport function DataTable<T>(props: DataTableProps<T>) {\n // Two thin wrappers so each calls its hooks unconditionally.\n return props.sortParam ? <UrlSortedTable {...props} sortParam={props.sortParam} /> : <LocalSortedTable {...props} />;\n}\n\nfunction LocalSortedTable<T>(props: DataTableProps<T>) {\n return <Table {...(props as unknown as DataTableProps<Rec>)} sortState={useLocalSort(props.initialSort)} />;\n}\n\nfunction UrlSortedTable<T>(props: DataTableProps<T> & { sortParam: string }) {\n return <Table {...(props as unknown as DataTableProps<Rec>)} sortState={useUrlSort(props.sortParam, props.initialSort)} />;\n}\n\ntype Meta = { numeric?: boolean; truncate?: boolean; hideHeader?: boolean; className?: string };\n\n// The one TanStack feature in use: sorting, on the client. TanStack Table 9 is tree-shaken by feature, so\n// nothing else (pagination, filtering, TanStack's own selection or expansion) is bundled.\nconst features = tableFeatures({ rowSortingFeature, sortedRowModel: createSortedRowModel() });\n// TanStack Table 9 requires object or array rows. Every row a DataTable draws is a record, but the\n// public `T` stays unconstrained so an app's row types need no change: the cast is in the two wrappers.\ntype Rec = Record<string, any>; // TanStack's own RowData\n\nfunction Table<T extends Rec>({\n caption,\n columns,\n rows,\n rowKey,\n sortState: [sort, setSort],\n virtualizeFrom = 100,\n maxHeight = 480,\n selection,\n expansion,\n className,\n}: DataTableProps<T> & { sortState: SortState }) {\n const baseId = React.useId();\n const defs = React.useMemo<ColumnDef<typeof features, T, unknown>[]>(\n () =>\n columns.map((c): ColumnDef<typeof features, T, unknown> => {\n const meta = { numeric: c.numeric, truncate: c.truncate, hideHeader: c.hideHeader, className: c.className } satisfies Meta;\n const { value, sort } = c;\n if (!value) {\n return {\n id: c.key,\n // TanStack only sorts columns with an accessor; the row itself is enough, since the\n // column's own comparator does the work.\n accessorFn: (row) => row,\n header: c.header,\n cell: (info) => c.cell?.(info.row.original),\n enableSorting: Boolean(sort),\n sortFn: sort ? (a, b) => sort(a.original, b.original) : undefined,\n meta,\n };\n }\n // The accessor is the value, with null as undefined, so TanStack's `sortUndefined: \"last\"`\n // keeps missing rows at the end whichever way the column is sorted (it applies before the\n // direction is). The comparator then sees only rows that have a value.\n return {\n id: c.key,\n accessorFn: (row) => value(row) ?? undefined,\n header: c.header,\n cell: (info) => {\n const v = value(info.row.original);\n if (v == null) return <Missing word={c.missing} />;\n return c.cell ? c.cell(info.row.original) : drawValue(v);\n },\n enableSorting: sort !== false,\n sortUndefined: \"last\",\n sortFn: sort\n ? (a, b) => sort(a.original, b.original)\n : (a, b) => compareValues(a.getValue<number | string | Date>(c.key), b.getValue<number | string | Date>(c.key)),\n meta,\n };\n }),\n [columns],\n );\n\n const sorting: SortingState = sort && columns.some((c) => c.key === sort.key && (c.value ? c.sort !== false : c.sort))\n ? [{ id: sort.key, desc: sort.dir === \"descending\" }]\n : [];\n\n const table = useTable({\n features,\n data: rows,\n columns: defs,\n state: { sorting },\n getRowId: (row) => rowKey(row),\n // No pagination here, and expansion is the caller's state, not TanStack's: nothing to reset. Left on, TanStack resets the page\n // index whenever `rows` is a new array; a screen that filters its rows on every render (the\n // kiln room after Withdraw) then re-renders forever and the tab freezes. Found by the\n // example app's visual suite, which jsdom did not show.\n autoResetAll: false,\n });\n\n const toggle = (key: string) =>\n setSort({ key, dir: sort?.key === key && sort.dir === \"ascending\" ? \"descending\" : \"ascending\" });\n\n const modelRows = table.getRowModel().rows;\n const canExpand = (row: T) => expansion?.isExpandable?.(row) ?? true;\n // What the body draws, in order: every row, and a detail line after each open one. The\n // virtualiser counts these lines, so an open detail takes its own measured slot.\n const lines = React.useMemo(\n () =>\n expansion\n ? modelRows.flatMap((row) =>\n expansion.expanded.has(row.id) && canExpand(row.original)\n ? [{ row, detail: false }, { row, detail: true }]\n : [{ row, detail: false }],\n )\n : modelRows.map((row) => ({ row, detail: false })),\n // canExpand reads `expansion`, which is a dependency.\n [modelRows, expansion],\n );\n // In the order shown, so a Shift-click range runs down the sorted table, not the data's order.\n const sortedRows = React.useMemo(() => modelRows.map((r) => r.original), [modelRows]);\n const select = useSelectRows(sortedRows, rowKey, selection);\n const selectAll = selection ? select.all : undefined;\n const virtual = modelRows.length >= virtualizeFrom;\n const scroller = React.useRef<HTMLDivElement>(null);\n const virtualizer = useVirtualizer({\n count: virtual ? lines.length : 0,\n getScrollElement: () => scroller.current,\n estimateSize: (i) => (lines[i]?.detail ? 160 : 41),\n // Keyed by row and line kind, not by position: opening or closing a detail shifts every line\n // after it, and a measured detail height must stay with its detail, not pass to the row that\n // takes its index (rows are not measured, so a wrong height would never be corrected).\n getItemKey: (i) => (lines[i] ? `${lines[i].row.id}${lines[i].detail ? \"\\u0000detail\" : \"\"}` : i),\n overscan: 8,\n // Until the region is measured, assume it is full height: the first paint (and a test DOM\n // with no layout) shows the first page of rows instead of none.\n initialRect: { width: 0, height: maxHeight },\n });\n const items = virtual ? virtualizer.getVirtualItems() : [];\n const padTop = items.length ? items[0].start : 0;\n const padBottom = items.length ? virtualizer.getTotalSize() - items[items.length - 1].end : 0;\n const visible = virtual ? items.map((i) => ({ ...lines[i.index], index: i.index })) : lines.map((l, index) => ({ ...l, index }));\n const lead = (selection ? 1 : 0) + (expansion ? 1 : 0);\n\n return (\n <div\n ref={scroller}\n role=\"region\"\n aria-label={caption}\n tabIndex={0}\n className={cn(\"relative min-w-0 overflow-x-auto\", virtual && \"overflow-y-auto\", className)}\n style={virtual ? { maxHeight } : undefined}\n >\n <table className=\"w-full border-collapse type-body-sm\" aria-rowcount={virtual ? lines.length + 1 : undefined}>\n <caption className=\"sr-only\">{caption}</caption>\n <thead className={cn(virtual && \"sticky top-0 z-10 bg-background\")}>\n {table.getHeaderGroups().map((group) => (\n <tr key={group.id}>\n {selectAll && (\n <th scope=\"col\" className=\"w-8 py-2 pr-2 text-left align-bottom\">\n <Checkbox\n className=\"-my-1\"\n label=\"Select all shown\"\n hideLabel\n checked={selectAll.checked}\n disabled={selectAll.disabled}\n onCheckedChange={selectAll.toggle}\n />\n </th>\n )}\n {expansion && (\n <th scope=\"col\" className=\"w-10 py-2 pr-2\">\n <span className=\"sr-only\">Details</span>\n </th>\n )}\n {group.headers.map((header) => {\n const meta = header.column.columnDef.meta as Meta | undefined;\n const active = sort?.key === header.id && header.column.getCanSort() ? sort.dir : undefined;\n const Icon = active === \"ascending\" ? ArrowUp : active === \"descending\" ? ArrowDown : ArrowUpDown;\n const rendered = flexRender(header.column.columnDef.header, header.getContext());\n const label = meta?.hideHeader ? <span className=\"sr-only\">{rendered}</span> : rendered;\n return (\n <th\n key={header.id}\n scope=\"col\"\n aria-sort={active}\n className={cn(\n \"py-2 pr-4 text-left align-bottom type-caption text-muted-foreground last:pr-0\",\n meta?.numeric && \"text-right\",\n )}\n >\n {header.column.getCanSort() ? (\n <button\n type=\"button\"\n onClick={() => toggle(header.id)}\n className={cn(\n \"-mx-1 inline-flex cursor-pointer items-center gap-1 rounded-control px-1 transition-state hover:text-foreground\",\n meta?.numeric && \"flex-row-reverse\",\n active && \"text-foreground\",\n )}\n >\n {label}\n <Icon aria-hidden className={cn(\"size-3.5\", !active && \"opacity-50\")} />\n </button>\n ) : (\n label\n )}\n </th>\n );\n })}\n </tr>\n ))}\n </thead>\n <tbody>\n {padTop > 0 && <tr aria-hidden style={{ height: padTop }} />}\n {visible.map(({ row, detail, index }) => {\n const chosen = selection?.selected.has(row.id) ?? false;\n const detailId = `${baseId}-detail-${row.id}`;\n if (detail && expansion)\n return (\n <tr\n key={`${row.id}-detail`}\n ref={virtual ? virtualizer.measureElement : undefined}\n data-index={index}\n className={cn(chosen && \"bg-surface-sunken\")}\n aria-rowindex={virtual ? index + 2 : undefined}\n >\n {lead > 0 && <td colSpan={lead} />}\n <td id={detailId} colSpan={columns.length} className=\"pt-0.5 pb-4 align-top\">\n {expansion.detail(row.original)}\n </td>\n </tr>\n );\n const open = expansion?.expanded.has(row.id) ?? false;\n return (\n <tr\n key={row.id}\n className={cn(\"border-t border-border\", chosen && \"bg-surface-sunken\")}\n aria-rowindex={virtual ? index + 2 : undefined}\n >\n {selection && (\n <td className=\"w-8 py-2.5 pr-2 align-middle\">\n <Checkbox\n className=\"-my-0.5\"\n label={`Select ${selection.rowLabel(row.original)}`}\n hideLabel\n checked={chosen}\n disabled={!(selection.isSelectable?.(row.original) ?? true)}\n onCheckedChange={(on, gesture) => select.toggle(row.id, on, gesture)}\n />\n </td>\n )}\n {expansion && (\n <td className=\"w-10 py-2.5 pr-2 align-middle\">\n {canExpand(row.original) && (\n <button\n type=\"button\"\n aria-expanded={open}\n aria-controls={open ? detailId : undefined}\n aria-label={expansion.rowLabel(row.original)}\n title={expansion.rowLabel(row.original)}\n onClick={() => {\n const next = new Set(expansion.expanded);\n if (open) next.delete(row.id);\n else next.add(row.id);\n expansion.onChange(next);\n }}\n className=\"-my-1.5 grid size-(--control-h-sm) cursor-pointer place-items-center rounded-control hover:bg-muted\"\n >\n <Chevron open={open} />\n </button>\n )}\n </td>\n )}\n {row.getAllCells().map((cell) => {\n const meta = cell.column.columnDef.meta as Meta | undefined;\n return (\n <td\n key={cell.id}\n className={cn(\n \"py-2.5 pr-4 align-middle last:pr-0\",\n meta?.numeric && \"text-right tabular-nums\",\n meta?.truncate && \"max-w-48 truncate\",\n meta?.className,\n )}\n >\n {flexRender(cell.column.columnDef.cell, cell.getContext())}\n </td>\n );\n })}\n </tr>\n );\n })}\n {padBottom > 0 && <tr aria-hidden style={{ height: padBottom }} />}\n </tbody>\n </table>\n </div>\n );\n}\n\n/** The loading placeholder for a `DataTable`, shaped like its rows. */\nexport function TableSkeleton({ rows = 4, columns = 5 }: { rows?: number; columns?: number }) {\n return (\n <div aria-hidden className=\"grid gap-0\">\n <div className=\"flex gap-4 py-2\">\n {Array.from({ length: columns }, (_, i) => (\n <div key={i} className=\"h-3 flex-1 rounded-control bg-muted\" />\n ))}\n </div>\n {Array.from({ length: rows }, (_, r) => (\n <div key={r} className=\"flex gap-4 border-t border-border py-3.5\">\n {Array.from({ length: columns }, (_, i) => (\n <div key={i} className=\"h-4 flex-1 rounded-control bg-muted motion-safe:animate-pulse\" />\n ))}\n </div>\n ))}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { useVirtualizer } from \"@tanstack/react-virtual\";\nimport { cn } from \"../lib/utils\";\nimport { Checkbox as AriaCheckbox } from \"react-aria-components\";\nimport { Check } from \"lucide-react\";\nimport { Checkbox, useShiftNote, type CheckboxGesture } from \"./checkbox\";\nimport type { RowSelection } from \"./data-table\";\nimport { useSelectRows } from \"./selection\";\n\n// Choosing from pictures: a review screen of face crops, a set of glaze test tiles, photos to\n// archive. It is `DataTable`'s selection drawn as a grid (strata-react issue #32, from the Bright\n// Horizons port, where the Groups screen had to be built by hand from `Checkbox` and\n// `useSelection`), and it shares the state and the rules: `useSelection` holds the keys, a\n// `BulkBar` holds the actions, select-all covers the selectable tiles shown (all of them, rendered\n// or not) and is mixed when some are chosen, and Shift-click or Shift+Space chooses or clears the\n// run from the last tile clicked (`useSelectRows`, the same code the table uses).\n//\n// Each tile is one target: the picture, the box and the detail line sit in one <label>, so a click\n// anywhere on the picture toggles it (Google Photos and Apple Photos select from the picture, not\n// only from the box). The box is named from the row (`rowLabel` is required, as the table's is),\n// so a screen reader hears \"Select Ada Lovelace, crop 3\", not twelve \"checkbox, not checked\". The\n// box sits on a chip of the page's ground in the picture's corner, so it stays visible on any\n// photo. A chosen tile takes the sunken fill and a primary border, not a ring: the focus outline is\n// the only ring, so a selection never reads as focus.\n//\n// The picture is the caller's (`renderImage`), in a frame of fixed aspect (`aspect`, square by\n// default) so tiles line up and nothing shifts as images load; an <img> or Strata's `Thumbnail`\n// fills it. Tiles are sized by a minimum width (`tileSize`) and fill the row. From\n// `virtualizeFrom` tiles (100, as the table and list) the grid renders only the visible rows of\n// tiles in a labelled, focusable scroll region, measuring its width to know how many fit a row.\n\n/** The frame each picture is drawn in. */\nexport type TileAspect = \"square\" | \"portrait\" | \"landscape\";\n\n/** Smallest tile width: `sm` 96px (dense crops), `md` 144px, `lg` 192px. Tiles grow to fill the row. */\nexport type TileSize = \"sm\" | \"md\" | \"lg\";\n\nexport type SelectableGridProps<T> = {\n /** Names the list of tiles (and its scroll region once virtualised). */\n label: string;\n rows: T[];\n rowKey: (row: T) => string;\n /** The picture, drawn to fill a frame of `aspect`. An `<img className=\"size-full object-cover\">` or a `Thumbnail`. */\n renderImage: (row: T) => React.ReactNode;\n /** A short line under the picture (a name, a date, a score). Truncated to one line. */\n detail?: (row: T) => React.ReactNode;\n /** The chosen keys and how to change them, as `DataTable` takes them; `rowLabel` names each tile's box. */\n selection: RowSelection<T>;\n /** Default `square`. `portrait` is 3:4, `landscape` 4:3. */\n aspect?: TileAspect;\n /** Default `md`. */\n tileSize?: TileSize;\n /** Tile count from which only the visible rows of tiles render. Default 100. */\n virtualizeFrom?: number;\n /** Height of the scroll region once virtualised, in px. Default 480. */\n maxHeight?: number;\n className?: string;\n};\n\nconst minWidth: Record<TileSize, number> = { sm: 96, md: 144, lg: 192 };\nconst aspectClass: Record<TileAspect, string> = { square: \"aspect-square\", portrait: \"aspect-3/4\", landscape: \"aspect-4/3\" };\nconst aspectRatio: Record<TileAspect, number> = { square: 1, portrait: 4 / 3, landscape: 3 / 4 };\n// gap-3, in px, for the column count of a virtualised grid.\nconst GAP = 12;\n// The detail line and the tile's padding, for the first estimate of a row's height.\nconst TILE_CHROME = 40;\n\n/** A grid of pictures to choose from: each tile one labelled target, \"Select all shown\", Shift-click ranges, virtualised from `virtualizeFrom` tiles. Pair with `useSelection` and a `BulkBar`. */\nexport function SelectableGrid<T>({\n label,\n rows,\n rowKey,\n renderImage,\n detail,\n selection,\n aspect = \"square\",\n tileSize = \"md\",\n virtualizeFrom = 100,\n maxHeight = 480,\n className,\n}: SelectableGridProps<T>) {\n const select = useSelectRows(rows, rowKey, selection);\n const virtual = rows.length >= virtualizeFrom;\n\n const tile = (row: T, index: number) => {\n const key = rowKey(row);\n return (\n <Tile\n name={`Select ${selection.rowLabel(row)}`}\n chosen={selection.selected.has(key)}\n disabled={!(selection.isSelectable?.(row) ?? true)}\n onChange={(on, gesture) => select.toggle(key, on, gesture)}\n aspect={aspect}\n image={renderImage(row)}\n detail={detail?.(row)}\n index={index}\n />\n );\n };\n\n return (\n <div className={cn(\"grid min-w-0 gap-3\", className)}>\n <Checkbox\n className=\"justify-self-start\"\n label=\"Select all shown\"\n checked={select.all.checked}\n disabled={select.all.disabled}\n onCheckedChange={select.all.toggle}\n />\n {virtual ? (\n <VirtualTiles label={label} rows={rows} rowKey={rowKey} tile={tile} aspect={aspect} tileSize={tileSize} maxHeight={maxHeight} />\n ) : (\n <ul\n aria-label={label}\n className=\"grid gap-3\"\n style={{ gridTemplateColumns: `repeat(auto-fill, minmax(min(${minWidth[tileSize]}px, 100%), 1fr))` }}\n >\n {rows.map((row, i) => (\n <li key={rowKey(row)}>{tile(row, i)}</li>\n ))}\n </ul>\n )}\n </div>\n );\n}\n\nfunction VirtualTiles<T>({\n label,\n rows,\n rowKey,\n tile,\n aspect,\n tileSize,\n maxHeight,\n}: {\n label: string;\n rows: T[];\n rowKey: (row: T) => string;\n tile: (row: T, index: number) => React.ReactNode;\n aspect: TileAspect;\n tileSize: TileSize;\n maxHeight: number;\n}) {\n const scroller = React.useRef<HTMLDivElement>(null);\n const [width, setWidth] = React.useState(0);\n React.useLayoutEffect(() => {\n const el = scroller.current;\n if (!el || typeof ResizeObserver === \"undefined\") return;\n const observer = new ResizeObserver(([entry]) => setWidth(entry.contentRect.width));\n observer.observe(el);\n return () => observer.disconnect();\n }, []);\n const min = minWidth[tileSize];\n const columns = Math.max(1, Math.floor((width + GAP) / (min + GAP)));\n const tileWidth = width > 0 ? (width - GAP * (columns - 1)) / columns : min;\n const lines = Math.ceil(rows.length / columns);\n const virtualizer = useVirtualizer({\n count: lines,\n getScrollElement: () => scroller.current,\n estimateSize: () => Math.round(tileWidth * aspectRatio[aspect]) + TILE_CHROME + GAP,\n overscan: 3,\n // Keyed by the column count as well as the row: a new count moves every tile to another row,\n // so each row of tiles is a new element, measured afresh, not an old height reused.\n getItemKey: (i) => `${columns}:${i}`,\n // Until the region is measured, assume it is full height, so the first paint shows tiles.\n initialRect: { width: 0, height: maxHeight },\n });\n const items = virtualizer.getVirtualItems();\n\n return (\n <div\n ref={scroller}\n role=\"region\"\n aria-label={label}\n tabIndex={0}\n data-strata-scroll=\"\"\n className=\"min-w-0 overflow-y-auto\"\n style={{ height: maxHeight }}\n >\n {/* role=\"list\" over plain rows of tiles: each row is laid out on its own, and the rows add nothing for a screen reader. */}\n <div role=\"list\" aria-label={label} className=\"relative w-full\" style={{ height: virtualizer.getTotalSize() }}>\n {items.map((v) => {\n const start = v.index * columns;\n return (\n <div\n key={v.key}\n ref={virtualizer.measureElement}\n data-index={v.index}\n role=\"none\"\n className=\"absolute inset-x-0 top-0 grid gap-3 pb-3\"\n style={{ translate: `0 ${v.start}px`, gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` }}\n >\n {rows.slice(start, start + columns).map((row, i) => (\n <div key={rowKey(row)} role=\"listitem\" aria-setsize={rows.length} aria-posinset={start + i + 1}>\n {tile(row, start + i)}\n </div>\n ))}\n </div>\n );\n })}\n </div>\n </div>\n );\n}\n\nfunction Tile({\n name,\n chosen,\n disabled,\n onChange,\n aspect,\n image,\n detail,\n index,\n}: {\n name: string;\n chosen: boolean;\n disabled: boolean;\n onChange: (on: boolean, gesture: CheckboxGesture) => void;\n aspect: TileAspect;\n image: React.ReactNode;\n detail?: React.ReactNode;\n index: number;\n}) {\n const shift = useShiftNote();\n // The whole tile is one React Aria Checkbox (a label around a hidden input), so a press anywhere\n // on it toggles; the visible box in the corner is drawn from tokens. Shift is noted in the capture\n // phase because React Aria's press handling stops the events it uses.\n return (\n <span className=\"contents\" onMouseDownCapture={shift.handlers.onMouseDown} onKeyDownCapture={shift.handlers.onKeyDown}>\n <AriaCheckbox\n isSelected={chosen}\n isDisabled={disabled}\n aria-label={name}\n onChange={(on) => onChange(on, shift.take())}\n data-index={index}\n className={cn(\n // select-none: a Shift-click range would otherwise also select the text between the tiles.\n \"group relative grid min-w-0 gap-1.5 rounded-surface border border-transparent p-1.5 select-none transition-state\",\n \"data-[focus-visible]:outline-2 data-[focus-visible]:outline-offset-2 data-[focus-visible]:outline-ring\",\n chosen && \"border-primary bg-surface-sunken\",\n disabled ? \"cursor-not-allowed opacity-50\" : \"cursor-pointer hover:bg-surface-sunken\",\n )}\n >\n <span className={cn(\"block overflow-hidden rounded-control bg-muted *:size-full *:object-cover\", aspectClass[aspect])}>\n {image}\n </span>\n <span className=\"absolute top-3 left-3 grid size-7 place-items-center rounded-control bg-background\">\n <span\n aria-hidden\n className={cn(\n \"grid size-4.5 place-items-center rounded-control border border-input bg-background\",\n chosen && \"border-primary bg-primary text-primary-foreground\",\n )}\n >\n {chosen && <Check className=\"size-3.5\" strokeWidth={3} />}\n </span>\n </span>\n {detail != null && <span className=\"truncate type-body-sm text-muted-foreground\">{detail}</span>}\n </AriaCheckbox>\n </span>\n );\n}\n","import * as React from \"react\";\nimport { useVirtualizer } from \"@tanstack/react-virtual\";\nimport { cn } from \"../lib/utils\";\n\n// A long list that keeps only its visible rows in the DOM (TanStack Virtual), for feeds, logs and\n// pickers with hundreds of items. Rows are measured after render, so variable heights work; the\n// estimate only sets the first paint. The list is a labelled, focusable region so it can be\n// scrolled from the keyboard, and keeps list semantics with aria-setsize/aria-posinset so screen\n// readers still hear \"12 of 480\". Under `virtualizeFrom` items it renders a plain list.\n//\n// `bounded` keeps a short list in the same scroll region (capped at `height`) that the virtual\n// one uses, so a list that grows past `virtualizeFrom` while someone scrolls it (InfiniteList)\n// does not jump from the page's flow into a box. `footer` renders after the last row, inside the\n// scroll region: where InfiniteList puts its next-page row. Rows carry `data-index` in both modes.\n\n/** A list that renders only its visible rows (TanStack Virtual) from `virtualizeFrom` items, keeping list semantics for screen readers. */\nexport function VirtualList<T>({\n label,\n items,\n itemKey,\n children,\n estimateSize = 48,\n height = 480,\n virtualizeFrom = 100,\n bounded = false,\n footer,\n className,\n}: {\n label: string;\n items: T[];\n itemKey: (item: T) => string;\n children: (item: T, index: number) => React.ReactNode;\n estimateSize?: number;\n height?: number;\n virtualizeFrom?: number;\n /** Scroll inside a region capped at `height` even below `virtualizeFrom`, so growing past it changes nothing on screen. */\n bounded?: boolean;\n /** After the last row, inside the scroll region (a next-page row, an end note). */\n footer?: React.ReactNode;\n className?: string;\n}) {\n const scroller = React.useRef<HTMLDivElement>(null);\n const virtual = items.length >= virtualizeFrom;\n const virtualizer = useVirtualizer({\n count: virtual ? items.length : 0,\n getScrollElement: () => scroller.current,\n estimateSize: () => estimateSize,\n overscan: 6,\n initialRect: { width: 0, height },\n });\n\n // Built only when it is shown: a virtual list must not render every row it keeps out of the DOM.\n const plain = () => (\n <ul aria-label={label} className={cn(\"grid min-w-0\", !bounded && !footer && className)}>\n {items.map((item, i) => (\n <li key={itemKey(item)} data-index={i} className=\"border-t border-border first:border-t-0\">\n {children(item, i)}\n </li>\n ))}\n </ul>\n );\n\n if (!virtual && !bounded) {\n return footer ? (\n <div className={cn(\"min-w-0\", className)}>\n {plain()}\n {footer}\n </div>\n ) : (\n plain()\n );\n }\n\n return (\n <div\n ref={scroller}\n role=\"region\"\n aria-label={label}\n tabIndex={0}\n data-strata-scroll=\"\"\n className={cn(\"min-w-0 overflow-y-auto\", className)}\n style={virtual ? { height } : { maxHeight: height }}\n >\n {virtual ? (\n <ul aria-label={label} className=\"relative w-full\" style={{ height: virtualizer.getTotalSize() }}>\n {virtualizer.getVirtualItems().map((v) => {\n const item = items[v.index];\n return (\n <li\n key={itemKey(item)}\n ref={virtualizer.measureElement}\n data-index={v.index}\n aria-setsize={items.length}\n aria-posinset={v.index + 1}\n className={cn(\"absolute inset-x-0 top-0\", v.index > 0 && \"border-t border-border\")}\n style={{ translate: `0 ${v.start}px` }}\n >\n {children(item, v.index)}\n </li>\n );\n })}\n </ul>\n ) : (\n plain()\n )}\n {footer}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { CircleAlert, RotateCcw } from \"lucide-react\";\nimport { Button } from \"./button\";\nimport { DataView, type LoadFailure } from \"./data-view\";\nimport { VirtualList } from \"./virtual-list\";\nimport type { InfiniteLoad } from \"../query/infinite\";\nimport { useInView } from \"../lib/in-view\";\nimport { cn } from \"../lib/utils\";\n\n// A list that loads its next page as the person nears the end: the view for `useInfiniteLoad`.\n// It is DataView for the first page (skeleton, error with Try again, empty state, all required)\n// and VirtualList for the rows (virtualised from 100, so a long session stays fast), with one row\n// after the last item that is always in one of four states:\n//\n// - more to come: an IntersectionObserver sentinel with a root margin, so the next page is asked\n// for before the person reaches the end, and a real \"Show more\" button behind it. The button is\n// the keyboard and screen-reader path (an automatic load is invisible to them) and the fallback\n// where the observer never fires.\n// - loading: `moreSkeleton`, mirroring the rows that are coming, not a spinner, and a polite\n// status so a screen reader hears it.\n// - a later page failed: an alert row with the reason and Try again. The items already loaded\n// stay; a failed page 4 is not a failed list. The sentinel stops asking until Try again, so a\n// dead server is not called in a loop.\n// - the end: `end`, if given (\"That's every firing since March\"), so the person knows it is all.\n//\n// `keepAtLeast` loads more whenever fewer items than that are held: a queue people work through\n// (answered items `dismiss`ed) refills before it runs dry, even when nothing scrolls. Showing\n// more by button moves focus to the first new item, because the button the person pressed is\n// gone. The list scrolls in its own region (`height`) from the first page, so passing 100 items\n// and switching to virtual rows changes nothing on screen.\n//\n// Not every paged view is a list in a box (strata-react issue #49, from the Tubes viewer, whose\n// videos are a responsive card grid that scrolls with the page). So the next-page row is its own\n// export, `LoadMore`, which an app puts after any list or grid it draws itself, and InfiniteList\n// is built on it. `scroll=\"page\"` is the same in InfiniteList: no scroll region of its own and no\n// virtual rows, the items in a plain `ul` laid out by `listClassName` (a grid), and the sentinel\n// watching the viewport. Virtual rows need a box of known height, which a page-scrolled grid is\n// not; a feed long enough to need them belongs in the region. `error` and `moreError` replace the\n// look of a failed first page and a failed later page, as DataView's `error` does.\n\n/** The next-page row's props: `InfiniteList`'s, for a list or grid the app draws itself. */\nexport type LoadMoreProps<T> = {\n state: InfiniteLoad<T>;\n /** The button behind the sentinel, in the product's words: \"Show older firings\". */\n moreLabel: string;\n /** The items of a page on its way, mirroring the ones already drawn. */\n moreSkeleton: React.ReactNode;\n /** After the last page: say that this is everything. */\n end?: React.ReactNode;\n /** How far before the end the next page is asked for (IntersectionObserver `rootMargin`). Default 400px. */\n rootMargin?: string;\n /** Load more whenever fewer than this many items are held. */\n keepAtLeast?: number;\n /** Draws a failed later page, given the reason and the Try again. Rendered inside a `role=\"alert\"` box. */\n error?: (failure: LoadFailure) => React.ReactNode;\n className?: string;\n};\n\nfunction MoreFailed({ message, retry }: LoadFailure) {\n return (\n <div className=\"flex flex-wrap items-start gap-3 border-t border-border bg-danger-subtle px-3 py-2 text-danger\">\n <CircleAlert aria-hidden className=\"mt-0.5 size-4 shrink-0\" />\n <p className=\"min-w-0 flex-1 type-body-sm\">{message}</p>\n <Button size=\"sm\" onClick={retry}>\n <RotateCcw aria-hidden />\n Try again\n </Button>\n </div>\n );\n}\n\nconst defaultMoreError = (failure: LoadFailure) => <MoreFailed {...failure} />;\n\n/**\n * The row after a cursor-paged list or grid: loads the next page as it nears the screen, shows\n * `moreSkeleton` while it comes, says why it failed with Try again, offers Show more for the\n * keyboard, and `end` after the last page. After Show more it focuses the first new item: mark\n * each item with `data-index` and put this row beside the list, in the same parent.\n */\nexport function LoadMore<T>({\n state,\n moreLabel,\n moreSkeleton,\n end,\n rootMargin = \"400px\",\n keepAtLeast = 0,\n error: drawError = defaultMoreError,\n className,\n}: LoadMoreProps<T>) {\n const { more } = state;\n const ready = state.status === \"ready\";\n const held = ready ? state.data.length : 0;\n const box = React.useRef<HTMLDivElement>(null);\n const near = useInView({ active: ready && more.hasMore, rootMargin });\n\n // Load on approach, and keep a worked-through queue topped up. Not after a failure: that waits\n // for Try again. Re-runs when a page lands, so a sentinel still in view asks for the next one.\n const { hasMore, loadingMore, error, loadMore } = more;\n React.useEffect(() => {\n if (!ready || !hasMore || loadingMore || error) return;\n if (near.inView || held < keepAtLeast) loadMore();\n }, [ready, hasMore, loadingMore, error, near.inView, held, keepAtLeast, loadMore]);\n\n // After a click on Show more or Try again, focus the first new item: the button is gone.\n const focusFrom = React.useRef<number | null>(null);\n const loadByHand = () => {\n focusFrom.current = held;\n loadMore();\n };\n React.useEffect(() => {\n const from = focusFrom.current;\n if (from === null || loadingMore) return;\n if (held > from) {\n const item = box.current?.parentElement?.querySelector<HTMLElement>(`[data-index=\"${from}\"]`);\n if (item) {\n item.tabIndex = -1;\n item.focus();\n }\n focusFrom.current = null;\n } else if (error || !hasMore) focusFrom.current = null;\n }, [held, loadingMore, error, hasMore]);\n\n if (!ready) return null;\n return (\n <div ref={box} className={className}>\n {hasMore && !error && <div ref={near.ref} aria-hidden className=\"h-px\" />}\n {loadingMore ? (\n <div aria-hidden className=\"border-t border-border\">{moreSkeleton}</div>\n ) : error ? (\n <div role=\"alert\">{drawError({ message: error, retry: loadByHand })}</div>\n ) : hasMore ? (\n <div className=\"border-t border-border py-3\">\n <Button size=\"sm\" onClick={loadByHand}>\n {moreLabel}\n </Button>\n </div>\n ) : (\n end && <div className=\"border-t border-border py-3 type-body-sm text-muted-foreground\">{end}</div>\n )}\n <p role=\"status\" className=\"sr-only\">\n {loadingMore ? \"Loading more\" : \"\"}\n </p>\n </div>\n );\n}\n\n/** The infinite list's props. */\nexport type InfiniteListProps<T> = {\n state: InfiniteLoad<T>;\n /** The list's accessible name, e.g. \"Firing log, newest first\". */\n label: string;\n children: (item: T, index: number) => React.ReactNode;\n /** The first load. Mirrors the final layout, so nothing jumps when data arrives. */\n skeleton: React.ReactNode;\n /** What goes here and how to add it, when the first page is empty and there are no more. */\n empty: React.ReactNode;\n /** The button behind the sentinel, in the product's words: \"Show older firings\". */\n moreLabel: string;\n /** The rows of a page on its way. Defaults to `skeleton`. */\n moreSkeleton?: React.ReactNode;\n /** After the last page: say that this is everything. */\n end?: React.ReactNode;\n /** How far before the end the next page is asked for (IntersectionObserver `rootMargin`). */\n rootMargin?: string;\n /** Load more whenever fewer than this many items are held. */\n keepAtLeast?: number;\n /** `region` (default): rows in a scroll region of `height`, virtual from `virtualizeFrom`. `page`: a plain list that scrolls with the page, laid out by `listClassName`. */\n scroll?: \"region\" | \"page\";\n /** With `scroll=\"page\"`: the classes of the `ul`, such as a responsive grid (`grid gap-4 sm:grid-cols-2 lg:grid-cols-3`). */\n listClassName?: string;\n /** Draws a failed first page. Defaults to DataView's `LoadError`. */\n error?: (failure: LoadFailure) => React.ReactNode;\n /** Draws a failed later page. Defaults to a danger row with Try again. */\n moreError?: (failure: LoadFailure) => React.ReactNode;\n estimateSize?: number;\n height?: number;\n virtualizeFrom?: number;\n className?: string;\n};\n\n/** A cursor-paged list for `useInfiniteLoad`: DataView's first-page states, virtual rows (or a page-scrolled grid), and a `LoadMore` row that loads on approach, shows a skeleton, or says why it failed with Try again. */\nexport function InfiniteList<T>({\n state,\n label,\n children,\n skeleton,\n empty,\n moreLabel,\n moreSkeleton = skeleton,\n end,\n rootMargin = \"400px\",\n keepAtLeast = 0,\n scroll = \"region\",\n listClassName,\n error,\n moreError,\n estimateSize,\n height = 480,\n virtualizeFrom,\n className,\n}: InfiniteListProps<T>) {\n const { more, itemKey } = state;\n const footer = (\n <LoadMore\n // A grid's cards have their own edges, so the row keeps a gap from them.\n className={scroll === \"page\" ? \"mt-4\" : undefined}\n state={state}\n moreLabel={moreLabel}\n moreSkeleton={moreSkeleton}\n end={end}\n rootMargin={rootMargin}\n keepAtLeast={keepAtLeast}\n error={moreError}\n />\n );\n\n return (\n <DataView\n state={state}\n isEmpty={(items) => items.length === 0 && !more.hasMore}\n skeleton={skeleton}\n empty={empty}\n error={error}\n className={className}\n >\n {(items) =>\n scroll === \"page\" ? (\n <div aria-busy={more.loadingMore || undefined}>\n <ul aria-label={label} className={cn(\"min-w-0\", listClassName ?? \"grid\")}>\n {items.map((item, i) => (\n <li key={itemKey(item)} data-index={i} className=\"min-w-0\">\n {children(item, i)}\n </li>\n ))}\n </ul>\n {footer}\n </div>\n ) : (\n <div aria-busy={more.loadingMore || undefined}>\n <VirtualList\n label={label}\n items={items}\n itemKey={itemKey}\n estimateSize={estimateSize}\n height={height}\n virtualizeFrom={virtualizeFrom}\n bounded\n footer={footer}\n >\n {children}\n </VirtualList>\n </div>\n )\n }\n </DataView>\n );\n}\n","import * as React from \"react\";\nimport { cn } from \"../lib/utils\";\n\n// A line chart with the defaults real product screens use: one measured series in one hue, a 2px\n// straight line with no fill and no markers, 3 to 5 faint gridlines, no y-axis line, no legend for a\n// single series (the series is labelled where it ends). Values never live only in a hover tooltip:\n// the latest and peak readings are labelled on the chart and every reading is in a table for screen\n// readers. Optional extras exist only where they answer a question: a dashed `planned` series, a\n// horizontal `band` (a threshold that matters), and a `now` marker.\n//\n//\n// `colourScale` colours the measured line by its own value, for subjects where that colour is a\n// fact rather than decoration: a kiln's glow by temperature, water by depth. The y position still\n// carries the value, so the colour is never the only cue. Without a reason in DESIGN.md, use one\n// hue.\n//\n// It draws in real pixels (measured with ResizeObserver) rather than scaling a fixed viewBox, so\n// the 12px labels stay 12px on a phone. Because the labels keep their size, the chart thins the\n// x ticks itself when they would collide (every second, third… tick, so the rhythm stays even)\n// and keeps the first and last label inside the chart, rather than overlapping on a phone.\n//\n// The y-axis autoscales to four gridline steps of a size people write on a scale, from zero (or\n// below it, if a reading is negative). `yMin` and `yMax` pin either end for a quantity whose range\n// is a fact of the subject (a percentage is 0 to 100, a battery 0 to 1): autoscaling a machine at\n// 1% CPU gives a 0 to 8% axis that makes it look busy (strata-react issue #23). A pin is a floor on\n// the extent, never a crop: a reading outside it widens the axis, because a chart that hides a\n// reading is worse than one with an untidy scale.\n\nexport type Point = { x: number; y: number };\n\nexport type LineChartProps = {\n /** What the chart shows, as a sentence. Used as the accessible name and the table caption. */\n label: string;\n series: Point[];\n seriesLabel: string;\n planned?: Point[];\n plannedLabel?: string;\n band?: { below: number; label: string };\n formatX: (x: number) => string;\n formatY: (y: number) => string;\n /** Where to put x labels, in x units. The chart drops every other one (and so on) when they would overlap at its width. */\n xTicks: number[];\n /** Pin the bottom of the y-axis (default: 0, or lower if a reading is negative). A reading below it still shows. */\n yMin?: number;\n /** Pin the top of the y-axis, for a bounded quantity such as a percentage (`yMax={100}`), so a low reading looks low. Choose a range that divides into four steps. A reading above it still shows. */\n yMax?: number;\n /** CSS colour for the measured series. Defaults to the first chart token. */\n colour?: string;\n /** Colour the measured series by value: each stop applies from `at` upwards, blending to the\n * next. Only where the colour means something in the subject; record the reason in DESIGN.md. */\n colourScale?: { at: number; colour: string }[];\n /** Says what the colours mean, shown beside the legend swatch when `colourScale` is set. */\n colourScaleLabel?: string;\n height?: number;\n className?: string;\n};\n\nfunction useWidth<T extends HTMLElement>() {\n const ref = React.useRef<T>(null);\n const [width, setWidth] = React.useState(0);\n React.useLayoutEffect(() => {\n const el = ref.current;\n if (!el) return;\n setWidth(el.getBoundingClientRect().width);\n const ro = new ResizeObserver(([entry]) => setWidth(entry.contentRect.width));\n ro.observe(el);\n return () => ro.disconnect();\n }, []);\n return [ref, width] as const;\n}\n\n/** The smallest step of a size people write on a scale (1, 2, 2.5, 4 or 5 × 10ⁿ) at least `raw`. */\nfunction niceStep(raw: number) {\n const mag = 10 ** Math.floor(Math.log10(raw));\n return [1, 2, 2.5, 4, 5, 10].map((m) => m * mag).find((s) => s >= raw * (1 - 1e-9)) ?? 10 * mag;\n}\n\n/**\n * The y-axis: four equal gridline steps covering every value. With no pins the steps are a size\n * people write on a scale (1, 2, 2.5, 4 or 5 × 10ⁿ), from zero or a round number below the lowest\n * reading. A pinned end is used as given unless a value lies beyond it.\n */\nexport function yScale(values: number[], pin: { min?: number; max?: number } = {}) {\n const finite = values.filter(Number.isFinite);\n const dMin = finite.length ? Math.min(...finite) : 0;\n const dMax = finite.length ? Math.max(...finite) : 0;\n const pinMin = pin.min !== undefined && dMin >= pin.min ? pin.min : undefined;\n const pinMax = pin.max !== undefined && dMax <= pin.max ? pin.max : undefined;\n let lo = pinMin ?? Math.min(0, dMin);\n // Readings all at a pinned top (say all -10 under yMax={-10}) leave no span: open one below.\n if (pinMax !== undefined && pinMin === undefined && !(pinMax > lo)) lo = pinMax - (Math.abs(pinMax) || 4);\n let min: number;\n let max: number;\n if (pinMax !== undefined) {\n max = pinMax;\n // Only the bottom is free: round it down to a step of the span, so 0 stays 0.\n min = pinMin ?? (lo < 0 ? Math.floor(lo / niceStep((max - lo) / 4)) * niceStep((max - lo) / 4) : 0);\n } else {\n const hi = Math.max(dMax, pin.max ?? -Infinity);\n // All-zero (or empty) data still needs a positive extent, or every coordinate divides by zero.\n let step = hi > lo ? niceStep((hi - lo) / 4) : 1;\n let base = pinMin ?? Math.floor(lo / step) * step;\n while (base + 4 * step < hi) {\n step = niceStep(step * 1.01);\n base = pinMin ?? Math.floor(lo / step) * step;\n }\n min = base;\n max = base + 4 * step;\n }\n if (!(max > min)) max = min + 4;\n return { min, max, ticks: [0, 1, 2, 3, 4].map((i) => min + ((max - min) * i) / 4) };\n}\n\n/** Roughly how wide a 12px caption label is, in px. jsdom cannot measure text, so the chart estimates. */\nconst labelWidth = (text: string) => text.length * 7;\n\n/**\n * The x ticks that fit at this width: every k-th tick, the smallest k for which neighbouring labels\n * leave a gap, so the spacing stays even. `scale` maps an x value to a pixel.\n */\nexport function fitTicks(ticks: number[], scale: (x: number) => number, widthOf: (t: number) => number, gap = 12) {\n if (ticks.length < 3) return ticks;\n const sorted = [...ticks].sort((a, b) => a - b);\n for (let k = 1; k < sorted.length; k++) {\n const kept = sorted.filter((_, i) => i % k === 0);\n const fits = kept.every((t, i) => i === 0 || scale(t) - scale(kept[i - 1]) >= (widthOf(t) + widthOf(kept[i - 1])) / 2 + gap);\n if (fits) return kept;\n }\n return sorted.slice(0, 1);\n}\n\n/** One measured series, drawn in real pixels, with the peak and current readings labelled on the chart and every reading in a screen-reader table. Optional plan, threshold band and `colourScale`. */\nexport function LineChart({\n label,\n series,\n seriesLabel,\n planned,\n plannedLabel,\n band,\n formatX,\n formatY,\n xTicks,\n yMin,\n yMax,\n colour = \"var(--chart-1)\",\n colourScale,\n colourScaleLabel,\n height = 280,\n className,\n}: LineChartProps) {\n const [ref, width] = useWidth<HTMLDivElement>();\n const gradientId = `heat-${React.useId().replace(/[^\\w-]/g, \"\")}`;\n const all = [...series, ...(planned ?? [])];\n const xMin = Math.min(...all.map((p) => p.x));\n const xMax = Math.max(...all.map((p) => p.x));\n const y = yScale(\n all.map((p) => p.y),\n { min: yMin, max: yMax },\n );\n\n const pad = { top: 16, right: 16, bottom: 28, left: 56 };\n const w = Math.max(0, width - pad.left - pad.right);\n const h = height - pad.top - pad.bottom;\n const sx = (x: number) => pad.left + ((x - xMin) / (xMax - xMin || 1)) * w;\n const sy = (v: number) => pad.top + h - ((v - y.min) / (y.max - y.min)) * h;\n const xLabelWidth = (t: number) => labelWidth(formatX(t));\n // Keep the first and last labels inside the chart instead of centring them past its edge.\n const xLabelAt = (t: number) => {\n const half = xLabelWidth(t) / 2;\n return Math.min(Math.max(sx(t), half), Math.max(half, width - half));\n };\n // Fit against where the labels are drawn, so pulling an end label in cannot make it collide.\n const shownXTicks = fitTicks(xTicks, xLabelAt, xLabelWidth);\n const path = (pts: Point[]) => pts.map((p, i) => `${i ? \"L\" : \"M\"}${sx(p.x).toFixed(1)},${sy(p.y).toFixed(1)}`).join(\"\");\n\n const last = series[series.length - 1];\n const peak = series.reduce((a, b) => (b.y > a.y ? b : a), series[0]);\n const stops = colourScale ? [...colourScale].sort((a, b) => a.at - b.at) : [];\n /** The colour a value lands on: the highest stop at or below it. Used for the labelled points. */\n const colourAt = (y: number) => (stops.length ? [...stops].reverse().find((s) => s.at <= y)?.colour ?? stops[0].colour : colour);\n const stroke = stops.length ? `url(#${gradientId})` : colour;\n\n return (\n <figure className={cn(\"grid min-w-0 gap-2\", className)}>\n <div ref={ref} className=\"min-w-0\">\n {width > 0 && (\n <svg width={width} height={height} role=\"img\" aria-label={label} className=\"block overflow-visible\">\n {stops.length > 0 && (\n // A vertical gradient in chart space, so a colour sits at a temperature, not at a\n // point along the line: the line is the same red wherever it crosses 600 °C.\n <defs>\n <linearGradient id={gradientId} gradientUnits=\"userSpaceOnUse\" x1={0} x2={0} y1={sy(y.min)} y2={sy(y.max)}>\n {stops.map((s) => (\n <stop key={s.at} offset={Math.min(1, Math.max(0, (s.at - y.min) / (y.max - y.min)))} stopColor={s.colour} />\n ))}\n </linearGradient>\n </defs>\n )}\n {band && band.below > y.min && (\n <g>\n <rect x={pad.left} y={sy(Math.min(band.below, y.max))} width={w} height={sy(y.min) - sy(Math.min(band.below, y.max))} fill=\"var(--success-subtle)\" />\n <text x={pad.left + 8} y={sy(Math.min(band.below, y.max)) + 16} className=\"fill-success type-caption\">\n {band.label}\n </text>\n </g>\n )}\n {y.ticks.map((t) => (\n <g key={t}>\n <line x1={pad.left} x2={pad.left + w} y1={sy(t)} y2={sy(t)} stroke=\"var(--border)\" strokeWidth={1} />\n <text x={pad.left - 8} y={sy(t)} dy=\"0.32em\" textAnchor=\"end\" className=\"fill-muted-foreground type-caption tabular-nums\">\n {formatY(t)}\n </text>\n </g>\n ))}\n {shownXTicks.map((t) => (\n <text key={t} x={xLabelAt(t)} y={height - 8} textAnchor=\"middle\" className=\"fill-muted-foreground type-caption tabular-nums\">\n {formatX(t)}\n </text>\n ))}\n {planned && (\n <path d={path(planned)} fill=\"none\" stroke=\"var(--muted-foreground)\" strokeWidth={1.5} strokeDasharray=\"4 4\" />\n )}\n <path d={path(series)} fill=\"none\" stroke={stroke} strokeWidth={stops.length ? 2.5 : 2} strokeLinejoin=\"round\" strokeLinecap=\"round\" />\n {/* Direct labels instead of a legend and a tooltip. */}\n <circle cx={sx(peak.x)} cy={sy(peak.y)} r={3} fill={colourAt(peak.y)} />\n <text x={sx(peak.x) + 8} y={sy(peak.y) - 8} className=\"fill-foreground type-caption tabular-nums\">\n {formatY(peak.y)} peak\n </text>\n <line x1={sx(last.x)} x2={sx(last.x)} y1={pad.top} y2={pad.top + h} stroke=\"var(--foreground)\" strokeWidth={1} />\n <circle cx={sx(last.x)} cy={sy(last.y)} r={3.5} fill={colourAt(last.y)} />\n <text\n x={sx(last.x) - 8}\n y={sy(last.y) - 10}\n textAnchor=\"end\"\n className=\"fill-foreground type-label tabular-nums\"\n >\n {formatY(last.y)} now\n </text>\n </svg>\n )}\n </div>\n <figcaption className=\"flex flex-wrap gap-x-5 gap-y-1 type-caption text-muted-foreground\">\n <span className=\"inline-flex items-center gap-2\">\n {stops.length ? (\n <svg width={stops.length * 8} height=\"3\" aria-hidden>\n {stops.map((s, i) => (\n <line key={s.at} x1={i * 8} x2={i * 8 + 8} y1=\"1.5\" y2=\"1.5\" stroke={s.colour} strokeWidth={3} />\n ))}\n </svg>\n ) : (\n <svg width=\"16\" height=\"2\" aria-hidden>\n <line x1=\"0\" x2=\"16\" y1=\"1\" y2=\"1\" stroke={colour} strokeWidth={2} />\n </svg>\n )}\n {seriesLabel}\n {stops.length > 0 && colourScaleLabel && <span>({colourScaleLabel})</span>}\n </span>\n {planned && plannedLabel && (\n <span className=\"inline-flex items-center gap-2\">\n <svg width=\"16\" height=\"2\" aria-hidden>\n <line x1=\"0\" x2=\"16\" y1=\"1\" y2=\"1\" stroke=\"var(--muted-foreground)\" strokeWidth={1.5} strokeDasharray=\"4 4\" />\n </svg>\n {plannedLabel}\n </span>\n )}\n </figcaption>\n {/* sr-only on a wrapper: a table ignores width: 1px and would widen the page. */}\n <div className=\"sr-only\">\n <table>\n <caption>{label}</caption>\n <thead>\n <tr>\n <th scope=\"col\">Time</th>\n <th scope=\"col\">{seriesLabel}</th>\n </tr>\n </thead>\n <tbody>\n {series.map((p) => (\n <tr key={p.x}>\n <td>{formatX(p.x)}</td>\n <td>{formatY(p.y)}</td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n </figure>\n );\n}\n","import * as React from \"react\";\n\n// The top of every Operate screen: a noun title at 24px (never \"Welcome back\"), its scope, the\n// screen's main action, and the finding. The finding is the one fact in today's data that most\n// needs attention; it sits where it is read first, beside the action it drives.\n\n/** The top of an Operate screen: a noun title, its scope, the main action, and the finding (the one fact in today's data that most needs attention). */\nexport function PageHeader({\n title,\n scope,\n actions,\n finding,\n as: Heading = \"h1\",\n}: {\n title: string;\n /** The title's element: h1 on a screen, h2 where the header is shown inside another page. */\n as?: \"h1\" | \"h2\";\n /** What the screen covers: a date, a range, a filter. */\n scope?: React.ReactNode;\n actions?: React.ReactNode;\n finding?: { text: React.ReactNode; action?: React.ReactNode };\n}) {\n return (\n <header className=\"grid gap-4\">\n <div className=\"flex flex-wrap items-end justify-between gap-x-6 gap-y-3\">\n <div className=\"grid min-w-0 gap-0.5\">\n <Heading className=\"type-title text-balance\">{title}</Heading>\n {scope && <p className=\"type-body-sm text-muted-foreground\">{scope}</p>}\n </div>\n {actions && <div className=\"flex flex-wrap gap-2\">{actions}</div>}\n </div>\n {finding && (\n <div className=\"flex flex-wrap items-center justify-between gap-x-6 gap-y-3 border-y border-border py-3\">\n <p className=\"max-w-prose min-w-0 type-body text-pretty\">{finding.text}</p>\n {finding.action}\n </div>\n )}\n </header>\n );\n}\n","import * as React from \"react\";\nimport { Button } from \"./button\";\nimport { describeActionError } from \"../lib/errors\";\n\n// Destructive actions take effect visibly at once and commit after a window, with Undo in reach.\n// For reversible removals this beats a confirm dialog: the dialog interrupts every time to protect\n// against the rare mistake, and people learn to click through it. Keep a confirm dialog for\n// actions that cannot be undone (deleting an account, firing a kiln).\n\n// A bulk removal is one removal with `ids`: the selected rows go, come back on Undo, and fail\n// together, under one message and one commit, because the person did one thing.\n//\n// One removal is pending at a time. Scheduling a second commits the first at once: in rapid-fire\n// triage (withdraw, withdraw, withdraw) Undo reaches back one step, and the bar never stacks up a\n// queue of messages nobody reads. Undo is for the slip just made, not for an audit trail.\n//\n// The hook owns which items are out of view (`isRemoved`), so a screen filters its rows by it and\n// never keeps a second \"hidden\" set that can drift from the pending one. An item stays removed\n// from when it is scheduled; Undo brings it back; a commit that fails brings it back and puts the\n// failure in the same bar, with \"Try again\", because the screen told the person it was done and a\n// silent failure would leave the screen lying. A committed item stays removed until the screen's\n// data drops it (the commit should invalidate the query it came from), so it never flickers back.\n//\n// `flush()` exists for the action that depends on the removal having happened (retrain on the\n// answers, export the list): commit now and await it, rather than racing the window.\n//\n// Failures are described like any other failed action (`describeActionError`, as AsyncButton uses,\n// unless the product passes its own): the same HTTP sentences as reads, without promising that\n// nothing changed, since a write that failed may still have reached the server.\n\n/** A removal waiting out its undo window: what to say, what to do when the window closes, and what to say if that fails. */\nexport type PendingRemoval = {\n /** Identifies the removed item: `isRemoved(id)` is true from `schedule` until Undo or a failed commit. */\n id: string;\n /** A bulk removal's items, all removed, undone, committed and restored together (one `commit` for the batch). `isRemoved` is true for each. Default `[id]`. */\n ids?: readonly string[];\n /** What happened, in the product's words: \"Withdrew Tom Ellery's 3 pieces from kiln 2.\" */\n message: string;\n /** What the person reads if the commit fails, saying the item is back: \"Tom Ellery's 3 pieces are back in kiln 2: the withdrawal did not go through.\" */\n failure: string;\n /** Makes the removal real (usually a request, then invalidating the query the item came from). Runs once per attempt: when the window closes, on `flush()`, when a second removal is scheduled, or when the owner unmounts. */\n commit: () => void | Promise<unknown>;\n /** Called after a failed commit, for anything beyond restoring the item and showing the failure (which the hook does). The only failure path once the owner has unmounted. */\n onError?: (error: unknown) => void;\n};\n\n/** A removal whose commit failed: the removal, and the error described for a person. */\nexport type FailedRemoval = { removal: PendingRemoval; message?: string };\n\n/** Options for `useUndoable`. */\nexport type UndoableOptions = {\n /** How long Undo stays in reach, in milliseconds. Default 8000. */\n windowMs?: number;\n /** Describes a failed commit for a person, or returns undefined to show the removal's `failure` alone. Default `describeActionError`, as for `useAsyncAction`. */\n describeError?: (error: unknown) => string | undefined;\n};\n\n/** What `useUndoable` returns. Pass it whole to `UndoBar`. */\nexport type Undoable = {\n /** The removal inside its window, or null. */\n pending: PendingRemoval | null;\n /** The last removal whose commit failed, until it is retried, dismissed or another removal is scheduled. */\n failed: FailedRemoval | null;\n /** Whether an item is out of view: scheduled, committing or committed, and not undone or failed. Filter rows with it. */\n isRemoved: (id: string) => boolean;\n /** Removes an item and starts its window. Commits any removal already pending first: only one is pending at a time. */\n schedule: (next: PendingRemoval) => void;\n /** Cancels the pending removal and brings the item back; its `commit` never runs. */\n undo: () => void;\n /** Commits the pending removal now and resolves when it and every earlier commit still in flight have settled; rejects if any failed, so a dependent action does not run. Resolves at once when nothing is pending or running. */\n flush: () => Promise<void>;\n /** Removes the failed item again and commits it now (the person already waited out the window); settles like `flush`. */\n retry: () => Promise<void>;\n /** Clears the failure from the bar; the item stays back. */\n dismiss: () => void;\n};\n\n/**\n * Schedules a reversible removal to commit after a window unless undone, and owns which items\n * are out of view meanwhile.\n *\n * Only one removal is pending at a time: scheduling a second commits the first immediately.\n * Unmounting inside the window commits the pending removal (leaving is not Undo), so a navigation\n * or a test that unmounts still sends the commit's request: await `flush()` before a dependent\n * action, and in tests let MSW answer the request or flush before unmounting.\n */\nexport function useUndoable(options: number | UndoableOptions = {}): Undoable {\n const { windowMs = 8000, describeError = describeActionError } =\n typeof options === \"number\" ? { windowMs: options } : options;\n const [pending, setPending] = React.useState<PendingRemoval | null>(null);\n const [failed, setFailed] = React.useState<FailedRemoval | null>(null);\n const [removed, setRemoved] = React.useState<ReadonlySet<string>>(() => new Set());\n const current = React.useRef<PendingRemoval | null>(null);\n const timer = React.useRef<number | undefined>(undefined);\n const mounted = React.useRef(true);\n // Every commit still running, whoever started it: flush() waits for all of them, not only the\n // pending one, because an earlier removal's request may still be in flight (its window closed,\n // or a second removal committed it) and a dependent action must not overtake it.\n const inFlight = React.useRef(new Set<Promise<void>>());\n const describe = React.useRef(describeError);\n describe.current = describeError;\n\n const hide = React.useCallback((p: PendingRemoval, out: boolean) => {\n const ids = p.ids ?? [p.id];\n setRemoved((s) => {\n if (ids.every((id) => s.has(id) === out)) return s;\n const n = new Set(s);\n for (const id of ids) {\n if (out) n.add(id);\n else n.delete(id);\n }\n return n;\n });\n }, []);\n\n // Runs one attempt at a removal's commit. A synchronous throw is treated like a rejection, so\n // there is one failure path: bring the item back, show the failure, tell onError, reject.\n const attempt = React.useCallback(\n (p: PendingRemoval): Promise<void> => {\n let result: void | Promise<unknown>;\n try {\n result = p.commit();\n } catch (error) {\n result = Promise.reject(error);\n }\n const done = Promise.resolve(result).then(\n () => undefined,\n (error: unknown) => {\n if (mounted.current) {\n hide(p, false);\n setFailed({ removal: p, message: describe.current(error) });\n }\n p.onError?.(error);\n throw error;\n },\n );\n inFlight.current.add(done);\n const settle = () => void inFlight.current.delete(done);\n done.then(settle, settle);\n return done;\n },\n [hide],\n );\n\n // Takes the pending removal out (so it commits only once) and attempts it.\n const take = React.useCallback((): { removal: PendingRemoval; done: Promise<void> } | null => {\n window.clearTimeout(timer.current);\n const p = current.current;\n if (!p) return null;\n current.current = null;\n if (mounted.current) setPending(null);\n return { removal: p, done: attempt(p) };\n }, [attempt]);\n\n // Commits the hook starts itself (window closed, second removal, unmount) have no caller to\n // await them. A failure is handled once it is in the bar or onError has it; only a failure\n // nobody can see (unmounted, no onError) is left to surface as an unhandled rejection.\n const commitDetached = React.useCallback(() => {\n const t = take();\n t?.done.catch((error: unknown) => {\n if (!mounted.current && !t.removal.onError) throw error;\n });\n }, [take]);\n\n const schedule = React.useCallback(\n (next: PendingRemoval) => {\n commitDetached(); // a second removal commits the first\n setFailed(null);\n hide(next, true);\n current.current = next;\n setPending(next);\n timer.current = window.setTimeout(commitDetached, windowMs);\n },\n [commitDetached, hide, windowMs],\n );\n\n const undo = React.useCallback(() => {\n window.clearTimeout(timer.current);\n const p = current.current;\n current.current = null;\n setPending(null);\n if (p) hide(p, false);\n }, [hide]);\n\n const flush = React.useCallback(async () => {\n take();\n const results = await Promise.allSettled([...inFlight.current]);\n const failure = results.find((r): r is PromiseRejectedResult => r.status === \"rejected\");\n if (failure) throw failure.reason;\n }, [take]);\n\n const retry = React.useCallback(() => {\n if (!failed) return Promise.resolve();\n setFailed(null);\n hide(failed.removal, true);\n return attempt(failed.removal);\n }, [attempt, failed, hide]);\n\n const dismiss = React.useCallback(() => setFailed(null), []);\n\n const isRemoved = React.useCallback((id: string) => removed.has(id), [removed]);\n\n // Leaving the screen is not Undo: if the owner unmounts inside the window (the person navigated\n // away), commit what was scheduled rather than silently dropping it.\n React.useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n commitDetached();\n };\n }, [commitDetached]);\n\n return { pending, failed, isRemoved, schedule, undo, flush, retry, dismiss };\n}\n\n// The bar lives in a polite live region that is always mounted, so screen readers hear the message\n// when it appears, and a failure replaces the message in the same place the person was looking.\n// It is fixed to the bottom of the viewport; a page that uses it keeps that much bottom padding so\n// the bar never covers the focused row. A failure stays until it is retried or dismissed: an error\n// that times out is one a person can miss.\n/** The polite live region that shows a pending removal with Undo, or a failed one with Try again. Pass it the whole `useUndoable()` result. */\nexport function UndoBar({\n undoable,\n inline = false,\n}: {\n undoable: Pick<Undoable, \"pending\" | \"failed\" | \"undo\" | \"retry\" | \"dismiss\">;\n /** Render in the flow instead of fixed to the viewport; for the state-matrix page. */\n inline?: boolean;\n}) {\n const { pending, failed, undo, retry, dismiss } = undoable;\n const ghost = \"text-background hover:bg-neutral-11\";\n return (\n <div\n aria-live=\"polite\"\n className={\n inline ? \"flex\" : \"layer-bar pointer-events-none fixed inset-x-0 bottom-4 flex justify-center px-4\"\n }\n >\n {(pending || failed) && (\n <div className=\"pointer-events-auto flex max-w-lg items-center gap-4 rounded-overlay bg-foreground py-2 pr-2 pl-4 text-background shadow-overlay\">\n {pending ? (\n <>\n <p className=\"min-w-0 type-body-sm\">{pending.message}</p>\n <Button size=\"sm\" variant=\"ghost\" className={ghost} onClick={undo}>\n Undo\n </Button>\n </>\n ) : (\n failed && (\n <>\n <p className=\"min-w-0 type-body-sm\">\n {failed.message ? `${failed.removal.failure} ${failed.message}` : failed.removal.failure}\n </p>\n <div className=\"flex shrink-0 gap-1\">\n <Button size=\"sm\" variant=\"ghost\" className={ghost} onClick={() => void retry().catch(() => undefined)}>\n Try again\n </Button>\n <Button size=\"sm\" variant=\"ghost\" className={ghost} onClick={dismiss}>\n Dismiss\n </Button>\n </div>\n </>\n )\n )}\n </div>\n )}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { Check } from \"lucide-react\";\nimport { cn } from \"../lib/utils\";\n\n// The completion moment: what a person sees after finishing something that took effort (a\n// booking, a submission, an import). It is the one place on an Operate product where the library\n// spends its delight budget (character.md §3), so it is a component with rules rather than a\n// confetti call:\n// - `title` says what happened, in the past tense, with the object: \"Booked: 6 pieces in kiln 2\".\n// - `next` is required. A finish that does not say what happens now is a dead end, however\n// pleasant.\n// - `figure` is optional and must be drawn from the person's own data in the subject's terms\n// (their pieces on a shelf, their route on a map), never a stock illustration.\n// - The part of the figure that is the person's result enters once, with the `enter-moment`\n// utility (500ms, hard ease-out, no overshoot): their pieces set down on the shelf. Reduced\n// motion makes it instant. Nothing loops and nothing plays a sound.\n// - Focus moves to the heading on mount, so keyboard and screen-reader users land on the result.\n\n/** The completion moment for a rare, earned finish: what happened (past tense, with its object), what happens next, and optionally a figure drawn from the person's own data. Focus moves to the heading. */\nexport function Done({\n title,\n next,\n figure,\n actions,\n focusOnMount = true,\n className,\n}: {\n /** What happened, past tense, with its object. */\n title: string;\n /** What the person does now, or what happens next and when. */\n next: React.ReactNode;\n /** A drawing of the result made from the person's data in the subject's own terms. */\n figure?: React.ReactNode;\n actions?: React.ReactNode;\n /** Off only where the result is not the page's subject (the state-matrix page). */\n focusOnMount?: boolean;\n className?: string;\n}) {\n const heading = React.useRef<HTMLHeadingElement>(null);\n const titleId = React.useId();\n React.useEffect(() => {\n if (focusOnMount) heading.current?.focus();\n }, [focusOnMount]);\n return (\n <section aria-labelledby={titleId} className={cn(\"grid gap-5\", className)}>\n <div className=\"grid gap-2\">\n <h1 id={titleId} ref={heading} tabIndex={-1} className=\"flex items-start gap-2 type-title\">\n <Check aria-hidden className=\"mt-1 size-6 shrink-0 text-success\" />\n {title}\n </h1>\n <div className=\"max-w-prose type-body text-muted-foreground\">{next}</div>\n </div>\n {figure}\n {actions && <div className=\"flex flex-wrap items-center gap-3\">{actions}</div>}\n </section>\n );\n}\n","import * as React from \"react\";\nimport { Link, NavLink } from \"react-router\";\nimport { cn } from \"../lib/utils\";\nimport type { IconComponent } from \"../lib/icon\";\n\n// The frame of an app: a side nav on the page ground (not a navy or tinted sidebar), the current\n// item as a neutral pill (no left bar, no accent), and the page beside it. A top bar exists only\n// when it holds something used on every screen, so it is a slot, not a default. Built on React\n// Router's NavLink, so \"current\" is the router's answer and aria-current is set for free. On\n// phones the nav becomes a horizontal, scrollable row above the page rather than a hamburger, so\n// every destination stays one tap away.\n\nexport type NavItem = {\n to: string;\n label: string;\n icon?: IconComponent;\n /** Match only this exact path, for an index route such as \"/\". */\n end?: boolean;\n};\n\n/** The app frame: product name, side nav on the page ground (a scrollable row on phones), optional top bar, and the main region. */\nexport function AppShell({\n product,\n nav,\n navLabel = \"Main\",\n topBar,\n children,\n className,\n}: {\n /** The product's name or mark, linking home. */\n product: React.ReactNode;\n nav: NavItem[];\n navLabel?: string;\n topBar?: React.ReactNode;\n children: React.ReactNode;\n className?: string;\n}) {\n return (\n <div className={cn(\"min-h-dvh md:grid md:grid-cols-[14rem_minmax(0,1fr)]\", className)}>\n <aside className=\"border-b border-border md:border-r md:border-b-0\">\n <div className=\"flex items-center gap-4 px-4 py-3 md:block md:px-3 md:py-4\">\n <Link to=\"/\" className=\"shrink-0 rounded-control px-2 type-heading text-foreground no-underline\">\n {product}\n </Link>\n <SideNav items={nav} label={navLabel} className=\"min-w-0 flex-1 md:mt-4\" />\n </div>\n </aside>\n <div className=\"min-w-0\">\n {topBar && <div className=\"flex items-center gap-3 border-b border-border px-4 py-2 md:px-8\">{topBar}</div>}\n <main className=\"px-4 py-6 md:px-8 md:py-8\">{children}</main>\n </div>\n </div>\n );\n}\n\n/** Navigation links (React Router `NavLink`); the current route is a neutral pill with `aria-current`. */\nexport function SideNav({ items, label, className }: { items: NavItem[]; label: string; className?: string }) {\n return (\n <nav aria-label={label} className={cn(\"min-w-0\", className)}>\n <ul className=\"flex gap-1 overflow-x-auto md:grid md:overflow-visible\">\n {items.map(({ to, label, icon: Icon, end }) => (\n <li key={to} className=\"shrink-0\">\n <NavLink\n to={to}\n end={end}\n className={({ isActive }) =>\n cn(\n \"flex h-(--control-h-sm) items-center gap-2 rounded-control px-2 type-label whitespace-nowrap no-underline transition-state\",\n isActive ? \"bg-muted text-foreground\" : \"text-muted-foreground hover:bg-muted hover:text-foreground\",\n )\n }\n >\n {Icon && <Icon aria-hidden className=\"size-4 shrink-0\" />}\n {label}\n </NavLink>\n </li>\n ))}\n </ul>\n </nav>\n );\n}\n\n// Plain links with a \"/\" separator in muted ink. The last crumb is the current page: text, not a\n// link, with aria-current.\n/** Plain links separated by `/`; the last crumb is the current page. */\nexport function Breadcrumb({ items }: { items: { label: string; to?: string }[] }) {\n return (\n <nav aria-label=\"Breadcrumb\">\n <ol className=\"flex flex-wrap items-center gap-x-2 type-body-sm text-muted-foreground\">\n {items.map((item, i) => {\n const last = i === items.length - 1;\n return (\n <li key={`${item.label}-${i}`} className=\"flex items-center gap-2\">\n {item.to && !last ? (\n <Link to={item.to} className=\"text-muted-foreground underline hover:text-foreground\">\n {item.label}\n </Link>\n ) : (\n <span aria-current={last ? \"page\" : undefined} className={cn(last && \"text-foreground\")}>\n {item.label}\n </span>\n )}\n {!last && <span aria-hidden>/</span>}\n </li>\n );\n })}\n </ol>\n </nav>\n );\n}\n","import * as React from \"react\";\nimport { useSearchParams } from \"react-router\";\nimport { Tab, TabList, TabPanel, Tabs as AriaTabs } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\n\n// Tabs whose state lives in the URL (?view=readings), so a tab can be linked, survives reload and\n// works with Back. Built on React Aria Tabs (ARIA tabs pattern: arrow keys move between tabs and\n// select them, Home and End jump, only the selected tab is in the tab order). The selected tab is marked by weight and a\n// 2px rule in ink, not by colour alone. The first tab is the default and is not written to the URL.\n\nexport type TabItem = { value: string; label: string };\n\n/** Tabs whose selection lives in a URL search parameter (React Router), with the ARIA tabs keyboard model. */\nexport function Tabs({\n param,\n items,\n label,\n children,\n className,\n}: {\n /** The search parameter that holds the selected tab. */\n param: string;\n items: TabItem[];\n /** Names the tab list for screen readers. */\n label: string;\n /** Renders the selected panel. */\n children: (value: string) => React.ReactNode;\n className?: string;\n}) {\n const [params, setParams] = useSearchParams();\n const fallback = items[0]?.value ?? \"\";\n const raw = params.get(param);\n const value = items.some((i) => i.value === raw) ? raw! : fallback;\n const select = (next: string) =>\n setParams(\n (p) => {\n const out = new URLSearchParams(p);\n if (next === fallback) out.delete(param);\n else out.set(param, next);\n return out;\n },\n { replace: true },\n );\n\n // React Aria's Tabs owns the keyboard model (arrows, Home and End, roving tab stop, automatic\n // activation) and the ids that tie each tab to the panel; the selected key is the URL's.\n return (\n <AriaTabs selectedKey={value} onSelectionChange={(key) => select(String(key))} className={cn(\"grid gap-4\", className)}>\n <TabList aria-label={label} className=\"flex gap-4 overflow-x-auto border-b border-border\">\n {items.map((item) => (\n <Tab\n key={item.value}\n id={item.value}\n className={cn(\n \"-mb-px cursor-pointer border-b-2 py-2 type-label whitespace-nowrap transition-state\",\n \"border-transparent text-muted-foreground hover:text-foreground\",\n \"data-[selected]:border-foreground data-[selected]:font-semibold data-[selected]:text-foreground\",\n )}\n >\n {item.label}\n </Tab>\n ))}\n </TabList>\n <TabPanel id={value} shouldForceMount={false}>\n {children(value)}\n </TabPanel>\n </AriaTabs>\n );\n}\n","import * as React from \"react\";\nimport { cn } from \"../lib/utils\";\nimport { isTypingTarget, type Shortcut } from \"./hotkeys\";\n\n// A queue someone works through from the keyboard: one item is active, j/k (or the arrow keys\n// inside the list) move it, and answering an item moves straight on to the next one. Three\n// decisions shape it:\n// 1. The active item is the one with focus. It is a roving tab stop (only it is in the tab order)\n// and carries aria-current, so a screen reader hears which item an answer applies to. It is\n// marked by a 2px rule in ink as well as a tint, not by colour alone.\n// 2. When the active item leaves the list (accepted, rejected, removed), the item that took its\n// place becomes active, or the one before it at the end of the list, and focus follows if it\n// was in the list. Otherwise focus would fall to <body> and the next key would do nothing.\n// 3. The hook remembers which item the person chose, not just a position. If an Undo puts the\n// item back, it is active again (pairs with `useUndoable`).\n// Moving is instant: no transition on the highlight (ux-research `ux-character.md`, 100+ a day).\n\n/** What `useActiveItem` returns: the active item, ways to move it, and the props each item element needs. */\nexport type ActiveItem<T> = {\n items: readonly T[];\n getKey: (item: T) => string;\n activeKey: string | null;\n activeItem: T | null;\n /** Position of the active item, or -1 when the list is empty. */\n index: number;\n next: () => void;\n prev: () => void;\n first: () => void;\n last: () => void;\n setActive: (key: string) => void;\n /** The j/k shortcuts for `useHotkeys` and `KeysLegend`. */\n shortcuts: Shortcut[];\n /** Props for the element that represents an item: ref, tabIndex, aria-current and focus tracking. */\n itemProps: (key: string) => {\n ref: (el: HTMLElement | null) => void;\n tabIndex: number;\n \"aria-current\": \"true\" | undefined;\n \"data-active\": \"\" | undefined;\n onFocus: () => void;\n onBlur: (e: React.FocusEvent) => void;\n };\n};\n\n/** Tracks the active item in a list worked through from the keyboard: moving, roving focus, and moving on when the active item is removed. */\nexport function useActiveItem<T>(\n items: readonly T[],\n getKey: (item: T) => string,\n {\n initial,\n noun,\n }: {\n /** Key of the item active at first; the first item otherwise. */\n initial?: string;\n /** Names an item in the shortcut labels: \"Next booking\". */\n noun?: string;\n } = {},\n): ActiveItem<T> {\n const [chosen, setChosen] = React.useState<string | null>(initial ?? null);\n const lastIndex = React.useRef(0);\n const elements = React.useRef(new Map<string, HTMLElement>());\n const navigated = React.useRef(false);\n const focusWithin = React.useRef(false);\n\n const keys = items.map(getKey);\n let index = chosen === null ? -1 : keys.indexOf(chosen);\n if (index === -1 && keys.length > 0) index = Math.min(lastIndex.current, keys.length - 1);\n const activeKey = index >= 0 ? keys[index] : null;\n\n // Remember the position, and the last item that left the list while active. Answering two in a\n // row (at the end of the queue, say) must make the second the one an Undo brings back as\n // active, not the first.\n const prevActive = React.useRef<string | null>(activeKey);\n React.useLayoutEffect(() => {\n if (index >= 0) lastIndex.current = index;\n const gone = prevActive.current;\n prevActive.current = activeKey;\n if (gone !== null && gone !== chosen && !keys.includes(gone)) setChosen(gone);\n });\n\n // Move focus to the active item when the person moved it, when the focused item was removed\n // (focus has fallen to <body>), or when focus is on another item in the list (an Undo made the\n // restored item active again). Never take focus from somewhere else on the page.\n React.useLayoutEffect(() => {\n const el = activeKey === null ? undefined : elements.current.get(activeKey);\n const focused = document.activeElement;\n const lost = focusWithin.current && (focused === null || focused === document.body);\n const elsewhereInList =\n focused !== null && !el?.contains(focused) && [...elements.current.values()].some((item) => item.contains(focused));\n if (el && (navigated.current || lost || elsewhereInList)) {\n el.focus({ preventScroll: true });\n el.scrollIntoView?.({ block: \"nearest\" });\n }\n navigated.current = false;\n }, [activeKey]);\n\n const moveTo = (i: number) => {\n if (keys.length === 0) return;\n const to = Math.max(0, Math.min(keys.length - 1, i));\n navigated.current = true;\n if (to === index) {\n // Already there: still bring focus back to it, as the person asked to move.\n const el = elements.current.get(keys[to]);\n el?.focus({ preventScroll: true });\n el?.scrollIntoView?.({ block: \"nearest\" });\n navigated.current = false;\n }\n setChosen(keys[to]);\n };\n\n const next = () => moveTo(index + 1);\n const prev = () => moveTo(index - 1);\n const first = () => moveTo(0);\n const last = () => moveTo(keys.length - 1);\n const setActive = (key: string) => {\n const i = keys.indexOf(key);\n if (i >= 0) moveTo(i);\n };\n\n const name = noun ? ` ${noun}` : \"\";\n const shortcuts: Shortcut[] = [\n { keys: [\"j\"], label: `Next${name}`, run: next, repeat: true, disabled: keys.length === 0 },\n { keys: [\"k\"], label: `Previous${name}`, run: prev, repeat: true, disabled: keys.length === 0 },\n ];\n\n const itemProps: ActiveItem<T>[\"itemProps\"] = (key) => ({\n ref: (el) => {\n if (el) elements.current.set(key, el);\n else elements.current.delete(key);\n },\n tabIndex: key === activeKey ? 0 : -1,\n \"aria-current\": key === activeKey ? \"true\" : undefined,\n \"data-active\": key === activeKey ? \"\" : undefined,\n onFocus: () => {\n focusWithin.current = true;\n // Clicking or tabbing into an item makes it active. If it already is (it took a removed\n // item's place), keep remembering the removed one so an Undo makes that active again.\n if (key !== activeKey) setChosen(key);\n },\n onBlur: (e) => {\n // Focus going nowhere (null) is what removal looks like, so only a move to a real element\n // outside the list counts as leaving it.\n const to = e.relatedTarget;\n if (to instanceof Node && ![...elements.current.values()].some((el) => el.contains(to))) focusWithin.current = false;\n },\n });\n\n return {\n items,\n getKey,\n activeKey,\n activeItem: index >= 0 ? items[index] : null,\n index,\n next,\n prev,\n first,\n last,\n setActive,\n shortcuts,\n itemProps,\n };\n}\n\n// The list renders the queue from `useActiveItem`. The arrow keys, Home and End move the active\n// item while focus is in the list (the window-wide j/k come from `active.shortcuts` via\n// `useHotkeys`, because only the screen knows whether it has one queue or two). An empty queue\n// is a state the list cannot be written without: say what clearing it means and what is next.\n/** A keyboard-worked queue: the active item is a roving tab stop with aria-current, and the arrow keys, Home and End move it. */\nexport function ActiveList<T>({\n label,\n active,\n empty,\n children,\n className,\n}: {\n /** Names the list for screen readers. */\n label: string;\n active: ActiveItem<T>;\n /** Shown when the queue is clear: what that means and what to do next. */\n empty: React.ReactNode;\n children: (item: T, state: { active: boolean }) => React.ReactNode;\n className?: string;\n}) {\n if (active.items.length === 0) return <>{empty}</>;\n\n const onKeyDown = (e: React.KeyboardEvent) => {\n if (e.ctrlKey || e.metaKey || e.altKey || isTypingTarget(e.target)) return;\n const move =\n e.key === \"ArrowDown\" ? active.next\n : e.key === \"ArrowUp\" ? active.prev\n : e.key === \"Home\" ? active.first\n : e.key === \"End\" ? active.last\n : undefined;\n if (!move) return;\n e.preventDefault();\n move();\n };\n\n return (\n <ul aria-label={label} onKeyDown={onKeyDown} className={cn(\"grid gap-px\", className)}>\n {active.items.map((item) => {\n const key = active.getKey(item);\n const isActive = key === active.activeKey;\n return (\n <li\n key={key}\n {...active.itemProps(key)}\n className={cn(\n \"rounded-control border-l-2 px-3 py-2 -outline-offset-2\",\n isActive ? \"border-foreground bg-accent text-accent-foreground\" : \"border-transparent\",\n )}\n >\n {children(item, { active: isActive })}\n </li>\n );\n })}\n </ul>\n );\n}\n","import * as React from \"react\";\nimport { hashKey, useInfiniteQuery, type QueryKey } from \"@tanstack/react-query\";\nimport type { Load } from \"../components/data-view\";\nimport { describeHttpError, staleOf, type DescribeError } from \"./index\";\n\n// Cursor-paged reads, the Strata way. `useLoad` covers a read that arrives whole; a feed, a log or\n// a triage queue arrives a page at a time. This is the same bridge for those: TanStack's\n// useInfiniteQuery underneath, a `Load<T[]>` on top (so `DataView` takes it unchanged for the\n// first page's loading, error and empty states), and a `more` object for everything after it.\n//\n// Three opinions:\n// 1. The cursor is \"after the last item held\", never an offset, and the hook works it out: the\n// app says how to make a cursor from an item (`cursorAfter`) and whether a page says there are\n// more (`hasMore`). In a queue people work through (answered reviews, archived firings), items\n// leave the server's list between pages, and an offset would skip the ones that moved up to\n// fill the gap. Two cases fall back to the last item *seen*, dismissed or not: when everything\n// held has been dismissed (there is no held item to go after, and starting again from the top\n// could fetch the same dismissed page forever), and when the last page brought nothing new\n// (only items already held or dismissed came back, so going after the last held item again\n// would ask for the same page in a loop).\n// 2. Items have keys. Pages are merged by key, so an item that shifts across a page boundary is\n// shown once, and `dismiss(key)` hides one at once (an optimistic remove, paired with\n// useUndoable) without the app rewriting TanStack's page cache by hand. Dismissals belong to\n// one query: a new `queryKey` (another filter) starts with none. A screen that removes items\n// with `useUndoable` passes its `isRemoved` instead, so the undo hook stays the one owner of\n// what is out of view (Undo, a failed commit and Try again all show through) and the cursor\n// still skips past what it hides.\n// 3. A later page failing is not the list failing. The held items stay; `more.error` says what\n// happened and `more.loadMore` is the Try again. A refetch of the held pages failing is not the\n// list failing either: the items stay and `stale` says how old they are, as with `useLoad`.\n// Only a failed first page is a `Load` error.\n\n/** The state of the pages after the first: whether there are more, whether one is on its way, and why the last one failed. */\nexport type More = {\n /** The server has said there is another page. */\n hasMore: boolean;\n /** A page after the first is being fetched. */\n loadingMore: boolean;\n /** Why the last page after the first failed, for a person. Cleared when a retry succeeds. */\n error?: string;\n /** Fetch the next page; also the Try again after `error`. Does nothing while one is loading or when there are no more. */\n loadMore: () => void;\n};\n\n/** A cursor-paged read: a `Load<T[]>` of the items held (so `DataView` takes it), plus the next page's state and keyed removal. */\nexport type InfiniteLoad<T> = Load<T[]> & {\n more: More;\n itemKey: (item: T) => string;\n /** Hide an item at once (an optimistic removal). The next cursor goes after the last item still held. */\n dismiss: (key: string) => void;\n /** Show a dismissed item again: the Undo of `dismiss`. */\n restore: (key: string) => void;\n};\n\n/** Options for `useInfiniteLoad`. */\nexport type InfiniteLoadOptions<T, Page, Cursor, K extends QueryKey> = {\n queryKey: K;\n /** Fetch one page. `cursor` is undefined for the first page, else `cursorAfter` of the last item held. */\n queryFn: (context: { cursor: Cursor | undefined; signal: AbortSignal }) => Promise<Page>;\n /** The items in a page. For an API that returns a bare array, `(page) => page`. */\n items: (page: Page) => T[];\n /** A stable key per item: merges pages, and is what `dismiss` takes. */\n itemKey: (item: T) => string;\n /** Whether the server says there is a page after this one. */\n hasMore: (lastPage: Page) => boolean;\n /** The cursor that asks for the items after this one; usually its id. Defaults to `itemKey`. */\n cursorAfter?: (item: T) => Cursor;\n /** Items hidden by someone else, usually `useUndoable().isRemoved`: treated like dismissed ones. */\n isRemoved?: (key: string) => boolean;\n describeError?: DescribeError;\n enabled?: boolean;\n staleTime?: number;\n};\n\ntype Dismissed = { query: string; keys: ReadonlySet<string> };\ntype PageParam<Cursor> = { cursor: Cursor | undefined };\n\n/** `useInfiniteQuery` for cursor-paged data, returned as an `InfiniteLoad<T>` for `InfiniteList` (or `DataView`). */\nexport function useInfiniteLoad<T, Page, Cursor = string, K extends QueryKey = QueryKey>({\n queryKey,\n queryFn,\n items,\n itemKey,\n hasMore,\n cursorAfter = itemKey as unknown as (item: T) => Cursor,\n isRemoved,\n describeError = describeHttpError,\n enabled,\n staleTime,\n}: InfiniteLoadOptions<T, Page, Cursor, K>): InfiniteLoad<T> {\n const queryHash = hashKey(queryKey);\n const [stored, setStored] = React.useState<Dismissed>(() => ({ query: queryHash, keys: new Set() }));\n const dismissed = stored.query === queryHash ? stored.keys : none;\n const hidden = React.useCallback((key: string) => dismissed.has(key) || (isRemoved?.(key) ?? false), [dismissed, isRemoved]);\n // TanStack calls getNextPageParam outside render; it reads the latest hidden set and accessors.\n const latest = React.useRef({ hidden, items, itemKey, hasMore, cursorAfter });\n latest.current = { hidden, items, itemKey, hasMore, cursorAfter };\n\n const query = useInfiniteQuery({\n queryKey,\n queryFn: ({ pageParam, signal }) => queryFn({ cursor: pageParam.cursor, signal }),\n initialPageParam: { cursor: undefined } as PageParam<Cursor>,\n getNextPageParam: (lastPage, pages): PageParam<Cursor> | null => {\n const l = latest.current;\n if (!l.hasMore(lastPage)) return null;\n const after = nextAfter(pages, l.items, l.itemKey, l.hidden);\n return { cursor: after === undefined ? undefined : l.cursorAfter(after) };\n },\n enabled,\n staleTime,\n });\n\n const pages = query.data?.pages;\n // Keyed on the pages and dismissals only, so inline `items`/`itemKey` arrows do not hand the\n // list a new array every render.\n const list = React.useMemo(\n () => (pages ? merge(pages, latest.current.items, latest.current.itemKey, hidden).held : undefined),\n [pages, hidden],\n );\n\n const { hasNextPage, isFetchingNextPage, fetchNextPage, refetch } = query;\n const loadMore = React.useCallback(() => {\n if (hasNextPage && !isFetchingNextPage) void fetchNextPage();\n }, [hasNextPage, isFetchingNextPage, fetchNextPage]);\n const change = React.useCallback(\n (edit: (keys: Set<string>) => void) =>\n setStored((s) => {\n const keys = new Set(s.query === queryHash ? s.keys : none);\n edit(keys);\n return { query: queryHash, keys };\n }),\n [queryHash],\n );\n const dismiss = React.useCallback((key: string) => change((keys) => keys.add(key)), [change]);\n const restore = React.useCallback((key: string) => change((keys) => keys.delete(key)), [change]);\n\n const more: More = {\n hasMore: Boolean(hasNextPage),\n loadingMore: isFetchingNextPage,\n error: query.isFetchNextPageError ? describeError(query.error) : undefined,\n loadMore,\n };\n const extra = { more, itemKey, dismiss, restore };\n if (list) {\n // isRefetchError excludes a failed next page, which is `more.error`'s to report.\n const stale = query.isRefetchError ? staleOf(query, describeError) : undefined;\n return { status: \"ready\", data: list, ...(stale && { stale }), ...extra };\n }\n if (query.status === \"error\") return { status: \"error\", message: describeError(query.error), retry: () => void refetch(), ...extra };\n return { status: \"loading\", ...extra };\n}\n\nconst none: ReadonlySet<string> = new Set();\n\n/** Every page's items, in order, once each by key: the ones held (not dismissed) and the last one seen. */\nfunction merge<T, Page>(pages: Page[], items: (page: Page) => T[], itemKey: (item: T) => string, hidden: (key: string) => boolean) {\n const seen = new Set<string>();\n const held: T[] = [];\n let last: T | undefined;\n let lastPageAddedAny = false;\n pages.forEach((page, p) => {\n for (const item of items(page)) {\n const key = itemKey(item);\n if (seen.has(key)) continue;\n seen.add(key);\n last = item;\n if (p === pages.length - 1) lastPageAddedAny = true;\n if (!hidden(key)) held.push(item);\n }\n });\n return { held, last, lastPageAddedAny };\n}\n\n/** The item the next page goes after: the last held, or the last seen when nothing is held or the last page brought nothing new. */\nfunction nextAfter<T, Page>(pages: Page[], items: (page: Page) => T[], itemKey: (item: T) => string, hidden: (key: string) => boolean) {\n const { held, last, lastPageAddedAny } = merge(pages, items, itemKey, hidden);\n if (held.length === 0 || (pages.length > 1 && !lastPageAddedAny)) return last;\n return held[held.length - 1];\n}\n","import * as React from \"react\";\nimport { hashKey, useQuery, useQueryClient, type QueryKey, type UseQueryOptions } from \"@tanstack/react-query\";\nimport type { Load } from \"../components/data-view\";\nimport type { DescribeError } from \"../lib/errors\";\nimport { toLoad } from \"./index\";\n\n// The read behind `JobStatus` (strata-react issue #45): a job's status, polled while it runs and\n// not otherwise, and the data it changed read again once, when it ends. Tubes wrote this as\n// `useLoad({ refetchInterval })` plus an effect watching `running` go from true to false; every\n// app with a job would write the same two pieces and get the second one subtly wrong (invalidating\n// on the first read of a job that had already finished, or on every poll). Here:\n//\n// - `isRunning(data)` says whether the job is going; the query polls `every` ms (default 2000)\n// only then, so an idle screen makes one request, not one every two seconds.\n// - `invalidates` names the queries the job changes; they are invalidated once, on the poll that\n// first sees the job stopped after one that saw it running, for the same query: a first read\n// of a finished job invalidates nothing, and neither does switching to another job's key (the\n// new query has no status yet, which is not the old job ending). The keys invalidated are the\n// ones given while that job was seen running.\n// - `poll()` reads the status now: the commit of the button that starts the job calls it, so\n// polling begins without waiting for a stale time.\n// - The result is a `Load<T>` (so a failed poll keeps the last status on screen with `stale`, as\n// any read does), plus `running`.\n\n/** Options for `useJob`: a query's, plus how to tell the job is running, how often to poll, and what it changes. */\nexport type JobOptions<T, K extends QueryKey = QueryKey> = UseQueryOptions<T, Error, T, K> & {\n /** Whether the status says the job is still going. */\n isRunning: (data: T) => boolean;\n /** Milliseconds between polls while it runs. Default 2000. */\n every?: number;\n /** Query keys the job changes, invalidated once when it ends. */\n invalidates?: QueryKey[];\n describeError?: DescribeError;\n};\n\n/** What `useJob` returns: the status as a `Load<T>`, whether the job is running, and `poll` to read it now. */\nexport type Job<T> = Load<T> & {\n /** The latest status says the job is going. */\n running: boolean;\n /** Read the status now, as after starting the job. */\n poll: () => void;\n};\n\n/** A long-running job's status: polled every `every` ms while `isRunning`, with the `invalidates` queries read again once when it ends. */\nexport function useJob<T, K extends QueryKey = QueryKey>({\n isRunning,\n every = 2000,\n invalidates = [],\n describeError,\n ...options\n}: JobOptions<T, K>): Job<T> {\n const client = useQueryClient();\n const query = useQuery({\n ...options,\n refetchInterval: (q) => (q.state.data !== undefined && isRunning(q.state.data) ? every : false),\n });\n const running = query.data !== undefined && isRunning(query.data);\n\n // What was last seen, for one query: whether its job ran, and what it said it would change.\n // Only a status that has arrived counts; no data yet (a new key loading) is not \"stopped\".\n const queryHash = hashKey(options.queryKey);\n const seen = query.data === undefined ? undefined : running;\n const was = React.useRef<{ query: string; running: boolean; invalidates: QueryKey[] } | undefined>(undefined);\n React.useEffect(() => {\n if (seen === undefined) return;\n const before = was.current;\n if (before && before.query === queryHash && before.running && !seen) {\n for (const queryKey of before.invalidates) void client.invalidateQueries({ queryKey });\n }\n was.current = { query: queryHash, running: seen, invalidates };\n });\n\n const { refetch } = query;\n const poll = React.useCallback(() => void refetch(), [refetch]);\n return { ...toLoad(query, describeError), running, poll };\n}\n"],"mappings":";;;;;;;;;;;AAqCA,IAAa,OAAO;;AAGpB,IAAa,UAAU;AAIvB,IAAM,aAAkC;CAAC;CAAK;CAAM;CAAM;CAAM;CAAM;AAAI;AAC1E,IAAM,YAAY,OAAO,YAAY,WAAW,KAAK,GAAG,MAAM,CAAC,GAAG,OAAQ,CAAC,CAAC,CAAC;;AAgC7E,SAAgB,OAAO,OAAwB;CAC7C,MAAM,OAAO,iBAAiB,OAAO,QAAQ,IAAI,KAAK,KAAK;CAC3D,IAAI,OAAO,MAAM,KAAK,QAAQ,CAAC,GAAG,MAAM,IAAI,WAAW,eAAe,KAAK,UAAU,OAAO,KAAK,CAAC,GAAG;CACrG,OAAO;AACT;AAEA,SAAS,aAAa,IAAyB,SAAgC;CAC7E,MAAM,UAAU,UAAyC,SAAS,OAAO,UAAU,GAAG,OAAO,OAAO,KAAK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AC;CACD,MAAM,UAAU,MAAM,SAAS,KAAA,KAAa,UAAU,MAAM,IAAI;CAIhE,MAAM,YAAY,QAAQ,QAAQ,QAAQ;CAC1C,MAAM,OAAO,MAAM,SAAS,KAAA,IAAY,KAAA,IAAY;CACpD,MAAM,MAAM,MAAM,OAAiF,KAAA,CAAS;CAC5G,MAAM,gBAAgB;EACpB,IAAI,SAAS,KAAA,GAAW;EACxB,MAAM,SAAS,IAAI;EACnB,IAAI,UAAU,OAAO,UAAU,aAAa,OAAO,WAAW,CAAC,MAC7D,KAAK,MAAM,YAAY,OAAO,aAAa,OAAY,kBAAkB,EAAE,SAAS,CAAC;EAEvF,IAAI,UAAU;GAAE,OAAO;GAAW,SAAS;GAAM;EAAY;CAC/D,CAAC;CAED,MAAM,EAAE,YAAY;CACpB,MAAM,OAAO,MAAM,kBAAkB,KAAK,QAAQ,GAAG,CAAC,OAAO,CAAC;CAC9D,OAAO;EAAE,GAAG,OAAO,OAAO,aAAa;EAAG;EAAS;CAAK;AAC1D"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["AriaButton","_Fragment","AriaPopover","AriaMenu","AriaDialog","AriaInput","AriaToolbar","sizes","_Fragment","AriaToggleButton","AriaSwitch","AriaDialog","_Fragment","AriaPopover","Dialog","AriaCheckbox","_Fragment","_Fragment","tones","_Fragment","_Fragment","AriaNumberField","AriaInput","AriaSlider","_Fragment","ToastQueue","ToastRegion","AriaToast","ToastContent","AriaButton","_Fragment","defaultFormat","format","AriaCheckbox","_Fragment","AriaTabs","_Fragment","AriaDialog","_Fragment","AriaSlider"],"sources":["../src/lib/format.ts","../src/lib/in-view.ts","../src/components/button.tsx","../src/lib/overlay.ts","../src/lib/chords.ts","../src/components/hotkeys.tsx","../src/components/commands.tsx","../src/components/toolbar.tsx","../src/components/toggle.tsx","../src/components/switch.tsx","../src/components/dialog.tsx","../src/components/popover.tsx","../src/components/checkbox.tsx","../src/components/async-button.tsx","../src/components/status.tsx","../src/components/metric.tsx","../src/components/meter.tsx","../src/components/composition.tsx","../src/components/link-card.tsx","../src/components/data-view.tsx","../src/lib/number-input.ts","../src/components/value-controls.tsx","../src/components/alert.tsx","../src/components/toast.tsx","../src/lib/client-work.ts","../src/components/job-status.tsx","../src/components/thumbnail.tsx","../src/components/disclosure.tsx","../src/components/selection.tsx","../src/components/data-table.tsx","../src/components/selectable-grid.tsx","../src/components/virtual-list.tsx","../src/components/infinite-list.tsx","../src/components/line-chart.tsx","../src/components/page-header.tsx","../src/components/undo.tsx","../src/components/done.tsx","../src/components/app-shell.tsx","../src/components/tabs.tsx","../src/components/active-list.tsx","../src/query/infinite.ts","../src/query/job.ts","../src/lib/viewport.ts","../src/components/fullscreen-frame.tsx","../src/components/viewport.tsx","../src/components/compare.tsx"],"sourcesContent":["// Every number and date on screen goes through Intl, once, here. Units are joined with a\n// non-breaking space so \"212 °C\" never wraps between figure and unit. A product that is not\n// en-GB calls createFormat with its locale once and exports the result from its own lib.\n//\n// The number formatters are callable (`format.integer(n)`) because that is the form people reach\n// for (strata-react issue #12), and they keep Intl's methods (`format.integer.format(n)`,\n// `formatToParts`, `resolvedOptions`) so existing calls and Intl knowledge still work.\n//\n// Dates follow the same shape. Every date formatter is callable with a Date, an ISO string or\n// epoch milliseconds (`format.dateTime(row.at)`), because rows arrive from an API as ISO strings\n// and an app that has to wrap each one in `new Date(...)` soon builds its own Intl.DateTimeFormat\n// beside it instead (strata-react issue #31, from the Bright Horizons History screen). An invalid\n// date throws a RangeError naming the input rather than printing \"Invalid Date\" into a row.\n// `date` and `dateTime` use Intl's medium/short styles, so the locale decides the order\n// (\"8 Nov 2026, 06:05\" in en-GB, \"Nov 8, 2026, 6:05 AM\" in en-US) and nobody hand-writes a\n// pattern. `timeZone` is optional: left out, times are the viewer's; a product that shows a place's\n// times (a kiln in one room, a shop's opening hours) passes that place's zone once.\n//\n// Tests: the non-breaking space is a real character in the DOM. Testing Library's text matchers\n// (`getByText`, `toHaveTextContent`) collapse whitespace and match \"6 pieces\", but accessible-name\n// matching (`getByRole(\"heading\", { name: \"6 pieces\" })`) compares the name exactly and does not.\n// Build the expected string with the same formatter (`{ name: format.count(6, \"piece\") }`), or\n// use a regex with `\\s` (`/6\\spieces/`), which matches U+00A0.\n//\n// A value that is not known (`null` or `undefined`: a count the source does not give, a date for\n// something never synced) prints as the placeholder, an en dash unless `createFormat`'s `missing`\n// says otherwise, from every number and date formatter (strata-react issue #47). Each screen used\n// to pick its own (\"–\", \"Never\", blank), so tables and cards disagreed. An invalid date still\n// throws: that is a bug, not a missing value.\n//\n// Three formatters came from the Tubes viewer, which wrote its own (strata-react issue #52): `ago`\n// (\"3 weeks ago\", from Intl.RelativeTimeFormat, with `now` passed in by tests), `compact` (\"1.2k\"\n// in en-GB, and `count`'s `{ compact: true }` for \"1.2k views\") and `runningTime` (\"4:05\", \"1:02:09\"), the\n// m:ss of a media player, which Intl.DurationFormat's long form is not. `share` is `percent` for a\n// part of a whole (strata-react issue #43): a part that is there never prints as \"0%\", nor a part\n// short of the whole as \"100%\".\n\nexport const NBSP = \" \";\n\n/** The placeholder printed for a value that is not known: an en dash. */\nexport const MISSING = \"–\";\n\n/** The decimal byte units `format.bytes` writes. */\nexport type ByteUnit = \"B\" | \"kB\" | \"MB\" | \"GB\" | \"TB\" | \"PB\";\nconst BYTE_UNITS: readonly ByteUnit[] = [\"B\", \"kB\", \"MB\", \"GB\", \"TB\", \"PB\"];\nconst BYTE_SIZE = Object.fromEntries(BYTE_UNITS.map((u, i) => [u, 1000 ** i])) as Record<ByteUnit, number>;\n\n/** An `Intl.NumberFormat` that can also be called directly: `f(n)` is `f.format(n)`. `null` or `undefined` prints the placeholder. */\nexport type NumberFormatter = ((value: number | bigint | Intl.StringNumericLiteral | null | undefined) => string) & {\n format: (value: number | bigint | Intl.StringNumericLiteral | null | undefined) => string;\n} & Pick<Intl.NumberFormat, \"formatToParts\" | \"resolvedOptions\">;\n\n/** What a date formatter accepts: a Date, an ISO 8601 string, or epoch milliseconds. */\nexport type DateInput = Date | string | number;\n\n/** An `Intl.DateTimeFormat` that can also be called directly, with a Date, an ISO string or epoch milliseconds. */\nexport type DateFormatter = ((value: DateInput | null | undefined) => string) & {\n format: (value: DateInput | null | undefined) => string;\n formatToParts: (value: DateInput) => Intl.DateTimeFormatPart[];\n formatRange: (start: DateInput, end: DateInput) => string;\n} & Pick<Intl.DateTimeFormat, \"resolvedOptions\">;\n\n/** Options shared by every date formatter one `createFormat` call makes. */\nexport interface FormatOptions {\n /** An IANA zone (\"Europe/London\", \"UTC\") to show times in. Left out, times are the viewer's own. */\n timeZone?: string;\n /** What a missing value (`null`, `undefined`) prints as. Default an en dash (`MISSING`). */\n missing?: string;\n}\n\n/** Options for `format.count`. */\nexport interface CountOptions {\n /** Write the figure compactly: \"1.2k views\". The noun still agrees with the exact count. */\n compact?: boolean;\n}\n\n/** A Date from a Date, an ISO string or epoch milliseconds; throws a RangeError naming the input when it is not a date. */\nexport function toDate(value: DateInput): Date {\n const date = value instanceof Date ? value : new Date(value);\n if (Number.isNaN(date.getTime())) throw new RangeError(`Not a date: ${JSON.stringify(String(value))}`);\n return date;\n}\n\nfunction callableDate(df: Intl.DateTimeFormat, missing: string): DateFormatter {\n const format = (value: DateInput | null | undefined) => (value == null ? missing : df.format(toDate(value)));\n return Object.assign(format, {\n format,\n formatToParts: (value: DateInput) => df.formatToParts(toDate(value)),\n formatRange: (start: DateInput, end: DateInput) => df.formatRange(toDate(start), toDate(end)),\n resolvedOptions: () => df.resolvedOptions(),\n });\n}\n\nfunction callable(nf: Intl.NumberFormat, missing: string): NumberFormatter {\n const format = (value: number | bigint | Intl.StringNumericLiteral | null | undefined) => (value == null ? missing : nf.format(value));\n return Object.assign(format, {\n format,\n formatToParts: (value: number | bigint) => nf.formatToParts(value),\n resolvedOptions: () => nf.resolvedOptions(),\n });\n}\n\n// Largest first: `ago` says a span in the largest unit it fills at least once, rounded down, so\n// 13 days is \"last week\" and 20 days \"2 weeks ago\", never \"3 weeks\" too early.\nconst DAY = 86_400_000;\nconst AGO_STEPS: readonly [Intl.RelativeTimeFormatUnit, number][] = [\n [\"year\", 365 * DAY],\n [\"month\", 30 * DAY],\n [\"week\", 7 * DAY],\n [\"day\", DAY],\n [\"hour\", 3_600_000],\n [\"minute\", 60_000],\n];\n\n/** Intl formatters for one locale (and optionally one time zone): integers, decimals, percent, dates, times, units with a non-breaking space, byte sizes, and counted nouns. */\nexport function createFormat(locale: string, options: FormatOptions = {}) {\n const { timeZone, missing = MISSING } = options;\n const dates = (opts: Intl.DateTimeFormatOptions) => callableDate(new Intl.DateTimeFormat(locale, { ...opts, timeZone }), missing);\n const integer = callable(new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }), missing);\n const decimal = callable(new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }), missing);\n const percent = callable(new Intl.NumberFormat(locale, { style: \"percent\", maximumFractionDigits: 0 }), missing);\n const compact = callable(new Intl.NumberFormat(locale, { notation: \"compact\", maximumFractionDigits: 1 }), missing);\n const relative = new Intl.RelativeTimeFormat(locale, { numeric: \"auto\" });\n const plurals = new Intl.PluralRules(locale);\n const clock = dates({ hour: \"2-digit\", minute: \"2-digit\" });\n const day = dates({ weekday: \"long\", day: \"numeric\", month: \"long\" });\n const shortDay = dates({ weekday: \"short\", hour: \"2-digit\", minute: \"2-digit\" });\n const date = dates({ dateStyle: \"medium\" });\n const dateTime = dates({ dateStyle: \"medium\", timeStyle: \"short\" });\n const withUnit = (value: number, unit: string, fmt: Pick<Intl.NumberFormat, \"format\"> = integer) =>\n `${fmt.format(value)}${NBSP}${unit}`;\n return {\n locale,\n /** The zone times are shown in, or `undefined` for the viewer's own. */\n timeZone,\n /** Whole numbers with grouping: `format.integer(1222)` is \"1,222\". */\n integer,\n /** One decimal place at most: `format.decimal(3.14)` is \"3.1\". */\n decimal,\n /** A ratio as a whole percent: `format.percent(0.42)` is \"42%\". */\n percent,\n /**\n * A part's share of a whole, as `percent` but never misleading at the ends: a part above 0 that\n * rounds to 0 is \"<1%\", and one short of the whole that rounds to 100 is \">99%\".\n * `format.share(2.4 / 512)` is \"<1%\".\n */\n share: (value: number | null | undefined) => {\n if (value == null || Number.isNaN(value)) return missing;\n if (value > 0 && value < 0.005) return `<${percent.format(0.01)}`;\n if (value >= 0.995 && value < 1) return `>${percent.format(0.99)}`;\n return percent.format(value);\n },\n /** A figure in short form for counts that run to thousands: `format.compact(1234)` is \"1.2k\" in en-GB, \"1.2K\" in en-US. */\n compact,\n /**\n * How long ago (or how far ahead) a time is, in the largest unit it reaches:\n * \"3 weeks ago\", \"yesterday\", \"in 2 hours\", \"now\" under a minute. Pass `now` in tests.\n */\n ago: (value: DateInput | null | undefined, now: DateInput = new Date()) => {\n if (value == null) return missing;\n const diff = toDate(value).getTime() - toDate(now).getTime();\n const span = Math.abs(diff);\n for (const [unit, size] of AGO_STEPS) {\n if (span >= size) return relative.format(Math.sign(diff) * Math.floor(span / size), unit);\n }\n return relative.format(0, \"second\");\n },\n /**\n * A media running time from seconds, as a player shows it: \"4:05\", \"1:02:09\". Unknown\n * (null, negative, not finite) prints the placeholder. Set it in `tabular-nums`.\n */\n runningTime: (seconds: number | null | undefined) => {\n if (seconds == null || !Number.isFinite(seconds) || seconds < 0) return missing;\n const s = Math.floor(seconds);\n const two = (n: number) => String(n).padStart(2, \"0\");\n const [h, m] = [Math.floor(s / 3600), Math.floor((s % 3600) / 60)];\n return h > 0 ? `${h}:${two(m)}:${two(s % 60)}` : `${m}:${two(s % 60)}`;\n },\n /** What a missing value prints as: an en dash unless `createFormat`'s `missing` says otherwise. */\n missing,\n /** A time of day: `format.clock(at)` is \"06:05\". */\n clock,\n /** A day without its year, for this week's things: `format.day(at)` is \"Sunday 8 November\". */\n day,\n /** A weekday and time, for chart axes and recent rows: `format.shortDay(at)` is \"Sun 06:05\". */\n shortDay,\n /** A date with its year, for a record or a deadline: `format.date(at)` is \"8 Nov 2026\". */\n date,\n /** A date and time, for a log or history row: `format.dateTime(at)` is \"8 Nov 2026, 06:05\". */\n dateTime,\n /** A figure and its unit joined by a non-breaking space (`NBSP`), so they never wrap apart. */\n withUnit,\n /** A temperature in °C, joined by a non-breaking space. */\n celsius: (value: number) => withUnit(value, \"°C\"),\n /**\n * A size in bytes in the largest decimal unit it reaches (kB, MB, GB, TB, as disks and\n * networks are sold): one decimal below 10 (\"5.2 GB\"), whole above (\"431 GB\"). Pass `unit`\n * to fix the unit, so figures compared side by side (\"431 of 466 GB\") share one.\n */\n bytes: (value: number, unit?: ByteUnit) => {\n const chosen = unit ?? [...BYTE_UNITS].reverse().find((u) => Math.abs(value) >= BYTE_SIZE[u]) ?? \"B\";\n const scaled = value / BYTE_SIZE[chosen];\n return withUnit(scaled, chosen, Math.abs(scaled) < 10 && chosen !== \"B\" ? decimal : integer);\n },\n /** The unit `bytes` would choose for a value, to share it across a set of figures. */\n byteUnit: (value: number): ByteUnit => [...BYTE_UNITS].reverse().find((u) => Math.abs(value) >= BYTE_SIZE[u]) ?? \"B\",\n /**\n * \"1 piece\", \"6 pieces\": the count and its noun, so copy never reads \"1 pieces\". They are\n * joined by a non-breaking space (`NBSP`), not a plain one: in a test, match with the same\n * call or a `\\s` regex, not a typed \"6 pieces\" string in a role's `name`.\n */\n count: (value: number | null | undefined, one: string, many = `${one}s`, { compact: short = false }: CountOptions = {}) =>\n value == null\n ? missing\n : `${(short ? compact : integer).format(value)}${NBSP}${plurals.select(value) === \"one\" ? one : many}`,\n };\n}\n\nexport type Format = ReturnType<typeof createFormat>;\n\n/** The en-GB formatters. */\nexport const format = createFormat(\"en-GB\");\n","import * as React from \"react\";\n\n// One IntersectionObserver hook for everything that waits until it is near the screen: the\n// sentinel at the end of an InfiniteList and an image in a Thumbnail. Both watch from the nearest\n// `[data-strata-scroll]` region (a VirtualList's) or else the viewport, with a root\n// margin so the work starts before the element is reached. They differ in two ways, which are\n// options rather than two hooks:\n//\n// - `once`: an image, once asked for, stays asked for; scrolling it away again must not unload it.\n// A sentinel reports in and out of view every time.\n// - `unsupported`: where there is no IntersectionObserver (an old browser, a test without the\n// fake), an image loads at once, because a photo that never loads is worse than one loaded\n// early. A sentinel reports out of view, because InfiniteList's Show more button is the path\n// that always works.\n\n/** Options for {@link useInView}. */\nexport type InViewOptions = {\n /** Watch only while this is true. Default true. */\n active?: boolean;\n /** How far outside the scroll region still counts as in view (IntersectionObserver `rootMargin`). */\n rootMargin?: string;\n /** Stay in view after the first time, and stop watching. */\n once?: boolean;\n /** What to report where `IntersectionObserver` does not exist. Default false. */\n unsupported?: boolean;\n};\n\n/**\n * Whether an element is within `rootMargin` of its scroll region (the nearest\n * `[data-strata-scroll]` ancestor, else the viewport). Returns a callback ref, so it follows the\n * element as it mounts and unmounts.\n */\nexport function useInView({ active = true, rootMargin = \"0px\", once = false, unsupported = false }: InViewOptions = {}) {\n const [inView, setInView] = React.useState(false);\n const [el, setEl] = React.useState<Element | null>(null);\n const seen = once && inView;\n React.useEffect(() => {\n if (seen) return;\n if (!active || !el) {\n setInView(false);\n return;\n }\n if (typeof IntersectionObserver === \"undefined\") {\n setInView(unsupported);\n return;\n }\n const root = el.parentElement?.closest<HTMLElement>(\"[data-strata-scroll]\") ?? null;\n const observer = new IntersectionObserver((entries) => setInView(entries[entries.length - 1].isIntersecting), { root, rootMargin });\n observer.observe(el);\n return () => observer.disconnect();\n }, [active, el, rootMargin, seen, unsupported]);\n return { ref: setEl, inView };\n}\n","import * as React from \"react\";\nimport { Button as AriaButton, type PressEvent } from \"react-aria-components\";\nimport { cva, type VariantProps } from \"class-variance-authority\";\nimport type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\nimport { Tooltip } from \"./tooltip\";\n\n// Variant names are shadcn's, so copied code and agents' prior knowledge still work. Two things\n// differ on purpose:\n// 1. The default variant is `outline`, not the filled accent. A bare <Button> is the restrained\n// one; the accent (`variant=\"default\"`) has to be asked for, once per view. Generated app screens\n// put the accent on every button; 12 of 23 real product screens had no filled primary at all.\n// 2. Heights come from --control-h, shared with Input and NativeSelect, so density changes move\n// every control together.\n// 3. React Aria is the primitives layer (CLAUDE.md, \"The stack\"): behaviour and accessibility come\n// from it, the look from our tokens. `asChild`/`Slot` is gone; a button that navigates is a link.\n// 4. `press`: the button gives 2% under a click or a finger, over 100ms. Buttons are used tens of\n// times a day, so that is all the motion they get (character.md, the frequency budget).\nexport const buttonVariants = cva(\n \"inline-flex shrink-0 cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-control type-label transition-state press disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0\",\n {\n variants: {\n variant: {\n default: \"bg-primary text-primary-foreground hover:bg-primary-10\",\n outline: \"border border-input bg-background text-foreground hover:bg-muted\",\n secondary: \"bg-muted text-foreground hover:bg-neutral-4\",\n ghost: \"text-foreground hover:bg-muted\",\n destructive: \"bg-destructive text-destructive-foreground hover:bg-danger\",\n link: \"h-auto px-0 text-primary-11 underline underline-offset-4 hover:text-primary-12\",\n },\n size: {\n default: \"h-(--control-h) px-4\",\n sm: \"h-(--control-h-sm) px-3\",\n icon: \"size-(--control-h)\",\n },\n },\n defaultVariants: { variant: \"outline\", size: \"default\" },\n },\n);\n\nexport type ButtonProps = Omit<React.ComponentProps<\"button\">, \"className\" | \"style\"> &\n VariantProps<typeof buttonVariants> & {\n className?: string;\n /** React Aria's press event (mouse, touch, pen and keyboard alike). `onClick` also works. */\n onPress?: (event: PressEvent) => void;\n };\n\n/**\n * A button with shadcn's variant names, built on React Aria's `Button` (press handling that behaves\n * the same for mouse, touch, pen and keyboard, focus-visible and hover state). The default variant is\n * `outline`; ask for the filled accent (`variant=\"default\"`) once per view. `type` defaults to `button`.\n * `onClick` and `disabled` are the DOM names and keep working; `onPress` is also accepted.\n */\nexport function Button({ className, variant, size, type = \"button\", disabled, ...props }: ButtonProps) {\n // data-variant says which variant was drawn, so a test can check \"one filled button per view\"\n // without reading class names (strata-react issue #48, `filledButtons` in strata-react/testing).\n return (\n <AriaButton\n type={type}\n isDisabled={disabled}\n data-variant={variant ?? \"outline\"}\n className={cn(buttonVariants({ variant, size }), className)}\n {...(props as object)}\n />\n );\n}\n\n// An icon-only button cannot be written without a name: `label` is required by the type, becomes\n// the accessible name and is shown as a `Tooltip` on hover and keyboard focus, so the name and the\n// visible hint come from one string and cannot drift. This makes the most common generated\n// accessibility defect (an unlabelled icon button) a compile error instead of an audit finding.\nexport type IconButtonProps = Omit<ButtonProps, \"size\" | \"children\" | \"aria-label\"> & {\n icon: IconComponent;\n label: string;\n /** Shown after the label in its tooltip, muted: \"Ctrl+Z\". */\n hint?: React.ReactNode;\n};\n\n/** An icon-only button. `label` is required and becomes the accessible name and the tooltip (hover and keyboard focus); `hint` adds a muted aside to it, such as a shortcut. */\nexport function IconButton({ icon: Icon, label, hint, variant = \"ghost\", ...props }: IconButtonProps) {\n return (\n <Tooltip label={label} hint={hint}>\n <Button size=\"icon\" variant={variant} aria-label={label} {...props}>\n <Icon aria-hidden />\n </Button>\n </Tooltip>\n );\n}\n\n// A row action says what it does in the row (\"Withdraw\") and whom it does it to in its name\n// (\"Withdraw Tom Ellery\"): a table of eight \"Withdraw\" buttons is eight identical names in a\n// screen reader's list of controls. The name is an aria-label that starts with the visible verb,\n// so it meets WCAG 2.5.3 (label in name) and voice control still finds it by \"Withdraw\". Visually\n// hidden suffix text is not used: a hidden span joined to the verb did not form a name with its\n// space in dom-testing-library (strata-react issue #11). Ghost and small, one per row, shown only\n// on the rows where it applies; an icon-only row action is an `IconButton` whose `label` names the\n// row the same way. It keeps the row's pitch: rows with and without the action are the same height.\nexport type RowActionProps = Omit<ButtonProps, \"children\" | \"aria-label\"> & {\n /** The visible verb, sentence case: \"Withdraw\", \"Remove\". */\n label: string;\n /** What the row is, as a person would say it: \"Tom Ellery\", \"Moonbeam\". Completes the accessible name. */\n subject: string;\n icon?: IconComponent;\n};\n\n/** A small ghost action for one table row: shows `label`, and is named \"`label` `subject`\" so every row's action has its own name. */\nexport function RowAction({ label, subject, icon: Icon, variant = \"ghost\", size = \"sm\", className, ...props }: RowActionProps) {\n // -my-1.5 lets the 32px button sit in the 20px line of a table row, inside the row's padding, so\n // rows with an action keep the same pitch as rows without one.\n return (\n <Button variant={variant} size={size} aria-label={`${label} ${subject}`} className={cn(\"-my-1.5\", className)} {...props}>\n {Icon && <Icon aria-hidden />}\n {label}\n </Button>\n );\n}\n","// The look every floating surface shares (Dialog, Popover, and later Menu and Toast): the popover\n// role pair, an overlay radius, one hairline and the one shadow that exists for what floats\n// (components.md §3.11). One string, so a menu and a popover cannot drift apart.\nexport const overlaySurface =\n \"rounded-overlay border border-border bg-popover text-popover-foreground shadow-overlay enter-overlay\";\n","// Chords: a shortcut written once (\"Mod+Shift+Z\") and shown per platform (⌘⇧Z on macOS, Ctrl+Shift+Z\n// elsewhere). `Mod` is the platform's command key: Meta on macOS, Ctrl everywhere else. The other\n// modifiers are Ctrl, Meta, Alt and Shift. The key is a `KeyboardEvent.key` value, compared without\n// case (\"z\" and \"Z\" are the same key; Shift is part of the chord when written).\n//\n// Matching is exact on the modifiers: \"Mod+Z\" is not \"Mod+Shift+Z\", so Undo and Redo cannot both\n// fire. Shift is ignored for a symbol key (\"?\" is typed with Shift on most layouts), and Alt is\n// matched on the physical key for letters, since Alt+Z types \"Ω\" on a Mac.\n\n/** `\"mac\"` or `\"other\"`: which modifier glyphs to draw and what `Mod` means. */\nexport type Platform = \"mac\" | \"other\";\n\n/** The platform this page runs on, read from the browser (`mac` for macOS and iOS). Server and test default: `other`. */\nexport function detectPlatform(): Platform {\n if (typeof navigator === \"undefined\") return \"other\";\n const nav = navigator as Navigator & { userAgentData?: { platform?: string } };\n const text = nav.userAgentData?.platform ?? nav.platform ?? \"\";\n return /mac|iphone|ipad|ipod/i.test(text) ? \"mac\" : \"other\";\n}\n\ntype Parsed = { ctrl: boolean; meta: boolean; alt: boolean; shift: boolean; key: string };\n\n/** Splits \"Mod+Shift+Z\" into modifiers and key for a platform. A bare \"+\" key is written \"Mod++\". */\nexport function parseChord(chord: string, platform: Platform = detectPlatform()): Parsed {\n const parts = chord.endsWith(\"++\") ? [...chord.slice(0, -2).split(\"+\").filter(Boolean), \"+\"] : chord.split(\"+\");\n const key = parts.pop() ?? \"\";\n const mods = new Set(parts.map((p) => p.toLowerCase()));\n const mod = mods.has(\"mod\");\n return {\n ctrl: mods.has(\"ctrl\") || (mod && platform !== \"mac\"),\n meta: mods.has(\"meta\") || (mod && platform === \"mac\"),\n alt: mods.has(\"alt\"),\n shift: mods.has(\"shift\"),\n key,\n };\n}\n\nconst symbol = (key: string) => key.length === 1 && key.toUpperCase() === key.toLowerCase();\n\n/** Whether a key event is this chord. Exact on Ctrl, Meta and Alt; Shift is exact for letters and named keys. */\nexport function matchesChord(e: Pick<KeyboardEvent, \"key\" | \"code\" | \"ctrlKey\" | \"metaKey\" | \"altKey\" | \"shiftKey\">, chord: string, platform: Platform = detectPlatform()): boolean {\n const c = parseChord(chord, platform);\n if (e.ctrlKey !== c.ctrl || e.metaKey !== c.meta || e.altKey !== c.alt) return false;\n if (!symbol(c.key) && e.shiftKey !== c.shift) return false;\n if (symbol(c.key) && c.shift && !e.shiftKey) return false;\n if (e.key.toLowerCase() === c.key.toLowerCase()) return true;\n return c.alt && /^[a-z]$/i.test(c.key) && e.code === `Key${c.key.toUpperCase()}`;\n}\n\nconst NAMES: Record<string, { mac: string; other: string }> = {\n ArrowUp: { mac: \"↑\", other: \"↑\" },\n ArrowDown: { mac: \"↓\", other: \"↓\" },\n ArrowLeft: { mac: \"←\", other: \"←\" },\n ArrowRight: { mac: \"→\", other: \"→\" },\n Escape: { mac: \"⎋\", other: \"Esc\" },\n Enter: { mac: \"↩\", other: \"Enter\" },\n Backspace: { mac: \"⌫\", other: \"Backspace\" },\n Delete: { mac: \"⌦\", other: \"Delete\" },\n \" \": { mac: \"Space\", other: \"Space\" },\n Tab: { mac: \"⇥\", other: \"Tab\" },\n Home: { mac: \"↖\", other: \"Home\" },\n End: { mac: \"↘\", other: \"End\" },\n};\n\n/** A chord as a person reads it on this platform: \"⌘⇧Z\" on macOS, \"Ctrl+Shift+Z\" elsewhere. */\nexport function formatChord(chord: string, platform: Platform = detectPlatform()): string {\n const c = parseChord(chord, platform);\n const key = NAMES[c.key]?.[platform] ?? (c.key.length === 1 ? c.key.toUpperCase() : c.key);\n if (platform === \"mac\") return `${c.ctrl ? \"⌃\" : \"\"}${c.alt ? \"⌥\" : \"\"}${c.shift ? \"⇧\" : \"\"}${c.meta ? \"⌘\" : \"\"}${key}`;\n return [c.ctrl && \"Ctrl\", c.meta && \"Meta\", c.alt && \"Alt\", c.shift && \"Shift\", key].filter(Boolean).join(\"+\");\n}\n\n// Chords the browser or the OS uses for itself. An app takes one over only on purpose (`claim` on\n// the command): silently stealing Ctrl+S from a person who wanted the browser's own is a choice.\nconst RESERVED = [\n \"Mod+S\", \"Mod+P\", \"Mod+F\", \"Mod+G\", \"Mod+O\", \"Mod+N\", \"Mod+T\", \"Mod+W\", \"Mod+R\", \"Mod+L\", \"Mod+D\", \"Mod+Q\", \"Mod+H\",\n \"Mod+J\", \"Mod+U\", \"Mod+Shift+T\", \"Mod+Shift+N\", \"Mod+Shift+W\", \"Alt+ArrowLeft\", \"Alt+ArrowRight\", \"F5\", \"F11\", \"F12\",\n];\n\n/** Whether the browser uses this chord for itself, so a command may take it only with `claim`. */\nexport function isReservedChord(chord: string, platform: Platform = detectPlatform()): boolean {\n const c = parseChord(chord, platform);\n return RESERVED.some((r) => {\n const p = parseChord(r, platform);\n return p.ctrl === c.ctrl && p.meta === c.meta && p.alt === c.alt && p.shift === c.shift && p.key.toLowerCase() === c.key.toLowerCase();\n });\n}\n","import * as React from \"react\";\nimport { cn } from \"../lib/utils\";\n\n// Single-key shortcuts for Operate screens that clear a queue (accept, reject, next). A person\n// doing the same answer a hundred times a day wants one key, no pointer and no motion\n// (ux-research `ux-character.md`: 100+ a day gets nothing but an instant change). Three rules\n// keep single keys from hurting anyone:\n// 1. They never fire while the person is typing: not in an input, textarea, select or\n// contenteditable (WCAG 2.1.4 Character Key Shortcuts), and not mid-composition (IME).\n// 2. They never take a chord: with Ctrl, Meta or Alt held the browser and the OS keep the key.\n// Shift is part of the key itself, so \"?\" works and \"A\" is not \"a\".\n// 3. Holding a key does not repeat an answer; only shortcuts marked `repeat` (moving) repeat.\n// The same list drives the handler and the legend, so a shortcut cannot exist without being\n// shown, and the legend cannot advertise a key that does nothing.\n\n/** One shortcut: the keys that run it (as `KeyboardEvent.key`), what it does in the product's words, and the action. */\nexport type Shortcut = {\n /** `KeyboardEvent.key` values, e.g. `[\"j\", \"ArrowDown\"]`. The first is the one the legend leads with. */\n keys: string[];\n /** What it does, in the product's words: \"Accept booking\", not \"Action 1\". */\n label: string;\n run: () => void;\n /** Fire again while the key is held. On for moving through a list, off (the default) for answers. */\n repeat?: boolean;\n /** Ignore the key for now, and show it muted in the legend (nothing is active, say). */\n disabled?: boolean;\n};\n\nconst TEXT_INPUTS_EXEMPT = new Set([\"checkbox\", \"radio\", \"button\", \"submit\", \"reset\", \"range\", \"color\", \"file\"]);\n\n/** True when a key pressed on this element is the person typing, so single-key shortcuts must leave it alone. */\nexport function isTypingTarget(target: EventTarget | null): boolean {\n if (!(target instanceof HTMLElement)) return false;\n if (target.isContentEditable || target.closest(\"[contenteditable=''],[contenteditable='true']\")) return true;\n if (target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement) return true;\n if (target instanceof HTMLInputElement) return !TEXT_INPUTS_EXEMPT.has(target.type);\n return false;\n}\n\nfunction toShortcuts(input: Shortcut[] | Record<string, () => void>): Shortcut[] {\n return Array.isArray(input) ? input : Object.entries(input).map(([key, run]) => ({ keys: [key], label: key, run }));\n}\n\n/**\n * Binds single-key shortcuts on the window, ignoring keys typed into fields, chords with Ctrl, Meta\n * or Alt, IME composition and (unless `repeat`) held keys. Pass the same list to `KeysLegend`.\n */\nexport function useHotkeys(shortcuts: Shortcut[] | Record<string, () => void>, { enabled = true }: { enabled?: boolean } = {}) {\n // The listener is bound once; it reads the latest list, so handlers can close over fresh state.\n const latest = React.useRef<Shortcut[]>([]);\n latest.current = toShortcuts(shortcuts);\n\n React.useEffect(() => {\n if (!enabled) return;\n const onKeyDown = (e: KeyboardEvent) => {\n if (e.defaultPrevented || e.isComposing || e.ctrlKey || e.metaKey || e.altKey) return;\n if (isTypingTarget(e.target)) return;\n const hit = latest.current.find((s) => !s.disabled && s.keys.includes(e.key));\n if (!hit || (e.repeat && !hit.repeat)) return;\n e.preventDefault();\n hit.run();\n };\n window.addEventListener(\"keydown\", onKeyDown);\n return () => window.removeEventListener(\"keydown\", onKeyDown);\n }, [enabled]);\n}\n\nconst KEY_NAMES: Record<string, string> = {\n ArrowDown: \"↓\",\n ArrowUp: \"↑\",\n ArrowLeft: \"←\",\n ArrowRight: \"→\",\n Escape: \"Esc\",\n Enter: \"Enter\",\n Backspace: \"Backspace\",\n Delete: \"Delete\",\n \" \": \"Space\",\n};\n\n// The legend is quiet, caption-sized and muted: it is there to be found, not read every time.\n// It hides on coarse pointers (phones, tablets without a keyboard), where the keys do not exist.\n// Each key is a <kbd>; alternatives are read as \"j or down arrow\".\n/** A quiet legend of the screen's shortcuts, from the same list `useHotkeys` binds. Hidden on touch screens. */\nexport function KeysLegend({\n shortcuts,\n label = \"Keyboard shortcuts\",\n className,\n}: {\n shortcuts: Pick<Shortcut, \"keys\" | \"label\" | \"disabled\">[];\n /** Names the legend for screen readers. */\n label?: string;\n className?: string;\n}) {\n return (\n <dl aria-label={label} className={cn(\"flex flex-wrap gap-x-4 gap-y-1 type-caption text-muted-foreground pointer-coarse:hidden\", className)}>\n {shortcuts.map((s) => (\n <div key={s.keys.join(\" \")} className={cn(\"flex items-center gap-1.5\", s.disabled && \"opacity-50\")}>\n <dt className=\"flex items-center gap-1\">\n {s.keys.map((k, i) => (\n <React.Fragment key={k}>\n {i > 0 && <span className=\"sr-only\"> or </span>}\n <kbd className=\"min-w-5 rounded-control border border-border bg-surface-sunken px-1 text-center font-mono text-foreground\">\n {KEY_NAMES[k] ?? k}\n </kbd>\n </React.Fragment>\n ))}\n </dt>\n <dd>{s.label}</dd>\n </div>\n ))}\n </dl>\n );\n}\n","import * as React from \"react\";\nimport {\n Autocomplete,\n Dialog as AriaDialog,\n Header,\n Heading,\n Keyboard,\n Menu as AriaMenu,\n MenuItem,\n MenuSection,\n MenuTrigger,\n Modal,\n ModalOverlay,\n Popover as AriaPopover,\n SearchField,\n Input as AriaInput,\n Separator,\n SubmenuTrigger,\n Text,\n useFilter,\n} from \"react-aria-components\";\nimport { Check, ChevronRight, Search, Trash2 } from \"lucide-react\";\nimport type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\nimport { overlaySurface } from \"../lib/overlay\";\nimport { formatChord, detectPlatform, isReservedChord, matchesChord, type Platform } from \"../lib/chords\";\nimport { isTypingTarget } from \"./hotkeys\";\n\n// One command, declared once, used everywhere a person can reach it: a dropdown or menu-bar menu,\n// a context menu, the command menu, the key handler and the legend. Each of those reads the same\n// object, so the label, the enabled state and the shortcut text cannot disagree (components.md\n// §3.16 and §3.11; strata-react issue #71). This is the single-key `Shortcut` idea of `useHotkeys`\n// carried to menus and chords: `useHotkeys` is unchanged for a queue worked with single keys.\n//\n// - A label is a string or a function, so Undo can say \"Undo move clip\" and follow the history.\n// - `keys` are chords written once (\"Mod+Z\"), shown per platform (⌘Z or Ctrl+Z). They never fire\n// while the person is typing (a field's own Ctrl+Z is the field's) unless the command says\n// `inFields`, never during IME composition, and a chord the browser uses (Ctrl+S, Ctrl+P, ...)\n// is taken only with `claim: true`, an explicit choice.\n// - `disabled` is `true` or a sentence saying why (\"Nothing to undo\"); a disabled command's chord\n// does nothing, and every menu shows the item as unavailable, with the reason.\n// - Menus use React Aria's menu: roles, arrows, Home and End, typeahead, Escape back to the\n// trigger, submenus. A destructive item carries an icon as well as its colour, since colour\n// alone is not a signal (components.md §3.4). A group whose commands all have `checked` is a\n// group of checkable items.\n// Motion: shortcuts and the command menu are used 100+ times a day, so they appear at once.\n\n/** A command: what it is called, how it is run, and everything the menus need to draw it. */\nexport type Command = {\n /** Stable key for the command. */\n id: string;\n /** The verb phrase, sentence case, in the product's words (\"Split clip\"); a function when it follows state (\"Undo move clip\"). */\n label: string | (() => string);\n run: () => void;\n /** Chords that run it, written once (\"Mod+Z\", \"Delete\", \"Shift+?\"); the first is the one shown. */\n keys?: string[];\n /** Cannot run now. A sentence says why (\"Nothing to undo\") and is shown in menus. */\n disabled?: boolean | string;\n /** Cannot be undone or removes something: drawn with an icon and the danger colour. */\n destructive?: boolean;\n /** Makes a menu item checkable: whether it is on now. `run` toggles it. */\n checked?: boolean;\n icon?: IconComponent;\n /** Fire again while the key is held (for moving). Default false. */\n repeat?: boolean;\n /** Run from inside a text field too. Default false: a field keeps its own keys. */\n inFields?: boolean;\n /** Take over a chord the browser uses (Ctrl+S, Ctrl+P). Required for those; otherwise the command is not bound. */\n claim?: boolean;\n};\n\n/** What goes in a menu: a command, a separator, a titled group, or a submenu. */\nexport type MenuEntry = Command | \"separator\" | { group: string; items: Command[] } | { submenu: string; items: MenuEntry[] };\n\n/** The text of a command's label, whether it is a string or a function. */\nexport const labelOf = (c: Command) => (typeof c.label === \"function\" ? c.label() : c.label);\nconst isDisabled = (c: Command) => Boolean(c.disabled);\nconst reasonOf = (c: Command) => (typeof c.disabled === \"string\" ? c.disabled : undefined);\nconst isCommand = (e: MenuEntry): e is Command => typeof e === \"object\" && \"run\" in e;\n\n/** Options for `useCommands`. */\nexport type CommandsOptions = {\n enabled?: boolean;\n /** Which platform's `Mod` to use; read from the browser when left out. */\n platform?: Platform;\n};\n\n/**\n * Binds every command's chords on the window. Never while typing (unless the command says\n * `inFields`), never during IME composition, not on a held key (unless `repeat`), not for a disabled\n * command, and not for a chord the browser uses unless the command `claim`s it. A command's chord\n * that clashes with another's is a mistake: the first in the list wins, and a dev warning names both.\n */\nexport function useCommands(commands: readonly Command[], { enabled = true, platform }: CommandsOptions = {}) {\n const latest = React.useRef<readonly Command[]>([]);\n latest.current = commands;\n const where = platform ?? detectPlatform();\n\n React.useEffect(() => {\n if (!enabled) return;\n const onKeyDown = (e: KeyboardEvent) => {\n if (e.defaultPrevented || e.isComposing) return;\n for (const c of latest.current) {\n const chord = c.keys?.find((k) => matchesChord(e, k, where));\n if (!chord) continue;\n if (isReservedChord(chord, where) && !c.claim) continue;\n if (isTypingTarget(e.target) && !c.inFields) continue;\n if (isDisabled(c) || (e.repeat && !c.repeat)) return;\n e.preventDefault();\n c.run();\n return;\n }\n };\n window.addEventListener(\"keydown\", onKeyDown);\n return () => window.removeEventListener(\"keydown\", onKeyDown);\n }, [enabled, where]);\n\n if (import.meta.env?.DEV) warnOnClashes(commands, where);\n}\n\nfunction warnOnClashes(commands: readonly Command[], platform: Platform) {\n const seen = new Map<string, string>();\n for (const c of commands) {\n for (const k of c.keys ?? []) {\n const shown = formatChord(k, platform);\n const other = seen.get(shown);\n if (other && other !== c.id) console.warn(`strata-react: \"${shown}\" is bound to both \"${other}\" and \"${c.id}\"; the first wins.`);\n else seen.set(shown, c.id);\n }\n if (c.keys?.some((k) => isReservedChord(k, platform)) && !c.claim) {\n console.warn(`strata-react: \"${c.id}\" uses a chord the browser keeps for itself; add \\`claim: true\\` to take it over.`);\n }\n }\n}\n\n/** The shortcut a command shows in menus and legends (\"⌘Z\", \"Ctrl+Z\"), or undefined. */\nexport function commandShortcut(c: Command, platform: Platform = detectPlatform()): string | undefined {\n return c.keys?.[0] ? formatChord(c.keys[0], platform) : undefined;\n}\n\n/** A quiet legend built from the same commands the key handler runs: only commands with keys, disabled ones muted. */\nexport function CommandLegend({\n commands,\n platform,\n label = \"Keyboard shortcuts\",\n className,\n}: {\n commands: readonly Command[];\n platform?: Platform;\n label?: string;\n className?: string;\n}) {\n const where = platform ?? detectPlatform();\n const shown = commands.filter((c) => c.keys?.length);\n return (\n <dl aria-label={label} className={cn(\"flex flex-wrap gap-x-4 gap-y-1 type-caption text-muted-foreground pointer-coarse:hidden\", className)}>\n {shown.map((c) => (\n <div key={c.id} className={cn(\"flex items-center gap-1.5\", isDisabled(c) && \"opacity-50\")}>\n <dt>\n <kbd className=\"min-w-5 rounded-control border border-border bg-surface-sunken px-1 text-center font-mono text-foreground\">\n {commandShortcut(c, where)}\n </kbd>\n </dt>\n <dd>{labelOf(c)}</dd>\n </div>\n ))}\n </dl>\n );\n}\n\nconst itemClass = cn(\n \"flex min-h-(--control-h-sm) cursor-pointer items-center gap-2 rounded-control px-2 type-body-sm outline-none\",\n \"focus:bg-muted disabled:cursor-not-allowed disabled:text-muted-foreground disabled:opacity-70\",\n \"open:bg-muted\",\n);\n\nfunction Item({ command, platform }: { command: Command; platform: Platform }) {\n const Icon = command.icon ?? (command.destructive ? Trash2 : undefined);\n const shortcut = commandShortcut(command, platform);\n const reason = reasonOf(command);\n return (\n <MenuItem\n id={command.id}\n textValue={labelOf(command)}\n isDisabled={isDisabled(command)}\n onAction={command.run}\n className={cn(itemClass, command.destructive && !isDisabled(command) && \"text-danger\", \"flex-wrap\")}\n >\n {({ isSelected, selectionMode }) => (\n <>\n {selectionMode !== \"none\" ? (\n <span aria-hidden className=\"grid size-4 shrink-0 place-items-center\">{isSelected && <Check className=\"size-4\" />}</span>\n ) : (\n Icon && <Icon aria-hidden className=\"size-4 shrink-0\" />\n )}\n <Text slot=\"label\" className=\"min-w-0 flex-1 truncate\">{labelOf(command)}</Text>\n {shortcut && <Keyboard className=\"ml-6 shrink-0 font-mono type-caption text-muted-foreground\">{shortcut}</Keyboard>}\n {reason && <Text slot=\"description\" className=\"w-full pl-6 type-caption text-muted-foreground\">{reason}</Text>}\n </>\n )}\n </MenuItem>\n );\n}\n\nfunction Entries({ entries, platform }: { entries: readonly MenuEntry[]; platform: Platform }) {\n return (\n <>\n {entries.map((entry, i) => {\n if (entry === \"separator\") return <Separator key={`sep-${i}`} className=\"my-1 h-px border-0 bg-border\" />;\n if (isCommand(entry)) return <Item key={entry.id} command={entry} platform={platform} />;\n if (\"group\" in entry) {\n const checkable = entry.items.length > 0 && entry.items.every((c) => c.checked !== undefined);\n return (\n <MenuSection\n key={`group-${entry.group}`}\n selectionMode={checkable ? \"multiple\" : undefined}\n selectedKeys={checkable ? entry.items.filter((c) => c.checked).map((c) => c.id) : undefined}\n >\n <Header className=\"px-2 pt-1 type-caption text-muted-foreground\">{entry.group}</Header>\n {entry.items.map((c) => <Item key={c.id} command={c} platform={platform} />)}\n </MenuSection>\n );\n }\n return (\n <SubmenuTrigger key={`sub-${entry.submenu}`}>\n <MenuItem textValue={entry.submenu} className={itemClass}>\n <Text slot=\"label\" className=\"min-w-0 flex-1 truncate\">{entry.submenu}</Text>\n <ChevronRight aria-hidden className=\"size-4 shrink-0 text-muted-foreground\" />\n </MenuItem>\n <AriaPopover offset={0} crossOffset={-4} className={cn(\"layer-overlay min-w-48 p-1\", overlaySurface)}>\n <AriaMenu aria-label={entry.submenu} className=\"outline-none\">\n <Entries entries={entry.items} platform={platform} />\n </AriaMenu>\n </AriaPopover>\n </SubmenuTrigger>\n );\n })}\n </>\n );\n}\n\nconst surface = cn(\"layer-overlay min-w-48 p-1\", overlaySurface);\n\n/** Props for `Menu`. */\nexport type MenuProps = {\n /** Names the menu: \"File\", \"Edit\". Required. */\n label: string;\n /** The control that opens it. */\n trigger: React.ReactElement;\n items: readonly MenuEntry[];\n /** Controlled open state, for a story or a test that needs it shown. */\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n platform?: Platform;\n className?: string;\n};\n\n/** A dropdown menu of commands: the menu roles and keyboard model, shortcuts shown per platform, unavailable items with their reason, separators, groups, checkable groups and submenus. */\nexport function Menu({ label, trigger, items, open, onOpenChange, platform, className }: MenuProps) {\n const where = platform ?? detectPlatform();\n return (\n <MenuTrigger isOpen={open} onOpenChange={onOpenChange}>\n {trigger}\n <AriaPopover placement=\"bottom start\" offset={4} className={cn(surface, className)}>\n <AriaMenu aria-label={label} className=\"outline-none\">\n <Entries entries={items} platform={where} />\n </AriaMenu>\n </AriaPopover>\n </MenuTrigger>\n );\n}\n\n/** Props for `ContextMenu`. */\nexport type ContextMenuProps = {\n /** Names the menu: \"Clip actions\". Required. */\n label: string;\n items: readonly MenuEntry[];\n /** The object it belongs to. It becomes the thing the menu opens on: right-click, the context-menu key and Shift+F10. */\n children: React.ReactElement<React.HTMLAttributes<HTMLElement>>;\n platform?: Platform;\n disabled?: boolean;\n};\n\n/**\n * A context menu for an object: opens on right-click at the pointer, and from the keyboard (the\n * context-menu key or Shift+F10) beside the focused object, with the same items and shortcuts as\n * every other menu. The child gets the handlers, so it should be focusable (a row, a clip).\n */\nexport function ContextMenu({ label, items, children, platform, disabled }: ContextMenuProps) {\n const where = platform ?? detectPlatform();\n const [at, setAt] = React.useState<{ x: number; y: number } | null>(null);\n const anchor = React.useRef<HTMLSpanElement>(null);\n const open = (x: number, y: number) => setAt({ x, y });\n const child = React.Children.only(children);\n return (\n <>\n {React.cloneElement(child, {\n onContextMenu: (e: React.MouseEvent<HTMLElement>) => {\n child.props.onContextMenu?.(e);\n if (disabled || e.defaultPrevented) return;\n e.preventDefault();\n open(e.clientX, e.clientY);\n },\n onKeyDown: (e: React.KeyboardEvent<HTMLElement>) => {\n child.props.onKeyDown?.(e);\n if (disabled || e.defaultPrevented) return;\n if (e.key === \"ContextMenu\" || (e.key === \"F10\" && e.shiftKey)) {\n e.preventDefault();\n const r = e.currentTarget.getBoundingClientRect();\n open(r.left + 8, r.bottom);\n }\n },\n })}\n {at && (\n <span ref={anchor} aria-hidden style={{ position: \"fixed\", left: at.x, top: at.y, width: 0, height: 0 }} />\n )}\n <AriaPopover triggerRef={anchor} isOpen={at !== null} onOpenChange={(o) => !o && setAt(null)} placement=\"bottom start\" offset={0} className={surface}>\n <AriaMenu aria-label={label} autoFocus=\"first\" onAction={() => setAt(null)} className=\"outline-none\">\n <Entries entries={items} platform={where} />\n </AriaMenu>\n </AriaPopover>\n </>\n );\n}\n\n/** Props for `CommandMenu`. */\nexport type CommandMenuProps = {\n /** The commands to search, usually the same list given to `useCommands`. Entries may be grouped. */\n commands: readonly MenuEntry[];\n /** Controlled open state; otherwise it opens on `shortcut`. */\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n /** The chord that opens it. Default `Mod+K`. `null` for none. */\n shortcut?: string | null;\n /** The search field's name and placeholder. Default \"Search commands\". */\n label?: string;\n platform?: Platform;\n};\n\nfunction flatten(entries: readonly MenuEntry[]): Command[] {\n return entries.flatMap((e) => (e === \"separator\" ? [] : isCommand(e) ? [e] : flatten(e.items)));\n}\n\n/** A searchable list of every command, opened by a chord (default Mod+K). Choosing one closes it and runs it; an unavailable command is shown with its reason and does nothing. */\nexport function CommandMenu({ commands, open, onOpenChange, shortcut = \"Mod+K\", label = \"Search commands\", platform }: CommandMenuProps) {\n const where = platform ?? detectPlatform();\n const [own, setOwn] = React.useState(false);\n const isOpen = open ?? own;\n const set = (next: boolean) => {\n setOwn(next);\n onOpenChange?.(next);\n };\n React.useEffect(() => {\n if (!shortcut) return;\n const onKeyDown = (e: KeyboardEvent) => {\n if (e.defaultPrevented || e.isComposing || !matchesChord(e, shortcut, where)) return;\n e.preventDefault();\n // A held key repeats keydown; toggling on each would flicker the dialog open and shut.\n if (e.repeat) return;\n set(!isOpen);\n };\n window.addEventListener(\"keydown\", onKeyDown);\n return () => window.removeEventListener(\"keydown\", onKeyDown);\n });\n const { contains } = useFilter({ sensitivity: \"base\" });\n const all = flatten(commands);\n return (\n <ModalOverlay isOpen={isOpen} onOpenChange={set} isDismissable className=\"layer-overlay fixed inset-0 grid justify-items-center overflow-hidden bg-foreground/40 p-4 pt-24\">\n <Modal className={cn(\"flex max-h-full w-full max-w-lg flex-col self-start outline-none\", overlaySurface)}>\n <AriaDialog aria-label={label} className=\"flex min-h-0 flex-col outline-none\">\n <Autocomplete filter={contains}>\n <SearchField aria-label={label} autoFocus className=\"flex items-center gap-2 border-b border-border px-3\">\n <Search aria-hidden className=\"size-4 shrink-0 text-muted-foreground\" />\n <AriaInput placeholder={label} className=\"h-(--control-h) min-w-0 flex-1 bg-transparent type-body outline-none placeholder:text-muted-foreground\" />\n </SearchField>\n <AriaMenu\n aria-label=\"Commands\"\n className=\"min-h-0 overflow-y-auto overscroll-contain p-1 outline-none\"\n renderEmptyState={() => <p className=\"px-3 py-4 type-body-sm text-muted-foreground\">No command matches.</p>}\n onAction={() => set(false)}\n >\n {all.map((c) => <Item key={c.id} command={c} platform={where} />)}\n </AriaMenu>\n </Autocomplete>\n </AriaDialog>\n <Heading slot=\"title\" className=\"sr-only\">{label}</Heading>\n </Modal>\n </ModalOverlay>\n );\n}\n","import * as React from \"react\";\nimport { Toolbar as AriaToolbar, Separator } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\nimport { isTypingTarget } from \"./hotkeys\";\n\n// A toolbar groups controls that act on what is shown (a preview's grid and quality, a timeline's\n// snap, a table's density). React Aria gives it the WAI-ARIA toolbar keyboard model: one tab stop,\n// arrow keys (and Home and End) move inside it, Tab leaves it. It needs a `label`, as an unnamed\n// toolbar is announced as nothing. Groups inside it are separated by a hairline (`ToolbarSeparator`)\n// rather than by space alone, so a row of eight small controls reads as three groups. It lays out\n// as one wrapping row: when it runs out of width, controls wrap to the next line instead of being\n// hidden behind an overflow menu, which keeps every control reachable with no extra state\n// (an overflow menu is the later step, once the Menu exists).\n\n/** Props for `Toolbar`. */\nexport type ToolbarProps = {\n /** Names the toolbar for screen readers: \"Preview options\". Required. */\n label: string;\n orientation?: \"horizontal\" | \"vertical\";\n children: React.ReactNode;\n className?: string;\n};\n\n/** A group of controls with one tab stop and arrow-key movement (the WAI-ARIA toolbar pattern). Needs a `label`. */\nexport function Toolbar({ label, orientation = \"horizontal\", children, className }: ToolbarProps) {\n // React Aria's toolbar moves with the arrow keys; Home and End (to the first and last control) are\n // added here, as the WAI-ARIA toolbar pattern lists them. The capture phase runs before React\n // Aria's own handler, and a typing target (a number field inside the toolbar) keeps its Home and End.\n const jump = (e: React.KeyboardEvent<HTMLElement>) => {\n // Only events from inside the toolbar's own DOM: a Popover opened from a control here renders in\n // a portal, and its events still reach this handler through React's tree.\n if ((e.key !== \"Home\" && e.key !== \"End\") || isTypingTarget(e.target) || !e.currentTarget.contains(e.target as Node)) return;\n const items = [...e.currentTarget.querySelectorAll<HTMLElement>(\"button, input, select, textarea, a[href], [tabindex]\")].filter(\n (el) => !el.hasAttribute(\"disabled\") && el.getAttribute(\"aria-disabled\") !== \"true\" && el.tabIndex >= -1 && el.getAttribute(\"role\") !== \"separator\",\n );\n const target = e.key === \"Home\" ? items[0] : items[items.length - 1];\n if (!target) return;\n e.preventDefault();\n e.stopPropagation();\n target.focus();\n };\n return (\n <div className=\"contents\" onKeyDownCapture={jump}>\n <AriaToolbar\n aria-label={label}\n orientation={orientation}\n className={cn(\"flex flex-wrap items-center gap-1\", orientation === \"vertical\" && \"flex-col items-stretch\", className)}\n >\n {children}\n </AriaToolbar>\n </div>\n );\n}\n\n/** A hairline between groups of controls inside a `Toolbar`. */\nexport function ToolbarSeparator({ className }: { className?: string }) {\n return <Separator className={cn(\"mx-1 h-5 w-px self-center border-0 bg-border\", className)} />;\n}\n","import * as React from \"react\";\nimport { ToggleButton as AriaToggleButton, ToggleButtonGroup } from \"react-aria-components\";\nimport type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\nimport { Tooltip } from \"./tooltip\";\n\n// On/off and one-of-a-few controls for what acts on the view: grid, snap, quality, view mode,\n// density. `Toggle` is one pressed-or-not button (`aria-pressed`); `ToggleGroup` is a single-choice\n// set of them for 2 to 7 short options that switch a view (components.md §3.3; for 2 to 5 options\n// that each need a sentence use `ChoiceGroup`).\n//\n// The chosen state must be seen without colour and must not look like the view's one filled\n// primary button (patterns.md §2, the one-filled-button rule): chosen is an ink border on a\n// neutral tint, with the label unchanged in weight (no layout shift), never `bg-primary`. An\n// icon-only toggle cannot be written without its name: `label` is required, becomes the accessible\n// name and is shown as a tooltip, as for `IconButton`. Toggles are used tens of times a day, so\n// they get the press and colour transitions and nothing more (character.md §3).\n\nconst base =\n \"inline-flex shrink-0 cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-control border type-label transition-state press [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 \" +\n \"border-input bg-background text-muted-foreground hover:bg-muted hover:text-foreground \" +\n \"selected:border-foreground selected:bg-muted selected:text-foreground \" +\n \"disabled:pointer-events-none disabled:opacity-50\";\n\nconst sizes = { default: \"h-(--control-h)\", sm: \"h-(--control-h-sm)\" } as const;\ntype Size = keyof typeof sizes;\n\n/** Props for `Toggle`. */\nexport type ToggleProps = {\n /** The name, always. Shown as the text unless `icon` is given with `iconOnly`, then it is the accessible name and the tooltip. */\n label: string;\n icon?: IconComponent;\n /** Show only the icon; `label` stays the name and tooltip. */\n iconOnly?: boolean;\n pressed?: boolean;\n defaultPressed?: boolean;\n onChange?: (pressed: boolean) => void;\n disabled?: boolean;\n size?: Size;\n className?: string;\n};\n\nfunction Face({ label, icon: Icon, iconOnly, pad }: { label: string; icon?: IconComponent; iconOnly?: boolean; pad: string }) {\n return (\n <>\n {Icon && <Icon aria-hidden />}\n {!iconOnly && <span className={pad}>{label}</span>}\n </>\n );\n}\n\n/** A button that is pressed or not (`aria-pressed`). Chosen reads as an ink border on a tint, never as the filled primary. */\nexport function Toggle({ label, icon, iconOnly = false, pressed, defaultPressed, onChange, disabled, size = \"default\", className }: ToggleProps) {\n const button = (\n <AriaToggleButton\n isSelected={pressed}\n defaultSelected={defaultPressed}\n onChange={onChange}\n isDisabled={disabled}\n aria-label={icon && iconOnly ? label : undefined}\n className={cn(base, sizes[size], icon && iconOnly ? (size === \"sm\" ? \"size-(--control-h-sm)\" : \"size-(--control-h)\") : \"px-3\", className)}\n >\n <Face label={label} icon={icon} iconOnly={iconOnly && Boolean(icon)} pad=\"\" />\n </AriaToggleButton>\n );\n return icon && iconOnly ? <Tooltip label={label}>{button}</Tooltip> : button;\n}\n\n/** One option of a `ToggleGroup`. */\nexport type ToggleOption = { value: string; label: string; icon?: IconComponent; iconOnly?: boolean };\n\n/** Props for `ToggleGroup`. */\nexport type ToggleGroupProps = {\n /** Names the group for screen readers: \"Preview quality\". Required. */\n label: string;\n options: readonly ToggleOption[];\n value: string;\n onChange: (value: string) => void;\n size?: Size;\n className?: string;\n};\n\n/** A single-choice set of toggle buttons for 2 to 7 short options that switch a view. One is always chosen; arrow keys move between them. */\nexport function ToggleGroup({ label, options, value, onChange, size = \"default\", className }: ToggleGroupProps) {\n return (\n <ToggleButtonGroup\n aria-label={label}\n selectionMode=\"single\"\n disallowEmptySelection\n selectedKeys={[value]}\n onSelectionChange={(keys) => {\n const next = [...keys][0];\n if (next !== undefined) onChange(String(next));\n }}\n className={cn(\"inline-flex gap-0.5 rounded-surface border border-border bg-background p-0.5\", className)}\n >\n {options.map((o) => {\n const iconOnly = Boolean(o.icon && o.iconOnly);\n const item = (\n <AriaToggleButton\n id={o.value}\n aria-label={iconOnly ? o.label : undefined}\n className={cn(\n base,\n // Inside the group the segments are 4px, the outer 6px less its 2px padding; the group's own\n // hairline replaces each segment's, and the chosen one keeps the ink border.\n \"border-transparent bg-transparent selected:border-foreground\",\n sizes[size],\n iconOnly ? (size === \"sm\" ? \"size-(--control-h-sm)\" : \"size-(--control-h)\") : \"px-3\",\n )}\n >\n <Face label={o.label} icon={o.icon} iconOnly={iconOnly} pad=\"\" />\n </AriaToggleButton>\n );\n return iconOnly ? <Tooltip key={o.value} label={o.label}>{item}</Tooltip> : React.cloneElement(item, { key: o.value });\n })}\n </ToggleButtonGroup>\n );\n}\n","import { Switch as AriaSwitch } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\n\n// A switch is for a setting that applies the moment it is flipped (show the grid, enable the\n// heatmap), never for one that needs a Save: that is a Checkbox in a form (components.md §3.3).\n// The label and the control are one target. \"On\" is shown by position and by a tick in the thumb\n// as well as by colour, so it survives a colour-blind reading. `role=\"switch\"` and its on state\n// come from React Aria. Used many times a day, so only a short colour and position transition.\n\n/** Props for `Switch`. */\nexport type SwitchProps = {\n /** What it turns on, as the visible label: \"Show elevation profile\". Required. */\n label: string;\n /** A muted second line under the label. */\n detail?: string;\n on?: boolean;\n defaultOn?: boolean;\n onChange?: (on: boolean) => void;\n disabled?: boolean;\n className?: string;\n};\n\n/** An on/off setting that applies at once, its label and control one target. */\nexport function Switch({ label, detail, on, defaultOn, onChange, disabled, className }: SwitchProps) {\n return (\n <AriaSwitch\n isSelected={on}\n defaultSelected={defaultOn}\n onChange={onChange}\n isDisabled={disabled}\n className={cn(\"group inline-flex min-h-6 cursor-pointer items-start gap-3 disabled:cursor-not-allowed disabled:opacity-50\", className)}\n >\n <span\n aria-hidden\n className={cn(\n \"mt-0.5 flex h-5 w-9 shrink-0 items-center rounded-pill border border-input bg-muted p-0.5 transition-state\",\n \"group-selected:border-primary group-selected:bg-primary\",\n \"group-focus-visible:outline-2 group-focus-visible:outline-offset-2 group-focus-visible:outline-ring\",\n )}\n >\n <span className=\"grid size-3.5 place-items-center rounded-pill bg-background text-primary group-selected:translate-x-4\">\n <span className=\"hidden size-1.5 rounded-pill bg-primary group-selected:block\" />\n </span>\n </span>\n <span className=\"grid\">\n <span className=\"type-body\">{label}</span>\n {detail && <span className=\"type-body-sm text-muted-foreground\">{detail}</span>}\n </span>\n </AriaSwitch>\n );\n}\n","import * as React from \"react\";\nimport {\n Dialog as AriaDialog,\n DialogTrigger,\n Heading,\n Modal,\n ModalOverlay,\n} from \"react-aria-components\";\nimport { X } from \"lucide-react\";\nimport { Button, IconButton } from \"./button\";\nimport { describeActionError } from \"../lib/errors\";\nimport { cn } from \"../lib/utils\";\nimport { overlaySurface } from \"../lib/overlay\";\n\n// Dialog is for a task that needs its own space; \"a modal is never the first idea for a form that\n// fits on the page\" (components.md §3.11). AlertDialog is the only confirm in the library, for what\n// cannot be undone: a reversible removal uses `UndoBar` instead (patterns.md §7).\n//\n// What the types and the component settle, so an app cannot get them wrong:\n// - A title is required (visible, or `hideTitle` for a screen-reader-only one): an unnamed dialog is\n// announced as \"dialog\" and nothing else. An AlertDialog's `confirm` is required and is the verb,\n// \"Delete 3 firings\", never \"OK\".\n// - React Aria moves focus in on open and back to the trigger on close, makes the page behind inert\n// and stops it scrolling. Content scrolls inside the dialog when tall (`overscroll-contain`), and\n// everything is portalled onto `layer-overlay`, above panes, sticky headers and the undo bar.\n// - A dialog can be made not closable while work runs (`closable={false}`: no close control, no\n// Escape, no outside press), so an export cannot lose its Close button halfway, as strata-vid's did.\n// - An AlertDialog ignores outside presses, focuses its safe choice (Cancel) first, and stays open\n// with the reason when an async confirm fails, since closing would hide that it did not happen.\n// - The same surface is a Sheet with `placement=\"end\"`: a side panel for a long form or a detail.\n\ntype Common = {\n /** What it is for: \"Export video\", \"Delete 3 firings?\". Required. */\n title: string;\n /** Shown under the title when it is not enough alone. */\n description?: React.ReactNode;\n /** The control that opens it. Leave out and drive it with `open` and `onOpenChange`. */\n trigger?: React.ReactElement;\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n className?: string;\n};\n\n/** Props for `Dialog`. */\nexport type DialogProps = Common & {\n /** The body. It scrolls inside the dialog when it is taller than the window. */\n children?: React.ReactNode;\n /** The buttons along the bottom, built with `DialogActions`'s `close` render prop when one should close it. One filled button at most. */\n actions?: React.ReactNode | ((close: () => void) => React.ReactNode);\n /** Keep the title for screen readers only, when the body already says it. */\n hideTitle?: boolean;\n /** `false` while work cannot be interrupted: no close control, Escape or outside press. Default true. */\n closable?: boolean;\n /** `center` is a dialog; `end` is a sheet down the right edge. Default `center`. */\n placement?: \"center\" | \"end\";\n size?: \"sm\" | \"md\" | \"lg\";\n};\n\nconst sizes = { sm: \"max-w-sm\", md: \"max-w-lg\", lg: \"max-w-3xl\" } as const;\n\nconst overlayClass = \"layer-overlay fixed inset-0 grid overflow-hidden bg-foreground/40\";\n\n/** A modal dialog with a required title; focus goes in and returns, Escape and a close control dismiss it. `placement=\"end\"` makes it a sheet. */\nexport function Dialog({\n title, description, trigger, open, onOpenChange, className, children, actions,\n hideTitle, closable = true, placement = \"center\", size = \"md\",\n}: DialogProps) {\n const descriptionId = React.useId();\n return (\n <DialogTrigger isOpen={open} onOpenChange={onOpenChange}>\n {trigger}\n <ModalOverlay isDismissable={closable} isKeyboardDismissDisabled={!closable} className={cn(overlayClass, placement === \"end\" ? \"justify-items-end\" : \"place-items-center p-4\")}>\n <Modal\n className={cn(\n \"flex max-h-full min-h-0 w-full flex-col outline-none\",\n overlaySurface,\n placement === \"end\" ? \"h-full max-w-md rounded-r-none\" : sizes[size],\n className,\n )}\n >\n <AriaDialog aria-describedby={description != null ? descriptionId : undefined} className=\"flex min-h-0 flex-1 flex-col gap-4 p-4 outline-none\">\n {({ close }) => (\n <>\n <div className=\"flex items-start justify-between gap-4\">\n <div className=\"grid gap-1\">\n <Heading slot=\"title\" className={cn(\"type-heading\", hideTitle && \"sr-only\")}>\n {title}\n </Heading>\n {description != null && <p id={descriptionId} className=\"type-body-sm text-muted-foreground\">{description}</p>}\n </div>\n {closable && <IconButton icon={X} label=\"Close\" onPress={close} className=\"-mr-2 -mt-2 shrink-0\" />}\n </div>\n {children != null && <div className=\"min-h-0 flex-1 overflow-y-auto overscroll-contain\">{children}</div>}\n {actions != null && (\n <div className=\"flex flex-wrap justify-end gap-2\">{typeof actions === \"function\" ? actions(close) : actions}</div>\n )}\n </>\n )}\n </AriaDialog>\n </Modal>\n </ModalOverlay>\n </DialogTrigger>\n );\n}\n\n/** Props for `AlertDialog`. */\nexport type AlertDialogProps = Common & {\n /** The verb, repeating the action: \"Delete 3 firings\". Required; \"OK\" and \"Confirm\" are what this prevents. */\n confirm: string;\n /** Runs on confirm. When it returns a promise the dialog waits, shows the button busy, and stays open with the reason if it rejects. */\n onConfirm: () => void | Promise<unknown>;\n /** The safe choice, which has initial focus. Default \"Cancel\". */\n cancel?: string;\n /** `destructive` fills the confirm button with the destructive role. Default `destructive`. */\n tone?: \"destructive\" | \"default\";\n};\n\n/**\n * A confirm for what cannot be undone. Names the object and the consequence in `title`, repeats the\n * verb on the confirm button, focuses Cancel first and ignores outside presses.\n */\nexport function AlertDialog({\n title, description, trigger, open, onOpenChange, className, confirm, onConfirm, cancel = \"Cancel\", tone = \"destructive\",\n}: AlertDialogProps) {\n const [busy, setBusy] = React.useState(false);\n const [error, setError] = React.useState<string>();\n const [inner, setInner] = React.useState(false);\n const descriptionId = React.useId();\n const isOpen = open ?? inner;\n const change = (next: boolean) => {\n if (busy) return;\n setError(undefined);\n setInner(next);\n onOpenChange?.(next);\n };\n const run = async () => {\n try {\n const result = onConfirm();\n if (result && typeof (result as Promise<unknown>).then === \"function\") {\n setBusy(true);\n await result;\n }\n setBusy(false);\n change(false);\n } catch (thrown) {\n setBusy(false);\n setError(describeActionError(thrown) ?? \"That did not go through. Nothing was confirmed; try again.\");\n }\n };\n return (\n <DialogTrigger isOpen={isOpen} onOpenChange={change}>\n {trigger}\n <ModalOverlay isDismissable={false} isKeyboardDismissDisabled={busy} className={cn(overlayClass, \"place-items-center p-4\")}>\n <Modal className={cn(\"flex max-h-full w-full max-w-sm flex-col outline-none\", overlaySurface, className)}>\n <AriaDialog role=\"alertdialog\" aria-describedby={description != null ? descriptionId : undefined} className=\"flex min-h-0 flex-1 flex-col gap-4 p-4 outline-none\">\n {({ close }) => (\n <>\n {/* The message scrolls inside the dialog on a short window or with large text; the buttons stay in view. */}\n <div className=\"grid min-h-0 gap-3 overflow-y-auto overscroll-contain\">\n <div className=\"grid gap-1\">\n <Heading slot=\"title\" className=\"type-heading\">{title}</Heading>\n {description != null && <p id={descriptionId} className=\"type-body-sm text-muted-foreground\">{description}</p>}\n </div>\n {error && (\n <p role=\"alert\" className=\"rounded-control bg-danger-subtle px-3 py-2 type-body-sm text-danger\">\n {error}\n </p>\n )}\n </div>\n <div className=\"flex flex-wrap justify-end gap-2\">\n <Button autoFocus disabled={busy} onPress={close}>{cancel}</Button>\n <Button variant={tone === \"destructive\" ? \"destructive\" : \"default\"} disabled={busy} aria-busy={busy || undefined} onPress={run}>\n {busy ? `${confirm}…` : confirm}\n </Button>\n </div>\n </>\n )}\n </AriaDialog>\n </Modal>\n </ModalOverlay>\n </DialogTrigger>\n );\n}\n\n","import * as React from \"react\";\nimport { Dialog, DialogTrigger, Popover as AriaPopover } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\nimport { overlaySurface } from \"../lib/overlay\";\n\n// A popover holds a small form or a choice anchored to the control that opened it (a colour, a\n// sort, a few filters) where a dialog would take the whole screen. Unlike a tooltip it may hold\n// anything interactive. React Aria keeps it inside the viewport (flips and shifts at the edges),\n// closes it on Escape and on a press outside, and returns focus to the trigger. It is a labelled\n// `dialog`, so `label` is required: an unnamed floating region is the same defect as an unnamed\n// icon button. It is portalled to the body on `layer-overlay`, so panes and sticky headers cannot\n// clip or cover it.\n\n/** Props for `Popover`. */\nexport type PopoverProps = {\n /** What the popover is, as a screen reader names it: \"Line colour\", \"Filters\". Required. */\n label: string;\n /** The control that opens it (a `Button`); it gets `aria-expanded` and focus back on close. */\n trigger: React.ReactElement;\n children: React.ReactNode;\n side?: \"top\" | \"right\" | \"bottom\" | \"left\";\n /** Where along the trigger it lines up. Default `start`. */\n align?: \"start\" | \"center\" | \"end\";\n /** Controlled open state. */\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n /** Width of the surface. Default `md` (18rem). */\n size?: \"sm\" | \"md\" | \"lg\";\n className?: string;\n};\n\nconst widths = { sm: \"w-52\", md: \"w-72\", lg: \"w-96\" } as const;\n\n/** A floating panel anchored to its trigger, for a small form or choice. Requires a `label`; closes on Escape and outside press, and returns focus. */\nexport function Popover({ label, trigger, children, side = \"bottom\", align = \"start\", open, onOpenChange, size = \"md\", className }: PopoverProps) {\n const placement = (align === \"center\" ? side : `${side} ${align}`) as React.ComponentProps<typeof AriaPopover>[\"placement\"];\n return (\n <DialogTrigger isOpen={open} onOpenChange={onOpenChange}>\n {trigger}\n <AriaPopover placement={placement} offset={6} className={cn(\"layer-overlay p-3\", widths[size], overlaySurface, className)}>\n <Dialog aria-label={label} className=\"outline-none\">\n {children}\n </Dialog>\n </AriaPopover>\n </DialogTrigger>\n );\n}\n","import * as React from \"react\";\nimport { Checkbox as AriaCheckbox } from \"react-aria-components\";\nimport { Check, Minus } from \"lucide-react\";\nimport { cn } from \"../lib/utils\";\n\n// A checkbox cannot be written without a name: `label` is required, as `IconButton`'s is. Shown,\n// it sits beside the box inside one <label>, so the label and the control are a single target\n// with no dead zone between them (Vercel's interface guidelines; ux-design audit.md). Hidden\n// (`hideLabel`, for a table cell where the row already says what it is), it becomes the\n// accessible name through aria-label, never through visually hidden text: a hidden span inside a\n// label joined to a neighbour did not form a name with its space in dom-testing-library (strata-\n// react issue #11), and an aria-label leaves no room for that.\n//\n// It is React Aria's Checkbox (a visually hidden native input inside the label), so keyboard,\n// forms, `aria-checked=\"mixed\"` and press handling are the library's, and the 18px box is drawn\n// from our tokens (it is no longer the platform's `accent-primary` control: that one could not show\n// a tick and a dash in the theme's own roles). `checked=\"mixed\"` is the indeterminate state a\n// select-all needs. It used to be native; the visual baselines changed for it (CHANGELOG).\n//\n// `onCheckedChange` also says whether Shift was held, which is how a list of checkboxes extends a\n// range (strata-react issue #32). A change event carries no modifier keys, so the label notes Shift\n// on the press that leads to it: a mouse press anywhere on the target, or Space on the box.\n\n/** A checkbox with its label as one target. `label` is required; `checked=\"mixed\"` is indeterminate. */\nexport type CheckboxProps = Omit<React.ComponentProps<\"input\">, \"type\" | \"checked\" | \"onChange\" | \"aria-label\" | \"children\" | \"style\"> & {\n /** Names the checkbox. Shown beside it unless `hideLabel`. */\n label: string;\n /** Keep the label as the accessible name only, for a cell or toolbar where the context shows what it is. */\n hideLabel?: boolean;\n /** A muted second line under a shown label. */\n detail?: string;\n checked: boolean | \"mixed\";\n /** Called with the new state, and whether Shift was held (a range click or Shift+Space). */\n onCheckedChange: (checked: boolean, gesture: CheckboxGesture) => void;\n};\n\n/** How a checkbox was changed: `shiftKey` is true for Shift+click and Shift+Space, which extend a range in a list. */\nexport type CheckboxGesture = { shiftKey: boolean };\n\n/** A checkbox and its label as one target. `label` is required; `hideLabel` keeps it as the accessible name only. */\nexport function Checkbox({ label, hideLabel = false, detail, checked, onCheckedChange, className, disabled, required, ...props }: CheckboxProps) {\n const shift = useShiftNote();\n // Shift is noted in the capture phase on a wrapper, because React Aria's press handling stops the\n // events it uses before they bubble. `contents` keeps the wrapper out of layout.\n return (\n <span className=\"contents\" onMouseDownCapture={shift.handlers.onMouseDown} onKeyDownCapture={shift.handlers.onKeyDown}>\n <AriaCheckbox\n isSelected={checked === true}\n isIndeterminate={checked === \"mixed\"}\n isDisabled={disabled}\n isRequired={required}\n onChange={(selected) => onCheckedChange(selected, shift.take())}\n aria-label={hideLabel ? label : undefined}\n {...(props as object)}\n className={cn(\n \"group inline-flex min-h-6 min-w-6 items-start gap-3\",\n hideLabel && \"items-center justify-center\",\n disabled ? \"cursor-not-allowed opacity-50\" : \"cursor-pointer\",\n className,\n )}\n >\n {({ isSelected, isIndeterminate }) => (\n <>\n <span\n aria-hidden\n className={cn(\n \"grid size-4.5 shrink-0 place-items-center rounded-control border border-input bg-background transition-state\",\n \"group-focus-visible:outline-2 group-focus-visible:outline-offset-2 group-focus-visible:outline-ring\",\n (isSelected || isIndeterminate) && \"border-primary bg-primary text-primary-foreground\",\n !hideLabel && \"mt-0.5\",\n )}\n >\n {isIndeterminate ? <Minus className=\"size-3.5\" strokeWidth={3} /> : isSelected ? <Check className=\"size-3.5\" strokeWidth={3} /> : null}\n </span>\n {!hideLabel && (\n <span className=\"grid\">\n <span className=\"type-body\">{label}</span>\n {detail && <span className=\"type-body-sm text-muted-foreground\">{detail}</span>}\n </span>\n )}\n </>\n )}\n </AriaCheckbox>\n </span>\n );\n}\n\n/** Notes Shift on the press that leads to a checkbox's change event, which has no modifier keys of its own. */\nexport function useShiftNote() {\n const held = React.useRef(false);\n return React.useMemo(\n () => ({\n handlers: {\n onMouseDown: (e: React.MouseEvent) => void (held.current = e.shiftKey),\n onKeyDown: (e: React.KeyboardEvent) => void (held.current = e.shiftKey),\n },\n take: (): CheckboxGesture => {\n const shiftKey = held.current;\n held.current = false;\n return { shiftKey };\n },\n }),\n [],\n );\n}\n","import * as React from \"react\";\nimport { Check, CircleAlert, LoaderCircle } from \"lucide-react\";\nimport { Button, type ButtonProps } from \"./button\";\nimport { describeActionError, fieldErrorsOf } from \"../lib/errors\";\n\n// One object through its states: \"Book firing\" becomes \"Booking…\" becomes \"Booked\", in the same\n// button, rather than the button being swapped for a spinner. The labels are stacked in one grid\n// cell so the button is always as wide as its longest label and nothing around it shifts. The\n// button stays enabled until the request starts (so a person can always try), and the outcome is\n// announced politely for screen readers. When the action fails, the announcement carries what\n// went wrong in the product's words before the retry label (\"Kiln 2 is already booked. Try\n// again\"), because \"Try again\" alone does not say whether trying again can help.\n//\n// The button carries `data-phase` (and Button's `data-variant`), so a test reads which phase it is\n// in without matching four stacked labels in its text (strata-react issue #48); `asyncButtonPhase`\n// in strata-react/testing reads it.\n//\n// `useAsyncAction` also owns a form's field messages (strata-react issues #42 and #46). `validate`\n// runs before the action, and messages it returns stop the run and land on `fieldErrors`, keyed by\n// field; a server's per-field messages (an HttpError's `fieldErrors`, from a 422) land there too.\n// A screen passes `fieldErrors.link` to `Field error=` and keeps no `problem` state of its own.\n// Failing validation leaves the button idle, not \"Try again\": nothing was tried. `onInvalid` runs\n// once the messages are on screen, to move focus to the first field named.\n\nexport type Phase = \"idle\" | \"pending\" | \"done\" | \"error\";\n\nexport type AsyncLabels = {\n idle: string;\n /** Ends in an ellipsis: \"Saving…\", \"Booking…\". */\n pending: string;\n /** The same verb, finished: \"Saved\", \"Booked\". */\n done: string;\n error?: string;\n};\n\n/** One button through idle, pending, done and error, with the label changing in place and its width fixed by the longest label. The outcome is announced politely, with the error's own words when `error` is given. */\nexport function AsyncButton({\n phase,\n labels,\n error,\n disabled,\n ...props\n}: Omit<ButtonProps, \"children\"> & {\n phase: Phase;\n labels: AsyncLabels;\n /** What went wrong, in the product's words (`useAsyncAction`'s `error`). Announced with the error label when `phase` is `error`. */\n error?: string;\n}) {\n const errorLabel = labels.error ?? \"Try again\";\n const current = { idle: labels.idle, pending: labels.pending, done: labels.done, error: errorLabel }[phase];\n const Icon = { idle: null, pending: LoaderCircle, done: Check, error: CircleAlert }[phase];\n const announcement = phase === \"done\" ? labels.done : phase === \"error\" ? (error ? `${error} ${errorLabel}` : errorLabel) : \"\";\n\n return (\n <>\n <Button {...props} data-phase={phase} disabled={disabled || phase === \"pending\"} aria-disabled={phase === \"pending\" || undefined}>\n {Icon && <Icon aria-hidden className={phase === \"pending\" ? \"motion-safe:animate-spin\" : undefined} />}\n <span className=\"grid\">\n {[labels.idle, labels.pending, labels.done, errorLabel].map((l) => (\n <span key={l} aria-hidden={l !== current} className={l === current ? \"[grid-area:1/1]\" : \"invisible [grid-area:1/1]\"}>\n {l}\n </span>\n ))}\n </span>\n </Button>\n <span role=\"status\" className=\"sr-only\">\n {announcement}\n </span>\n </>\n );\n}\n\n/** Messages for a form's fields, keyed by field name. */\nexport type FieldErrors = Readonly<Record<string, string>>;\n\n/** Options for `useAsyncAction`. */\nexport type AsyncActionOptions<A extends unknown[] = unknown[]> = {\n /** How long `done` shows before returning to `idle`. Default 2000ms. */\n settleMs?: number;\n /** Called with whatever the action threw, once the `error` render has committed: for logging, or to move focus to the retry button or an error message. */\n onError?: (error: unknown) => void;\n /** Turns what was thrown into `error`'s sentence, in the product's words. Default `describeActionError`: HTTP status sentences for `fetchJson`'s `HttpError`, else the Error's message. */\n describeError?: (error: unknown) => string | undefined;\n /** Checks the arguments before the action runs. A message for any field stops the run and is put on `fieldErrors`; the button stays idle. */\n validate?: (...args: A) => Record<string, string | undefined> | undefined;\n /** Called once validation's messages are on screen: to move focus to the first field named. */\n onInvalid?: (fieldErrors: FieldErrors) => void;\n};\n\n/** What `useAsyncAction` returns: the phase for `AsyncButton`, a stable `run`, and what went wrong while `phase` is `error`. */\nexport type AsyncAction<A extends unknown[]> = {\n phase: Phase;\n run: (...args: A) => Promise<void>;\n /** What went wrong, from `describeError`, while `phase` is `error`; otherwise undefined. Pass it to `AsyncButton`'s `error`. */\n error: string | undefined;\n /** What the action threw, while `phase` is `error`: to read more than the sentence (an HttpError's `status` or `body`). */\n thrown: unknown;\n /** Messages per field, from `validate` or from the server (an HttpError's `fieldErrors`). Pass each to its `Field`'s `error`. Cleared by the next run. */\n fieldErrors: FieldErrors;\n /** Clears one field's message (as the person edits it), or all of them. */\n clearFieldError: (field?: string) => void;\n};\n\n// The action and its options are read through a ref so `run` keeps one identity for the\n// component's life: a caller can pass an inline arrow without re-rendering every child that takes\n// `run`, and without the try/catch and error state each caller used to write to reach the phase.\n\n/** Runs an async action and reports its phase, its error and any field messages. `done` returns to `idle` after `settleMs`; `run` never changes identity. */\nexport function useAsyncAction<A extends unknown[]>(\n action: (...args: A) => Promise<unknown>,\n { settleMs = 2000, onError, describeError = describeActionError, validate, onInvalid }: AsyncActionOptions<A> = {},\n): AsyncAction<A> {\n const [state, setState] = React.useState<ActionState>(idle);\n const timer = React.useRef<number | undefined>(undefined);\n const unreported = React.useRef<{ thrown: unknown } | { invalid: FieldErrors } | undefined>(undefined);\n const latest = React.useRef({ action, onError, settleMs, describeError, validate, onInvalid });\n React.useLayoutEffect(() => {\n latest.current = { action, onError, settleMs, describeError, validate, onInvalid };\n });\n React.useEffect(() => () => window.clearTimeout(timer.current), []);\n const run = React.useCallback(async (...args: A) => {\n window.clearTimeout(timer.current);\n const invalid = messages(latest.current.validate?.(...args));\n if (invalid) {\n unreported.current = { invalid };\n setState({ ...idle, fieldErrors: invalid });\n return;\n }\n setState({ ...idle, phase: \"pending\" });\n try {\n await latest.current.action(...args);\n setState({ ...idle, phase: \"done\" });\n timer.current = window.setTimeout(() => setState(idle), latest.current.settleMs);\n } catch (thrown) {\n unreported.current = { thrown };\n setState({ phase: \"error\", error: latest.current.describeError(thrown), thrown, fieldErrors: fieldErrorsOf(thrown) });\n }\n }, []);\n // onError and onInvalid run after their render commits, not inside run: there the button is\n // still disabled from `pending` and a message rendered on `error` does not exist yet, so a\n // callback that moves focus to either would find nothing to focus.\n React.useEffect(() => {\n const note = unreported.current;\n if (!note) return;\n if (\"thrown\" in note && state.phase === \"error\") latest.current.onError?.(note.thrown);\n else if (\"invalid\" in note) latest.current.onInvalid?.(note.invalid);\n else return;\n unreported.current = undefined;\n }, [state]);\n const clearFieldError = React.useCallback(\n (field?: string) =>\n setState((s) => {\n if (field === undefined) return Object.keys(s.fieldErrors).length ? { ...s, fieldErrors: {} } : s;\n if (!(field in s.fieldErrors)) return s;\n const { [field]: _gone, ...rest } = s.fieldErrors;\n return { ...s, fieldErrors: rest };\n }),\n [],\n );\n return { phase: state.phase, run, error: state.error, thrown: state.thrown, fieldErrors: state.fieldErrors, clearFieldError };\n}\n\ntype ActionState = { phase: Phase; error: string | undefined; thrown: unknown; fieldErrors: FieldErrors };\nconst idle: ActionState = { phase: \"idle\", error: undefined, thrown: undefined, fieldErrors: {} };\n\n/** The messages `validate` returned, without the empty ones; undefined when there are none. */\nfunction messages(found: Record<string, string | undefined> | undefined): FieldErrors | undefined {\n if (!found) return undefined;\n const kept = Object.fromEntries(Object.entries(found).filter((e): e is [string, string] => Boolean(e[1])));\n return Object.keys(kept).length ? kept : undefined;\n}\n","import type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\n\n// Status is a word first. `children` is required and must be a string, so a status can never be a\n// bare coloured dot. The tint and ink come from the fixed status roles, which are kept apart from\n// the brand accent: pale tint, dark ink of the same hue, never a saturated chip with white text.\n// No pulsing variant exists; nothing on a status mark moves unless the data behind it is live.\n\nexport type Tone = \"neutral\" | \"info\" | \"success\" | \"warning\" | \"danger\";\n\nconst tones: Record<Tone, string> = {\n neutral: \"bg-muted text-muted-foreground\",\n info: \"bg-info-subtle text-info\",\n success: \"bg-success-subtle text-success\",\n warning: \"bg-warning-subtle text-warning\",\n danger: \"bg-danger-subtle text-danger\",\n};\n\n/** A status as a word on a pale tint of its tone, with an optional icon. Never colour alone. */\nexport function Status({\n tone,\n icon: Icon,\n children,\n className,\n}: {\n tone: Tone;\n icon?: IconComponent;\n children: string;\n className?: string;\n}) {\n return (\n <span\n className={cn(\n \"inline-flex items-center gap-1.5 whitespace-nowrap rounded-pill py-0.5 pr-2.5 pl-2 type-caption font-medium\",\n tones[tone],\n className,\n )}\n >\n {Icon && <Icon aria-hidden className=\"size-3.5 shrink-0\" />}\n {children}\n </span>\n );\n}\n","import * as React from \"react\";\nimport { cn } from \"../lib/utils\";\n\n// Headline figures as one container split by hairlines, label over value: what real product screens\n// do, instead of four cards each with an icon in a tinted circle. There is deliberately no `icon`,\n// `sparkline` or `trend` prop. A change is written in words with its window (\"4 more than last\n// Thursday\"), because a green \"+12.5%\" pill says neither what changed nor since when, and the trend\n// gets its own chart.\n\n/** Headline figures as one description list split by hairlines. Holds `Metric`s. */\nexport function MetricStrip({ label, children, className }: { label: string; children: React.ReactNode; className?: string }) {\n return (\n <dl\n aria-label={label}\n className={cn(\n \"grid grid-cols-1 border-y border-border sm:auto-cols-fr sm:grid-flow-col sm:divide-x sm:divide-border\",\n className,\n )}\n >\n {children}\n </dl>\n );\n}\n\nexport type MetricProps = {\n label: string;\n /** Already formatted. Ink colour, 28px, tabular figures: never the brand colour, never 48px. */\n value: string;\n unit?: string;\n /** One sentence: the change in words with its window, or what the figure means right now. */\n note?: React.ReactNode;\n};\n\n/** One figure: label over value, an optional muted unit and a note that states any change in words with its window. */\nexport function Metric({ label, value, unit, note }: MetricProps) {\n return (\n <div className=\"grid content-start gap-0.5 border-border py-3 not-first:border-t sm:px-5 sm:not-first:border-t-0 sm:first:pl-0\">\n <dt className=\"type-label text-muted-foreground\">{label}</dt>\n <dd className=\"type-figure text-foreground\">\n {value}\n {unit && <span className=\"type-body text-muted-foreground\">{\" \" + unit}</span>}\n </dd>\n {note && <dd className=\"type-body-sm text-muted-foreground\">{note}</dd>}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { format } from \"../lib/format\";\nimport { cn } from \"../lib/utils\";\nimport { Status } from \"./status\";\n\n// A usage bar: how full one thing is (a disk, a quota, a kiln's shelves), for status dashboards\n// that otherwise hand-roll a div with a width (strata-react issue #25, from jburnhams/homepage).\n// The rules it encodes, from ux-research ui-library/components.md §3.8 and patterns.md §5:\n// - It is a `meter`, not a `progressbar`: a progress bar is a task moving to done, a meter is a\n// level that can go up or down. Its accessible name is what is measured (\"Disk /\") and its\n// value text says the reading in words (\"72% used\"), so a screen reader hears \"Disk /, meter,\n// 72% used\" rather than a bare 72.\n// - The figure is always printed beside the bar. A bar alone is read to ±10% at best.\n// - Thresholds are what the person compares against, so they are drawn on the track as notches,\n// like LineChart's `band`. Each threshold must name its state (\"Filling up\", \"Nearly full\"):\n// when the reading crosses one, the fill takes the status ink and the word is shown as a\n// `Status`, so colour is never the only cue. Thresholds are shares of `max` (0.8 is 80%),\n// because a dashboard of disks of different sizes shares one set of them.\n// - `worseWhen=\"lower\"` turns the thresholds round for levels where empty is the problem (a\n// battery, credit left): a threshold then applies at or below its share.\n// - Below every threshold the fill is one chart hue (`--chart-1` unless `colour` says otherwise),\n// the same default as LineChart, never the brand accent and never a status colour, since\n// \"fine\" needs no colour of its own.\n// - `hideLabel` is for a meter in a table row, where the row already says what it measures; the\n// label stays as the meter's accessible name.\n// - No animation on the fill: a dashboard re-renders readings, and a bar that slides on each one\n// draws the eye to nothing.\n\n/** A level on a `Meter` at which the reading changes state, with the word for that state. */\nexport type MeterThreshold = {\n /** A share of `max`, from 0 to 1: 0.8 is 80%. */\n at: number;\n tone: \"warning\" | \"danger\";\n /** What the state is called, in the product's words: \"Filling up\", \"Nearly full\". */\n label: string;\n};\n\nexport type MeterProps = {\n /** What is measured, such as \"Disk /\". The meter's accessible name. */\n label: string;\n value: number;\n /** The full scale, in the same units as `value`. Defaults to 1, so a share can be passed as is. */\n max?: number;\n /** The reading in words, shown beside the bar and used as `aria-valuetext`. Defaults to \"72% used\". */\n valueText?: string;\n /** A second line of fact, such as \"36 of 50 GB\". */\n detail?: React.ReactNode;\n thresholds?: MeterThreshold[];\n /** \"lower\" when an emptier reading is the worse one (a battery, credit left). */\n worseWhen?: \"higher\" | \"lower\";\n /** Keeps the label as the accessible name only, for a meter in a table row that names it. */\n hideLabel?: boolean;\n /** CSS colour for the fill below every threshold. Defaults to the first chart token. */\n colour?: string;\n className?: string;\n};\n\n/** The threshold a share has crossed, if any: the most severe one reached in the worse direction. */\nexport function crossedThreshold(\n share: number,\n thresholds: readonly MeterThreshold[] = [],\n worseWhen: \"higher\" | \"lower\" = \"higher\",\n): MeterThreshold | undefined {\n const reached = thresholds.filter((t) => (worseWhen === \"higher\" ? share >= t.at : share <= t.at));\n // The one furthest in the worse direction wins, so danger beats warning when both are reached.\n return reached.sort((a, b) => (worseWhen === \"higher\" ? b.at - a.at : a.at - b.at))[0];\n}\n\nconst fills = { warning: \"var(--warning)\", danger: \"var(--danger)\" } as const;\n\n/** How full one thing is: a labelled `meter` with its reading in words, threshold notches, and a status word once a threshold is crossed. */\nexport function Meter({\n label,\n value,\n max = 1,\n valueText,\n detail,\n thresholds,\n worseWhen = \"higher\",\n hideLabel = false,\n colour = \"var(--chart-1)\",\n className,\n}: MeterProps) {\n const labelId = React.useId();\n const statusId = React.useId();\n const detailId = React.useId();\n const share = max > 0 ? Math.min(1, Math.max(0, value / max)) : 0;\n const crossed = crossedThreshold(share, thresholds, worseWhen);\n // `share`, not `percent`: a disk with a little on it reads \"<1% used\", never \"0% used\".\n const text = valueText ?? `${format.share(share)} used`;\n const hasNote = Boolean(crossed || detail);\n // Two ids rather than one wrapper, so the description reads \"Nearly full, 431 GB of 466 GB\"\n // with a break between the parts instead of running them together.\n const describedBy = [crossed && statusId, detail && detailId].filter(Boolean).join(\" \") || undefined;\n\n const bar = (\n <div\n role=\"meter\"\n aria-labelledby={hideLabel ? undefined : labelId}\n aria-label={hideLabel ? label : undefined}\n aria-valuemin={0}\n aria-valuemax={max}\n aria-valuenow={Math.min(max, Math.max(0, value))}\n aria-valuetext={text}\n aria-describedby={describedBy}\n className=\"relative h-2 min-w-16 flex-1 overflow-hidden rounded-pill bg-muted\"\n >\n <div\n className=\"absolute inset-y-0 left-0\"\n style={{ width: `${share * 100}%`, background: crossed ? fills[crossed.tone] : colour }}\n />\n {/* Notches in the ground colour: the levels the reading is judged against. */}\n {thresholds?.map((t) => (\n <div\n key={t.at}\n className=\"absolute inset-y-0 w-0.5 -translate-x-1/2 bg-background\"\n style={{ left: `${Math.min(1, Math.max(0, t.at)) * 100}%` }}\n />\n ))}\n </div>\n );\n\n // The visible figure is the meter's value text, so it is hidden from the accessibility tree\n // rather than read twice.\n const figure = (\n <span aria-hidden className=\"shrink-0 type-body-sm tabular-nums text-foreground\">\n {text}\n </span>\n );\n\n const note = hasNote && (\n <div className=\"flex flex-wrap items-center gap-x-3 gap-y-1\">\n {crossed && (\n <span id={statusId} className=\"contents\">\n <Status tone={crossed.tone}>{crossed.label}</Status>\n </span>\n )}\n {detail && (\n <span id={detailId} className=\"type-body-sm text-muted-foreground tabular-nums\">\n {detail}\n </span>\n )}\n </div>\n );\n\n if (hideLabel) {\n return (\n <div className={cn(\"grid min-w-0 gap-1.5\", className)}>\n <div className=\"flex items-center gap-3\">\n {bar}\n {figure}\n </div>\n {note}\n </div>\n );\n }\n\n return (\n <div className={cn(\"grid min-w-0 gap-1.5\", className)}>\n <div className=\"flex items-baseline justify-between gap-3\">\n <span id={labelId} className=\"min-w-0 truncate type-label text-foreground\">\n {label}\n </span>\n {figure}\n </div>\n <div className=\"flex\">{bar}</div>\n {note}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { format } from \"../lib/format\";\nimport { cn } from \"../lib/utils\";\n\n// What a whole is made of (memory: used, cached, buffers, free; a kiln load: bisque, glaze, empty\n// shelves), as one stacked bar over a table. strata-react issue #25 asked for it after\n// jburnhams/homepage hand-rolled one. The rules, from ux-research ui-library/components.md §3.8\n// and patterns.md §5:\n// - Colour is never the only cue. The bar shows proportion at a glance; the table under it says\n// every part's name, amount and share in words, with a swatch that ties the row to its\n// segment. The bar is hidden from screen readers because the table already carries all of it.\n// - The parts stay in the order given, in the bar and the table, so the order is the caller's\n// meaning (used before cached before free), not sorted by size.\n// - Categorical colours come from `--chart-1…5` in order, which palette.mjs checks are told apart\n// by colour-blind readers. A sixth part has no token to take, so it must bring its own colour;\n// more than five parts usually means the small ones belong in an \"Other\" part.\n// - Segments are split by a 2px gap in the ground colour, so two neighbours of similar lightness\n// still read as two.\n// - When the parts do not fill the whole (`total` is larger than their sum), the remainder is the\n// empty track, and it must be named (`restLabel`, such as \"Free\"), so the table can say what the\n// gap is. Neither the remainder nor a part is ever left unlabelled.\n// - Values are formatted by the caller (`formatValue`), as LineChart's `formatY` is, so units stay\n// the product's; shares go through `format.share` unless `formatShare` says otherwise.\n// - A part that is there is never shown as nothing (strata-react issue #43: 2.4 GB of a 512 GB\n// disk read \"0%\"). Its share prints \"<1%\" (`format.share`), and its segment keeps a 4px sliver\n// however small it is; the table carries the exact figure.\n\n/** One part of a `CompositionBar`'s whole. */\nexport type CompositionPart = {\n /** Stable key for the part. */\n key: string;\n label: string;\n value: number;\n /** CSS colour for the segment and swatch. Defaults to the chart token for its position. */\n colour?: string;\n};\n\nexport type CompositionBarProps = {\n /** What the whole is, such as \"Memory\". Shown above the bar and names the table. */\n label: string;\n parts: CompositionPart[];\n formatValue: (value: number) => string;\n /** Formats a part's share of the whole (0 to 1). Defaults to `format.share` (\"<1%\" for a part that rounds to 0). */\n formatShare?: (share: number) => string;\n /** Header of the parts column, for screen readers and over the table. Defaults to \"Part\". */\n partHeader?: string;\n /** Header of the amounts column. Defaults to \"Amount\". */\n valueHeader?: string;\n /** Header of the shares column. Defaults to \"Share\". */\n shareHeader?: string;\n className?: string;\n} & (\n | {\n /** The size of the whole, when the parts do not fill it. The remainder is the empty track. */\n total: number;\n /** What the remainder is called (\"Free\", \"Empty shelves\"). Required with `total`. */\n restLabel: string;\n }\n | { total?: undefined; restLabel?: undefined }\n);\n\nconst MAX_TOKENS = 5;\n\n/** A part's colour: its own, or the chart token for its position. Throws past the fifth token. */\nfunction colourFor(part: CompositionPart, index: number) {\n if (part.colour) return part.colour;\n if (index >= MAX_TOKENS) {\n throw new Error(\n `CompositionBar: part \"${part.label}\" is number ${index + 1}, and there are only ${MAX_TOKENS} chart colours. ` +\n `Combine the smallest parts into one \"Other\" part, or give this part a colour.`,\n );\n }\n return `var(--chart-${index + 1})`;\n}\n\n/** What a whole is made of: a stacked bar for proportion and a table that names every part, its amount and its share, so colour is never the only cue. */\nexport function CompositionBar({\n label,\n parts,\n formatValue,\n formatShare = format.share,\n partHeader = \"Part\",\n valueHeader = \"Amount\",\n shareHeader = \"Share\",\n className,\n ...whole\n}: CompositionBarProps) {\n const captionId = React.useId();\n const sum = parts.reduce((n, p) => n + Math.max(0, p.value), 0);\n const total = Math.max(whole.total ?? sum, sum);\n const rest = whole.total !== undefined ? total - sum : 0;\n const shareOf = (value: number) => (total > 0 ? Math.max(0, value) / total : 0);\n const rows = parts.map((p, i) => ({ ...p, colour: colourFor(p, i), share: shareOf(p.value) }));\n\n return (\n <figure className={cn(\"grid min-w-0 gap-3\", className)}>\n <figcaption id={captionId} className=\"type-label text-foreground\">\n {label}\n </figcaption>\n <div aria-hidden className=\"flex h-3 gap-0.5 overflow-hidden rounded-pill bg-muted\">\n {rows\n .filter((r) => r.value > 0)\n .map((r) => (\n // Grow by share from a zero basis, so the gaps come out of every segment fairly and the\n // parts fill the track exactly. Shares, not raw values: flex-grow factors that sum to\n // less than 1 fill only that fraction of the track (found in review).\n <div key={r.key} className=\"h-full min-w-1\" style={{ flex: `${r.share} 1 0`, background: r.colour }} />\n ))}\n {rest > 0 && <div className=\"h-full min-w-0\" style={{ flex: `${shareOf(rest)} 1 0` }} />}\n </div>\n <table aria-labelledby={captionId} className=\"w-full border-collapse type-body-sm\">\n <thead className=\"sr-only\">\n <tr>\n <th scope=\"col\">{partHeader}</th>\n <th scope=\"col\">{valueHeader}</th>\n <th scope=\"col\">{shareHeader}</th>\n </tr>\n </thead>\n <tbody>\n {rows.map((r) => (\n <tr key={r.key} className=\"border-t border-border first:border-t-0\">\n <th scope=\"row\" className=\"py-1.5 pr-4 text-left font-normal\">\n <span className=\"inline-flex items-center gap-2\">\n <span aria-hidden className=\"size-3 shrink-0 rounded-control\" style={{ background: r.colour }} />\n {r.label}\n </span>\n </th>\n <td className=\"py-1.5 pr-4 text-right tabular-nums\">{formatValue(r.value)}</td>\n <td className=\"w-px py-1.5 text-right whitespace-nowrap text-muted-foreground tabular-nums\">\n {formatShare(r.share)}\n </td>\n </tr>\n ))}\n {whole.total !== undefined && (\n <tr className=\"border-t border-border\">\n <th scope=\"row\" className=\"py-1.5 pr-4 text-left font-normal\">\n <span className=\"inline-flex items-center gap-2\">\n {/* The empty track's colour with a hairline, so the swatch reads as \"nothing here\". */}\n <span aria-hidden className=\"size-3 shrink-0 rounded-control border border-border bg-muted\" />\n {whole.restLabel}\n </span>\n </th>\n <td className=\"py-1.5 pr-4 text-right tabular-nums\">{formatValue(rest)}</td>\n <td className=\"w-px py-1.5 text-right whitespace-nowrap text-muted-foreground tabular-nums\">\n {formatShare(shareOf(rest))}\n </td>\n </tr>\n )}\n </tbody>\n </table>\n </figure>\n );\n}\n","import * as React from \"react\";\nimport { Link, type To } from \"react-router\";\nimport { ArrowUpRight } from \"lucide-react\";\nimport { cn } from \"../lib/utils\";\n\n// A card that is a way to somewhere: an app on a homepage, a project in a list of projects.\n// strata-react issue #25 asked for it after jburnhams/homepage built `AppCard` by hand. A card is\n// right here because each destination *is* a separate object a person picks (ux-research\n// ui-library/patterns.md §3); a section of a screen is not, and gets space and hairlines instead.\n// - The whole card is the target, but it is one link with a short name. The link sits on the\n// title and its `::after` covers the card, so a pointer can press anywhere while a screen reader\n// hears \"Kiln log, link\" and then the description and status marks as its description, instead\n// of a link named with every word on the card. There is one tab stop per card.\n// - Because the whole card is one link, nothing else on it can be interactive (a button or a\n// second link inside a link is invalid and unreachable). `marks` is for `Status` words only.\n// - Status marks are words (`Status`), never a coloured dot in a corner.\n// - `to` is a route in this app (React Router's `Link`); `href` leaves it (a plain anchor) and is\n// marked with an arrow, so a person knows before pressing that they will leave.\n// - Hover and focus change the border and draw the ring around the card, not the title. There is\n// no lift, scale or shadow: elevation is for what floats above the page, and a card on a\n// homepage is pressed many times a day (ux-research ux-character.md, character by frequency).\n\n/** A destination card's props: `to` for a route in this app, or `href` for anywhere else, never both. */\nexport type LinkCardProps = (\n | {\n /** A route in this app, followed with React Router. */\n to: To;\n href?: undefined;\n }\n | {\n /** Somewhere outside this app; the card shows an arrow. */\n href: string;\n to?: undefined;\n }\n) & {\n /** The destination's name, and the link's accessible name. */\n title: string;\n /** One sentence on what is there. Read as the link's description. */\n description?: string;\n /** `Status` words about the destination (\"Running\", \"Updated today\"). Nothing interactive. */\n marks?: React.ReactNode;\n /** The title's element. h3 under a section heading; h2 when the cards are the page's sections. */\n as?: \"h2\" | \"h3\" | \"h4\";\n className?: string;\n};\n\n/** A destination as a card that is one link: its title is the link's name, the description and status marks are its description, and the whole card is the target. */\nexport function LinkCard({ title, description, marks, as: Heading = \"h3\", className, ...destination }: LinkCardProps) {\n const descriptionId = React.useId();\n const marksId = React.useId();\n const describedBy = [description && descriptionId, marks && marksId].filter(Boolean).join(\" \") || undefined;\n const linkClass =\n \"rounded-control outline-none after:absolute after:inset-0 after:rounded-surface\";\n\n return (\n <div\n className={cn(\n \"relative grid content-start gap-1.5 rounded-surface border border-border bg-background p-4 transition-state\",\n \"hover:border-muted-foreground has-focus-visible:outline-2 has-focus-visible:outline-offset-2 has-focus-visible:outline-ring\",\n className,\n )}\n >\n <Heading className=\"flex items-start justify-between gap-3 type-heading text-foreground\">\n {destination.href !== undefined ? (\n <>\n <a href={destination.href} aria-describedby={describedBy} className={linkClass}>\n {title}\n </a>\n <ArrowUpRight aria-hidden className=\"mt-0.5 size-4 shrink-0 text-muted-foreground\" />\n </>\n ) : (\n <Link to={destination.to} aria-describedby={describedBy} className={linkClass}>\n {title}\n </Link>\n )}\n </Heading>\n {description && (\n <p id={descriptionId} className=\"type-body-sm text-pretty text-muted-foreground\">\n {description}\n </p>\n )}\n {marks && (\n <div id={marksId} className=\"mt-1.5 flex flex-wrap gap-2\">\n {marks}\n </div>\n )}\n </div>\n );\n}\n\n/** A labelled list of `LinkCard`s in a grid: one column on a phone, up to three on a wide screen. */\nexport function LinkCardList({ label, children, className }: { label: string; children: React.ReactNode; className?: string }) {\n return (\n <ul aria-label={label} className={cn(\"grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3\", className)}>\n {React.Children.toArray(children).map((child, i) => (\n <li key={React.isValidElement(child) && child.key != null ? child.key : i} className=\"grid\">\n {child}\n </li>\n ))}\n </ul>\n );\n}\n","import * as React from \"react\";\nimport { CircleAlert, History, RotateCcw } from \"lucide-react\";\nimport { Button } from \"./button\";\nimport { format } from \"../lib/format\";\nimport { cn } from \"../lib/utils\";\n\n// Every view of remote data goes through DataView, and DataView will not type-check without a\n// skeleton and an empty state. Generated UI renders the happy path; this makes the other three\n// states part of the component's signature rather than a review comment.\n//\n// A failed refresh is not a failed read (strata-react issue #26). Once data has arrived, a later\n// refetch that fails (a poll while the server restarts, a Try again on a flaky link) leaves the\n// data on screen with `stale` set: a polite notice above it says what happened, when the data\n// shown was read, and offers Try again. Swapping a whole dashboard for an error panel throws away\n// readings the person was using, and a silent failure lets them act on old numbers as if live, so\n// the data stays and its age is said in words. Only a read that never produced data is an error.\n//\n// The failed read's look is replaceable (strata-react issue #50): an app with a second look (the\n// Tubes viewer, with its own tokens and pill buttons) passes `error`, a render function given the\n// message and the retry, and keeps the state machine (loading, error, ready, stale, empty) rather\n// than copying DataView to change one panel. Whatever it draws sits inside a `role=\"alert\"` box,\n// so the failure is still announced; the default is `LoadError`, exported for reuse.\n\n/** Data still shown after a refresh failed: why the refresh failed, when the data was read, and the Try again. */\nexport type Stale = {\n /** Why the refresh failed, for a person: the sentence an error panel would have shown. */\n message: string;\n /** When the data on screen was read. */\n readAt: Date;\n /** Fetch again. */\n retry: () => void;\n /** A fetch is on its way (a Try again or the next poll). */\n retrying?: boolean;\n};\n\n/** The state of one remote read, for `DataView`: loading, failed with no data, or ready (and `stale` when a later refresh failed). */\nexport type Load<T> =\n | { status: \"loading\" }\n | { status: \"error\"; message: string; retry: () => void }\n | { status: \"ready\"; data: T; stale?: Stale };\n\n/** What a failed read hands to an `error` renderer: the sentence for a person, and the Try again. */\nexport type LoadFailure = { message: string; retry: () => void };\n\n/** The default failed-read panel: the reason on the danger tint, with Try again. Its parent carries `role=\"alert\"`. */\nexport function LoadError({ message, retry, className }: LoadFailure & { className?: string }) {\n return (\n <div className={cn(\"flex flex-wrap items-start gap-3 rounded-surface bg-danger-subtle p-4 text-danger\", className)}>\n <CircleAlert aria-hidden className=\"mt-0.5 size-5 shrink-0\" />\n <p className=\"min-w-0 flex-1 type-body\">{message}</p>\n <Button size=\"sm\" onClick={retry}>\n <RotateCcw aria-hidden />\n Try again\n </Button>\n </div>\n );\n}\n\nconst defaultError = (failure: LoadFailure) => <LoadError {...failure} />;\n\n/** Every view of remote data: renders `skeleton` while loading, an alert with Try again on error, `empty` when `isEmpty`, else `children(data)`, under a `StaleNotice` when a refresh failed. The skeleton and empty state are required. */\nexport function DataView<T>({\n state,\n isEmpty,\n skeleton,\n empty,\n children,\n staleNotice = (stale) => <StaleNotice stale={stale} />,\n error = defaultError,\n className,\n}: {\n state: Load<T>;\n /** When the loaded data counts as empty. For arrays, `(rows) => rows.length === 0`. */\n isEmpty: (data: T) => boolean;\n /** Mirrors the final layout, so nothing jumps when data arrives. Not a centred spinner. */\n skeleton: React.ReactNode;\n /** What goes here and how to add it. An `EmptyState`, not an illustration. */\n empty: React.ReactNode;\n children: (data: T) => React.ReactNode;\n /** Shown above the data when a refresh failed. Defaults to a `StaleNotice`; pass one with the product's words for what is old (\"Readings from 13:50\"). */\n staleNotice?: (stale: Stale) => React.ReactNode;\n /** Draws a read that failed with no data, given the message and the retry. Defaults to `LoadError`. Rendered inside a `role=\"alert\"` box. */\n error?: (failure: LoadFailure) => React.ReactNode;\n className?: string;\n}) {\n return (\n <div className={cn(\"min-w-0\", className)} aria-busy={state.status === \"loading\" || undefined}>\n {state.status === \"loading\" && skeleton}\n {state.status === \"error\" && <div role=\"alert\">{error({ message: state.message, retry: state.retry })}</div>}\n {state.status === \"ready\" && (\n <>\n {state.stale && staleNotice(state.stale)}\n {isEmpty(state.data) ? empty : children(state.data)}\n </>\n )}\n </div>\n );\n}\n\n/** When `readAt` was, for a person: the clock time today, else the weekday and time. */\nfunction readTime(readAt: Date, now = new Date()) {\n return readAt.toDateString() === now.toDateString() ? format.clock.format(readAt) : format.shortDay.format(readAt);\n}\n\n/** The notice over data whose refresh failed: what happened, how old the data shown is, and Try again. A polite status, not an alert: nothing was lost. */\nexport function StaleNotice({\n stale,\n shown,\n className,\n}: {\n stale: Stale;\n /** What is old, in the product's words, given when it was read (\"13:50\", or \"Sat 13:50\" before today). Defaults to \"Showing data from 13:50.\" */\n shown?: (when: string) => React.ReactNode;\n className?: string;\n}) {\n return (\n <div role=\"status\" className={cn(\"mb-4 flex flex-wrap items-start gap-3 rounded-surface bg-warning-subtle p-3 text-warning\", className)}>\n <History aria-hidden className=\"mt-0.5 size-4 shrink-0\" />\n <p className=\"min-w-0 flex-1 type-body-sm\">\n {stale.message} {shown ? shown(readTime(stale.readAt)) : `Showing data from ${readTime(stale.readAt)}.`}\n </p>\n <Button size=\"sm\" onClick={stale.retry} disabled={stale.retrying}>\n <RotateCcw aria-hidden />\n {stale.retrying ? \"Trying again…\" : \"Try again\"}\n </Button>\n </div>\n );\n}\n\n// An empty state teaches the next action. No illustration slot exists, on purpose.\n/** An empty state that teaches the next action: a title, a sentence and an action. No illustration slot, on purpose. */\nexport function EmptyState({ title, children, action }: { title: string; children?: React.ReactNode; action?: React.ReactNode }) {\n return (\n <div className=\"grid justify-items-start gap-2 border-y border-border py-6\">\n <p className=\"type-heading\">{title}</p>\n {children && <p className=\"max-w-prose type-body text-muted-foreground\">{children}</p>}\n {action && <div className=\"mt-2\">{action}</div>}\n </div>\n );\n}\n\n/** A placeholder block for a loading layout. Size it with layout classes so it mirrors the final content. */\nexport function Skeleton({ className }: { className?: string }) {\n return <div aria-hidden className={cn(\"rounded-control bg-muted motion-safe:animate-pulse\", className)} />;\n}\n","// Colour rules for `ColorField` (issue #73): reading a typed hex, and the WCAG contrast ratio\n// against what the colour is drawn on, which a user-chosen colour (content, not theme) is checked\n// with. Number parsing and stepping are React Aria's.\n\n/** Reads `#rgb`, `#rrggbb` (with or without the #) as lower-case `#rrggbb`, or null. */\nexport function parseHex(text: string): string | null {\n const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(text.trim());\n if (!m) return null;\n const h = m[1].toLowerCase();\n return \"#\" + (h.length === 3 ? [...h].map((c) => c + c).join(\"\") : h);\n}\n\nfunction luminance(hex: string): number {\n const v = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255).map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));\n return 0.2126 * v[0] + 0.7152 * v[1] + 0.0722 * v[2];\n}\n\n/** WCAG contrast ratio between two `#rrggbb` colours, 1 to 21. */\nexport function contrastRatio(a: string, b: string): number {\n const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);\n return (hi + 0.05) / (lo + 0.05);\n}\n","import * as React from \"react\";\nimport {\n I18nProvider,\n Input as AriaInput,\n NumberField as AriaNumberField,\n Slider as AriaSlider,\n SliderOutput,\n SliderThumb,\n SliderTrack,\n} from \"react-aria-components\";\nimport { useFieldControl } from \"./field\";\nimport { NBSP, format } from \"../lib/format\";\nimport { contrastRatio, parseHex } from \"../lib/number-input\";\nimport { cn } from \"../lib/utils\";\n\n// Controls for setting a number or a colour precisely (strata-react issue #73, from moving\n// strata-vid onto Strata: opacity, rotation, volume, bitrate, a line colour). The native ones fail\n// in the same few ways, and each rule below answers one:\n//\n// - `parseFloat(e.target.value)` turns an empty field into NaN. Here a value that is not known is\n// `null`, stays `null`, and prints `format.missing`; a typed value outside the limits is NOT\n// clamped and NOT passed on: React Aria's field runs with `commitBehavior=\"validate\"` (it keeps\n// what was typed instead of snapping 600 to 500), and the control tells the surrounding `Field`\n// what is wrong (\"Enter a value from 0% to 500%.\"), the same place a server's 422 appears. The\n// callback only ever receives a number inside the limits, or null.\n// - The unit lives inside the control, muted. A slider's spoken value carries it (\"40%\", \"90°\")\n// when `Intl` knows the unit (percent, degree, millisecond, megabit-per-second and the like):\n// React Aria builds `aria-valuetext` from an `Intl.NumberFormat`, so \"px\" or \"steps\" are in the\n// printed value and the label but cannot be in the spoken one.\n// - Digits are the locale's: what is printed and what is read back go through `Intl` (React Aria's\n// `NumberParser`), so 12,5 works in a de-DE app, and the message is in the same digits.\n// - Behaviour is React Aria's: arrows step, PageUp/PageDown take ten steps, Home/End jump to the\n// limits, a field commits on Enter and blur. Nothing animates when a value changes: these are\n// dragged and stepped dozens of times a minute (character.md, the frequency budget).\n// - A colour a person picks for their own content (a route's line) is content, not theme, so it is\n// the one place a raw colour value is right; `against` checks it against what it is drawn on.\n// The colour field's text box is ours: React Aria's colour field puts the old colour back when\n// the text is not a colour, where this one says so under the control; the swatch opens the\n// platform picker.\n\nconst box =\n \"flex h-(--control-h) w-full min-w-0 items-center rounded-control border border-input bg-background px-3 type-body text-foreground transition-state disabled:cursor-not-allowed disabled:bg-muted disabled:opacity-70 has-[input:disabled]:cursor-not-allowed has-[input:disabled]:bg-muted has-[input:disabled]:opacity-70 aria-invalid:border-danger has-[input:focus-visible]:outline-2 has-[input:focus-visible]:outline-offset-2 has-[input:focus-visible]:outline-ring\";\n\n/** A number with its unit joined by a non-breaking space; `%` and `°` stay attached. */\nfunction withUnit(text: string, unit?: string) {\n if (!unit) return text;\n return unit === \"%\" || unit === \"°\" ? text + unit : text + NBSP + unit;\n}\n\n// Units `Intl` can speak, by the symbol an app prints. Anything else is printed but not spoken.\nconst intlUnits: Record<string, string> = {\n \"%\": \"percent\",\n \"°\": \"degree\",\n ms: \"millisecond\",\n s: \"second\",\n kB: \"kilobyte\",\n MB: \"megabyte\",\n GB: \"gigabyte\",\n kbps: \"kilobit-per-second\",\n Mbps: \"megabit-per-second\",\n};\n\nfunction decimalsOf(n: number): number {\n const s = String(n);\n if (s.includes(\"e-\")) return Number(s.split(\"e-\")[1]) + (s.split(\"e-\")[0].split(\".\")[1]?.length ?? 0);\n return s.split(\".\")[1]?.length ?? 0;\n}\n\nfunction useNumberText(locale: string, places: number) {\n return React.useMemo(() => {\n const f = new Intl.NumberFormat(locale, { maximumFractionDigits: places, minimumFractionDigits: 0 });\n return (n: number) => f.format(n);\n }, [locale, places]);\n}\n\nfunction formatOptionsFor(places: number, unit?: string): Intl.NumberFormatOptions {\n const base: Intl.NumberFormatOptions = { maximumFractionDigits: places, minimumFractionDigits: 0 };\n const known = unit ? intlUnits[unit] : undefined;\n return known ? { ...base, style: \"unit\", unit: known, unitDisplay: \"narrow\" } : base;\n}\n\n/** Props shared by the number field and the slider. */\nexport type RangeProps = {\n min?: number;\n max?: number;\n /** The size of one arrow-key step. Default 1. */\n step?: number;\n /** The unit shown with the value: \"%\", \"°\", \"Mbps\", \"px\". Spoken too when `Intl` has it (%, °, ms, s, kB, MB, GB, kbps, Mbps). */\n unit?: string;\n /** The locale for digits and the decimal mark. Default the app's `format` locale. */\n locale?: string;\n};\n\n/** Props for `NumberField`. */\nexport type NumberFieldProps = RangeProps & {\n /** The current value; `null` when it is not known (shown as an en dash, not 0). */\n value: number | null;\n /** Receives a number inside the limits, or `null` when the field is cleared. Never NaN, never out of range. */\n onChange: (value: number | null) => void;\n /** Decimal places to show and keep. Default the places in `step` (and `min`). */\n places?: number;\n /** An empty field is an error (\"Enter a value.\") rather than `null`. */\n required?: boolean;\n disabled?: boolean;\n /** Names the control when it is used without a `Field`. */\n \"aria-label\"?: string;\n id?: string;\n name?: string;\n className?: string;\n};\n\nfunction describeRange(min: number | undefined, max: number | undefined, show: (n: number) => string, unit?: string) {\n const a = min === undefined ? \"\" : withUnit(show(min), unit);\n const b = max === undefined ? \"\" : withUnit(show(max), unit);\n if (min !== undefined && max !== undefined) return `Enter a value from ${a} to ${b}.`;\n if (min !== undefined) return `Enter ${a} or more.`;\n if (max !== undefined) return `Enter ${b} or less.`;\n return \"Enter a number.\";\n}\n\n/** A number with a unit on React Aria's number field: typed input is validated, not clamped, so an out-of-range value is explained in the surrounding `Field` and never passed on; empty stays `null`. */\nexport function NumberField({\n value,\n onChange,\n min,\n max,\n step = 1,\n places,\n unit,\n locale = format.locale,\n required = false,\n disabled,\n id: idProp,\n name,\n className,\n \"aria-label\": ariaLabel,\n}: NumberFieldProps) {\n const { field, report } = useFieldControl();\n const digits = places ?? Math.max(decimalsOf(step), min === undefined ? 0 : decimalsOf(min));\n const show = useNumberText(locale, digits);\n const [own, setOwn] = React.useState(false); // invalid, when there is no Field to say so\n const unitId = React.useId();\n // What the field shows. It follows `value`, but also holds an entry we refused, so the person sees\n // (and can correct) what they typed instead of the field snapping back to the old value.\n const [local, setLocal] = React.useState<number>(value ?? Number.NaN);\n const [seen, setSeen] = React.useState(value);\n if (seen !== value) {\n setSeen(value);\n setLocal(value ?? Number.NaN);\n }\n\n const fail = (message: string) => {\n setOwn(true);\n report(message);\n };\n const ok = () => {\n setOwn(false);\n report(undefined);\n };\n\n const handle = (n: number) => {\n setLocal(n);\n if (Number.isNaN(n)) {\n if (required) return fail(\"Enter a value.\");\n ok();\n if (value !== null) onChange(null);\n return;\n }\n if ((min !== undefined && n < min) || (max !== undefined && n > max)) return fail(describeRange(min, max, show, unit));\n ok();\n if (n !== value) onChange(n);\n };\n\n const invalid = field?.invalid || own;\n return (\n <I18nProvider locale={locale}>\n <AriaNumberField\n value={local}\n onChange={handle}\n minValue={min}\n maxValue={max}\n step={step}\n formatOptions={{ maximumFractionDigits: digits, minimumFractionDigits: 0 }}\n commitBehavior=\"validate\"\n isDisabled={disabled}\n isInvalid={invalid || undefined}\n name={name}\n aria-label={ariaLabel ?? field?.label}\n className={cn(box, className)}\n >\n <AriaInput\n id={idProp ?? field?.id}\n placeholder={format.missing}\n aria-describedby={[field?.describedBy, unit ? unitId : undefined].filter(Boolean).join(\" \") || undefined}\n className=\"min-w-0 flex-1 bg-transparent tabular-nums outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed\"\n />\n {unit && (\n <span id={unitId} className=\"ml-2 shrink-0 type-body-sm text-muted-foreground\">\n <span aria-hidden>{unit}</span>\n <span className=\"sr-only\">{intlUnits[unit] ? intlUnits[unit].replace(/-/g, \" \") : unit}</span>\n </span>\n )}\n </AriaNumberField>\n </I18nProvider>\n );\n}\n\n/** Props for `Slider`. */\nexport type SliderProps = RangeProps & {\n value: number;\n onChange: (value: number) => void;\n /** Both limits are required: a slider with no ends is not a slider. */\n min: number;\n max: number;\n /** Replace the printed value with a `NumberField` beside the track, so an exact value can be typed. */\n editable?: boolean;\n /** Hide the printed value (when something else beside it already shows it). */\n hideValue?: boolean;\n /** Decimal places in the printed and spoken value. Default the places in `step`. */\n places?: number;\n disabled?: boolean;\n /** Names the slider when it is used without a `Field`. */\n \"aria-label\"?: string;\n className?: string;\n};\n\n/** A slider on React Aria with its current value always printed beside the track (and spoken with the unit when `Intl` knows it); `editable` adds a number field to type an exact value. */\nexport function Slider({\n value,\n onChange,\n min,\n max,\n step = 1,\n unit,\n locale = format.locale,\n editable = false,\n hideValue = false,\n places,\n disabled,\n className,\n \"aria-label\": ariaLabel,\n}: SliderProps) {\n const { field } = useFieldControl();\n const digits = places ?? Math.max(decimalsOf(step), decimalsOf(min));\n const show = useNumberText(locale, digits);\n const name = ariaLabel ?? field?.label ?? \"Value\";\n const text = withUnit(show(value), unit);\n return (\n <I18nProvider locale={locale}>\n <AriaSlider\n value={value}\n onChange={(v) => onChange(v as number)}\n minValue={min}\n maxValue={max}\n step={step}\n formatOptions={formatOptionsFor(digits, unit)}\n isDisabled={disabled}\n aria-label={name}\n aria-describedby={field?.describedBy}\n className={cn(\"flex min-w-0 items-center gap-3\", className)}\n >\n <SliderTrack className=\"relative flex h-(--control-h) min-w-0 flex-1 cursor-pointer items-center disabled:cursor-not-allowed disabled:opacity-50\">\n {({ state }) => (\n <>\n <span aria-hidden className=\"absolute inset-x-0 h-1.5 rounded-pill bg-muted\" />\n <span aria-hidden className=\"absolute left-0 h-1.5 rounded-pill bg-primary\" style={{ width: `${state.getThumbPercent(0) * 100}%` }} />\n <SliderThumb className=\"top-1/2 size-5 rounded-pill border-2 border-primary bg-background focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring\" />\n </>\n )}\n </SliderTrack>\n {editable ? (\n <NumberField className=\"w-28 shrink-0\" aria-label={`${name}, exact value`} value={value} onChange={(v) => v !== null && onChange(v)} min={min} max={max} step={step} unit={unit} locale={locale} places={digits} required disabled={disabled} />\n ) : (\n !hideValue && (\n <SliderOutput aria-hidden className=\"w-16 shrink-0 text-right type-body-sm tabular-nums text-foreground\">\n {text}\n </SliderOutput>\n )\n )}\n </AriaSlider>\n </I18nProvider>\n );\n}\n\n/** Props for `ColorField`. */\nexport type ColorFieldProps = {\n /** `#rrggbb`, or `null` when no colour is set. */\n value: string | null;\n /** Receives a valid `#rrggbb` (lower case) or `null` when cleared; never a half-typed value. */\n onChange: (value: string | null) => void;\n /** A short list the app suggests, as `#rrggbb`. Pressing one chooses it. */\n suggestions?: readonly string[];\n /** The colour this will be drawn on, `#rrggbb`: a note appears when the contrast would be low. */\n against?: string;\n /** What it is drawn on, in words: \"the map\". Completes the note. */\n againstLabel?: string;\n /** The lowest contrast ratio accepted before the note shows. Default 3, the WCAG minimum for graphics. */\n minContrast?: number;\n disabled?: boolean;\n \"aria-label\"?: string;\n id?: string;\n className?: string;\n};\n\n/** Choose a colour with the platform picker, see and type its hex value, pick from the app's suggestions, and get a note when it would be hard to see on `against`. A half-typed value is never passed on. */\nexport function ColorField({ value, onChange, suggestions, against, againstLabel = \"the background\", minContrast = 3, disabled, id: idProp, className, \"aria-label\": ariaLabel }: ColorFieldProps) {\n const { field, report } = useFieldControl();\n const [draft, setDraft] = React.useState<string | null>(null);\n const [own, setOwn] = React.useState(false);\n const text = draft ?? value ?? \"\";\n const ratio = value && against ? contrastRatio(value, against) : null;\n\n const commitText = (t: string): boolean => {\n if (t.trim() === \"\") {\n setOwn(false);\n report(undefined);\n if (value !== null) onChange(null);\n return true;\n }\n const hex = parseHex(t);\n if (!hex) {\n setOwn(true);\n report(\"Enter a colour like #1a7f64.\");\n return false;\n }\n setOwn(false);\n report(undefined);\n if (hex !== value) onChange(hex);\n return true;\n };\n\n const pick = (hex: string) => {\n setDraft(null);\n setOwn(false);\n report(undefined);\n if (hex !== value) onChange(hex);\n };\n\n const invalid = field?.invalid || own;\n return (\n <div className={cn(\"grid min-w-0 gap-2\", className)}>\n <div className={cn(box, \"gap-2 px-2\")} aria-invalid={invalid || undefined}>\n <span className=\"relative size-6 shrink-0 overflow-hidden rounded-control border border-input\">\n {/* The swatch is the chosen colour itself: user content, not a theme role. */}\n <span aria-hidden className={cn(\"absolute inset-0\", value === null && \"bg-muted\")} style={value ? { background: value } : undefined} />\n <input\n type=\"color\"\n aria-label={ariaLabel ? `${ariaLabel}, picker` : \"Colour picker\"}\n value={value ?? \"#000000\"}\n disabled={disabled}\n onChange={(e) => pick(e.target.value)}\n className=\"absolute inset-0 size-full cursor-pointer opacity-0 disabled:cursor-not-allowed\"\n />\n </span>\n <input\n id={idProp ?? field?.id}\n type=\"text\"\n autoComplete=\"off\"\n spellCheck={false}\n disabled={disabled}\n aria-label={ariaLabel}\n aria-describedby={field?.describedBy}\n aria-invalid={invalid || undefined}\n placeholder={format.missing}\n value={text}\n onChange={(e) => setDraft(e.target.value)}\n onBlur={() => {\n if (draft !== null && commitText(draft)) setDraft(null);\n }}\n onKeyDown={(e) => {\n if (e.key === \"Enter\" && draft !== null && commitText(draft)) setDraft(null);\n if (e.key === \"Escape\" && draft !== null) {\n setDraft(null);\n setOwn(false);\n report(undefined);\n }\n }}\n className=\"min-w-0 flex-1 bg-transparent tabular-nums outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed\"\n />\n </div>\n {suggestions && suggestions.length > 0 && (\n <div role=\"group\" aria-label=\"Suggested colours\" className=\"flex flex-wrap gap-1.5\">\n {suggestions.map((hex) => (\n <button\n key={hex}\n type=\"button\"\n disabled={disabled}\n aria-label={hex}\n aria-pressed={value === hex}\n onClick={() => pick(hex)}\n className=\"size-6 cursor-pointer rounded-control border border-input transition-state aria-pressed:outline-2 aria-pressed:outline-offset-2 aria-pressed:outline-foreground disabled:cursor-not-allowed disabled:opacity-50\"\n style={{ background: hex }}\n />\n ))}\n </div>\n )}\n {ratio !== null && ratio < minContrast && (\n <p className=\"type-body-sm text-warning\">\n Hard to see on {againstLabel}: contrast {format.decimal(ratio)}:1, aim for {format.decimal(minContrast)}:1 or more.\n </p>\n )}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { CircleAlert, CircleCheck, Info, TriangleAlert } from \"lucide-react\";\nimport type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\nimport type { Tone } from \"./status\";\n\n// An alert is one inline sentence about a problem or a fact, where it applies: a failed export\n// under the export, a stale reading above the chart. It is how an error a person must act on is\n// shown, with its recovery as `action`; a toast is not (components.md §3.13, patterns.md §7).\n//\n// Drawn as a pale tint of its tone with its icon and, for `title`, a heavier first line: never a\n// coloured stripe down one side of a rounded box (the tell in ux-slop-taxonomy), and never colour\n// alone, since the icon and the words carry the tone. `role=\"alert\"` interrupts a screen reader,\n// so it is on only when the alert appears in response to something the person just did\n// (`announce`); a banner that is simply there on load is a plain region the reader finds in order.\n\n/** Props for `Alert`. */\nexport type AlertProps = {\n tone: Exclude<Tone, \"neutral\">;\n /** A short first line, when the sentence needs one: \"Export failed\". */\n title?: string;\n /** The sentence, in the product's words: what happened and what to do. */\n children: React.ReactNode;\n /** One recovery, a `Button` (\"Try again\"). */\n action?: React.ReactNode;\n /** It appeared because of something the person just did (a failed submit): announce it at once (`role=\"alert\"`). */\n announce?: boolean;\n className?: string;\n};\n\nconst tones: Record<Exclude<Tone, \"neutral\">, { box: string; icon: IconComponent }> = {\n info: { box: \"bg-info-subtle text-info\", icon: Info },\n success: { box: \"bg-success-subtle text-success\", icon: CircleCheck },\n warning: { box: \"bg-warning-subtle text-warning\", icon: TriangleAlert },\n danger: { box: \"bg-danger-subtle text-danger\", icon: CircleAlert },\n};\n\n/** An inline sentence about a problem or a fact, in a tone with an icon, with one optional action. `announce` makes it `role=\"alert\"` for a result of the person's own action. */\nexport function Alert({ tone, title, children, action, announce = false, className }: AlertProps) {\n const { box, icon: Icon } = tones[tone];\n return (\n <div role={announce ? \"alert\" : \"region\"} aria-label={announce ? undefined : title ?? \"Notice\"} className={cn(\"flex items-start gap-3 rounded-surface px-3 py-2.5\", box, className)}>\n <Icon aria-hidden className=\"mt-0.5 size-4 shrink-0\" />\n <div className=\"grid min-w-0 flex-1 gap-0.5\">\n {title && <p className=\"type-label\">{title}</p>}\n <div className=\"type-body-sm\">{children}</div>\n </div>\n {action && <div className=\"shrink-0 self-center\">{action}</div>}\n </div>\n );\n}\n","import { UNSTABLE_Toast as AriaToast, UNSTABLE_ToastContent as ToastContent, UNSTABLE_ToastQueue as ToastQueue, UNSTABLE_ToastRegion as ToastRegion, Button as AriaButton, Text } from \"react-aria-components\";\nimport { CircleCheck, Info, TriangleAlert, X } from \"lucide-react\";\nimport { Button } from \"./button\";\nimport { cn } from \"../lib/utils\";\nimport { overlaySurface } from \"../lib/overlay\";\n\n// A toast confirms background work that finished (\"Export finished\", \"3 pieces synced\"). It is a\n// polite live region; it never carries an error a person must act on, which goes inline as an\n// `Alert` with its recovery (components.md §3.13, patterns.md §7), so there is no danger tone:\n// the type refuses it. `warning` is for a fact worth a glance (\"Kiln 2 is 40 min behind\").\n//\n// Rules the component owns so an app does not have to:\n// - One region, once, at the app root (`ToastRegion`), on the `layer-bar` layer: bottom end of the\n// window on a wide screen, the top on a phone, so it does not sit on the undo bar or cover the\n// focused control. It is a labelled landmark the keyboard reaches with F6 (React Aria).\n// - It stays long enough to read: 5 s plus 40 ms a character, up to 15 s, at least 8 s with an\n// action. The timer pauses while the pointer or focus is on it. There is always a dismiss control.\n// - At most one action, a button (\"Open file\"); content is words, not a form.\n// - Announcements are React Aria's: the toast's text is read when it appears and not again.\n// - The queue is module-level, so `toast.show()` works from a mutation's `onSuccess` outside any\n// component; `toast.clear()` empties it for a test. React Aria marks its toast API unstable; it\n// is used only here, behind this small surface, so a change upstream stays in this file.\n// Toasts are rare and brief, so they get the overlay entrance and nothing else (character.md §3).\n\n/** What a toast says. */\nexport type ToastContentProps = {\n /** What finished, past tense, in the product's words: \"Export finished\". */\n title: string;\n /** One more sentence: what and where (\"run.mp4, 2:31 at 1080p, in your Downloads folder.\"). */\n description?: string;\n /** `info` by default. There is no danger tone: an error the person must act on is an `Alert`. */\n tone?: \"info\" | \"success\" | \"warning\";\n /** One action beside the words. */\n action?: { label: string; onPress: () => void };\n /** Milliseconds before it goes. Defaults to enough to read the words. */\n timeout?: number;\n};\n\nconst queue = new ToastQueue<ToastContentProps>({ maxVisibleToasts: 3 });\n\n/** Milliseconds a toast stays: 5 s plus 40 ms a character, to at most 15 s, and at least 8 s with an action. */\nexport function toastTimeout(content: Pick<ToastContentProps, \"title\" | \"description\" | \"action\" | \"timeout\">): number {\n if (content.timeout !== undefined) return content.timeout;\n const chars = content.title.length + (content.description?.length ?? 0) + (content.action?.label.length ?? 0);\n return Math.max(content.action ? 8000 : 0, Math.min(15000, 5000 + 40 * chars));\n}\n\n/** The toast queue: `toast.show({ title })` from anywhere; `toast.close(key)`; `toast.clear()`. */\nexport const toast = {\n /** Shows a toast and returns its key. */\n show(content: ToastContentProps): string {\n return queue.add(content, { timeout: toastTimeout(content) });\n },\n close(key: string) {\n queue.close(key);\n },\n clear() {\n queue.clear();\n },\n};\n\nconst marks = { info: { icon: Info, color: \"text-info\" }, success: { icon: CircleCheck, color: \"text-success\" }, warning: { icon: TriangleAlert, color: \"text-warning\" } } as const;\n\n/** Props for `ToastRegion`. */\nexport type StrataToastRegionProps = {\n /** Names the landmark. Default \"Notifications\". */\n label?: string;\n className?: string;\n};\n\n/** The one place toasts appear. Render it once at the app root. A labelled landmark (F6), polite, above panes and the undo bar. */\nexport function StrataToastRegion({ label = \"Notifications\", className }: StrataToastRegionProps) {\n return (\n <ToastRegion\n queue={queue}\n aria-label={label}\n className={cn(\"layer-bar fixed inset-x-4 top-4 grid justify-items-end gap-2 outline-none sm:inset-x-auto sm:top-auto sm:right-4 sm:bottom-4\", className)}\n >\n {({ toast: t }) => (\n <AriaToast\n toast={t}\n className={cn(\"flex w-full max-w-sm items-start gap-3 p-3 outline-none focus-visible:outline-2 focus-visible:outline-ring\", overlaySurface)}\n >\n {(() => {\n const { icon: Icon, color } = marks[t.content.tone ?? \"info\"];\n return <Icon aria-hidden className={cn(\"mt-0.5 size-4 shrink-0\", color)} />;\n })()}\n <ToastContent className=\"grid min-w-0 flex-1 gap-0.5\">\n <Text slot=\"title\" className=\"type-label\">\n {t.content.title}\n </Text>\n {t.content.description && <Text slot=\"description\" className=\"type-body-sm text-muted-foreground\">{t.content.description}</Text>}\n </ToastContent>\n {t.content.action && (\n <Button size=\"sm\" onPress={() => { t.content.action?.onPress(); queue.close(t.key); }}>\n {t.content.action.label}\n </Button>\n )}\n <AriaButton slot=\"close\" aria-label=\"Dismiss\" className=\"grid size-6 shrink-0 cursor-pointer place-items-center rounded-control text-muted-foreground transition-state hover:bg-muted hover:text-foreground\">\n <X aria-hidden className=\"size-4\" />\n </AriaButton>\n </AriaToast>\n )}\n </ToastRegion>\n );\n}\n","import * as React from \"react\";\n\n// Work the browser does for a while (an export, an upload, a render) has the same shape as a\n// server job: it runs, reports how far it is, and ends finished, failed or cancelled (issue #72).\n// `useClientWork` holds that shape so a screen hands it straight to `JobStatus` and a toast,\n// instead of each screen keeping its own booleans. Cancelling aborts the `signal` the work was\n// given (pass it to `fetch`, or check it between steps) and ends as `cancelled`, never as a\n// failure: an abort is the person's decision, and its error is not reported. Starting again while\n// running is ignored, so a double click does not run the work twice. A stale run (cancelled, then\n// restarted) cannot write over the newer one.\n\n/** What the work is given: a signal that aborts on cancel, and a way to report progress. */\nexport type WorkContext = {\n signal: AbortSignal;\n /** Report items done, and the total when it is known. */\n progress: (current: number, total?: number) => void;\n};\n\n/** Where client work is. */\nexport type WorkPhase = \"idle\" | \"running\" | \"finished\" | \"failed\" | \"cancelled\";\n\n/** The state `useClientWork` returns. */\nexport type ClientWork<T> = {\n phase: WorkPhase;\n current?: number;\n total?: number;\n result?: T;\n error?: unknown;\n /** Runs the work. Ignored while it is already running. */\n start: () => Promise<void>;\n /** Aborts the work's signal; the phase becomes `cancelled`. */\n cancel: () => void;\n /** Back to `idle`, forgetting the result. */\n dismiss: () => void;\n};\n\ntype State<T> = { phase: WorkPhase; current?: number; total?: number; result?: T; error?: unknown };\n\n/** Runs browser-side work with progress, cancel and a clear end state, ready for `JobStatus`. */\nexport function useClientWork<T>(run: (ctx: WorkContext) => Promise<T>): ClientWork<T> {\n const [state, setState] = React.useState<State<T>>({ phase: \"idle\" });\n const controller = React.useRef<AbortController | null>(null);\n const runRef = React.useRef(run);\n runRef.current = run;\n\n const start = React.useCallback(async () => {\n if (controller.current) return;\n const mine = new AbortController();\n controller.current = mine;\n const live = () => controller.current === mine;\n setState({ phase: \"running\" });\n try {\n const result = await runRef.current({\n signal: mine.signal,\n progress: (current, total) => live() && setState((s) => ({ ...s, current, total: total ?? s.total })),\n });\n if (!live()) return;\n setState(mine.signal.aborted ? { phase: \"cancelled\" } : { phase: \"finished\", result });\n } catch (error) {\n if (!live()) return;\n setState(mine.signal.aborted ? { phase: \"cancelled\" } : { phase: \"failed\", error });\n } finally {\n if (live()) controller.current = null;\n }\n }, []);\n\n const cancel = React.useCallback(() => {\n const c = controller.current;\n if (!c) return;\n c.abort();\n controller.current = null;\n setState({ phase: \"cancelled\" });\n }, []);\n\n const dismiss = React.useCallback(() => {\n if (!controller.current) setState({ phase: \"idle\" });\n }, []);\n\n // Unmounting aborts the run and forgets it, so a remount (Strict Mode's setup, cleanup, setup) can\n // start again and the aborted run can no longer write state.\n React.useEffect(\n () => () => {\n controller.current?.abort();\n controller.current = null;\n },\n [],\n );\n\n return { ...state, start, cancel, dismiss };\n}\n","import * as React from \"react\";\nimport { Check, CircleAlert, LoaderCircle, TriangleAlert, Ban } from \"lucide-react\";\nimport { format } from \"../lib/format\";\nimport type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\nimport { Button } from \"./button\";\nimport { Status, type Tone } from \"./status\";\n\n// A job the server runs for a while (syncing sources one after another, an import, a re-index),\n// as the screen that started it shows it (strata-react issue #45, from the Tubes Library screen,\n// which built each part by hand). Three things are true of every such job, and the props make\n// each one impossible to leave out:\n//\n// - Its state is a word, as `Status` is: `words` names running, finished and failed in the\n// product's terms (\"Syncing\", \"Finished\", \"Finished with failures\"), all three required, so a\n// screen cannot forget the end it did not test. Beside the word, `summary` is the app's own\n// sentence (\"Syncing 2 of 3: Night Sky. 42 new videos so far.\").\n// - How far it has got is a bar only when the total is known (`current` of `total`), a\n// `progressbar`, not a `meter`: this is a task moving to done. Without a total there is no bar,\n// because a bar that guesses is worse than the sentence.\n// - When it ends, each item that failed is named with its reason (`failures`), because \"3\n// failed\" alone sends the person hunting. A job that failed as a whole (`failed`, the summary\n// saying why) names no item.\n//\n// It is announced, politely, only when something a person waits for happens: the item changes\n// (`current`) or the job ends. A poll every two seconds that rewrites \"42 new videos so far\" in\n// a live region would talk over everything else, so the visible sentence is not the live region;\n// a separate one carries the word and the sentence at those moments.\n//\n// Work the browser does (an export, an upload, a render; issue #72) uses the same component, so one\n// idea of \"a job\" covers both: `onCancel` shows a Cancel button while it runs (work the person can\n// stop is stoppable), `cancelled` is a fourth ending in neutral (\"Cancelled\": not a failure, nothing\n// to retry), and `onDismiss` shows Dismiss once it has ended so the result does not linger. With no\n// `total` there is no bar, only the turning mark and the sentence, which is the indeterminate case. The spinner turns only\n// while running, the one case where a status mark's data is live. Polling and re-reading what\n// the job changed is `useJob`'s.\n\n/** An item a job could not do, and why, in the product's words. */\nexport type JobFailure = { key: string; label: string; reason: string };\n\n/** A job's three states as words, all required: \"Syncing\", \"Finished\", \"Finished with failures\". */\nexport type JobWords = { running: string; finished: string; failed: string; /** Shown when `cancelled`. Default \"Cancelled\". */ cancelled?: string };\n\n/** The job status's props. */\nexport type JobStatusProps = {\n /** What the job is (\"Library sync\"): names the section and the progress bar. */\n label: string;\n /** The job is still going. */\n running: boolean;\n words: JobWords;\n /** The app's sentence for where the job is or how it went: \"Syncing 2 of 3: Night Sky.\" */\n summary: string;\n /** Items done or being done, with `total`, for the bar. */\n current?: number;\n /** Items in all, when known. No bar without it. */\n total?: number;\n /** Each item that failed, with its reason. Any failure makes a finished job `failed`'s word. */\n failures?: JobFailure[];\n /** The job failed as a whole, for a reason that names no item (the summary says it). */\n failed?: boolean;\n /** Names the list of failures for screen readers. Default \"Failures\". */\n failuresLabel?: string;\n /** The person stopped it. A neutral ending, not a failure. */\n cancelled?: boolean;\n /** Stops the job. Shows a Cancel button while it runs. */\n onCancel?: () => void;\n /** Label of the cancel button. Default \"Cancel\". */\n cancelLabel?: string;\n /** Clears the result. Shows a Dismiss button once the job has ended. */\n onDismiss?: () => void;\n className?: string;\n};\n\nconst Spinner: IconComponent = ({ className, ...props }) => (\n <LoaderCircle {...props} className={cn(className, \"motion-safe:animate-spin\")} />\n);\n\n/** A long-running server job: its state as a required word beside the app's sentence, a progress bar when the total is known, each failure named with its reason, and a polite announcement only when the item changes or the job ends. */\nexport function JobStatus({\n label,\n running,\n words,\n summary,\n current,\n total,\n failures = [],\n failed = false,\n failuresLabel = \"Failures\",\n cancelled = false,\n onCancel,\n cancelLabel = \"Cancel\",\n onDismiss,\n className,\n}: JobStatusProps) {\n const ended: { tone: Tone; icon: IconComponent; word: string } = cancelled\n ? { tone: \"neutral\", icon: Ban, word: words.cancelled ?? \"Cancelled\" }\n : failed\n ? { tone: \"danger\", icon: CircleAlert, word: words.failed }\n : failures.length\n ? { tone: \"warning\", icon: TriangleAlert, word: words.failed }\n : { tone: \"success\", icon: Check, word: words.finished };\n const { tone, icon, word } = running ? { tone: \"info\" as const, icon: Spinner, word: words.running } : ended;\n\n // What is announced changes only with the item or the end, not with every poll's sentence.\n const moment = running ? `running:${current ?? \"\"}` : `ended:${word}`;\n const [said, setSaid] = React.useState({ moment, text: \"\" });\n if (said.moment !== moment) setSaid({ moment, text: `${word}. ${summary}` });\n\n const bar = running && total !== undefined && total > 0 && current !== undefined;\n const done = Math.min(total ?? 0, Math.max(0, current ?? 0));\n\n return (\n <section aria-label={label} className={cn(\"grid min-w-0 gap-3\", className)}>\n <div className=\"flex flex-wrap items-center gap-x-3 gap-y-1\">\n <Status tone={tone} icon={icon}>\n {word}\n </Status>\n <p className=\"min-w-0 flex-1 type-body-sm text-foreground\">{summary}</p>\n {running && onCancel && (\n <Button size=\"sm\" onPress={onCancel}>\n {cancelLabel}\n </Button>\n )}\n {!running && onDismiss && (\n <Button size=\"sm\" variant=\"ghost\" onPress={onDismiss}>\n Dismiss\n </Button>\n )}\n </div>\n {bar && (\n <div\n role=\"progressbar\"\n aria-label={label}\n aria-valuemin={0}\n aria-valuemax={total}\n aria-valuenow={done}\n aria-valuetext={`${format.integer(done)} of ${format.integer(total)}`}\n className=\"relative h-2 overflow-hidden rounded-pill bg-muted\"\n >\n <div className=\"absolute inset-y-0 left-0\" style={{ width: `${(done / total) * 100}%`, background: \"var(--chart-1)\" }} />\n </div>\n )}\n {!running && failures.length > 0 && (\n <ul aria-label={failuresLabel} className=\"grid gap-1 border-l-2 border-warning pl-3 type-body-sm\">\n {failures.map((f) => (\n <li key={f.key}>\n <span className=\"type-label\">{f.label}</span>\n <span className=\"text-muted-foreground\">: {f.reason}</span>\n </li>\n ))}\n </ul>\n )}\n <p role=\"status\" className=\"sr-only\">\n {said.text}\n </p>\n </section>\n );\n}\n","import * as React from \"react\";\nimport { ImageOff } from \"lucide-react\";\nimport { Skeleton } from \"./data-view\";\nimport { useInView } from \"../lib/in-view\";\nimport { cn } from \"../lib/utils\";\n\n// A photo or crop from an API, in a list, a table cell or a grid (strata-react issue #33, from\n// the Bright Horizons review app, where some crops 404 because the file is missing on disk). A\n// plain <img> gets three things wrong there, and each is a state generated UI leaves out:\n//\n// - it has no size until it loads, so the rows below jump as each one arrives. The box here has\n// its aspect ratio before anything is fetched, and the image is cropped (`cover`) or fitted\n// (`contain`) into it, so nothing moves.\n// - while it loads it is a blank, and on a slow connection a blank reads as \"no photo\". Here it\n// is a `Skeleton`, the same placeholder DataView's loading layouts are made of.\n// - when it fails it is the browser's broken-image icon and the alt text crammed into the box.\n// Here it says what happened in the product's words: `missing` is required (\"Photo not\n// found\"), for the same reason DataView requires `empty`. A record with no photo at all\n// (`src={null}`) shows the same words without a request.\n//\n// `alt` is required too; pass \"\" only when the name beside the thumbnail already says everything\n// it shows. The missing state is an `img` named \"<alt>: <missing>\", so a screen reader hears\n// which photo is gone. Thumbnails come in dozens, so the request waits until the box is near the\n// screen (`useInView`, the hook InfiniteList's sentinel uses, with the same scroll region and a\n// root margin), and once asked for it is not unloaded. `eager` is for the first few on screen.\n// There is no fade-in: a list of thumbnails is seen many times a day (ux-character.md, character\n// by frequency), so the photo simply replaces its skeleton.\n//\n// Two more uses from the Tubes viewer (strata-react issue #51), which drew plain <img>s and lost\n// all of the above:\n//\n// - `children` are drawn above the image in the same positioned box: a video's running time in\n// one corner, \"Saved\" in another. They keep their place while the image loads, fails or is\n// missing, because the box, not the image, holds them. Position them yourself (`absolute\n// bottom-1 right-1`); they are not part of the image's name.\n// - `fallback` replaces the icon and words with the product's own drawing, such as a channel's\n// first letter on a disc for an avatar with no picture. The missing state is still one `img`,\n// named `alt` (with `missing` after it, when given, as \"Night Sky: No picture\"), so a person\n// using a screen reader hears whose picture it is either way. A round avatar is `aspect={1}`\n// with `className=\"rounded-pill\"`.\n\n/** A width-over-height ratio: a number (`1.5`) or a fraction (`\"4/3\"`). */\nexport type AspectRatio = number | `${number}/${number}`;\n\n/** The thumbnail's props. Either `missing` (the words shown when there is no image) or a `fallback` drawing is required. */\nexport type ThumbnailProps = {\n /** The image URL. `null` when the record has no photo: the `missing` words show without a request. */\n src: string | null;\n /** What the photo shows (\"Celadon bowl, front\"). `\"\"` only when the text beside it already says it. */\n alt: string;\n /** Width over height. The box has this shape before the image loads. Default `1`. */\n aspect?: AspectRatio;\n /** `cover` crops to fill the box (default); `contain` fits the whole image in it. */\n fit?: \"cover\" | \"contain\";\n srcSet?: string;\n sizes?: string;\n /** Load at once rather than when near the screen: for the first few above the fold. */\n eager?: boolean;\n /** How far outside the scroll region the request starts (IntersectionObserver `rootMargin`). */\n rootMargin?: string;\n /** Layout at the call site: a width (`w-24`, `w-full`), or `rounded-pill` for an avatar. The height follows from `aspect`. */\n className?: string;\n /** Overlays drawn above the image in the same box (a running time, a \"Saved\" badge), in place whether the image has loaded, failed or is missing. */\n children?: React.ReactNode;\n} & (\n | {\n /** What to show when there is no photo or it cannot be loaded, in the product's words: \"Photo not found\". */\n missing: string;\n /** Drawn instead of the icon and `missing` words when there is no image: a letter on a disc for an avatar. */\n fallback?: React.ReactNode;\n }\n | {\n /** Added to the missing state's name after `alt` (\"Night Sky: No picture\"), when given. */\n missing?: string;\n /** Drawn when there is no image or it cannot be loaded: a letter on a disc for an avatar. */\n fallback: React.ReactNode;\n }\n);\n\ntype Phase = \"loading\" | \"loaded\" | \"missing\";\n\nconst ratio = (aspect: AspectRatio) => (typeof aspect === \"number\" ? String(aspect) : aspect.replace(\"/\", \" / \"));\n\n/** A box of fixed aspect ratio for a remote image: a skeleton until it loads, the `missing` words (or a `fallback`) if it cannot, a request only when it nears the screen, and `children` overlaid in its corners. `alt` and `missing` or `fallback` are required. */\nexport function Thumbnail({\n src,\n alt,\n missing,\n aspect = 1,\n fit = \"cover\",\n srcSet,\n sizes,\n eager = false,\n rootMargin = \"200px\",\n className,\n fallback,\n children,\n}: ThumbnailProps) {\n // The outcome is kept with the request it belongs to (`src` and `srcSet`, since the browser may\n // have loaded a candidate from either), so a new request starts loading again without an effect\n // to reset it, and a late event from the old image cannot mark the new one.\n const request = src ? `${src} ${srcSet ?? \"\"}` : null;\n const [result, setResult] = React.useState<{ request: string; ok: boolean } | null>(null);\n const phase: Phase = !request ? \"missing\" : result?.request === request ? (result.ok ? \"loaded\" : \"missing\") : \"loading\";\n const near = useInView({ active: !eager && !!src, rootMargin, once: true, unsupported: true });\n const requested = eager || near.inView;\n\n return (\n <div\n ref={near.ref}\n className={cn(\"relative overflow-hidden rounded-control bg-muted\", className)}\n style={{ aspectRatio: ratio(aspect) }}\n aria-busy={phase === \"loading\" || undefined}\n >\n {phase === \"loading\" && <Skeleton className=\"absolute inset-0\" />}\n {src && request && phase !== \"missing\" && requested && (\n <img\n key={request}\n src={src}\n srcSet={srcSet}\n sizes={sizes}\n alt={alt}\n decoding=\"async\"\n onLoad={() => setResult({ request, ok: true })}\n onError={() => setResult({ request, ok: false })}\n className={cn(\"absolute inset-0 size-full\", fit === \"cover\" ? \"object-cover\" : \"object-contain\", phase === \"loading\" && \"opacity-0\")}\n />\n )}\n {phase === \"missing\" && (\n <div\n role=\"img\"\n aria-label={[alt, missing].filter(Boolean).join(\": \")}\n className={cn(\n \"absolute inset-0 grid\",\n fallback === undefined && \"content-center justify-items-center gap-0.5 p-1 text-center text-muted-foreground\",\n )}\n >\n {fallback === undefined ? (\n <>\n <ImageOff aria-hidden className=\"size-4 shrink-0\" />\n <span className=\"type-caption text-balance\">{missing}</span>\n </>\n ) : (\n <div aria-hidden className=\"grid size-full min-h-0 min-w-0\">\n {fallback}\n </div>\n )}\n </div>\n )}\n {children}\n </div>\n );\n}\n\n/** The loading shape of a `Thumbnail`, for a `DataView` skeleton: the same box and aspect ratio, so nothing moves when the list arrives. */\nexport function ThumbnailSkeleton({ aspect = 1, className }: { aspect?: AspectRatio; className?: string }) {\n return (\n <div aria-hidden className={cn(\"relative overflow-hidden rounded-control bg-muted\", className)} style={{ aspectRatio: ratio(aspect) }}>\n <Skeleton className=\"absolute inset-0\" />\n </div>\n );\n}\n","import * as React from \"react\";\nimport { ChevronRight } from \"lucide-react\";\nimport { useSearchParams } from \"react-router\";\nimport { cn } from \"../lib/utils\";\n\n// Show more of one thing in place: a batch's faces under its row in a history list, a firing's\n// pieces under its line in the log. Strata issue #34, from an app that wrote its own <details>.\n//\n// Not <details>. A closed <details> still mounts its content, so every row's detail component\n// runs, and a list of forty batches makes forty requests on load for bodies nobody opened. Here\n// the body is mounted only while it is open: a `useLoad` inside it runs on the first open, and on\n// a later open the query cache answers at once. Closed, nothing of the body is in the DOM.\n//\n// The trigger is a native button (Enter and Space, focus outline from the base layer) with\n// `aria-expanded`, and `aria-controls` naming the body while it exists (the WAI-ARIA disclosure\n// pattern). Focus stays on the button through open and close, so a keyboard user walks a list of\n// rows with Tab and opens each in place. The summary is the button's name, so it holds text and\n// marks (a Status, a count), never controls; actions for the row go in `actions`, beside it.\n//\n// No height animation: people open rows in a list many times a session, and character by\n// frequency (ux-research ux-character.md) gives frequent actions no motion. The chevron turns\n// with the state, which is the only signal besides the body itself.\n//\n// Many disclosures over one list share their state through `useExpanded`, which can keep it in\n// the URL (`?open=f-0412`), so an opened row survives a reload and can be linked. `DataTable`'s\n// `expansion` prop draws the same thing as a detail row under a table row.\n\n/** Open and closed disclosure state: controlled with `open` and `onOpenChange`, or uncontrolled from `defaultOpen`. */\nexport type DisclosureOpenProps =\n | { open: boolean; onOpenChange: (open: boolean) => void; defaultOpen?: never }\n | { open?: never; onOpenChange?: (open: boolean) => void; defaultOpen?: boolean };\n\nexport type DisclosureProps = DisclosureOpenProps & {\n /** The always-visible line, and the button's accessible name: text and marks, no controls. */\n summary: React.ReactNode;\n /** Mounted only while open, so a request inside runs when the person opens it. */\n children: React.ReactNode;\n /** Controls for the row (a `RowAction`), beside the summary and outside its button. */\n actions?: React.ReactNode;\n className?: string;\n};\n\n/** Shows more of one thing in place: a button with `aria-expanded` around `summary`, and a body mounted only while open (so a request inside it runs on first open). Controlled with `open`/`onOpenChange` or `useExpanded`, or uncontrolled with `defaultOpen`. */\nexport function Disclosure({ summary, children, actions, open, defaultOpen = false, onOpenChange, className }: DisclosureProps) {\n const [own, setOwn] = React.useState(defaultOpen);\n const isOpen = open ?? own;\n const bodyId = React.useId();\n const toggle = () => {\n if (open === undefined) setOwn(!isOpen);\n onOpenChange?.(!isOpen);\n };\n return (\n <div className={cn(\"min-w-0\", className)}>\n <div className=\"flex items-center gap-3\">\n <button\n type=\"button\"\n aria-expanded={isOpen}\n aria-controls={isOpen ? bodyId : undefined}\n onClick={toggle}\n className=\"-mx-1 flex min-h-(--control-h-sm) min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-control px-1 text-left hover:bg-muted\"\n >\n <Chevron open={isOpen} />\n <span className=\"min-w-0 flex-1\">{summary}</span>\n </button>\n {actions && <div className=\"flex shrink-0 items-center gap-2\">{actions}</div>}\n </div>\n {isOpen && (\n <div id={bodyId} className=\"pt-2 pb-3 pl-6\">\n {children}\n </div>\n )}\n </div>\n );\n}\n\n/** The disclosure chevron: points right when closed, down when open. Shared with `DataTable`'s row toggle. */\nexport function Chevron({ open, className }: { open: boolean; className?: string }) {\n return <ChevronRight aria-hidden className={cn(\"size-4 shrink-0 text-muted-foreground\", open && \"rotate-90\", className)} />;\n}\n\n/** Which of many disclosures are open, by key: spread into `DataTable`'s `expansion`, or read with `isOpen`/`setOpen` for a list of `Disclosure`s. */\nexport type Expanded = {\n /** Keys of the open items. */\n expanded: ReadonlySet<string>;\n /** Replaces the open set. `DataTable` calls this. */\n onChange: (next: Set<string>) => void;\n isOpen: (key: string) => boolean;\n setOpen: (key: string, open: boolean) => void;\n collapseAll: () => void;\n};\n\nexport type ExpandedOptions = {\n /** Keep the open keys in this URL search parameter (`?open=a&open=b`), so an opened row can be linked and survives a reload. Needs a React Router context. */\n param?: string;\n /** Keys open at first. Ignored with `param`: there the URL says what is open, so a link that opens a row carries it. */\n initial?: Iterable<string>;\n /** Opening one closes the others (an accordion). Default false: people compare two rows. */\n single?: boolean;\n};\n\n/** Shared open state for the disclosures of one list or table, optionally kept in the URL (`param`). */\nexport function useExpanded(options: ExpandedOptions = {}): Expanded {\n // One of two hooks, chosen by whether `param` is given; a screen does not switch between the two\n // while mounted (as with DataTable's `sortParam`), so the hook order is stable.\n return options.param ? useUrlExpanded(options.param, options) : useLocalExpanded(options);\n}\n\nfunction api(expanded: ReadonlySet<string>, set: (next: Set<string>) => void, single?: boolean): Expanded {\n return {\n expanded,\n // With `single`, a change that opens a key keeps only that key, so `DataTable` (which calls\n // onChange with the whole set) gets the accordion too, not only `setOpen`.\n onChange: (next) => {\n const opened = single ? [...next].filter((k) => !expanded.has(k)) : [];\n set(opened.length ? new Set([opened[opened.length - 1]]) : next);\n },\n isOpen: (key) => expanded.has(key),\n setOpen: (key, open) => {\n const next = single ? new Set<string>() : new Set(expanded);\n if (open) next.add(key);\n else next.delete(key);\n set(next);\n },\n collapseAll: () => set(new Set()),\n };\n}\n\nfunction useLocalExpanded({ initial = [], single }: ExpandedOptions): Expanded {\n const [expanded, setExpanded] = React.useState<ReadonlySet<string>>(() => new Set(initial));\n return React.useMemo(() => api(expanded, setExpanded, single), [expanded, single]);\n}\n\nfunction useUrlExpanded(param: string, { single }: ExpandedOptions): Expanded {\n const [params, setParams] = useSearchParams();\n const fromUrl = params.getAll(param);\n const joined = fromUrl.join(\"\\u0000\");\n // `fromUrl` is a new array each render; its joined form is the dependency.\n const expanded = React.useMemo<ReadonlySet<string>>(() => new Set(fromUrl), [joined]);\n const set = React.useCallback(\n (next: Set<string>) =>\n setParams(\n (p) => {\n const out = new URLSearchParams(p);\n out.delete(param);\n for (const k of next) out.append(param, k);\n return out;\n },\n { replace: true },\n ),\n [param, setParams],\n );\n return React.useMemo(() => api(expanded, set, single), [expanded, set, single]);\n}\n","import * as React from \"react\";\nimport { X } from \"lucide-react\";\nimport { format as defaultFormat, type Format } from \"../lib/format\";\nimport { cn } from \"../lib/utils\";\nimport { Button } from \"./button\";\n\n// Select many, then act: the state (`useSelection`), and the bar that says how many are chosen and\n// holds what can be done to them (`BulkBar`). `DataTable`'s `selection` prop draws the checkboxes.\n//\n// The selection is pruned to the rows that exist. After a bulk removal, a refetch or a new filter,\n// a key whose row is gone is not counted and not acted on: the bar never says \"3 selected\" over\n// two visible rows, and an action never reaches a row the person cannot see. (Gmail and Linear\n// both drop a selection a filter hides; acting on hidden rows is how a bulk delete surprises.)\n//\n// Shift extends a range from the last row clicked, on every surface (`useSelectRows`), and\n// `initial` chooses a row when it first appears rather than only on mount, so a selection seeded\n// from data still applies once the data arrives (both from strata-react issue #32, a review screen\n// of face crops with the likely matches pre-chosen).\n//\n// The count is the bar's live region, and only the count: it is always mounted, so a screen reader\n// hears \"2 bookings selected\" on each change, and the buttons are outside it, so their names are\n// not read again with every tick. The actions are a labelled group. Per the research, at most one\n// of them is filled (`variant=\"default\"`), named with its verb and count (\"Withdraw 3\"), and a\n// reversible bulk removal goes through `useUndoable` like a single one, not through a confirm.\n\n/** Which rows start chosen: their keys, or a test on each row. Either applies to a row the first time it appears. */\nexport type InitialSelection<T> = Iterable<string> | ((row: T) => boolean);\n\ntype SelectionState = { keys: readonly string[]; seen: ReadonlySet<string>; raw: ReadonlySet<string> };\n\n// Bring the state up to the rows now shown: drop keys whose row has gone, and choose the rows seen\n// for the first time that `initial` names. A row seen before keeps the person's choice, even if it\n// left and came back (it returns unchosen, as it was forgotten when it left).\nfunction reconcile<T>(prev: SelectionState, rows: readonly T[], keys: readonly string[], initial: (row: T, key: string) => boolean): SelectionState {\n const present = new Set(keys);\n const raw = new Set([...prev.raw].filter((k) => present.has(k)));\n const seen = new Set(prev.seen);\n rows.forEach((row, i) => {\n const key = keys[i];\n if (seen.has(key)) return;\n seen.add(key);\n if (initial(row, key)) raw.add(key);\n });\n return { keys, seen, raw };\n}\n\nconst sameKeys = (a: readonly string[], b: readonly string[]) => a.length === b.length && a.every((k, i) => k === b[i]);\n\n/**\n * Chosen row keys, pruned to the rows that exist, and the calls that change them. Spread into\n * `DataTable`'s or `SelectableGrid`'s `selection` with a `rowLabel`. `initial` (keys, or a test on\n * the row) chooses each row the first time it appears, so a selection seeded from data that loads\n * later, or a next page, still starts right.\n */\nexport function useSelection<T>(rows: readonly T[], rowKey: (row: T) => string, initial: InitialSelection<T> = []) {\n // `initial` is read when a row first appears, so a new function each render is fine.\n const initialRef = React.useRef(initial);\n initialRef.current = initial;\n // Keys are read into a set once per `initial` value, not once per row: a single-use iterable (a\n // generator, `set.values()`) would otherwise be used up by the first row, and an array rebuilt\n // for every row. The set is kept for rows that arrive later.\n const initialKeys = React.useRef<{ source: InitialSelection<T>; keys: ReadonlySet<string> } | undefined>(undefined);\n const test = (row: T, key: string) => {\n const init = initialRef.current;\n if (typeof init === \"function\") return init(row);\n if (initialKeys.current?.source !== init) initialKeys.current = { source: init, keys: new Set(init) };\n return initialKeys.current.keys.has(key);\n };\n const keys = rows.map(rowKey);\n const [state, setState] = React.useState<SelectionState>(() =>\n reconcile({ keys: [], seen: new Set(), raw: new Set() }, rows, keys, test),\n );\n // Adjusted while rendering (React's pattern for state derived from props), not in an effect, so\n // the first paint of new rows already shows them chosen. Compared by key, not by array identity,\n // so `rows={data ?? []}` does not loop.\n let current = state;\n if (!sameKeys(state.keys, keys)) {\n current = reconcile(state, rows, keys, test);\n setState(current);\n }\n const selected = current.raw;\n // rowKey is usually an inline arrow, so it is left out of the dependencies: the rows change.\n const selectedRows = React.useMemo(() => rows.filter((r) => selected.has(rowKey(r))), [rows, selected]);\n // A key with no row is never kept, so an action never reaches a row the person cannot see.\n const onChange = React.useCallback(\n (next: Set<string>) =>\n setState((s) => {\n const present = new Set(s.keys);\n return { ...s, raw: new Set([...next].filter((k) => present.has(k))) };\n }),\n [],\n );\n const clear = React.useCallback(() => setState((s) => ({ ...s, raw: new Set() })), []);\n return { selected, selectedRows, count: selected.size, onChange, clear };\n}\n\n/** The part of a selection the surfaces drawing it (`DataTable`, `SelectableGrid`) need. */\ntype SelectionLike<T> = {\n selected: ReadonlySet<string>;\n onChange: (next: Set<string>) => void;\n isSelectable?: (row: T) => boolean;\n};\n\n/**\n * Selecting rows of a surface in the order it shows them: one row, a range with Shift, and all\n * shown. Shared by `DataTable` and `SelectableGrid`, so a range and select-all behave the same on\n * both. `rows` are in display order (after sorting) and include rows a virtualised surface has not\n * rendered.\n *\n * A range runs from the last row clicked (the anchor) to this one, over the selectable rows\n * between, and sets them all to this row's new state, as Gmail and Finder do: Shift-clicking an\n * unchosen row chooses the run, Shift-clicking a chosen one clears it. Every click moves the\n * anchor. An anchor that has left the rows (filtered, removed) makes the next Shift-click a plain\n * one.\n * @internal\n */\nexport function useSelectRows<T>(rows: readonly T[], rowKey: (row: T) => string, selection?: SelectionLike<T>) {\n const anchor = React.useRef<string | undefined>(undefined);\n const keys = selection ? rows.filter((r) => selection.isSelectable?.(r) ?? true).map(rowKey) : [];\n const chosen = selection ? keys.filter((k) => selection.selected.has(k)).length : 0;\n const allChecked: boolean | \"mixed\" = chosen === 0 ? false : chosen === keys.length ? true : \"mixed\";\n\n const toggle = (key: string, on: boolean, { shiftKey }: { shiftKey: boolean }) => {\n if (!selection) return;\n const next = new Set(selection.selected);\n const from = shiftKey && anchor.current !== undefined ? keys.indexOf(anchor.current) : -1;\n const to = keys.indexOf(key);\n if (from >= 0 && to >= 0) {\n const [a, b] = from < to ? [from, to] : [to, from];\n for (const k of keys.slice(a, b + 1)) {\n if (on) next.add(k);\n else next.delete(k);\n }\n } else if (on) next.add(key);\n else next.delete(key);\n anchor.current = key;\n selection.onChange(next);\n };\n\n // A full or mixed box clears what is shown; an empty one selects every selectable row shown.\n // Keys outside `rows` (filtered away) are left as they are.\n const toggleAll = () => {\n if (!selection) return;\n const next = new Set(selection.selected);\n if (allChecked === false) keys.forEach((k) => next.add(k));\n else keys.forEach((k) => next.delete(k));\n selection.onChange(next);\n };\n\n return { toggle, all: { checked: allChecked, toggle: toggleAll, disabled: keys.length === 0 } };\n}\n\n/** The bar for a selection: a polite live count (\"2 bookings selected\"), the bulk actions, and Clear selection. Renders only the live region while nothing is chosen. */\nexport function BulkBar({\n count,\n noun,\n onClear,\n children,\n format = defaultFormat,\n className,\n}: {\n count: number;\n /** What is chosen, singular, or singular and plural: `\"booking\"`, `[\"person\", \"people\"]`. */\n noun: string | [one: string, many: string];\n onClear: () => void;\n /** The actions. At most one filled button, named with its verb and count; while the bar is up it is the view's only filled button, so the screen's own primary goes to `outline`. */\n children: React.ReactNode;\n /** The product's formatters, for the count's figures and plural. Default en-GB. */\n format?: Format;\n className?: string;\n}) {\n const [one, many] = typeof noun === \"string\" ? [noun, `${noun}s`] : noun;\n const label = `${format.count(count, one, many)} selected`;\n return (\n <div\n className={cn(\n count > 0 && \"flex flex-wrap items-center gap-x-4 gap-y-2 rounded-surface bg-surface-sunken py-1.5 pr-1.5 pl-3\",\n className,\n )}\n >\n <p aria-live=\"polite\" className={count > 0 ? \"type-label tabular-nums\" : \"sr-only\"}>\n {count > 0 ? label : `No ${many} selected`}\n </p>\n {count > 0 && (\n <div role=\"group\" aria-label={`Actions for the selected ${many}`} className=\"flex flex-1 flex-wrap items-center gap-2\">\n {children}\n <Button size=\"sm\" variant=\"ghost\" className=\"ml-auto\" onClick={onClear}>\n <X aria-hidden />\n Clear selection\n </Button>\n </div>\n )}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { ArrowDown, ArrowUp, ArrowUpDown } from \"lucide-react\";\nimport {\n createSortedRowModel,\n flexRender,\n rowSortingFeature,\n tableFeatures,\n useTable,\n type ColumnDef,\n type SortingState,\n} from \"@tanstack/react-table\";\nimport { useVirtualizer } from \"@tanstack/react-virtual\";\nimport { useSearchParams } from \"react-router\";\nimport { format } from \"../lib/format\";\nimport { cn } from \"../lib/utils\";\nimport { Checkbox } from \"./checkbox\";\nimport { Chevron } from \"./disclosure\";\nimport { useSelectRows } from \"./selection\";\n\n// The table real product screens use: 12px muted sentence-case headers, row rules (no zebra),\n// numbers right-aligned in tabular figures, one status mark and at most one action per row.\n// Sortable headers are buttons and look sortable; aria-sort says which way. The scroll container is\n// a labelled, focusable region so keyboard users can scroll a wide table.\n//\n// Underneath: TanStack Table for the row model and sorting, TanStack Virtual once a table passes\n// `virtualizeFrom` rows (only the visible rows are in the DOM; the header sticks). The column API\n// stays small on purpose (key, header, cell, numeric, sort), so a screen reads as a list of\n// decisions about columns, not as table plumbing. `sortParam` keeps the sort in the URL\n// (?sort=when.desc) so a sorted view can be linked and survives a reload.\n//\n// Selection is opt-in (`selection`), because checkboxes belong only where a bulk action exists\n// (one of 23 real product screens had them; a checkbox on every row is a generated-UI tell). When\n// it is on, the first column is a checkbox per row, named from the row (`rowLabel` is required),\n// disabled where `isSelectable` says no; the header's \"Select all shown\" covers the selectable rows\n// in `rows` (all of them, not only the rendered ones of a virtualised table) and is mixed when some\n// are chosen. Shift-click (or Shift+Space) chooses or clears the run from the last row clicked, in\n// the sorted order shown (`useSelectRows`, shared with `SelectableGrid`). Selected rows take the sunken fill, not a ring, so a selection never reads as focus.\n// The table only draws the selection; the state is the caller's, usually `useSelection`, and the\n// actions live in a `BulkBar`.\n//\n// Expansion is opt-in too (`expansion`): a row opens a detail row under it, for what belongs to\n// the row but would crowd the table (a firing's pieces, a batch's faces). It follows `Disclosure`:\n// the toggle is a button with `aria-expanded`, named for what it shows (`rowLabel`, \"Pieces in\n// firing 412\"), and the detail is mounted only while open, so a `useLoad` inside it runs on the\n// first open and not for every row on load. The detail row spans the data columns, starts under\n// the first of them, and has no rule between it and its row, so the two read as one. State is the\n// caller's, usually `useExpanded` (which can keep it in the URL). A virtualised table measures\n// each detail row, so details of any height scroll correctly.\n//\n// Missing values (strata-react issue #47, from the Tubes Library table): a column that gives\n// `value` gets a typed sort (numbers, then text in the locale's order with numbers in it read as\n// numbers, then dates) and a placeholder for a row whose value is `null` or `undefined`: an en\n// dash in the muted ink, named \"No value\" for a screen reader, or the column's `missing` word\n// where the word carries meaning (\"Never\"). Missing rows sort after every real value in both\n// directions, because \"not known\" is not \"smallest\"; a column's own `sort` still decides the\n// order among the rows that have a value. Without `value` a column works as before.\n\n/** What a column's `value` may be: a number, text or a date, or `null`/`undefined` when the row has none. */\nexport type CellValue = number | string | Date | null | undefined;\n\nexport type Column<T> = {\n key: string;\n header: string;\n /** Right-aligns and sets tabular figures. Use for every quantity. */\n numeric?: boolean;\n /** Orders two rows. With `value`, it orders only rows that have one (missing ones go last); `false` turns off `value`'s default sort. */\n sort?: ((a: T, b: T) => number) | false;\n /** What the cell shows when the row's `value` is missing, where the word carries meaning (\"Never\"). Default an en dash. */\n missing?: string;\n /** Cells that may hold long text get truncated rather than stretching the table. */\n truncate?: boolean;\n /** Keep the header for screen readers only, as for a column of row actions. `header` still names it. */\n hideHeader?: boolean;\n className?: string;\n} & (\n | {\n cell: (row: T) => React.ReactNode;\n /** The row's value for this column: gives a typed default sort with missing values last, and the missing placeholder. */\n value?: (row: T) => CellValue;\n }\n | {\n /** How a row with a value is drawn. Default: numbers through `format.decimal`, dates through `format.date`, text as it is. */\n cell?: (row: T) => React.ReactNode;\n /** The row's value for this column: gives a typed default sort with missing values last, and the missing placeholder. */\n value: (row: T) => CellValue;\n }\n);\n\nconst collator = new Intl.Collator(undefined, { numeric: true, sensitivity: \"base\" });\nconst kind = (v: number | string | Date) => (typeof v === \"number\" ? 0 : typeof v === \"string\" ? 1 : 2);\n\n/** Orders two present values: numbers, then text (locale order, numbers in text read as numbers), then dates. */\nfunction compareValues(a: number | string | Date, b: number | string | Date) {\n if (kind(a) !== kind(b)) return kind(a) - kind(b);\n if (typeof a === \"string\") return collator.compare(a, b as string);\n return Number(a) - Number(b);\n}\n\n/** A cell with no value: the column's word, or an en dash named \"No value\" for a screen reader. */\nfunction Missing({ word }: { word?: string }) {\n return word ? (\n <span className=\"text-muted-foreground\">{word}</span>\n ) : (\n <span className=\"text-muted-foreground\">\n <span aria-hidden>{format.missing}</span>\n <span className=\"sr-only\">No value</span>\n </span>\n );\n}\n\nfunction drawValue(v: number | string | Date) {\n return typeof v === \"number\" ? format.decimal(v) : v instanceof Date ? format.date(v) : v;\n}\n\n/** Row selection for a `DataTable`: the chosen row keys, how to change them, and how to name each row's checkbox. */\nexport type RowSelection<T> = {\n /** Keys (from `rowKey`) of the chosen rows. */\n selected: ReadonlySet<string>;\n onChange: (next: Set<string>) => void;\n /** Names the row in its checkbox (\"Select <rowLabel>\"). Required: an unnamed checkbox is a column of \"checkbox, not checked\". */\n rowLabel: (row: T) => string;\n /** Rows that cannot be chosen get a disabled checkbox and are left out of select-all. Default: every row. */\n isSelectable?: (row: T) => boolean;\n};\n\n/** Row expansion for a `DataTable`: the open row keys, how to change them, how to name each toggle, and the detail to show. */\nexport type RowExpansion<T> = {\n /** Keys (from `rowKey`) of the open rows. */\n expanded: ReadonlySet<string>;\n onChange: (next: Set<string>) => void;\n /** Names the row's toggle by what it shows: \"Pieces in firing 412\". Its state is `aria-expanded`, so the name stays the same open or closed. */\n rowLabel: (row: T) => string;\n /** The row's detail, mounted only while it is open. Return an element whose component makes any request, so the request runs on open. */\n detail: (row: T) => React.ReactNode;\n /** Rows with nothing to show get no toggle. Default: every row. */\n isExpandable?: (row: T) => boolean;\n};\n\nexport type Sort = { key: string; dir: \"ascending\" | \"descending\" };\n\nexport type DataTableProps<T> = {\n /** Names the table for screen readers and labels the scroll region. */\n caption: string;\n columns: Column<T>[];\n rows: T[];\n rowKey: (row: T) => string;\n initialSort?: Sort;\n /** Keep the sort in this URL search parameter. Needs a React Router context. */\n sortParam?: string;\n /** Row count from which only the visible rows render. Default 100. */\n virtualizeFrom?: number;\n /** Height of the scroll region once virtualised, in px. Default 480. */\n maxHeight?: number;\n /** Adds a checkbox column and \"Select all shown\". Use only where a `BulkBar` acts on the selection. */\n selection?: RowSelection<T>;\n /** Adds a toggle per row that opens a detail row under it. Spread `useExpanded()` in with a `rowLabel` and `detail`. */\n expansion?: RowExpansion<T>;\n className?: string;\n};\n\ntype SortState = [Sort | undefined, (next: Sort) => void];\n\nfunction useLocalSort(initial?: Sort): SortState {\n const [sort, setSort] = React.useState(initial);\n return [sort, setSort];\n}\n\n/** Reads a sort from its URL form (`pieces.desc`). */\nexport function parseSort(value: string | null): Sort | undefined {\n if (!value) return undefined;\n const [key, dir] = value.split(\".\");\n if (!key) return undefined;\n return { key, dir: dir === \"desc\" ? \"descending\" : \"ascending\" };\n}\n\n/** Writes a sort in its URL form (`pieces.desc`). */\nexport function serialiseSort(sort: Sort) {\n return `${sort.key}.${sort.dir === \"descending\" ? \"desc\" : \"asc\"}`;\n}\n\nfunction useUrlSort(param: string, initial?: Sort): SortState {\n const [params, setParams] = useSearchParams();\n const sort = parseSort(params.get(param)) ?? initial;\n const set = React.useCallback(\n (next: Sort) =>\n setParams(\n (p) => {\n const out = new URLSearchParams(p);\n out.set(param, serialiseSort(next));\n return out;\n },\n { replace: true },\n ),\n [param, setParams],\n );\n return [sort, set];\n}\n\n/** A table on TanStack Table: muted headers, row rules, right-aligned tabular numbers, sortable headers with `aria-sort`, virtualised from `virtualizeFrom` rows, sort optionally kept in the URL (`sortParam`). */\nexport function DataTable<T>(props: DataTableProps<T>) {\n // Two thin wrappers so each calls its hooks unconditionally.\n return props.sortParam ? <UrlSortedTable {...props} sortParam={props.sortParam} /> : <LocalSortedTable {...props} />;\n}\n\nfunction LocalSortedTable<T>(props: DataTableProps<T>) {\n return <Table {...(props as unknown as DataTableProps<Rec>)} sortState={useLocalSort(props.initialSort)} />;\n}\n\nfunction UrlSortedTable<T>(props: DataTableProps<T> & { sortParam: string }) {\n return <Table {...(props as unknown as DataTableProps<Rec>)} sortState={useUrlSort(props.sortParam, props.initialSort)} />;\n}\n\ntype Meta = { numeric?: boolean; truncate?: boolean; hideHeader?: boolean; className?: string };\n\n// The one TanStack feature in use: sorting, on the client. TanStack Table 9 is tree-shaken by feature, so\n// nothing else (pagination, filtering, TanStack's own selection or expansion) is bundled.\nconst features = tableFeatures({ rowSortingFeature, sortedRowModel: createSortedRowModel() });\n// TanStack Table 9 requires object or array rows. Every row a DataTable draws is a record, but the\n// public `T` stays unconstrained so an app's row types need no change: the cast is in the two wrappers.\ntype Rec = Record<string, any>; // TanStack's own RowData\n\nfunction Table<T extends Rec>({\n caption,\n columns,\n rows,\n rowKey,\n sortState: [sort, setSort],\n virtualizeFrom = 100,\n maxHeight = 480,\n selection,\n expansion,\n className,\n}: DataTableProps<T> & { sortState: SortState }) {\n const baseId = React.useId();\n const defs = React.useMemo<ColumnDef<typeof features, T, unknown>[]>(\n () =>\n columns.map((c): ColumnDef<typeof features, T, unknown> => {\n const meta = { numeric: c.numeric, truncate: c.truncate, hideHeader: c.hideHeader, className: c.className } satisfies Meta;\n const { value, sort } = c;\n if (!value) {\n return {\n id: c.key,\n // TanStack only sorts columns with an accessor; the row itself is enough, since the\n // column's own comparator does the work.\n accessorFn: (row) => row,\n header: c.header,\n cell: (info) => c.cell?.(info.row.original),\n enableSorting: Boolean(sort),\n sortFn: sort ? (a, b) => sort(a.original, b.original) : undefined,\n meta,\n };\n }\n // The accessor is the value, with null as undefined, so TanStack's `sortUndefined: \"last\"`\n // keeps missing rows at the end whichever way the column is sorted (it applies before the\n // direction is). The comparator then sees only rows that have a value.\n return {\n id: c.key,\n accessorFn: (row) => value(row) ?? undefined,\n header: c.header,\n cell: (info) => {\n const v = value(info.row.original);\n if (v == null) return <Missing word={c.missing} />;\n return c.cell ? c.cell(info.row.original) : drawValue(v);\n },\n enableSorting: sort !== false,\n sortUndefined: \"last\",\n sortFn: sort\n ? (a, b) => sort(a.original, b.original)\n : (a, b) => compareValues(a.getValue<number | string | Date>(c.key), b.getValue<number | string | Date>(c.key)),\n meta,\n };\n }),\n [columns],\n );\n\n const sorting: SortingState = sort && columns.some((c) => c.key === sort.key && (c.value ? c.sort !== false : c.sort))\n ? [{ id: sort.key, desc: sort.dir === \"descending\" }]\n : [];\n\n const table = useTable({\n features,\n data: rows,\n columns: defs,\n state: { sorting },\n getRowId: (row) => rowKey(row),\n // No pagination here, and expansion is the caller's state, not TanStack's: nothing to reset. Left on, TanStack resets the page\n // index whenever `rows` is a new array; a screen that filters its rows on every render (the\n // kiln room after Withdraw) then re-renders forever and the tab freezes. Found by the\n // example app's visual suite, which jsdom did not show.\n autoResetAll: false,\n });\n\n const toggle = (key: string) =>\n setSort({ key, dir: sort?.key === key && sort.dir === \"ascending\" ? \"descending\" : \"ascending\" });\n\n const modelRows = table.getRowModel().rows;\n const canExpand = (row: T) => expansion?.isExpandable?.(row) ?? true;\n // What the body draws, in order: every row, and a detail line after each open one. The\n // virtualiser counts these lines, so an open detail takes its own measured slot.\n const lines = React.useMemo(\n () =>\n expansion\n ? modelRows.flatMap((row) =>\n expansion.expanded.has(row.id) && canExpand(row.original)\n ? [{ row, detail: false }, { row, detail: true }]\n : [{ row, detail: false }],\n )\n : modelRows.map((row) => ({ row, detail: false })),\n // canExpand reads `expansion`, which is a dependency.\n [modelRows, expansion],\n );\n // In the order shown, so a Shift-click range runs down the sorted table, not the data's order.\n const sortedRows = React.useMemo(() => modelRows.map((r) => r.original), [modelRows]);\n const select = useSelectRows(sortedRows, rowKey, selection);\n const selectAll = selection ? select.all : undefined;\n const virtual = modelRows.length >= virtualizeFrom;\n const scroller = React.useRef<HTMLDivElement>(null);\n const virtualizer = useVirtualizer({\n count: virtual ? lines.length : 0,\n getScrollElement: () => scroller.current,\n estimateSize: (i) => (lines[i]?.detail ? 160 : 41),\n // Keyed by row and line kind, not by position: opening or closing a detail shifts every line\n // after it, and a measured detail height must stay with its detail, not pass to the row that\n // takes its index (rows are not measured, so a wrong height would never be corrected).\n getItemKey: (i) => (lines[i] ? `${lines[i].row.id}${lines[i].detail ? \"\\u0000detail\" : \"\"}` : i),\n overscan: 8,\n // Until the region is measured, assume it is full height: the first paint (and a test DOM\n // with no layout) shows the first page of rows instead of none.\n initialRect: { width: 0, height: maxHeight },\n });\n const items = virtual ? virtualizer.getVirtualItems() : [];\n const padTop = items.length ? items[0].start : 0;\n const padBottom = items.length ? virtualizer.getTotalSize() - items[items.length - 1].end : 0;\n const visible = virtual ? items.map((i) => ({ ...lines[i.index], index: i.index })) : lines.map((l, index) => ({ ...l, index }));\n const lead = (selection ? 1 : 0) + (expansion ? 1 : 0);\n\n return (\n <div\n ref={scroller}\n role=\"region\"\n aria-label={caption}\n tabIndex={0}\n className={cn(\"relative min-w-0 overflow-x-auto\", virtual && \"overflow-y-auto\", className)}\n style={virtual ? { maxHeight } : undefined}\n >\n <table className=\"w-full border-collapse type-body-sm\" aria-rowcount={virtual ? lines.length + 1 : undefined}>\n <caption className=\"sr-only\">{caption}</caption>\n <thead className={cn(virtual && \"sticky top-0 z-10 bg-background\")}>\n {table.getHeaderGroups().map((group) => (\n <tr key={group.id}>\n {selectAll && (\n <th scope=\"col\" className=\"w-8 py-2 pr-2 text-left align-bottom\">\n <Checkbox\n className=\"-my-1\"\n label=\"Select all shown\"\n hideLabel\n checked={selectAll.checked}\n disabled={selectAll.disabled}\n onCheckedChange={selectAll.toggle}\n />\n </th>\n )}\n {expansion && (\n <th scope=\"col\" className=\"w-10 py-2 pr-2\">\n <span className=\"sr-only\">Details</span>\n </th>\n )}\n {group.headers.map((header) => {\n const meta = header.column.columnDef.meta as Meta | undefined;\n const active = sort?.key === header.id && header.column.getCanSort() ? sort.dir : undefined;\n const Icon = active === \"ascending\" ? ArrowUp : active === \"descending\" ? ArrowDown : ArrowUpDown;\n const rendered = flexRender(header.column.columnDef.header, header.getContext());\n const label = meta?.hideHeader ? <span className=\"sr-only\">{rendered}</span> : rendered;\n return (\n <th\n key={header.id}\n scope=\"col\"\n aria-sort={active}\n className={cn(\n \"py-2 pr-4 text-left align-bottom type-caption text-muted-foreground last:pr-0\",\n meta?.numeric && \"text-right\",\n )}\n >\n {header.column.getCanSort() ? (\n <button\n type=\"button\"\n onClick={() => toggle(header.id)}\n className={cn(\n \"-mx-1 inline-flex cursor-pointer items-center gap-1 rounded-control px-1 transition-state hover:text-foreground\",\n meta?.numeric && \"flex-row-reverse\",\n active && \"text-foreground\",\n )}\n >\n {label}\n <Icon aria-hidden className={cn(\"size-3.5\", !active && \"opacity-50\")} />\n </button>\n ) : (\n label\n )}\n </th>\n );\n })}\n </tr>\n ))}\n </thead>\n <tbody>\n {padTop > 0 && <tr aria-hidden style={{ height: padTop }} />}\n {visible.map(({ row, detail, index }) => {\n const chosen = selection?.selected.has(row.id) ?? false;\n const detailId = `${baseId}-detail-${row.id}`;\n if (detail && expansion)\n return (\n <tr\n key={`${row.id}-detail`}\n ref={virtual ? virtualizer.measureElement : undefined}\n data-index={index}\n className={cn(chosen && \"bg-surface-sunken\")}\n aria-rowindex={virtual ? index + 2 : undefined}\n >\n {lead > 0 && <td colSpan={lead} />}\n <td id={detailId} colSpan={columns.length} className=\"pt-0.5 pb-4 align-top\">\n {expansion.detail(row.original)}\n </td>\n </tr>\n );\n const open = expansion?.expanded.has(row.id) ?? false;\n return (\n <tr\n key={row.id}\n className={cn(\"border-t border-border\", chosen && \"bg-surface-sunken\")}\n aria-rowindex={virtual ? index + 2 : undefined}\n >\n {selection && (\n <td className=\"w-8 py-2.5 pr-2 align-middle\">\n <Checkbox\n className=\"-my-0.5\"\n label={`Select ${selection.rowLabel(row.original)}`}\n hideLabel\n checked={chosen}\n disabled={!(selection.isSelectable?.(row.original) ?? true)}\n onCheckedChange={(on, gesture) => select.toggle(row.id, on, gesture)}\n />\n </td>\n )}\n {expansion && (\n <td className=\"w-10 py-2.5 pr-2 align-middle\">\n {canExpand(row.original) && (\n <button\n type=\"button\"\n aria-expanded={open}\n aria-controls={open ? detailId : undefined}\n aria-label={expansion.rowLabel(row.original)}\n title={expansion.rowLabel(row.original)}\n onClick={() => {\n const next = new Set(expansion.expanded);\n if (open) next.delete(row.id);\n else next.add(row.id);\n expansion.onChange(next);\n }}\n className=\"-my-1.5 grid size-(--control-h-sm) cursor-pointer place-items-center rounded-control hover:bg-muted\"\n >\n <Chevron open={open} />\n </button>\n )}\n </td>\n )}\n {row.getAllCells().map((cell) => {\n const meta = cell.column.columnDef.meta as Meta | undefined;\n return (\n <td\n key={cell.id}\n className={cn(\n \"py-2.5 pr-4 align-middle last:pr-0\",\n meta?.numeric && \"text-right tabular-nums\",\n meta?.truncate && \"max-w-48 truncate\",\n meta?.className,\n )}\n >\n {flexRender(cell.column.columnDef.cell, cell.getContext())}\n </td>\n );\n })}\n </tr>\n );\n })}\n {padBottom > 0 && <tr aria-hidden style={{ height: padBottom }} />}\n </tbody>\n </table>\n </div>\n );\n}\n\n/** The loading placeholder for a `DataTable`, shaped like its rows. */\nexport function TableSkeleton({ rows = 4, columns = 5 }: { rows?: number; columns?: number }) {\n return (\n <div aria-hidden className=\"grid gap-0\">\n <div className=\"flex gap-4 py-2\">\n {Array.from({ length: columns }, (_, i) => (\n <div key={i} className=\"h-3 flex-1 rounded-control bg-muted\" />\n ))}\n </div>\n {Array.from({ length: rows }, (_, r) => (\n <div key={r} className=\"flex gap-4 border-t border-border py-3.5\">\n {Array.from({ length: columns }, (_, i) => (\n <div key={i} className=\"h-4 flex-1 rounded-control bg-muted motion-safe:animate-pulse\" />\n ))}\n </div>\n ))}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { useVirtualizer } from \"@tanstack/react-virtual\";\nimport { cn } from \"../lib/utils\";\nimport { Checkbox as AriaCheckbox } from \"react-aria-components\";\nimport { Check } from \"lucide-react\";\nimport { Checkbox, useShiftNote, type CheckboxGesture } from \"./checkbox\";\nimport type { RowSelection } from \"./data-table\";\nimport { useSelectRows } from \"./selection\";\n\n// Choosing from pictures: a review screen of face crops, a set of glaze test tiles, photos to\n// archive. It is `DataTable`'s selection drawn as a grid (strata-react issue #32, from the Bright\n// Horizons port, where the Groups screen had to be built by hand from `Checkbox` and\n// `useSelection`), and it shares the state and the rules: `useSelection` holds the keys, a\n// `BulkBar` holds the actions, select-all covers the selectable tiles shown (all of them, rendered\n// or not) and is mixed when some are chosen, and Shift-click or Shift+Space chooses or clears the\n// run from the last tile clicked (`useSelectRows`, the same code the table uses).\n//\n// Each tile is one target: the picture, the box and the detail line sit in one <label>, so a click\n// anywhere on the picture toggles it (Google Photos and Apple Photos select from the picture, not\n// only from the box). The box is named from the row (`rowLabel` is required, as the table's is),\n// so a screen reader hears \"Select Ada Lovelace, crop 3\", not twelve \"checkbox, not checked\". The\n// box sits on a chip of the page's ground in the picture's corner, so it stays visible on any\n// photo. A chosen tile takes the sunken fill and a primary border, not a ring: the focus outline is\n// the only ring, so a selection never reads as focus.\n//\n// The picture is the caller's (`renderImage`), in a frame of fixed aspect (`aspect`, square by\n// default) so tiles line up and nothing shifts as images load; an <img> or Strata's `Thumbnail`\n// fills it. Tiles are sized by a minimum width (`tileSize`) and fill the row. From\n// `virtualizeFrom` tiles (100, as the table and list) the grid renders only the visible rows of\n// tiles in a labelled, focusable scroll region, measuring its width to know how many fit a row.\n\n/** The frame each picture is drawn in. */\nexport type TileAspect = \"square\" | \"portrait\" | \"landscape\";\n\n/** Smallest tile width: `sm` 96px (dense crops), `md` 144px, `lg` 192px. Tiles grow to fill the row. */\nexport type TileSize = \"sm\" | \"md\" | \"lg\";\n\nexport type SelectableGridProps<T> = {\n /** Names the list of tiles (and its scroll region once virtualised). */\n label: string;\n rows: T[];\n rowKey: (row: T) => string;\n /** The picture, drawn to fill a frame of `aspect`. An `<img className=\"size-full object-cover\">` or a `Thumbnail`. */\n renderImage: (row: T) => React.ReactNode;\n /** A short line under the picture (a name, a date, a score). Truncated to one line. */\n detail?: (row: T) => React.ReactNode;\n /** The chosen keys and how to change them, as `DataTable` takes them; `rowLabel` names each tile's box. */\n selection: RowSelection<T>;\n /** Default `square`. `portrait` is 3:4, `landscape` 4:3. */\n aspect?: TileAspect;\n /** Default `md`. */\n tileSize?: TileSize;\n /** Tile count from which only the visible rows of tiles render. Default 100. */\n virtualizeFrom?: number;\n /** Height of the scroll region once virtualised, in px. Default 480. */\n maxHeight?: number;\n className?: string;\n};\n\nconst minWidth: Record<TileSize, number> = { sm: 96, md: 144, lg: 192 };\nconst aspectClass: Record<TileAspect, string> = { square: \"aspect-square\", portrait: \"aspect-3/4\", landscape: \"aspect-4/3\" };\nconst aspectRatio: Record<TileAspect, number> = { square: 1, portrait: 4 / 3, landscape: 3 / 4 };\n// gap-3, in px, for the column count of a virtualised grid.\nconst GAP = 12;\n// The detail line and the tile's padding, for the first estimate of a row's height.\nconst TILE_CHROME = 40;\n\n/** A grid of pictures to choose from: each tile one labelled target, \"Select all shown\", Shift-click ranges, virtualised from `virtualizeFrom` tiles. Pair with `useSelection` and a `BulkBar`. */\nexport function SelectableGrid<T>({\n label,\n rows,\n rowKey,\n renderImage,\n detail,\n selection,\n aspect = \"square\",\n tileSize = \"md\",\n virtualizeFrom = 100,\n maxHeight = 480,\n className,\n}: SelectableGridProps<T>) {\n const select = useSelectRows(rows, rowKey, selection);\n const virtual = rows.length >= virtualizeFrom;\n\n const tile = (row: T, index: number) => {\n const key = rowKey(row);\n return (\n <Tile\n name={`Select ${selection.rowLabel(row)}`}\n chosen={selection.selected.has(key)}\n disabled={!(selection.isSelectable?.(row) ?? true)}\n onChange={(on, gesture) => select.toggle(key, on, gesture)}\n aspect={aspect}\n image={renderImage(row)}\n detail={detail?.(row)}\n index={index}\n />\n );\n };\n\n return (\n <div className={cn(\"grid min-w-0 gap-3\", className)}>\n <Checkbox\n className=\"justify-self-start\"\n label=\"Select all shown\"\n checked={select.all.checked}\n disabled={select.all.disabled}\n onCheckedChange={select.all.toggle}\n />\n {virtual ? (\n <VirtualTiles label={label} rows={rows} rowKey={rowKey} tile={tile} aspect={aspect} tileSize={tileSize} maxHeight={maxHeight} />\n ) : (\n <ul\n aria-label={label}\n className=\"grid gap-3\"\n style={{ gridTemplateColumns: `repeat(auto-fill, minmax(min(${minWidth[tileSize]}px, 100%), 1fr))` }}\n >\n {rows.map((row, i) => (\n <li key={rowKey(row)}>{tile(row, i)}</li>\n ))}\n </ul>\n )}\n </div>\n );\n}\n\nfunction VirtualTiles<T>({\n label,\n rows,\n rowKey,\n tile,\n aspect,\n tileSize,\n maxHeight,\n}: {\n label: string;\n rows: T[];\n rowKey: (row: T) => string;\n tile: (row: T, index: number) => React.ReactNode;\n aspect: TileAspect;\n tileSize: TileSize;\n maxHeight: number;\n}) {\n const scroller = React.useRef<HTMLDivElement>(null);\n const [width, setWidth] = React.useState(0);\n React.useLayoutEffect(() => {\n const el = scroller.current;\n if (!el || typeof ResizeObserver === \"undefined\") return;\n const observer = new ResizeObserver(([entry]) => setWidth(entry.contentRect.width));\n observer.observe(el);\n return () => observer.disconnect();\n }, []);\n const min = minWidth[tileSize];\n const columns = Math.max(1, Math.floor((width + GAP) / (min + GAP)));\n const tileWidth = width > 0 ? (width - GAP * (columns - 1)) / columns : min;\n const lines = Math.ceil(rows.length / columns);\n const virtualizer = useVirtualizer({\n count: lines,\n getScrollElement: () => scroller.current,\n estimateSize: () => Math.round(tileWidth * aspectRatio[aspect]) + TILE_CHROME + GAP,\n overscan: 3,\n // Keyed by the column count as well as the row: a new count moves every tile to another row,\n // so each row of tiles is a new element, measured afresh, not an old height reused.\n getItemKey: (i) => `${columns}:${i}`,\n // Until the region is measured, assume it is full height, so the first paint shows tiles.\n initialRect: { width: 0, height: maxHeight },\n });\n const items = virtualizer.getVirtualItems();\n\n return (\n <div\n ref={scroller}\n role=\"region\"\n aria-label={label}\n tabIndex={0}\n data-strata-scroll=\"\"\n className=\"min-w-0 overflow-y-auto\"\n style={{ height: maxHeight }}\n >\n {/* role=\"list\" over plain rows of tiles: each row is laid out on its own, and the rows add nothing for a screen reader. */}\n <div role=\"list\" aria-label={label} className=\"relative w-full\" style={{ height: virtualizer.getTotalSize() }}>\n {items.map((v) => {\n const start = v.index * columns;\n return (\n <div\n key={v.key}\n ref={virtualizer.measureElement}\n data-index={v.index}\n role=\"none\"\n className=\"absolute inset-x-0 top-0 grid gap-3 pb-3\"\n style={{ translate: `0 ${v.start}px`, gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` }}\n >\n {rows.slice(start, start + columns).map((row, i) => (\n <div key={rowKey(row)} role=\"listitem\" aria-setsize={rows.length} aria-posinset={start + i + 1}>\n {tile(row, start + i)}\n </div>\n ))}\n </div>\n );\n })}\n </div>\n </div>\n );\n}\n\nfunction Tile({\n name,\n chosen,\n disabled,\n onChange,\n aspect,\n image,\n detail,\n index,\n}: {\n name: string;\n chosen: boolean;\n disabled: boolean;\n onChange: (on: boolean, gesture: CheckboxGesture) => void;\n aspect: TileAspect;\n image: React.ReactNode;\n detail?: React.ReactNode;\n index: number;\n}) {\n const shift = useShiftNote();\n // The whole tile is one React Aria Checkbox (a label around a hidden input), so a press anywhere\n // on it toggles; the visible box in the corner is drawn from tokens. Shift is noted in the capture\n // phase because React Aria's press handling stops the events it uses.\n return (\n <span className=\"contents\" onMouseDownCapture={shift.handlers.onMouseDown} onKeyDownCapture={shift.handlers.onKeyDown}>\n <AriaCheckbox\n isSelected={chosen}\n isDisabled={disabled}\n aria-label={name}\n onChange={(on) => onChange(on, shift.take())}\n data-index={index}\n className={cn(\n // select-none: a Shift-click range would otherwise also select the text between the tiles.\n \"group relative grid min-w-0 gap-1.5 rounded-surface border border-transparent p-1.5 select-none transition-state\",\n \"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring\",\n chosen && \"border-primary bg-surface-sunken\",\n disabled ? \"cursor-not-allowed opacity-50\" : \"cursor-pointer hover:bg-surface-sunken\",\n )}\n >\n <span className={cn(\"block overflow-hidden rounded-control bg-muted *:size-full *:object-cover\", aspectClass[aspect])}>\n {image}\n </span>\n <span className=\"absolute top-3 left-3 grid size-7 place-items-center rounded-control bg-background\">\n <span\n aria-hidden\n className={cn(\n \"grid size-4.5 place-items-center rounded-control border border-input bg-background\",\n chosen && \"border-primary bg-primary text-primary-foreground\",\n )}\n >\n {chosen && <Check className=\"size-3.5\" strokeWidth={3} />}\n </span>\n </span>\n {detail != null && <span className=\"truncate type-body-sm text-muted-foreground\">{detail}</span>}\n </AriaCheckbox>\n </span>\n );\n}\n","import * as React from \"react\";\nimport { useVirtualizer } from \"@tanstack/react-virtual\";\nimport { cn } from \"../lib/utils\";\n\n// A long list that keeps only its visible rows in the DOM (TanStack Virtual), for feeds, logs and\n// pickers with hundreds of items. Rows are measured after render, so variable heights work; the\n// estimate only sets the first paint. The list is a labelled, focusable region so it can be\n// scrolled from the keyboard, and keeps list semantics with aria-setsize/aria-posinset so screen\n// readers still hear \"12 of 480\". Under `virtualizeFrom` items it renders a plain list.\n//\n// `bounded` keeps a short list in the same scroll region (capped at `height`) that the virtual\n// one uses, so a list that grows past `virtualizeFrom` while someone scrolls it (InfiniteList)\n// does not jump from the page's flow into a box. `footer` renders after the last row, inside the\n// scroll region: where InfiniteList puts its next-page row. Rows carry `data-index` in both modes.\n\n/** A list that renders only its visible rows (TanStack Virtual) from `virtualizeFrom` items, keeping list semantics for screen readers. */\nexport function VirtualList<T>({\n label,\n items,\n itemKey,\n children,\n estimateSize = 48,\n height = 480,\n virtualizeFrom = 100,\n bounded = false,\n footer,\n className,\n}: {\n label: string;\n items: T[];\n itemKey: (item: T) => string;\n children: (item: T, index: number) => React.ReactNode;\n estimateSize?: number;\n height?: number;\n virtualizeFrom?: number;\n /** Scroll inside a region capped at `height` even below `virtualizeFrom`, so growing past it changes nothing on screen. */\n bounded?: boolean;\n /** After the last row, inside the scroll region (a next-page row, an end note). */\n footer?: React.ReactNode;\n className?: string;\n}) {\n const scroller = React.useRef<HTMLDivElement>(null);\n const virtual = items.length >= virtualizeFrom;\n const virtualizer = useVirtualizer({\n count: virtual ? items.length : 0,\n getScrollElement: () => scroller.current,\n estimateSize: () => estimateSize,\n overscan: 6,\n initialRect: { width: 0, height },\n });\n\n // Built only when it is shown: a virtual list must not render every row it keeps out of the DOM.\n const plain = () => (\n <ul aria-label={label} className={cn(\"grid min-w-0\", !bounded && !footer && className)}>\n {items.map((item, i) => (\n <li key={itemKey(item)} data-index={i} className=\"border-t border-border first:border-t-0\">\n {children(item, i)}\n </li>\n ))}\n </ul>\n );\n\n if (!virtual && !bounded) {\n return footer ? (\n <div className={cn(\"min-w-0\", className)}>\n {plain()}\n {footer}\n </div>\n ) : (\n plain()\n );\n }\n\n return (\n <div\n ref={scroller}\n role=\"region\"\n aria-label={label}\n tabIndex={0}\n data-strata-scroll=\"\"\n className={cn(\"min-w-0 overflow-y-auto\", className)}\n style={virtual ? { height } : { maxHeight: height }}\n >\n {virtual ? (\n <ul aria-label={label} className=\"relative w-full\" style={{ height: virtualizer.getTotalSize() }}>\n {virtualizer.getVirtualItems().map((v) => {\n const item = items[v.index];\n return (\n <li\n key={itemKey(item)}\n ref={virtualizer.measureElement}\n data-index={v.index}\n aria-setsize={items.length}\n aria-posinset={v.index + 1}\n className={cn(\"absolute inset-x-0 top-0\", v.index > 0 && \"border-t border-border\")}\n style={{ translate: `0 ${v.start}px` }}\n >\n {children(item, v.index)}\n </li>\n );\n })}\n </ul>\n ) : (\n plain()\n )}\n {footer}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { CircleAlert, RotateCcw } from \"lucide-react\";\nimport { Button } from \"./button\";\nimport { DataView, type LoadFailure } from \"./data-view\";\nimport { VirtualList } from \"./virtual-list\";\nimport type { InfiniteLoad } from \"../query/infinite\";\nimport { useInView } from \"../lib/in-view\";\nimport { cn } from \"../lib/utils\";\n\n// A list that loads its next page as the person nears the end: the view for `useInfiniteLoad`.\n// It is DataView for the first page (skeleton, error with Try again, empty state, all required)\n// and VirtualList for the rows (virtualised from 100, so a long session stays fast), with one row\n// after the last item that is always in one of four states:\n//\n// - more to come: an IntersectionObserver sentinel with a root margin, so the next page is asked\n// for before the person reaches the end, and a real \"Show more\" button behind it. The button is\n// the keyboard and screen-reader path (an automatic load is invisible to them) and the fallback\n// where the observer never fires.\n// - loading: `moreSkeleton`, mirroring the rows that are coming, not a spinner, and a polite\n// status so a screen reader hears it.\n// - a later page failed: an alert row with the reason and Try again. The items already loaded\n// stay; a failed page 4 is not a failed list. The sentinel stops asking until Try again, so a\n// dead server is not called in a loop.\n// - the end: `end`, if given (\"That's every firing since March\"), so the person knows it is all.\n//\n// `keepAtLeast` loads more whenever fewer items than that are held: a queue people work through\n// (answered items `dismiss`ed) refills before it runs dry, even when nothing scrolls. Showing\n// more by button moves focus to the first new item, because the button the person pressed is\n// gone. The list scrolls in its own region (`height`) from the first page, so passing 100 items\n// and switching to virtual rows changes nothing on screen.\n//\n// Not every paged view is a list in a box (strata-react issue #49, from the Tubes viewer, whose\n// videos are a responsive card grid that scrolls with the page). So the next-page row is its own\n// export, `LoadMore`, which an app puts after any list or grid it draws itself, and InfiniteList\n// is built on it. `scroll=\"page\"` is the same in InfiniteList: no scroll region of its own and no\n// virtual rows, the items in a plain `ul` laid out by `listClassName` (a grid), and the sentinel\n// watching the viewport. Virtual rows need a box of known height, which a page-scrolled grid is\n// not; a feed long enough to need them belongs in the region. `error` and `moreError` replace the\n// look of a failed first page and a failed later page, as DataView's `error` does.\n\n/** The next-page row's props: `InfiniteList`'s, for a list or grid the app draws itself. */\nexport type LoadMoreProps<T> = {\n state: InfiniteLoad<T>;\n /** The button behind the sentinel, in the product's words: \"Show older firings\". */\n moreLabel: string;\n /** The items of a page on its way, mirroring the ones already drawn. */\n moreSkeleton: React.ReactNode;\n /** After the last page: say that this is everything. */\n end?: React.ReactNode;\n /** How far before the end the next page is asked for (IntersectionObserver `rootMargin`). Default 400px. */\n rootMargin?: string;\n /** Load more whenever fewer than this many items are held. */\n keepAtLeast?: number;\n /** Draws a failed later page, given the reason and the Try again. Rendered inside a `role=\"alert\"` box. */\n error?: (failure: LoadFailure) => React.ReactNode;\n className?: string;\n};\n\nfunction MoreFailed({ message, retry }: LoadFailure) {\n return (\n <div className=\"flex flex-wrap items-start gap-3 border-t border-border bg-danger-subtle px-3 py-2 text-danger\">\n <CircleAlert aria-hidden className=\"mt-0.5 size-4 shrink-0\" />\n <p className=\"min-w-0 flex-1 type-body-sm\">{message}</p>\n <Button size=\"sm\" onClick={retry}>\n <RotateCcw aria-hidden />\n Try again\n </Button>\n </div>\n );\n}\n\nconst defaultMoreError = (failure: LoadFailure) => <MoreFailed {...failure} />;\n\n/**\n * The row after a cursor-paged list or grid: loads the next page as it nears the screen, shows\n * `moreSkeleton` while it comes, says why it failed with Try again, offers Show more for the\n * keyboard, and `end` after the last page. After Show more it focuses the first new item: mark\n * each item with `data-index` and put this row beside the list, in the same parent.\n */\nexport function LoadMore<T>({\n state,\n moreLabel,\n moreSkeleton,\n end,\n rootMargin = \"400px\",\n keepAtLeast = 0,\n error: drawError = defaultMoreError,\n className,\n}: LoadMoreProps<T>) {\n const { more } = state;\n const ready = state.status === \"ready\";\n const held = ready ? state.data.length : 0;\n const box = React.useRef<HTMLDivElement>(null);\n const near = useInView({ active: ready && more.hasMore, rootMargin });\n\n // Load on approach, and keep a worked-through queue topped up. Not after a failure: that waits\n // for Try again. Re-runs when a page lands, so a sentinel still in view asks for the next one.\n const { hasMore, loadingMore, error, loadMore } = more;\n React.useEffect(() => {\n if (!ready || !hasMore || loadingMore || error) return;\n if (near.inView || held < keepAtLeast) loadMore();\n }, [ready, hasMore, loadingMore, error, near.inView, held, keepAtLeast, loadMore]);\n\n // After a click on Show more or Try again, focus the first new item: the button is gone.\n const focusFrom = React.useRef<number | null>(null);\n const loadByHand = () => {\n focusFrom.current = held;\n loadMore();\n };\n React.useEffect(() => {\n const from = focusFrom.current;\n if (from === null || loadingMore) return;\n if (held > from) {\n const item = box.current?.parentElement?.querySelector<HTMLElement>(`[data-index=\"${from}\"]`);\n if (item) {\n item.tabIndex = -1;\n item.focus();\n }\n focusFrom.current = null;\n } else if (error || !hasMore) focusFrom.current = null;\n }, [held, loadingMore, error, hasMore]);\n\n if (!ready) return null;\n return (\n <div ref={box} className={className}>\n {hasMore && !error && <div ref={near.ref} aria-hidden className=\"h-px\" />}\n {loadingMore ? (\n <div aria-hidden className=\"border-t border-border\">{moreSkeleton}</div>\n ) : error ? (\n <div role=\"alert\">{drawError({ message: error, retry: loadByHand })}</div>\n ) : hasMore ? (\n <div className=\"border-t border-border py-3\">\n <Button size=\"sm\" onClick={loadByHand}>\n {moreLabel}\n </Button>\n </div>\n ) : (\n end && <div className=\"border-t border-border py-3 type-body-sm text-muted-foreground\">{end}</div>\n )}\n <p role=\"status\" className=\"sr-only\">\n {loadingMore ? \"Loading more\" : \"\"}\n </p>\n </div>\n );\n}\n\n/** The infinite list's props. */\nexport type InfiniteListProps<T> = {\n state: InfiniteLoad<T>;\n /** The list's accessible name, e.g. \"Firing log, newest first\". */\n label: string;\n children: (item: T, index: number) => React.ReactNode;\n /** The first load. Mirrors the final layout, so nothing jumps when data arrives. */\n skeleton: React.ReactNode;\n /** What goes here and how to add it, when the first page is empty and there are no more. */\n empty: React.ReactNode;\n /** The button behind the sentinel, in the product's words: \"Show older firings\". */\n moreLabel: string;\n /** The rows of a page on its way. Defaults to `skeleton`. */\n moreSkeleton?: React.ReactNode;\n /** After the last page: say that this is everything. */\n end?: React.ReactNode;\n /** How far before the end the next page is asked for (IntersectionObserver `rootMargin`). */\n rootMargin?: string;\n /** Load more whenever fewer than this many items are held. */\n keepAtLeast?: number;\n /** `region` (default): rows in a scroll region of `height`, virtual from `virtualizeFrom`. `page`: a plain list that scrolls with the page, laid out by `listClassName`. */\n scroll?: \"region\" | \"page\";\n /** With `scroll=\"page\"`: the classes of the `ul`, such as a responsive grid (`grid gap-4 sm:grid-cols-2 lg:grid-cols-3`). */\n listClassName?: string;\n /** Draws a failed first page. Defaults to DataView's `LoadError`. */\n error?: (failure: LoadFailure) => React.ReactNode;\n /** Draws a failed later page. Defaults to a danger row with Try again. */\n moreError?: (failure: LoadFailure) => React.ReactNode;\n estimateSize?: number;\n height?: number;\n virtualizeFrom?: number;\n className?: string;\n};\n\n/** A cursor-paged list for `useInfiniteLoad`: DataView's first-page states, virtual rows (or a page-scrolled grid), and a `LoadMore` row that loads on approach, shows a skeleton, or says why it failed with Try again. */\nexport function InfiniteList<T>({\n state,\n label,\n children,\n skeleton,\n empty,\n moreLabel,\n moreSkeleton = skeleton,\n end,\n rootMargin = \"400px\",\n keepAtLeast = 0,\n scroll = \"region\",\n listClassName,\n error,\n moreError,\n estimateSize,\n height = 480,\n virtualizeFrom,\n className,\n}: InfiniteListProps<T>) {\n const { more, itemKey } = state;\n const footer = (\n <LoadMore\n // A grid's cards have their own edges, so the row keeps a gap from them.\n className={scroll === \"page\" ? \"mt-4\" : undefined}\n state={state}\n moreLabel={moreLabel}\n moreSkeleton={moreSkeleton}\n end={end}\n rootMargin={rootMargin}\n keepAtLeast={keepAtLeast}\n error={moreError}\n />\n );\n\n return (\n <DataView\n state={state}\n isEmpty={(items) => items.length === 0 && !more.hasMore}\n skeleton={skeleton}\n empty={empty}\n error={error}\n className={className}\n >\n {(items) =>\n scroll === \"page\" ? (\n <div aria-busy={more.loadingMore || undefined}>\n <ul aria-label={label} className={cn(\"min-w-0\", listClassName ?? \"grid\")}>\n {items.map((item, i) => (\n <li key={itemKey(item)} data-index={i} className=\"min-w-0\">\n {children(item, i)}\n </li>\n ))}\n </ul>\n {footer}\n </div>\n ) : (\n <div aria-busy={more.loadingMore || undefined}>\n <VirtualList\n label={label}\n items={items}\n itemKey={itemKey}\n estimateSize={estimateSize}\n height={height}\n virtualizeFrom={virtualizeFrom}\n bounded\n footer={footer}\n >\n {children}\n </VirtualList>\n </div>\n )\n }\n </DataView>\n );\n}\n","import * as React from \"react\";\nimport { cn } from \"../lib/utils\";\n\n// A line chart with the defaults real product screens use: one measured series in one hue, a 2px\n// straight line with no fill and no markers, 3 to 5 faint gridlines, no y-axis line, no legend for a\n// single series (the series is labelled where it ends). Values never live only in a hover tooltip:\n// the latest and peak readings are labelled on the chart and every reading is in a table for screen\n// readers. Optional extras exist only where they answer a question: a dashed `planned` series, a\n// horizontal `band` (a threshold that matters), and a `now` marker.\n//\n//\n// `colourScale` colours the measured line by its own value, for subjects where that colour is a\n// fact rather than decoration: a kiln's glow by temperature, water by depth. The y position still\n// carries the value, so the colour is never the only cue. Without a reason in DESIGN.md, use one\n// hue.\n//\n// It draws in real pixels (measured with ResizeObserver) rather than scaling a fixed viewBox, so\n// the 12px labels stay 12px on a phone. Because the labels keep their size, the chart thins the\n// x ticks itself when they would collide (every second, third… tick, so the rhythm stays even)\n// and keeps the first and last label inside the chart, rather than overlapping on a phone.\n//\n// The y-axis autoscales to four gridline steps of a size people write on a scale, from zero (or\n// below it, if a reading is negative). `yMin` and `yMax` pin either end for a quantity whose range\n// is a fact of the subject (a percentage is 0 to 100, a battery 0 to 1): autoscaling a machine at\n// 1% CPU gives a 0 to 8% axis that makes it look busy (strata-react issue #23). A pin is a floor on\n// the extent, never a crop: a reading outside it widens the axis, because a chart that hides a\n// reading is worse than one with an untidy scale.\n\nexport type Point = { x: number; y: number };\n\nexport type LineChartProps = {\n /** What the chart shows, as a sentence. Used as the accessible name and the table caption. */\n label: string;\n series: Point[];\n seriesLabel: string;\n planned?: Point[];\n plannedLabel?: string;\n band?: { below: number; label: string };\n formatX: (x: number) => string;\n formatY: (y: number) => string;\n /** Where to put x labels, in x units. The chart drops every other one (and so on) when they would overlap at its width. */\n xTicks: number[];\n /** Pin the bottom of the y-axis (default: 0, or lower if a reading is negative). A reading below it still shows. */\n yMin?: number;\n /** Pin the top of the y-axis, for a bounded quantity such as a percentage (`yMax={100}`), so a low reading looks low. Choose a range that divides into four steps. A reading above it still shows. */\n yMax?: number;\n /** CSS colour for the measured series. Defaults to the first chart token. */\n colour?: string;\n /** Colour the measured series by value: each stop applies from `at` upwards, blending to the\n * next. Only where the colour means something in the subject; record the reason in DESIGN.md. */\n colourScale?: { at: number; colour: string }[];\n /** Says what the colours mean, shown beside the legend swatch when `colourScale` is set. */\n colourScaleLabel?: string;\n height?: number;\n className?: string;\n};\n\nfunction useWidth<T extends HTMLElement>() {\n const ref = React.useRef<T>(null);\n const [width, setWidth] = React.useState(0);\n React.useLayoutEffect(() => {\n const el = ref.current;\n if (!el) return;\n setWidth(el.getBoundingClientRect().width);\n const ro = new ResizeObserver(([entry]) => setWidth(entry.contentRect.width));\n ro.observe(el);\n return () => ro.disconnect();\n }, []);\n return [ref, width] as const;\n}\n\n/** The smallest step of a size people write on a scale (1, 2, 2.5, 4 or 5 × 10ⁿ) at least `raw`. */\nfunction niceStep(raw: number) {\n const mag = 10 ** Math.floor(Math.log10(raw));\n return [1, 2, 2.5, 4, 5, 10].map((m) => m * mag).find((s) => s >= raw * (1 - 1e-9)) ?? 10 * mag;\n}\n\n/**\n * The y-axis: four equal gridline steps covering every value. With no pins the steps are a size\n * people write on a scale (1, 2, 2.5, 4 or 5 × 10ⁿ), from zero or a round number below the lowest\n * reading. A pinned end is used as given unless a value lies beyond it.\n */\nexport function yScale(values: number[], pin: { min?: number; max?: number } = {}) {\n const finite = values.filter(Number.isFinite);\n const dMin = finite.length ? Math.min(...finite) : 0;\n const dMax = finite.length ? Math.max(...finite) : 0;\n const pinMin = pin.min !== undefined && dMin >= pin.min ? pin.min : undefined;\n const pinMax = pin.max !== undefined && dMax <= pin.max ? pin.max : undefined;\n let lo = pinMin ?? Math.min(0, dMin);\n // Readings all at a pinned top (say all -10 under yMax={-10}) leave no span: open one below.\n if (pinMax !== undefined && pinMin === undefined && !(pinMax > lo)) lo = pinMax - (Math.abs(pinMax) || 4);\n let min: number;\n let max: number;\n if (pinMax !== undefined) {\n max = pinMax;\n // Only the bottom is free: round it down to a step of the span, so 0 stays 0.\n min = pinMin ?? (lo < 0 ? Math.floor(lo / niceStep((max - lo) / 4)) * niceStep((max - lo) / 4) : 0);\n } else {\n const hi = Math.max(dMax, pin.max ?? -Infinity);\n // All-zero (or empty) data still needs a positive extent, or every coordinate divides by zero.\n let step = hi > lo ? niceStep((hi - lo) / 4) : 1;\n let base = pinMin ?? Math.floor(lo / step) * step;\n while (base + 4 * step < hi) {\n step = niceStep(step * 1.01);\n base = pinMin ?? Math.floor(lo / step) * step;\n }\n min = base;\n max = base + 4 * step;\n }\n if (!(max > min)) max = min + 4;\n return { min, max, ticks: [0, 1, 2, 3, 4].map((i) => min + ((max - min) * i) / 4) };\n}\n\n/** Roughly how wide a 12px caption label is, in px. jsdom cannot measure text, so the chart estimates. */\nconst labelWidth = (text: string) => text.length * 7;\n\n/**\n * The x ticks that fit at this width: every k-th tick, the smallest k for which neighbouring labels\n * leave a gap, so the spacing stays even. `scale` maps an x value to a pixel.\n */\nexport function fitTicks(ticks: number[], scale: (x: number) => number, widthOf: (t: number) => number, gap = 12) {\n if (ticks.length < 3) return ticks;\n const sorted = [...ticks].sort((a, b) => a - b);\n for (let k = 1; k < sorted.length; k++) {\n const kept = sorted.filter((_, i) => i % k === 0);\n const fits = kept.every((t, i) => i === 0 || scale(t) - scale(kept[i - 1]) >= (widthOf(t) + widthOf(kept[i - 1])) / 2 + gap);\n if (fits) return kept;\n }\n return sorted.slice(0, 1);\n}\n\n/** One measured series, drawn in real pixels, with the peak and current readings labelled on the chart and every reading in a screen-reader table. Optional plan, threshold band and `colourScale`. */\nexport function LineChart({\n label,\n series,\n seriesLabel,\n planned,\n plannedLabel,\n band,\n formatX,\n formatY,\n xTicks,\n yMin,\n yMax,\n colour = \"var(--chart-1)\",\n colourScale,\n colourScaleLabel,\n height = 280,\n className,\n}: LineChartProps) {\n const [ref, width] = useWidth<HTMLDivElement>();\n const gradientId = `heat-${React.useId().replace(/[^\\w-]/g, \"\")}`;\n const all = [...series, ...(planned ?? [])];\n const xMin = Math.min(...all.map((p) => p.x));\n const xMax = Math.max(...all.map((p) => p.x));\n const y = yScale(\n all.map((p) => p.y),\n { min: yMin, max: yMax },\n );\n\n const pad = { top: 16, right: 16, bottom: 28, left: 56 };\n const w = Math.max(0, width - pad.left - pad.right);\n const h = height - pad.top - pad.bottom;\n const sx = (x: number) => pad.left + ((x - xMin) / (xMax - xMin || 1)) * w;\n const sy = (v: number) => pad.top + h - ((v - y.min) / (y.max - y.min)) * h;\n const xLabelWidth = (t: number) => labelWidth(formatX(t));\n // Keep the first and last labels inside the chart instead of centring them past its edge.\n const xLabelAt = (t: number) => {\n const half = xLabelWidth(t) / 2;\n return Math.min(Math.max(sx(t), half), Math.max(half, width - half));\n };\n // Fit against where the labels are drawn, so pulling an end label in cannot make it collide.\n const shownXTicks = fitTicks(xTicks, xLabelAt, xLabelWidth);\n const path = (pts: Point[]) => pts.map((p, i) => `${i ? \"L\" : \"M\"}${sx(p.x).toFixed(1)},${sy(p.y).toFixed(1)}`).join(\"\");\n\n const last = series[series.length - 1];\n const peak = series.reduce((a, b) => (b.y > a.y ? b : a), series[0]);\n const stops = colourScale ? [...colourScale].sort((a, b) => a.at - b.at) : [];\n /** The colour a value lands on: the highest stop at or below it. Used for the labelled points. */\n const colourAt = (y: number) => (stops.length ? [...stops].reverse().find((s) => s.at <= y)?.colour ?? stops[0].colour : colour);\n const stroke = stops.length ? `url(#${gradientId})` : colour;\n\n return (\n <figure className={cn(\"grid min-w-0 gap-2\", className)}>\n <div ref={ref} className=\"min-w-0\">\n {width > 0 && (\n <svg width={width} height={height} role=\"img\" aria-label={label} className=\"block overflow-visible\">\n {stops.length > 0 && (\n // A vertical gradient in chart space, so a colour sits at a temperature, not at a\n // point along the line: the line is the same red wherever it crosses 600 °C.\n <defs>\n <linearGradient id={gradientId} gradientUnits=\"userSpaceOnUse\" x1={0} x2={0} y1={sy(y.min)} y2={sy(y.max)}>\n {stops.map((s) => (\n <stop key={s.at} offset={Math.min(1, Math.max(0, (s.at - y.min) / (y.max - y.min)))} stopColor={s.colour} />\n ))}\n </linearGradient>\n </defs>\n )}\n {band && band.below > y.min && (\n <g>\n <rect x={pad.left} y={sy(Math.min(band.below, y.max))} width={w} height={sy(y.min) - sy(Math.min(band.below, y.max))} fill=\"var(--success-subtle)\" />\n <text x={pad.left + 8} y={sy(Math.min(band.below, y.max)) + 16} className=\"fill-success type-caption\">\n {band.label}\n </text>\n </g>\n )}\n {y.ticks.map((t) => (\n <g key={t}>\n <line x1={pad.left} x2={pad.left + w} y1={sy(t)} y2={sy(t)} stroke=\"var(--border)\" strokeWidth={1} />\n <text x={pad.left - 8} y={sy(t)} dy=\"0.32em\" textAnchor=\"end\" className=\"fill-muted-foreground type-caption tabular-nums\">\n {formatY(t)}\n </text>\n </g>\n ))}\n {shownXTicks.map((t) => (\n <text key={t} x={xLabelAt(t)} y={height - 8} textAnchor=\"middle\" className=\"fill-muted-foreground type-caption tabular-nums\">\n {formatX(t)}\n </text>\n ))}\n {planned && (\n <path d={path(planned)} fill=\"none\" stroke=\"var(--muted-foreground)\" strokeWidth={1.5} strokeDasharray=\"4 4\" />\n )}\n <path d={path(series)} fill=\"none\" stroke={stroke} strokeWidth={stops.length ? 2.5 : 2} strokeLinejoin=\"round\" strokeLinecap=\"round\" />\n {/* Direct labels instead of a legend and a tooltip. */}\n <circle cx={sx(peak.x)} cy={sy(peak.y)} r={3} fill={colourAt(peak.y)} />\n <text x={sx(peak.x) + 8} y={sy(peak.y) - 8} className=\"fill-foreground type-caption tabular-nums\">\n {formatY(peak.y)} peak\n </text>\n <line x1={sx(last.x)} x2={sx(last.x)} y1={pad.top} y2={pad.top + h} stroke=\"var(--foreground)\" strokeWidth={1} />\n <circle cx={sx(last.x)} cy={sy(last.y)} r={3.5} fill={colourAt(last.y)} />\n <text\n x={sx(last.x) - 8}\n y={sy(last.y) - 10}\n textAnchor=\"end\"\n className=\"fill-foreground type-label tabular-nums\"\n >\n {formatY(last.y)} now\n </text>\n </svg>\n )}\n </div>\n <figcaption className=\"flex flex-wrap gap-x-5 gap-y-1 type-caption text-muted-foreground\">\n <span className=\"inline-flex items-center gap-2\">\n {stops.length ? (\n <svg width={stops.length * 8} height=\"3\" aria-hidden>\n {stops.map((s, i) => (\n <line key={s.at} x1={i * 8} x2={i * 8 + 8} y1=\"1.5\" y2=\"1.5\" stroke={s.colour} strokeWidth={3} />\n ))}\n </svg>\n ) : (\n <svg width=\"16\" height=\"2\" aria-hidden>\n <line x1=\"0\" x2=\"16\" y1=\"1\" y2=\"1\" stroke={colour} strokeWidth={2} />\n </svg>\n )}\n {seriesLabel}\n {stops.length > 0 && colourScaleLabel && <span>({colourScaleLabel})</span>}\n </span>\n {planned && plannedLabel && (\n <span className=\"inline-flex items-center gap-2\">\n <svg width=\"16\" height=\"2\" aria-hidden>\n <line x1=\"0\" x2=\"16\" y1=\"1\" y2=\"1\" stroke=\"var(--muted-foreground)\" strokeWidth={1.5} strokeDasharray=\"4 4\" />\n </svg>\n {plannedLabel}\n </span>\n )}\n </figcaption>\n {/* sr-only on a wrapper: a table ignores width: 1px and would widen the page. */}\n <div className=\"sr-only\">\n <table>\n <caption>{label}</caption>\n <thead>\n <tr>\n <th scope=\"col\">Time</th>\n <th scope=\"col\">{seriesLabel}</th>\n </tr>\n </thead>\n <tbody>\n {series.map((p) => (\n <tr key={p.x}>\n <td>{formatX(p.x)}</td>\n <td>{formatY(p.y)}</td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n </figure>\n );\n}\n","import * as React from \"react\";\n\n// The top of every Operate screen: a noun title at 24px (never \"Welcome back\"), its scope, the\n// screen's main action, and the finding. The finding is the one fact in today's data that most\n// needs attention; it sits where it is read first, beside the action it drives.\n\n/** The top of an Operate screen: a noun title, its scope, the main action, and the finding (the one fact in today's data that most needs attention). */\nexport function PageHeader({\n title,\n scope,\n actions,\n finding,\n as: Heading = \"h1\",\n}: {\n title: string;\n /** The title's element: h1 on a screen, h2 where the header is shown inside another page. */\n as?: \"h1\" | \"h2\";\n /** What the screen covers: a date, a range, a filter. */\n scope?: React.ReactNode;\n actions?: React.ReactNode;\n finding?: { text: React.ReactNode; action?: React.ReactNode };\n}) {\n return (\n <header className=\"grid gap-4\">\n <div className=\"flex flex-wrap items-end justify-between gap-x-6 gap-y-3\">\n <div className=\"grid min-w-0 gap-0.5\">\n <Heading className=\"type-title text-balance\">{title}</Heading>\n {scope && <p className=\"type-body-sm text-muted-foreground\">{scope}</p>}\n </div>\n {actions && <div className=\"flex flex-wrap gap-2\">{actions}</div>}\n </div>\n {finding && (\n <div className=\"flex flex-wrap items-center justify-between gap-x-6 gap-y-3 border-y border-border py-3\">\n <p className=\"max-w-prose min-w-0 type-body text-pretty\">{finding.text}</p>\n {finding.action}\n </div>\n )}\n </header>\n );\n}\n","import * as React from \"react\";\nimport { Button } from \"./button\";\nimport { describeActionError } from \"../lib/errors\";\n\n// Destructive actions take effect visibly at once and commit after a window, with Undo in reach.\n// For reversible removals this beats a confirm dialog: the dialog interrupts every time to protect\n// against the rare mistake, and people learn to click through it. Keep a confirm dialog for\n// actions that cannot be undone (deleting an account, firing a kiln).\n\n// A bulk removal is one removal with `ids`: the selected rows go, come back on Undo, and fail\n// together, under one message and one commit, because the person did one thing.\n//\n// One removal is pending at a time. Scheduling a second commits the first at once: in rapid-fire\n// triage (withdraw, withdraw, withdraw) Undo reaches back one step, and the bar never stacks up a\n// queue of messages nobody reads. Undo is for the slip just made, not for an audit trail.\n//\n// The hook owns which items are out of view (`isRemoved`), so a screen filters its rows by it and\n// never keeps a second \"hidden\" set that can drift from the pending one. An item stays removed\n// from when it is scheduled; Undo brings it back; a commit that fails brings it back and puts the\n// failure in the same bar, with \"Try again\", because the screen told the person it was done and a\n// silent failure would leave the screen lying. A committed item stays removed until the screen's\n// data drops it (the commit should invalidate the query it came from), so it never flickers back.\n//\n// `flush()` exists for the action that depends on the removal having happened (retrain on the\n// answers, export the list): commit now and await it, rather than racing the window.\n//\n// Failures are described like any other failed action (`describeActionError`, as AsyncButton uses,\n// unless the product passes its own): the same HTTP sentences as reads, without promising that\n// nothing changed, since a write that failed may still have reached the server.\n\n/** A removal waiting out its undo window: what to say, what to do when the window closes, and what to say if that fails. */\nexport type PendingRemoval = {\n /** Identifies the removed item: `isRemoved(id)` is true from `schedule` until Undo or a failed commit. */\n id: string;\n /** A bulk removal's items, all removed, undone, committed and restored together (one `commit` for the batch). `isRemoved` is true for each. Default `[id]`. */\n ids?: readonly string[];\n /** What happened, in the product's words: \"Withdrew Tom Ellery's 3 pieces from kiln 2.\" */\n message: string;\n /** What the person reads if the commit fails, saying the item is back: \"Tom Ellery's 3 pieces are back in kiln 2: the withdrawal did not go through.\" */\n failure: string;\n /** Makes the removal real (usually a request, then invalidating the query the item came from). Runs once per attempt: when the window closes, on `flush()`, when a second removal is scheduled, or when the owner unmounts. */\n commit: () => void | Promise<unknown>;\n /** Called after a failed commit, for anything beyond restoring the item and showing the failure (which the hook does). The only failure path once the owner has unmounted. */\n onError?: (error: unknown) => void;\n};\n\n/** A removal whose commit failed: the removal, and the error described for a person. */\nexport type FailedRemoval = { removal: PendingRemoval; message?: string };\n\n/** Options for `useUndoable`. */\nexport type UndoableOptions = {\n /** How long Undo stays in reach, in milliseconds. Default 8000. */\n windowMs?: number;\n /** Describes a failed commit for a person, or returns undefined to show the removal's `failure` alone. Default `describeActionError`, as for `useAsyncAction`. */\n describeError?: (error: unknown) => string | undefined;\n};\n\n/** What `useUndoable` returns. Pass it whole to `UndoBar`. */\nexport type Undoable = {\n /** The removal inside its window, or null. */\n pending: PendingRemoval | null;\n /** The last removal whose commit failed, until it is retried, dismissed or another removal is scheduled. */\n failed: FailedRemoval | null;\n /** Whether an item is out of view: scheduled, committing or committed, and not undone or failed. Filter rows with it. */\n isRemoved: (id: string) => boolean;\n /** Removes an item and starts its window. Commits any removal already pending first: only one is pending at a time. */\n schedule: (next: PendingRemoval) => void;\n /** Cancels the pending removal and brings the item back; its `commit` never runs. */\n undo: () => void;\n /** Commits the pending removal now and resolves when it and every earlier commit still in flight have settled; rejects if any failed, so a dependent action does not run. Resolves at once when nothing is pending or running. */\n flush: () => Promise<void>;\n /** Removes the failed item again and commits it now (the person already waited out the window); settles like `flush`. */\n retry: () => Promise<void>;\n /** Clears the failure from the bar; the item stays back. */\n dismiss: () => void;\n};\n\n/**\n * Schedules a reversible removal to commit after a window unless undone, and owns which items\n * are out of view meanwhile.\n *\n * Only one removal is pending at a time: scheduling a second commits the first immediately.\n * Unmounting inside the window commits the pending removal (leaving is not Undo), so a navigation\n * or a test that unmounts still sends the commit's request: await `flush()` before a dependent\n * action, and in tests let MSW answer the request or flush before unmounting.\n */\nexport function useUndoable(options: number | UndoableOptions = {}): Undoable {\n const { windowMs = 8000, describeError = describeActionError } =\n typeof options === \"number\" ? { windowMs: options } : options;\n const [pending, setPending] = React.useState<PendingRemoval | null>(null);\n const [failed, setFailed] = React.useState<FailedRemoval | null>(null);\n const [removed, setRemoved] = React.useState<ReadonlySet<string>>(() => new Set());\n const current = React.useRef<PendingRemoval | null>(null);\n const timer = React.useRef<number | undefined>(undefined);\n const mounted = React.useRef(true);\n // Every commit still running, whoever started it: flush() waits for all of them, not only the\n // pending one, because an earlier removal's request may still be in flight (its window closed,\n // or a second removal committed it) and a dependent action must not overtake it.\n const inFlight = React.useRef(new Set<Promise<void>>());\n const describe = React.useRef(describeError);\n describe.current = describeError;\n\n const hide = React.useCallback((p: PendingRemoval, out: boolean) => {\n const ids = p.ids ?? [p.id];\n setRemoved((s) => {\n if (ids.every((id) => s.has(id) === out)) return s;\n const n = new Set(s);\n for (const id of ids) {\n if (out) n.add(id);\n else n.delete(id);\n }\n return n;\n });\n }, []);\n\n // Runs one attempt at a removal's commit. A synchronous throw is treated like a rejection, so\n // there is one failure path: bring the item back, show the failure, tell onError, reject.\n const attempt = React.useCallback(\n (p: PendingRemoval): Promise<void> => {\n let result: void | Promise<unknown>;\n try {\n result = p.commit();\n } catch (error) {\n result = Promise.reject(error);\n }\n const done = Promise.resolve(result).then(\n () => undefined,\n (error: unknown) => {\n if (mounted.current) {\n hide(p, false);\n setFailed({ removal: p, message: describe.current(error) });\n }\n p.onError?.(error);\n throw error;\n },\n );\n inFlight.current.add(done);\n const settle = () => void inFlight.current.delete(done);\n done.then(settle, settle);\n return done;\n },\n [hide],\n );\n\n // Takes the pending removal out (so it commits only once) and attempts it.\n const take = React.useCallback((): { removal: PendingRemoval; done: Promise<void> } | null => {\n window.clearTimeout(timer.current);\n const p = current.current;\n if (!p) return null;\n current.current = null;\n if (mounted.current) setPending(null);\n return { removal: p, done: attempt(p) };\n }, [attempt]);\n\n // Commits the hook starts itself (window closed, second removal, unmount) have no caller to\n // await them. A failure is handled once it is in the bar or onError has it; only a failure\n // nobody can see (unmounted, no onError) is left to surface as an unhandled rejection.\n const commitDetached = React.useCallback(() => {\n const t = take();\n t?.done.catch((error: unknown) => {\n if (!mounted.current && !t.removal.onError) throw error;\n });\n }, [take]);\n\n const schedule = React.useCallback(\n (next: PendingRemoval) => {\n commitDetached(); // a second removal commits the first\n setFailed(null);\n hide(next, true);\n current.current = next;\n setPending(next);\n timer.current = window.setTimeout(commitDetached, windowMs);\n },\n [commitDetached, hide, windowMs],\n );\n\n const undo = React.useCallback(() => {\n window.clearTimeout(timer.current);\n const p = current.current;\n current.current = null;\n setPending(null);\n if (p) hide(p, false);\n }, [hide]);\n\n const flush = React.useCallback(async () => {\n take();\n const results = await Promise.allSettled([...inFlight.current]);\n const failure = results.find((r): r is PromiseRejectedResult => r.status === \"rejected\");\n if (failure) throw failure.reason;\n }, [take]);\n\n const retry = React.useCallback(() => {\n if (!failed) return Promise.resolve();\n setFailed(null);\n hide(failed.removal, true);\n return attempt(failed.removal);\n }, [attempt, failed, hide]);\n\n const dismiss = React.useCallback(() => setFailed(null), []);\n\n const isRemoved = React.useCallback((id: string) => removed.has(id), [removed]);\n\n // Leaving the screen is not Undo: if the owner unmounts inside the window (the person navigated\n // away), commit what was scheduled rather than silently dropping it.\n React.useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n commitDetached();\n };\n }, [commitDetached]);\n\n return { pending, failed, isRemoved, schedule, undo, flush, retry, dismiss };\n}\n\n// The bar lives in a polite live region that is always mounted, so screen readers hear the message\n// when it appears, and a failure replaces the message in the same place the person was looking.\n// It is fixed to the bottom of the viewport; a page that uses it keeps that much bottom padding so\n// the bar never covers the focused row. A failure stays until it is retried or dismissed: an error\n// that times out is one a person can miss.\n/** The polite live region that shows a pending removal with Undo, or a failed one with Try again. Pass it the whole `useUndoable()` result. */\nexport function UndoBar({\n undoable,\n inline = false,\n}: {\n undoable: Pick<Undoable, \"pending\" | \"failed\" | \"undo\" | \"retry\" | \"dismiss\">;\n /** Render in the flow instead of fixed to the viewport; for the state-matrix page. */\n inline?: boolean;\n}) {\n const { pending, failed, undo, retry, dismiss } = undoable;\n const ghost = \"text-background hover:bg-neutral-11\";\n return (\n <div\n aria-live=\"polite\"\n className={\n inline ? \"flex\" : \"layer-bar pointer-events-none fixed inset-x-0 bottom-4 flex justify-center px-4\"\n }\n >\n {(pending || failed) && (\n <div className=\"pointer-events-auto flex max-w-lg items-center gap-4 rounded-overlay bg-foreground py-2 pr-2 pl-4 text-background shadow-overlay\">\n {pending ? (\n <>\n <p className=\"min-w-0 type-body-sm\">{pending.message}</p>\n <Button size=\"sm\" variant=\"ghost\" className={ghost} onClick={undo}>\n Undo\n </Button>\n </>\n ) : (\n failed && (\n <>\n <p className=\"min-w-0 type-body-sm\">\n {failed.message ? `${failed.removal.failure} ${failed.message}` : failed.removal.failure}\n </p>\n <div className=\"flex shrink-0 gap-1\">\n <Button size=\"sm\" variant=\"ghost\" className={ghost} onClick={() => void retry().catch(() => undefined)}>\n Try again\n </Button>\n <Button size=\"sm\" variant=\"ghost\" className={ghost} onClick={dismiss}>\n Dismiss\n </Button>\n </div>\n </>\n )\n )}\n </div>\n )}\n </div>\n );\n}\n","import * as React from \"react\";\nimport { Check } from \"lucide-react\";\nimport { cn } from \"../lib/utils\";\n\n// The completion moment: what a person sees after finishing something that took effort (a\n// booking, a submission, an import). It is the one place on an Operate product where the library\n// spends its delight budget (character.md §3), so it is a component with rules rather than a\n// confetti call:\n// - `title` says what happened, in the past tense, with the object: \"Booked: 6 pieces in kiln 2\".\n// - `next` is required. A finish that does not say what happens now is a dead end, however\n// pleasant.\n// - `figure` is optional and must be drawn from the person's own data in the subject's terms\n// (their pieces on a shelf, their route on a map), never a stock illustration.\n// - The part of the figure that is the person's result enters once, with the `enter-moment`\n// utility (500ms, hard ease-out, no overshoot): their pieces set down on the shelf. Reduced\n// motion makes it instant. Nothing loops and nothing plays a sound.\n// - Focus moves to the heading on mount, so keyboard and screen-reader users land on the result.\n\n/** The completion moment for a rare, earned finish: what happened (past tense, with its object), what happens next, and optionally a figure drawn from the person's own data. Focus moves to the heading. */\nexport function Done({\n title,\n next,\n figure,\n actions,\n focusOnMount = true,\n className,\n}: {\n /** What happened, past tense, with its object. */\n title: string;\n /** What the person does now, or what happens next and when. */\n next: React.ReactNode;\n /** A drawing of the result made from the person's data in the subject's own terms. */\n figure?: React.ReactNode;\n actions?: React.ReactNode;\n /** Off only where the result is not the page's subject (the state-matrix page). */\n focusOnMount?: boolean;\n className?: string;\n}) {\n const heading = React.useRef<HTMLHeadingElement>(null);\n const titleId = React.useId();\n React.useEffect(() => {\n if (focusOnMount) heading.current?.focus();\n }, [focusOnMount]);\n return (\n <section aria-labelledby={titleId} className={cn(\"grid gap-5\", className)}>\n <div className=\"grid gap-2\">\n <h1 id={titleId} ref={heading} tabIndex={-1} className=\"flex items-start gap-2 type-title\">\n <Check aria-hidden className=\"mt-1 size-6 shrink-0 text-success\" />\n {title}\n </h1>\n <div className=\"max-w-prose type-body text-muted-foreground\">{next}</div>\n </div>\n {figure}\n {actions && <div className=\"flex flex-wrap items-center gap-3\">{actions}</div>}\n </section>\n );\n}\n","import * as React from \"react\";\nimport { Link, NavLink } from \"react-router\";\nimport { cn } from \"../lib/utils\";\nimport type { IconComponent } from \"../lib/icon\";\n\n// The frame of an app: a side nav on the page ground (not a navy or tinted sidebar), the current\n// item as a neutral pill (no left bar, no accent), and the page beside it. A top bar exists only\n// when it holds something used on every screen, so it is a slot, not a default. Built on React\n// Router's NavLink, so \"current\" is the router's answer and aria-current is set for free. On\n// phones the nav becomes a horizontal, scrollable row above the page rather than a hamburger, so\n// every destination stays one tap away.\n\nexport type NavItem = {\n to: string;\n label: string;\n icon?: IconComponent;\n /** Match only this exact path, for an index route such as \"/\". */\n end?: boolean;\n};\n\n/** The app frame: product name, side nav on the page ground (a scrollable row on phones), optional top bar, and the main region. */\nexport function AppShell({\n product,\n nav,\n navLabel = \"Main\",\n topBar,\n children,\n className,\n}: {\n /** The product's name or mark, linking home. */\n product: React.ReactNode;\n nav: NavItem[];\n navLabel?: string;\n topBar?: React.ReactNode;\n children: React.ReactNode;\n className?: string;\n}) {\n return (\n <div className={cn(\"min-h-dvh md:grid md:grid-cols-[14rem_minmax(0,1fr)]\", className)}>\n <aside className=\"border-b border-border md:border-r md:border-b-0\">\n <div className=\"flex items-center gap-4 px-4 py-3 md:block md:px-3 md:py-4\">\n <Link to=\"/\" className=\"shrink-0 rounded-control px-2 type-heading text-foreground no-underline\">\n {product}\n </Link>\n <SideNav items={nav} label={navLabel} className=\"min-w-0 flex-1 md:mt-4\" />\n </div>\n </aside>\n <div className=\"min-w-0\">\n {topBar && <div className=\"flex items-center gap-3 border-b border-border px-4 py-2 md:px-8\">{topBar}</div>}\n <main className=\"px-4 py-6 md:px-8 md:py-8\">{children}</main>\n </div>\n </div>\n );\n}\n\n/** Navigation links (React Router `NavLink`); the current route is a neutral pill with `aria-current`. */\nexport function SideNav({ items, label, className }: { items: NavItem[]; label: string; className?: string }) {\n return (\n <nav aria-label={label} className={cn(\"min-w-0\", className)}>\n <ul className=\"flex gap-1 overflow-x-auto md:grid md:overflow-visible\">\n {items.map(({ to, label, icon: Icon, end }) => (\n <li key={to} className=\"shrink-0\">\n <NavLink\n to={to}\n end={end}\n className={({ isActive }) =>\n cn(\n \"flex h-(--control-h-sm) items-center gap-2 rounded-control px-2 type-label whitespace-nowrap no-underline transition-state\",\n isActive ? \"bg-muted text-foreground\" : \"text-muted-foreground hover:bg-muted hover:text-foreground\",\n )\n }\n >\n {Icon && <Icon aria-hidden className=\"size-4 shrink-0\" />}\n {label}\n </NavLink>\n </li>\n ))}\n </ul>\n </nav>\n );\n}\n\n// Plain links with a \"/\" separator in muted ink. The last crumb is the current page: text, not a\n// link, with aria-current.\n/** Plain links separated by `/`; the last crumb is the current page. */\nexport function Breadcrumb({ items }: { items: { label: string; to?: string }[] }) {\n return (\n <nav aria-label=\"Breadcrumb\">\n <ol className=\"flex flex-wrap items-center gap-x-2 type-body-sm text-muted-foreground\">\n {items.map((item, i) => {\n const last = i === items.length - 1;\n return (\n <li key={`${item.label}-${i}`} className=\"flex items-center gap-2\">\n {item.to && !last ? (\n <Link to={item.to} className=\"text-muted-foreground underline hover:text-foreground\">\n {item.label}\n </Link>\n ) : (\n <span aria-current={last ? \"page\" : undefined} className={cn(last && \"text-foreground\")}>\n {item.label}\n </span>\n )}\n {!last && <span aria-hidden>/</span>}\n </li>\n );\n })}\n </ol>\n </nav>\n );\n}\n","import * as React from \"react\";\nimport { useSearchParams } from \"react-router\";\nimport { Tab, TabList, TabPanel, Tabs as AriaTabs } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\n\n// Tabs whose state lives in the URL (?view=readings), so a tab can be linked, survives reload and\n// works with Back. Built on React Aria Tabs (ARIA tabs pattern: arrow keys move between tabs and\n// select them, Home and End jump, only the selected tab is in the tab order). The selected tab is marked by weight and a\n// 2px rule in ink, not by colour alone. The first tab is the default and is not written to the URL.\n\nexport type TabItem = { value: string; label: string };\n\n/** Tabs whose selection lives in a URL search parameter (React Router), with the ARIA tabs keyboard model. */\nexport function Tabs({\n param,\n items,\n label,\n children,\n className,\n}: {\n /** The search parameter that holds the selected tab. */\n param: string;\n items: TabItem[];\n /** Names the tab list for screen readers. */\n label: string;\n /** Renders the selected panel. */\n children: (value: string) => React.ReactNode;\n className?: string;\n}) {\n const [params, setParams] = useSearchParams();\n const fallback = items[0]?.value ?? \"\";\n const raw = params.get(param);\n const value = items.some((i) => i.value === raw) ? raw! : fallback;\n const select = (next: string) =>\n setParams(\n (p) => {\n const out = new URLSearchParams(p);\n if (next === fallback) out.delete(param);\n else out.set(param, next);\n return out;\n },\n { replace: true },\n );\n\n // React Aria's Tabs owns the keyboard model (arrows, Home and End, roving tab stop, automatic\n // activation) and the ids that tie each tab to the panel; the selected key is the URL's.\n return (\n <AriaTabs selectedKey={value} onSelectionChange={(key) => select(String(key))} className={cn(\"grid gap-4\", className)}>\n <TabList aria-label={label} className=\"flex gap-4 overflow-x-auto border-b border-border\">\n {items.map((item) => (\n <Tab\n key={item.value}\n id={item.value}\n className={cn(\n \"-mb-px cursor-pointer border-b-2 py-2 type-label whitespace-nowrap transition-state\",\n \"border-transparent text-muted-foreground hover:text-foreground\",\n \"selected:border-foreground selected:font-semibold selected:text-foreground\",\n )}\n >\n {item.label}\n </Tab>\n ))}\n </TabList>\n <TabPanel id={value} shouldForceMount={false}>\n {children(value)}\n </TabPanel>\n </AriaTabs>\n );\n}\n","import * as React from \"react\";\nimport { cn } from \"../lib/utils\";\nimport { isTypingTarget, type Shortcut } from \"./hotkeys\";\n\n// A queue someone works through from the keyboard: one item is active, j/k (or the arrow keys\n// inside the list) move it, and answering an item moves straight on to the next one. Three\n// decisions shape it:\n// 1. The active item is the one with focus. It is a roving tab stop (only it is in the tab order)\n// and carries aria-current, so a screen reader hears which item an answer applies to. It is\n// marked by a 2px rule in ink as well as a tint, not by colour alone.\n// 2. When the active item leaves the list (accepted, rejected, removed), the item that took its\n// place becomes active, or the one before it at the end of the list, and focus follows if it\n// was in the list. Otherwise focus would fall to <body> and the next key would do nothing.\n// 3. The hook remembers which item the person chose, not just a position. If an Undo puts the\n// item back, it is active again (pairs with `useUndoable`).\n// Moving is instant: no transition on the highlight (ux-research `ux-character.md`, 100+ a day).\n\n/** What `useActiveItem` returns: the active item, ways to move it, and the props each item element needs. */\nexport type ActiveItem<T> = {\n items: readonly T[];\n getKey: (item: T) => string;\n activeKey: string | null;\n activeItem: T | null;\n /** Position of the active item, or -1 when the list is empty. */\n index: number;\n next: () => void;\n prev: () => void;\n first: () => void;\n last: () => void;\n setActive: (key: string) => void;\n /** The j/k shortcuts for `useHotkeys` and `KeysLegend`. */\n shortcuts: Shortcut[];\n /** Props for the element that represents an item: ref, tabIndex, aria-current and focus tracking. */\n itemProps: (key: string) => {\n ref: (el: HTMLElement | null) => void;\n tabIndex: number;\n \"aria-current\": \"true\" | undefined;\n \"data-active\": \"\" | undefined;\n onFocus: () => void;\n onBlur: (e: React.FocusEvent) => void;\n };\n};\n\n/** Tracks the active item in a list worked through from the keyboard: moving, roving focus, and moving on when the active item is removed. */\nexport function useActiveItem<T>(\n items: readonly T[],\n getKey: (item: T) => string,\n {\n initial,\n noun,\n }: {\n /** Key of the item active at first; the first item otherwise. */\n initial?: string;\n /** Names an item in the shortcut labels: \"Next booking\". */\n noun?: string;\n } = {},\n): ActiveItem<T> {\n const [chosen, setChosen] = React.useState<string | null>(initial ?? null);\n const lastIndex = React.useRef(0);\n const elements = React.useRef(new Map<string, HTMLElement>());\n const navigated = React.useRef(false);\n const focusWithin = React.useRef(false);\n\n const keys = items.map(getKey);\n let index = chosen === null ? -1 : keys.indexOf(chosen);\n if (index === -1 && keys.length > 0) index = Math.min(lastIndex.current, keys.length - 1);\n const activeKey = index >= 0 ? keys[index] : null;\n\n // Remember the position, and the last item that left the list while active. Answering two in a\n // row (at the end of the queue, say) must make the second the one an Undo brings back as\n // active, not the first.\n const prevActive = React.useRef<string | null>(activeKey);\n React.useLayoutEffect(() => {\n if (index >= 0) lastIndex.current = index;\n const gone = prevActive.current;\n prevActive.current = activeKey;\n if (gone !== null && gone !== chosen && !keys.includes(gone)) setChosen(gone);\n });\n\n // Move focus to the active item when the person moved it, when the focused item was removed\n // (focus has fallen to <body>), or when focus is on another item in the list (an Undo made the\n // restored item active again). Never take focus from somewhere else on the page.\n React.useLayoutEffect(() => {\n const el = activeKey === null ? undefined : elements.current.get(activeKey);\n const focused = document.activeElement;\n const lost = focusWithin.current && (focused === null || focused === document.body);\n const elsewhereInList =\n focused !== null && !el?.contains(focused) && [...elements.current.values()].some((item) => item.contains(focused));\n if (el && (navigated.current || lost || elsewhereInList)) {\n el.focus({ preventScroll: true });\n el.scrollIntoView?.({ block: \"nearest\" });\n }\n navigated.current = false;\n }, [activeKey]);\n\n const moveTo = (i: number) => {\n if (keys.length === 0) return;\n const to = Math.max(0, Math.min(keys.length - 1, i));\n navigated.current = true;\n if (to === index) {\n // Already there: still bring focus back to it, as the person asked to move.\n const el = elements.current.get(keys[to]);\n el?.focus({ preventScroll: true });\n el?.scrollIntoView?.({ block: \"nearest\" });\n navigated.current = false;\n }\n setChosen(keys[to]);\n };\n\n const next = () => moveTo(index + 1);\n const prev = () => moveTo(index - 1);\n const first = () => moveTo(0);\n const last = () => moveTo(keys.length - 1);\n const setActive = (key: string) => {\n const i = keys.indexOf(key);\n if (i >= 0) moveTo(i);\n };\n\n const name = noun ? ` ${noun}` : \"\";\n const shortcuts: Shortcut[] = [\n { keys: [\"j\"], label: `Next${name}`, run: next, repeat: true, disabled: keys.length === 0 },\n { keys: [\"k\"], label: `Previous${name}`, run: prev, repeat: true, disabled: keys.length === 0 },\n ];\n\n const itemProps: ActiveItem<T>[\"itemProps\"] = (key) => ({\n ref: (el) => {\n if (el) elements.current.set(key, el);\n else elements.current.delete(key);\n },\n tabIndex: key === activeKey ? 0 : -1,\n \"aria-current\": key === activeKey ? \"true\" : undefined,\n \"data-active\": key === activeKey ? \"\" : undefined,\n onFocus: () => {\n focusWithin.current = true;\n // Clicking or tabbing into an item makes it active. If it already is (it took a removed\n // item's place), keep remembering the removed one so an Undo makes that active again.\n if (key !== activeKey) setChosen(key);\n },\n onBlur: (e) => {\n // Focus going nowhere (null) is what removal looks like, so only a move to a real element\n // outside the list counts as leaving it.\n const to = e.relatedTarget;\n if (to instanceof Node && ![...elements.current.values()].some((el) => el.contains(to))) focusWithin.current = false;\n },\n });\n\n return {\n items,\n getKey,\n activeKey,\n activeItem: index >= 0 ? items[index] : null,\n index,\n next,\n prev,\n first,\n last,\n setActive,\n shortcuts,\n itemProps,\n };\n}\n\n// The list renders the queue from `useActiveItem`. The arrow keys, Home and End move the active\n// item while focus is in the list (the window-wide j/k come from `active.shortcuts` via\n// `useHotkeys`, because only the screen knows whether it has one queue or two). An empty queue\n// is a state the list cannot be written without: say what clearing it means and what is next.\n/** A keyboard-worked queue: the active item is a roving tab stop with aria-current, and the arrow keys, Home and End move it. */\nexport function ActiveList<T>({\n label,\n active,\n empty,\n children,\n className,\n}: {\n /** Names the list for screen readers. */\n label: string;\n active: ActiveItem<T>;\n /** Shown when the queue is clear: what that means and what to do next. */\n empty: React.ReactNode;\n children: (item: T, state: { active: boolean }) => React.ReactNode;\n className?: string;\n}) {\n if (active.items.length === 0) return <>{empty}</>;\n\n const onKeyDown = (e: React.KeyboardEvent) => {\n if (e.ctrlKey || e.metaKey || e.altKey || isTypingTarget(e.target)) return;\n const move =\n e.key === \"ArrowDown\" ? active.next\n : e.key === \"ArrowUp\" ? active.prev\n : e.key === \"Home\" ? active.first\n : e.key === \"End\" ? active.last\n : undefined;\n if (!move) return;\n e.preventDefault();\n move();\n };\n\n return (\n <ul aria-label={label} onKeyDown={onKeyDown} className={cn(\"grid gap-px\", className)}>\n {active.items.map((item) => {\n const key = active.getKey(item);\n const isActive = key === active.activeKey;\n return (\n <li\n key={key}\n {...active.itemProps(key)}\n className={cn(\n \"rounded-control border-l-2 px-3 py-2 -outline-offset-2\",\n isActive ? \"border-foreground bg-accent text-accent-foreground\" : \"border-transparent\",\n )}\n >\n {children(item, { active: isActive })}\n </li>\n );\n })}\n </ul>\n );\n}\n","import * as React from \"react\";\nimport { hashKey, useInfiniteQuery, type QueryKey } from \"@tanstack/react-query\";\nimport type { Load } from \"../components/data-view\";\nimport { describeHttpError, staleOf, type DescribeError } from \"./index\";\n\n// Cursor-paged reads, the Strata way. `useLoad` covers a read that arrives whole; a feed, a log or\n// a triage queue arrives a page at a time. This is the same bridge for those: TanStack's\n// useInfiniteQuery underneath, a `Load<T[]>` on top (so `DataView` takes it unchanged for the\n// first page's loading, error and empty states), and a `more` object for everything after it.\n//\n// Three opinions:\n// 1. The cursor is \"after the last item held\", never an offset, and the hook works it out: the\n// app says how to make a cursor from an item (`cursorAfter`) and whether a page says there are\n// more (`hasMore`). In a queue people work through (answered reviews, archived firings), items\n// leave the server's list between pages, and an offset would skip the ones that moved up to\n// fill the gap. Two cases fall back to the last item *seen*, dismissed or not: when everything\n// held has been dismissed (there is no held item to go after, and starting again from the top\n// could fetch the same dismissed page forever), and when the last page brought nothing new\n// (only items already held or dismissed came back, so going after the last held item again\n// would ask for the same page in a loop).\n// 2. Items have keys. Pages are merged by key, so an item that shifts across a page boundary is\n// shown once, and `dismiss(key)` hides one at once (an optimistic remove, paired with\n// useUndoable) without the app rewriting TanStack's page cache by hand. Dismissals belong to\n// one query: a new `queryKey` (another filter) starts with none. A screen that removes items\n// with `useUndoable` passes its `isRemoved` instead, so the undo hook stays the one owner of\n// what is out of view (Undo, a failed commit and Try again all show through) and the cursor\n// still skips past what it hides.\n// 3. A later page failing is not the list failing. The held items stay; `more.error` says what\n// happened and `more.loadMore` is the Try again. A refetch of the held pages failing is not the\n// list failing either: the items stay and `stale` says how old they are, as with `useLoad`.\n// Only a failed first page is a `Load` error.\n\n/** The state of the pages after the first: whether there are more, whether one is on its way, and why the last one failed. */\nexport type More = {\n /** The server has said there is another page. */\n hasMore: boolean;\n /** A page after the first is being fetched. */\n loadingMore: boolean;\n /** Why the last page after the first failed, for a person. Cleared when a retry succeeds. */\n error?: string;\n /** Fetch the next page; also the Try again after `error`. Does nothing while one is loading or when there are no more. */\n loadMore: () => void;\n};\n\n/** A cursor-paged read: a `Load<T[]>` of the items held (so `DataView` takes it), plus the next page's state and keyed removal. */\nexport type InfiniteLoad<T> = Load<T[]> & {\n more: More;\n itemKey: (item: T) => string;\n /** Hide an item at once (an optimistic removal). The next cursor goes after the last item still held. */\n dismiss: (key: string) => void;\n /** Show a dismissed item again: the Undo of `dismiss`. */\n restore: (key: string) => void;\n};\n\n/** Options for `useInfiniteLoad`. */\nexport type InfiniteLoadOptions<T, Page, Cursor, K extends QueryKey> = {\n queryKey: K;\n /** Fetch one page. `cursor` is undefined for the first page, else `cursorAfter` of the last item held. */\n queryFn: (context: { cursor: Cursor | undefined; signal: AbortSignal }) => Promise<Page>;\n /** The items in a page. For an API that returns a bare array, `(page) => page`. */\n items: (page: Page) => T[];\n /** A stable key per item: merges pages, and is what `dismiss` takes. */\n itemKey: (item: T) => string;\n /** Whether the server says there is a page after this one. */\n hasMore: (lastPage: Page) => boolean;\n /** The cursor that asks for the items after this one; usually its id. Defaults to `itemKey`. */\n cursorAfter?: (item: T) => Cursor;\n /** Items hidden by someone else, usually `useUndoable().isRemoved`: treated like dismissed ones. */\n isRemoved?: (key: string) => boolean;\n describeError?: DescribeError;\n enabled?: boolean;\n staleTime?: number;\n};\n\ntype Dismissed = { query: string; keys: ReadonlySet<string> };\ntype PageParam<Cursor> = { cursor: Cursor | undefined };\n\n/** `useInfiniteQuery` for cursor-paged data, returned as an `InfiniteLoad<T>` for `InfiniteList` (or `DataView`). */\nexport function useInfiniteLoad<T, Page, Cursor = string, K extends QueryKey = QueryKey>({\n queryKey,\n queryFn,\n items,\n itemKey,\n hasMore,\n cursorAfter = itemKey as unknown as (item: T) => Cursor,\n isRemoved,\n describeError = describeHttpError,\n enabled,\n staleTime,\n}: InfiniteLoadOptions<T, Page, Cursor, K>): InfiniteLoad<T> {\n const queryHash = hashKey(queryKey);\n const [stored, setStored] = React.useState<Dismissed>(() => ({ query: queryHash, keys: new Set() }));\n const dismissed = stored.query === queryHash ? stored.keys : none;\n const hidden = React.useCallback((key: string) => dismissed.has(key) || (isRemoved?.(key) ?? false), [dismissed, isRemoved]);\n // TanStack calls getNextPageParam outside render; it reads the latest hidden set and accessors.\n const latest = React.useRef({ hidden, items, itemKey, hasMore, cursorAfter });\n latest.current = { hidden, items, itemKey, hasMore, cursorAfter };\n\n const query = useInfiniteQuery({\n queryKey,\n queryFn: ({ pageParam, signal }) => queryFn({ cursor: pageParam.cursor, signal }),\n initialPageParam: { cursor: undefined } as PageParam<Cursor>,\n getNextPageParam: (lastPage, pages): PageParam<Cursor> | null => {\n const l = latest.current;\n if (!l.hasMore(lastPage)) return null;\n const after = nextAfter(pages, l.items, l.itemKey, l.hidden);\n return { cursor: after === undefined ? undefined : l.cursorAfter(after) };\n },\n enabled,\n staleTime,\n });\n\n const pages = query.data?.pages;\n // Keyed on the pages and dismissals only, so inline `items`/`itemKey` arrows do not hand the\n // list a new array every render.\n const list = React.useMemo(\n () => (pages ? merge(pages, latest.current.items, latest.current.itemKey, hidden).held : undefined),\n [pages, hidden],\n );\n\n const { hasNextPage, isFetchingNextPage, fetchNextPage, refetch } = query;\n const loadMore = React.useCallback(() => {\n if (hasNextPage && !isFetchingNextPage) void fetchNextPage();\n }, [hasNextPage, isFetchingNextPage, fetchNextPage]);\n const change = React.useCallback(\n (edit: (keys: Set<string>) => void) =>\n setStored((s) => {\n const keys = new Set(s.query === queryHash ? s.keys : none);\n edit(keys);\n return { query: queryHash, keys };\n }),\n [queryHash],\n );\n const dismiss = React.useCallback((key: string) => change((keys) => keys.add(key)), [change]);\n const restore = React.useCallback((key: string) => change((keys) => keys.delete(key)), [change]);\n\n const more: More = {\n hasMore: Boolean(hasNextPage),\n loadingMore: isFetchingNextPage,\n error: query.isFetchNextPageError ? describeError(query.error) : undefined,\n loadMore,\n };\n const extra = { more, itemKey, dismiss, restore };\n if (list) {\n // isRefetchError excludes a failed next page, which is `more.error`'s to report.\n const stale = query.isRefetchError ? staleOf(query, describeError) : undefined;\n return { status: \"ready\", data: list, ...(stale && { stale }), ...extra };\n }\n if (query.status === \"error\") return { status: \"error\", message: describeError(query.error), retry: () => void refetch(), ...extra };\n return { status: \"loading\", ...extra };\n}\n\nconst none: ReadonlySet<string> = new Set();\n\n/** Every page's items, in order, once each by key: the ones held (not dismissed) and the last one seen. */\nfunction merge<T, Page>(pages: Page[], items: (page: Page) => T[], itemKey: (item: T) => string, hidden: (key: string) => boolean) {\n const seen = new Set<string>();\n const held: T[] = [];\n let last: T | undefined;\n let lastPageAddedAny = false;\n pages.forEach((page, p) => {\n for (const item of items(page)) {\n const key = itemKey(item);\n if (seen.has(key)) continue;\n seen.add(key);\n last = item;\n if (p === pages.length - 1) lastPageAddedAny = true;\n if (!hidden(key)) held.push(item);\n }\n });\n return { held, last, lastPageAddedAny };\n}\n\n/** The item the next page goes after: the last held, or the last seen when nothing is held or the last page brought nothing new. */\nfunction nextAfter<T, Page>(pages: Page[], items: (page: Page) => T[], itemKey: (item: T) => string, hidden: (key: string) => boolean) {\n const { held, last, lastPageAddedAny } = merge(pages, items, itemKey, hidden);\n if (held.length === 0 || (pages.length > 1 && !lastPageAddedAny)) return last;\n return held[held.length - 1];\n}\n","import * as React from \"react\";\nimport { hashKey, useQuery, useQueryClient, type QueryKey, type UseQueryOptions } from \"@tanstack/react-query\";\nimport type { Load } from \"../components/data-view\";\nimport type { DescribeError } from \"../lib/errors\";\nimport { toLoad } from \"./index\";\n\n// The read behind `JobStatus` (strata-react issue #45): a job's status, polled while it runs and\n// not otherwise, and the data it changed read again once, when it ends. Tubes wrote this as\n// `useLoad({ refetchInterval })` plus an effect watching `running` go from true to false; every\n// app with a job would write the same two pieces and get the second one subtly wrong (invalidating\n// on the first read of a job that had already finished, or on every poll). Here:\n//\n// - `isRunning(data)` says whether the job is going; the query polls `every` ms (default 2000)\n// only then, so an idle screen makes one request, not one every two seconds.\n// - `invalidates` names the queries the job changes; they are invalidated once, on the poll that\n// first sees the job stopped after one that saw it running, for the same query: a first read\n// of a finished job invalidates nothing, and neither does switching to another job's key (the\n// new query has no status yet, which is not the old job ending). The keys invalidated are the\n// ones given while that job was seen running.\n// - `poll()` reads the status now: the commit of the button that starts the job calls it, so\n// polling begins without waiting for a stale time.\n// - The result is a `Load<T>` (so a failed poll keeps the last status on screen with `stale`, as\n// any read does), plus `running`.\n\n/** Options for `useJob`: a query's, plus how to tell the job is running, how often to poll, and what it changes. */\nexport type JobOptions<T, K extends QueryKey = QueryKey> = UseQueryOptions<T, Error, T, K> & {\n /** Whether the status says the job is still going. */\n isRunning: (data: T) => boolean;\n /** Milliseconds between polls while it runs. Default 2000. */\n every?: number;\n /** Query keys the job changes, invalidated once when it ends. */\n invalidates?: QueryKey[];\n describeError?: DescribeError;\n};\n\n/** What `useJob` returns: the status as a `Load<T>`, whether the job is running, and `poll` to read it now. */\nexport type Job<T> = Load<T> & {\n /** The latest status says the job is going. */\n running: boolean;\n /** Read the status now, as after starting the job. */\n poll: () => void;\n};\n\n/** A long-running job's status: polled every `every` ms while `isRunning`, with the `invalidates` queries read again once when it ends. */\nexport function useJob<T, K extends QueryKey = QueryKey>({\n isRunning,\n every = 2000,\n invalidates = [],\n describeError,\n ...options\n}: JobOptions<T, K>): Job<T> {\n const client = useQueryClient();\n const query = useQuery({\n ...options,\n refetchInterval: (q) => (q.state.data !== undefined && isRunning(q.state.data) ? every : false),\n });\n const running = query.data !== undefined && isRunning(query.data);\n\n // What was last seen, for one query: whether its job ran, and what it said it would change.\n // Only a status that has arrived counts; no data yet (a new key loading) is not \"stopped\".\n const queryHash = hashKey(options.queryKey);\n const seen = query.data === undefined ? undefined : running;\n const was = React.useRef<{ query: string; running: boolean; invalidates: QueryKey[] } | undefined>(undefined);\n React.useEffect(() => {\n if (seen === undefined) return;\n const before = was.current;\n if (before && before.query === queryHash && before.running && !seen) {\n for (const queryKey of before.invalidates) void client.invalidateQueries({ queryKey });\n }\n was.current = { query: queryHash, running: seen, invalidates };\n });\n\n const { refetch } = query;\n const poll = React.useCallback(() => void refetch(), [refetch]);\n return { ...toLoad(query, describeError), running, poll };\n}\n","// The arithmetic of a shared zoom and pan, kept apart from the DOM so it is unit tested without a\n// layout engine (jsdom has none). Used by `ViewportFrame` and so by every comparison view.\n//\n// Scale is relative to \"fit\" (1 = the whole picture inside its frame). The offset is in pixels from\n// the frame's centre, and the picture's transform origin is that centre, so zooming about a point\n// is one line of algebra and a fit picture is always centred.\n\n/** Zoom and pan of a picture inside its frame. `scale` 1 is the picture fitted; `x` and `y` are pixels from the centre. */\nexport type Viewport = { scale: number; x: number; y: number };\n\n/** The picture fitted in its frame, not panned. */\nexport const FIT: Viewport = { scale: 1, x: 0, y: 0 };\n\n/** The least zoom: the whole picture fitted. */\nexport const MIN_SCALE = 1;\n/** The most zoom, 32 times the fit. */\nexport const MAX_SCALE = 32;\n\n/** Keeps the picture from being dragged out of its frame: at most half the extra width or height past each edge. */\nexport function clampViewport(v: Viewport, frame: { width: number; height: number }): Viewport {\n const scale = Math.min(MAX_SCALE, Math.max(MIN_SCALE, v.scale));\n if (scale === MIN_SCALE) return FIT;\n const mx = ((scale - 1) * frame.width) / 2;\n const my = ((scale - 1) * frame.height) / 2;\n return { scale, x: Math.min(mx, Math.max(-mx, v.x)), y: Math.min(my, Math.max(-my, v.y)) };\n}\n\n/** A new scale with the point under `at` (pixels from the frame's centre) staying under it. */\nexport function zoomAt(v: Viewport, nextScale: number, at: { x: number; y: number }, frame: { width: number; height: number }): Viewport {\n const scale = Math.min(MAX_SCALE, Math.max(MIN_SCALE, nextScale));\n const k = scale / v.scale;\n return clampViewport({ scale, x: at.x - k * (at.x - v.x), y: at.y - k * (at.y - v.y) }, frame);\n}\n\n/** The scale at which the picture's own pixels are drawn one to one: its natural width over the width it is fitted at. */\nexport function actualPixelsScale(naturalWidth: number, fittedWidth: number): number {\n if (!naturalWidth || !fittedWidth) return 1;\n return Math.min(MAX_SCALE, Math.max(MIN_SCALE, naturalWidth / fittedWidth));\n}\n\n/** The CSS transform for a viewport. */\nexport function viewportTransform(v: Viewport): string {\n return `translate(${v.x}px, ${v.y}px) scale(${v.scale})`;\n}\n","import * as React from \"react\";\nimport { Dialog as AriaDialog, Modal, ModalOverlay } from \"react-aria-components\";\nimport { cn } from \"../lib/utils\";\nimport { overlaySurface } from \"../lib/overlay\";\n\n// Full screen for a picture, a pair to compare or a player: the thing being judged gets the whole\n// screen, with its controls still around it. The browser's Fullscreen API is the first choice,\n// because it hides the browser's own chrome too; the iPhone's Safari has no such API for anything\n// but video, so there the same content opens in a React Aria modal that fills the window. Either\n// way the caller holds `active` (so a key and a button can both toggle it), and zoom, mode and the\n// question being answered live in the caller's state, so they survive the change. In the modal the\n// content is re-mounted (an image is drawn again from the browser's cache); natively it is not.\n//\n// React Aria checked: `Modal`/`ModalOverlay` give the fallback its focus containment, inert page\n// behind it and Escape; they do not offer the Fullscreen API, which is why the native path is\n// ours (an effect on `requestFullscreen` and the `fullscreenchange` event, the browser's own way\n// to say the person pressed Escape). If the browser refuses (it needs a recent click or key) the\n// fallback is used, so asking for full screen never silently does nothing.\n\n/** Props for `FullscreenFrame`. */\nexport type FullscreenFrameProps = {\n /** Names the full-screen view for screen readers: \"Compare renderings\". Required. */\n label: string;\n /** Whether the frame is full screen. The caller owns it so a button and a key can share it. */\n active: boolean;\n /** Called with `false` when the person leaves with Escape or the browser's own control. */\n onActiveChange: (active: boolean) => void;\n children: React.ReactNode;\n className?: string;\n};\n\n/** Whether this browser can show an element full screen. False in jsdom and on iPhone, where the modal fallback is used. */\nexport function canFullscreen(): boolean {\n return typeof document !== \"undefined\" && document.fullscreenEnabled === true && typeof Element.prototype.requestFullscreen === \"function\";\n}\n\n/** Shows its children full screen while `active`: the browser's Fullscreen API where there is one, a window-filling modal where there is not. */\nexport function FullscreenFrame({ label, active, onActiveChange, children, className }: FullscreenFrameProps) {\n const ref = React.useRef<HTMLDivElement>(null);\n const [native, setNative] = React.useState(false);\n const [refused, setRefused] = React.useState(false);\n const change = React.useRef(onActiveChange);\n change.current = onActiveChange;\n\n React.useEffect(() => {\n const el = ref.current;\n if (!active) {\n setNative(false);\n setRefused(false);\n if (document.fullscreenElement && document.fullscreenElement === el) void document.exitFullscreen();\n return;\n }\n if (!el || !canFullscreen()) return;\n let cancelled = false;\n el.requestFullscreen().then(\n () => !cancelled && setNative(true),\n () => !cancelled && setRefused(true), // refused (no recent click or key, say): the modal below opens instead\n );\n const onChange = () => {\n if (document.fullscreenElement !== el && !cancelled) change.current(false);\n };\n document.addEventListener(\"fullscreenchange\", onChange);\n return () => {\n cancelled = true;\n document.removeEventListener(\"fullscreenchange\", onChange);\n };\n }, [active]);\n\n // The modal is the answer where the browser cannot, or has refused. While a request is in flight the content stays in place.\n const modal = active && !native && (!canFullscreen() || refused);\n const inner = (\n <div ref={ref} className={cn(active && \"flex h-full min-h-0 flex-col bg-background p-4\", className)}>\n {children}\n </div>\n );\n if (!modal) return inner;\n return (\n <ModalOverlay isOpen onOpenChange={(o) => !o && onActiveChange(false)} isDismissable className=\"layer-overlay fixed inset-0 bg-foreground/40\">\n <Modal className={cn(\"h-full w-full outline-none\", overlaySurface, \"rounded-none\")}>\n <AriaDialog aria-label={label} className=\"h-full outline-none\">\n {inner}\n </AriaDialog>\n </Modal>\n </ModalOverlay>\n );\n}\n","import * as React from \"react\";\nimport { cn } from \"../lib/utils\";\nimport { FIT, clampViewport, viewportTransform, zoomAt, type Viewport } from \"../lib/viewport\";\n\n// One picture's frame, with zoom and pan that other frames can share (strata-react issue: shared\n// comparison and voting components). Judging two renderings of a photo is mostly looking at the same\n// detail in both, so the viewport is state the caller holds and gives to every frame: zoom one, the\n// other follows. `ViewportFrame` is only the frame; `Compare` holds the state and draws the controls.\n//\n// React Aria checked: Aria Components has no zoom or pan part, and its `useMove` (in the\n// `react-aria` package, which is not a dependency here) only reports deltas that a pointer capture\n// gives us as well, so the gestures are pointer events on the frame. Keyboard, which is not\n// optional: the frame is focusable, `+` `-` `0` zoom and the arrow keys pan once zoomed in.\n// Plain wheel scrolls the page (a frame in the middle of a page must not trap it); Ctrl or Cmd with\n// the wheel zooms, which is also what a trackpad pinch sends. Touch pinch is not handled yet.\n\n/** The caller's zoom and pan, and how to change them. */\nexport type ViewportState = { viewport: Viewport; setViewport: (next: Viewport) => void };\n\n/** Zoom and pan held in React state, to give to every `ViewportFrame` that should move together. */\nexport function useViewport(initial: Viewport = FIT): ViewportState {\n const [viewport, setViewport] = React.useState(initial);\n return { viewport, setViewport };\n}\n\nconst PAN_STEP = 48;\n\n/** Props for `ViewportFrame`. */\nexport type ViewportFrameProps = ViewportState & {\n /** Names the frame for screen readers: \"Picture A\". Required. */\n label: string;\n /** Width over height of the frame before anything inside it has loaded. */\n aspect: number;\n children: React.ReactNode;\n /** A second picture layer above `children`, zoomed and panned with them but cut at `shown` percent of the *frame's* width from the left, so a swipe divider in `overlay` stays where the cut is at any zoom. */\n cover?: { content: React.ReactNode; shown: number };\n /** Drawn over the frame, not zoomed with it: a divider to drag, a corner label. Its pointer, key and double-click events do not reach the frame, so using it never pans the picture. */\n overlay?: React.ReactNode;\n className?: string;\n};\n\n/** A clipped frame whose children zoom and pan together; the viewport is the caller's, so frames can share one. */\nexport const ViewportFrame = React.forwardRef<HTMLDivElement, ViewportFrameProps>(function ViewportFrame(\n { label, aspect, viewport, setViewport, children, cover, overlay, className },\n forwardedRef,\n) {\n const ref = React.useRef<HTMLDivElement>(null);\n React.useImperativeHandle(forwardedRef, () => ref.current!);\n const latest = React.useRef(viewport);\n latest.current = viewport;\n const drag = React.useRef<{ x: number; y: number } | null>(null);\n\n const size = () => {\n const r = ref.current!.getBoundingClientRect();\n return { width: r.width, height: r.height };\n };\n const fromCentre = (clientX: number, clientY: number) => {\n const r = ref.current!.getBoundingClientRect();\n return { x: clientX - r.left - r.width / 2, y: clientY - r.top - r.height / 2 };\n };\n\n // React attaches wheel listeners as passive, so preventing the browser's page zoom needs a native one.\n const setViewportRef = React.useRef(setViewport);\n setViewportRef.current = setViewport;\n React.useEffect(() => {\n const el = ref.current;\n if (!el) return;\n const onWheel = (e: WheelEvent) => {\n if (!e.ctrlKey && !e.metaKey) return;\n e.preventDefault();\n const r = el.getBoundingClientRect();\n const at = { x: e.clientX - r.left - r.width / 2, y: e.clientY - r.top - r.height / 2 };\n setViewportRef.current(zoomAt(latest.current, latest.current.scale * Math.exp(-e.deltaY / 200), at, { width: r.width, height: r.height }));\n };\n el.addEventListener(\"wheel\", onWheel, { passive: false });\n return () => el.removeEventListener(\"wheel\", onWheel);\n }, []);\n\n const onKeyDown = (e: React.KeyboardEvent) => {\n const v = latest.current;\n const centre = { x: 0, y: 0 };\n if (e.key === \"+\" || e.key === \"=\") setViewport(zoomAt(v, v.scale * 1.5, centre, size()));\n else if (e.key === \"-\") setViewport(zoomAt(v, v.scale / 1.5, centre, size()));\n else if (e.key === \"0\") setViewport(FIT);\n else if (v.scale > 1 && e.key.startsWith(\"Arrow\")) {\n // Arrow right looks right: the picture moves left.\n const dx = e.key === \"ArrowRight\" ? -PAN_STEP : e.key === \"ArrowLeft\" ? PAN_STEP : 0;\n const dy = e.key === \"ArrowDown\" ? -PAN_STEP : e.key === \"ArrowUp\" ? PAN_STEP : 0;\n setViewport(clampViewport({ ...v, x: v.x + dx, y: v.y + dy }, size()));\n } else return;\n e.preventDefault();\n e.stopPropagation();\n };\n\n const zoomed = viewport.scale > 1;\n return (\n <div\n ref={ref}\n role=\"group\"\n aria-label={label}\n aria-roledescription=\"zoomable picture\"\n tabIndex={0}\n onKeyDown={onKeyDown}\n onPointerDown={(e) => {\n if (!zoomed || e.button !== 0) return;\n drag.current = { x: e.clientX, y: e.clientY };\n e.currentTarget.setPointerCapture?.(e.pointerId);\n }}\n onPointerMove={(e) => {\n if (!drag.current) return;\n const dx = e.clientX - drag.current.x;\n const dy = e.clientY - drag.current.y;\n drag.current = { x: e.clientX, y: e.clientY };\n setViewport(clampViewport({ ...latest.current, x: latest.current.x + dx, y: latest.current.y + dy }, size()));\n }}\n onPointerUp={() => (drag.current = null)}\n onPointerCancel={() => (drag.current = null)}\n onDoubleClick={(e) => {\n const v = latest.current;\n setViewport(v.scale > 1 ? FIT : zoomAt(v, 2, fromCentre(e.clientX, e.clientY), size()));\n }}\n style={{ aspectRatio: String(aspect), touchAction: zoomed ? \"none\" : \"pan-y\" }}\n className={cn(\n \"relative w-full overflow-hidden rounded-surface border border-border bg-muted select-none\",\n zoomed ? \"cursor-grab active:cursor-grabbing\" : \"cursor-zoom-in\",\n \"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring\",\n className,\n )}\n >\n <div className=\"absolute inset-0\" style={{ transform: viewportTransform(viewport), transformOrigin: \"center\" }}>\n {children}\n </div>\n {cover && (\n <div className=\"absolute inset-0\" style={{ clipPath: `inset(0 ${100 - cover.shown}% 0 0)` }}>\n <div className=\"absolute inset-0\" style={{ transform: viewportTransform(viewport), transformOrigin: \"center\" }}>\n {cover.content}\n </div>\n </div>\n )}\n {overlay != null && (\n <div\n className=\"pointer-events-none absolute inset-0\"\n onPointerDown={(e) => e.stopPropagation()}\n onKeyDown={(e) => e.stopPropagation()}\n onDoubleClick={(e) => e.stopPropagation()}\n >\n {overlay}\n </div>\n )}\n </div>\n );\n});\n","import * as React from \"react\";\nimport { Slider as AriaSlider, SliderThumb, SliderTrack } from \"react-aria-components\";\nimport { ImageOff, Maximize, Minimize, Scan, ZoomIn, ZoomOut } from \"lucide-react\";\nimport { cn } from \"../lib/utils\";\nimport { FIT, actualPixelsScale, zoomAt } from \"../lib/viewport\";\nimport { Button, IconButton } from \"./button\";\nimport { FullscreenFrame } from \"./fullscreen-frame\";\nimport { KeysLegend, useHotkeys, type Shortcut } from \"./hotkeys\";\nimport { Skeleton } from \"./data-view\";\nimport { Toolbar, ToolbarSeparator } from \"./toolbar\";\nimport { ToggleGroup } from \"./toggle\";\nimport { Slider } from \"./value-controls\";\nimport { ViewportFrame, useViewport } from \"./viewport\";\n\n// Two renderings of the same thing, to be looked at closely and judged. It exists because four\n// apps draw this by hand (the stills arena, the models judge, the listory match queue, the\n// Bright Horizons review) and none of them can zoom both sides together, lay one over the other or\n// look at it full screen. The design and the survey are in the project's design.md; this file is the\n// first piece, for pictures. Text, audio, video and data kinds, a difference view and voting come\n// in later changes and join the same `Candidate` and `CompareMode` types.\n//\n// Four views, because each answers a different question: side by side (which do I prefer),\n// swipe (where exactly do they differ, along this edge), fade (the same, softly) and blink (flip\n// between them in place, the most sensitive way to see a small change). Zoom and pan are one state\n// for both sides, so the same detail is in view in both. Full screen keeps everything.\n//\n// Blind by type: `blind` is required with no default, because showing a judge which variant is which\n// is a validity bug, not a style choice. When it is true the picture's name is its `label` (the\n// caller passes \"A\" and \"B\"), the caller's `alt` and `note` are never put on the page, and the\n// real `id` is never rendered at all. Mind the URL: `src` reaches the DOM, so a blind caller serves\n// the pictures under neutral addresses (the arena's `img/{token}/left`).\n//\n// Failure is a state: a picture that does not load says so in `missing` (required, in the product's\n// words) in its own place, and the other side is still usable. One filled button rule: this\n// component draws none, a vote bar will be the view's filled control.\n\n/** A picture to compare. */\nexport type ImageMedia = {\n kind: \"image\";\n src: string;\n /** What it shows. Ignored when the comparison is `blind`: the label names it then. */\n alt: string;\n /** Its natural size in pixels, if known, so the frame has its shape and \"1:1\" is exact before the picture loads. */\n size?: readonly [number, number];\n};\n\n/** One side of a comparison. */\nexport type Candidate<M = ImageMedia> = {\n /** Who it is: a variant name, a model. Never put on the page when `blind`, and never needed by it. */\n id: string;\n /** What the person sees it called: \"Original\", or \"A\" when blind. */\n label: string;\n media: M;\n /** A line under the label (\"auto2, 14 s\"). Not shown when `blind`. */\n note?: string;\n};\n\n/** How two pictures are laid out. */\nexport type CompareMode = \"side\" | \"swipe\" | \"fade\" | \"blink\";\n\nconst MODE_LABEL: Record<CompareMode, string> = { side: \"Side by side\", swipe: \"Swipe\", fade: \"Fade\", blink: \"Blink\" };\nconst ALL_MODES: readonly CompareMode[] = [\"side\", \"swipe\", \"fade\", \"blink\"];\n\n/** Props for `Compare`. */\nexport type CompareProps = {\n /** Names the comparison for screen readers: \"Photo 1 of 12, two versions\". Required. */\n label: string;\n a: Candidate;\n b: Candidate;\n /** Whether the person must not learn which variant is which. Required, no default. */\n blind: boolean;\n /** The words shown where a picture could not be loaded: \"Picture not found\". Required. */\n missing: string;\n mode: CompareMode;\n onModeChange: (mode: CompareMode) => void;\n /** Which views are offered. Default all four. Must include `mode`. */\n modes?: readonly CompareMode[];\n /** Bind the view, zoom and full-screen keys on the window. Default true; turn off when a surrounding screen binds the same keys. */\n keys?: boolean;\n className?: string;\n};\n\n/** A word for a picture's name on the page: its label, with its note unless blind. */\nfunction Caption({ c, blind }: { c: Candidate; blind: boolean }) {\n return (\n <div className=\"flex items-baseline gap-2\">\n <span className=\"type-label\">{c.label}</span>\n {!blind && c.note && <span className=\"type-caption text-muted-foreground\">{c.note}</span>}\n </div>\n );\n}\n\n/** One picture inside a frame: a skeleton while it loads, the product's words if it fails. */\nfunction Picture({ c, blind, missing, onNatural, imgRef }: { c: Candidate; blind: boolean; missing: string; onNatural?: (w: number, h: number) => void; imgRef?: React.Ref<HTMLImageElement> }) {\n const [state, setState] = React.useState<\"loading\" | \"ready\" | \"failed\">(\"loading\");\n React.useEffect(() => setState(\"loading\"), [c.media.src]);\n const alt = blind ? c.label : c.media.alt;\n if (state === \"failed\")\n return (\n <div role=\"img\" aria-label={`${alt}: ${missing}`} className=\"absolute inset-0 grid place-content-center justify-items-center gap-2 text-muted-foreground\">\n <ImageOff aria-hidden className=\"size-6\" />\n <span className=\"type-body-sm\">{missing}</span>\n </div>\n );\n return (\n <>\n {state === \"loading\" && <Skeleton aria-hidden className=\"absolute inset-0 size-full rounded-none\" />}\n <img\n ref={imgRef}\n src={c.media.src}\n alt={alt}\n draggable={false}\n onLoad={(e) => {\n setState(\"ready\");\n onNatural?.(e.currentTarget.naturalWidth, e.currentTarget.naturalHeight);\n }}\n onError={() => setState(\"failed\")}\n className=\"absolute inset-0 size-full object-contain\"\n />\n </>\n );\n}\n\n/** Two pictures to judge, side by side or laid over each other, zoomed and panned together, and full screen. */\nexport function Compare({ label, a, b, blind, missing, mode, onModeChange, modes = ALL_MODES, keys = true, className }: CompareProps) {\n const { viewport, setViewport } = useViewport();\n const [full, setFull] = React.useState(false);\n // Learned from the picture once it loads, and only for the pair it was learned from: a new pair starts again.\n const pairKey = `${a.media.src}|${b.media.src}`;\n const [learned, setLearned] = React.useState<{ key: string; size: readonly [number, number] } | null>(null);\n const natural = a.media.size ?? (learned?.key === pairKey ? learned.size : null);\n const [divider, setDivider] = React.useState(50);\n const [blend, setBlend] = React.useState(50);\n const [showing, setShowing] = React.useState<\"a\" | \"b\">(\"a\");\n const frameRef = React.useRef<HTMLDivElement>(null);\n const imgRef = React.useRef<HTMLImageElement>(null);\n const aspect = natural ? natural[0] / natural[1] : 3 / 2;\n\n const frameSize = () => {\n const r = frameRef.current?.getBoundingClientRect();\n return { width: r?.width ?? 0, height: r?.height ?? 0 };\n };\n const zoomBy = (k: number) => setViewport(zoomAt(viewport, viewport.scale * k, { x: 0, y: 0 }, frameSize()));\n const actual = () => {\n const f = frameSize();\n // The width the picture is drawn at when fitted: the frame's, unless the picture is taller than it is wide for the frame.\n const fitted = natural ? Math.min(f.width, f.height * (natural[0] / natural[1])) : f.width;\n setViewport(zoomAt(viewport, actualPixelsScale(natural?.[0] ?? 0, fitted), { x: 0, y: 0 }, f));\n };\n const flip = () => setShowing((s) => (s === \"a\" ? \"b\" : \"a\"));\n\n const offered = modes.includes(mode) ? modes : [mode, ...modes];\n const shortcuts: Shortcut[] = [\n ...offered.map((m, i): Shortcut => ({ keys: [String(i + 1)], label: MODE_LABEL[m], run: () => onModeChange(m) })),\n { keys: [\"x\"], label: \"Flip A and B\", run: flip, disabled: mode !== \"blink\" },\n { keys: [\"+\", \"=\"], label: \"Zoom in\", run: () => zoomBy(1.5), repeat: true },\n { keys: [\"-\"], label: \"Zoom out\", run: () => zoomBy(1 / 1.5), repeat: true },\n { keys: [\"0\"], label: \"Fit\", run: () => setViewport(FIT) },\n { keys: [\"f\"], label: full ? \"Leave full screen\" : \"Full screen\", run: () => setFull((f) => !f) },\n ];\n useHotkeys(shortcuts, { enabled: keys });\n\n const pane = (c: Candidate, ref?: React.Ref<HTMLImageElement>, onNatural?: (w: number, h: number) => void) => (\n <Picture c={c} blind={blind} missing={missing} imgRef={ref} onNatural={onNatural} />\n );\n const learn = (w: number, h: number) => setLearned({ key: pairKey, size: [w, h] });\n const frameProps = { viewport, setViewport, aspect };\n\n let body: React.ReactNode;\n if (mode === \"side\") {\n body = (\n <div className=\"grid gap-3 sm:grid-cols-2\">\n {[a, b].map((c, i) => (\n <figure key={i} className=\"grid gap-1.5\">\n <Caption c={c} blind={blind} />\n <ViewportFrame {...frameProps} label={blind ? `Picture ${c.label}` : `${c.label}`} ref={i === 0 ? frameRef : undefined}>\n {pane(c, i === 0 ? imgRef : undefined, i === 0 ? learn : undefined)}\n </ViewportFrame>\n </figure>\n ))}\n </div>\n );\n } else {\n // One frame, both pictures in it. Swipe clips the top one at the divider; fade lays it over at an opacity; blink shows one.\n const top = mode === \"blink\" ? (showing === \"a\" ? a : b) : a;\n const bottom = b;\n body = (\n <figure className=\"grid gap-1.5\">\n <div className=\"flex justify-between gap-4\">\n {mode === \"blink\" ? <Caption c={top} blind={blind} /> : <Caption c={a} blind={blind} />}\n {mode !== \"blink\" && <Caption c={b} blind={blind} />}\n </div>\n <ViewportFrame\n {...frameProps}\n ref={frameRef}\n cover={mode === \"swipe\" ? { content: pane(a, imgRef, learn), shown: divider } : undefined}\n label={mode === \"blink\" ? `Picture ${top.label}` : `${a.label} over ${b.label}`}\n overlay={\n mode === \"swipe\" && (\n <AriaSlider\n aria-label={`Divider between ${a.label} and ${b.label}`}\n value={divider}\n onChange={(v) => setDivider(v as number)}\n minValue={0}\n maxValue={100}\n step={1}\n className=\"absolute inset-0\"\n >\n <SliderTrack className=\"pointer-events-none h-full w-full\">\n <SliderThumb\n className=\"pointer-events-auto grid h-full w-8 cursor-ew-resize place-items-center focus-visible:outline-2 focus-visible:outline-ring\"\n style={{ top: \"50%\" }}\n >\n <span aria-hidden className=\"col-start-1 row-start-1 h-full w-1 border-x border-background bg-foreground\" />\n <span aria-hidden className=\"col-start-1 row-start-1 size-6 rounded-pill border-2 border-foreground bg-background\" />\n </SliderThumb>\n </SliderTrack>\n </AriaSlider>\n )\n }\n >\n {pane(bottom)}\n {mode !== \"swipe\" && (\n <div className=\"absolute inset-0\" style={mode === \"fade\" ? { opacity: 1 - blend / 100 } : undefined}>\n {pane(top, imgRef, learn)}\n </div>\n )}\n </ViewportFrame>\n </figure>\n );\n }\n\n return (\n <FullscreenFrame label={label} active={full} onActiveChange={setFull} className={className}>\n <section aria-label={label} className={cn(\"grid gap-3\", full && \"min-h-0 flex-1 content-start overflow-auto\")}>\n <Toolbar label=\"Comparison view\" className=\"items-center gap-2\">\n <ToggleGroup label=\"View\" options={offered.map((m) => ({ value: m, label: MODE_LABEL[m] }))} value={mode} onChange={(v) => onModeChange(v as CompareMode)} size=\"sm\" />\n <ToolbarSeparator />\n <IconButton icon={ZoomOut} label=\"Zoom out\" onPress={() => zoomBy(1 / 1.5)} disabled={viewport.scale <= 1} />\n <IconButton icon={ZoomIn} label=\"Zoom in\" onPress={() => zoomBy(1.5)} />\n <IconButton icon={Scan} label=\"Fit\" onPress={() => setViewport(FIT)} disabled={viewport.scale === 1} />\n <Button size=\"sm\" variant=\"ghost\" onPress={actual} disabled={!natural}>1:1</Button>\n <span aria-live=\"off\" className=\"type-caption tabular-nums text-muted-foreground\">{viewport.scale === 1 ? \"Fit\" : `${viewport.scale.toFixed(1)}×`}</span>\n <ToolbarSeparator />\n <IconButton icon={full ? Minimize : Maximize} label={full ? \"Leave full screen\" : \"Full screen\"} onPress={() => setFull(!full)} />\n </Toolbar>\n {mode === \"fade\" && (\n <div className=\"flex items-center gap-3\">\n <span className=\"type-caption text-muted-foreground\">{a.label}</span>\n <Slider aria-label={`Blend from ${a.label} to ${b.label}`} value={blend} onChange={setBlend} min={0} max={100} unit=\"%\" hideValue className=\"flex-1\" />\n <span className=\"type-caption text-muted-foreground\">{b.label}</span>\n </div>\n )}\n {mode === \"blink\" && (\n <div>\n <ToggleGroup label=\"Showing\" options={[{ value: \"a\", label: a.label }, { value: \"b\", label: b.label }]} value={showing} onChange={(v) => setShowing(v as \"a\" | \"b\")} size=\"sm\" />\n </div>\n )}\n {body}\n {keys && <KeysLegend shortcuts={shortcuts} />}\n </section>\n </FullscreenFrame>\n );\n}\n"],"mappings":";;;;;;;;;;;AAqCA,IAAa,OAAO;;AAGpB,IAAa,UAAU;AAIvB,IAAM,aAAkC;CAAC;CAAK;CAAM;CAAM;CAAM;CAAM;AAAI;AAC1E,IAAM,YAAY,OAAO,YAAY,WAAW,KAAK,GAAG,MAAM,CAAC,GAAG,OAAQ,CAAC,CAAC,CAAC;;AAgC7E,SAAgB,OAAO,OAAwB;CAC7C,MAAM,OAAO,iBAAiB,OAAO,QAAQ,IAAI,KAAK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