strata-react 2.1.0 → 2.1.2

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/dist/map.js CHANGED
@@ -5,9 +5,9 @@ import { n as useSharedCursor, r as geo } from "./cursor-Cwyvgwsw.js";
5
5
  import * as React from "react";
6
6
  import { Button } from "react-aria-components";
7
7
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
8
+ import { createPortal } from "react-dom";
8
9
  import L from "leaflet";
9
10
  import leafletCss from "leaflet/dist/leaflet.css?inline";
10
- import { createPortal } from "react-dom";
11
11
 
12
12
  // src/map/map-styles.ts
13
13
  const strata = `
@@ -370,11 +370,13 @@ type VolumeControlProps = {
370
370
  onVolumeChange: (volume: number) => void;
371
371
  /** Allow over 100 (a boost), up to this. Default 100. */
372
372
  max?: number;
373
+ /** Allow over 100, up to this, behind a Louder toggle: the slider stops at 100 until it is pressed, so a slip of the thumb or the wheel never doubles the sound. Turning it off brings the volume back to 100. Takes the place of `max`. */
374
+ boost?: number;
373
375
  disabled?: boolean;
374
376
  className?: string;
375
377
  };
376
- /** A mute button and a volume slider with its value in percent. Muting sets the volume to 0 and remembers the level; unmuting puts it back. Moving the slider from 0 unmutes. */
377
- declare function VolumeControl({ volume, onVolumeChange, max, disabled, className }: VolumeControlProps): React.JSX.Element;
378
+ /** A mute button and a volume slider with its value in percent. Muting sets the volume to 0 and remembers the level; unmuting puts it back. Moving the slider from 0 unmutes. With `boost`, a Louder toggle lets it past 100. */
379
+ declare function VolumeControl({ volume, onVolumeChange, max, boost, disabled, className }: VolumeControlProps): React.JSX.Element;
378
380
  /** A choice of playback speed ("0.5×", "1×", "1.5×"), named "Playback speed": React Aria's Select. */
379
381
  declare function RateChoice({ rate, onRateChange, rates, className }: {
380
382
  rate: number;
@@ -543,9 +545,11 @@ type MediaElementState = {
543
545
  duration: number | null;
544
546
  /** Seconds buffered from the start of the range holding `time`. */
545
547
  buffered: number;
546
- /** 0 to 100; 0 while muted. */
548
+ /** 0 to 100 (to `maxVolume` with a boost); 0 while muted. */
547
549
  volume: number;
548
550
  muted: boolean;
551
+ /** The most `setVolume` takes: 100, or the `boost` option's level where the browser can play past the element's own (Web Audio). */
552
+ maxVolume: number;
549
553
  rate: number;
550
554
  ended: boolean;
551
555
  /** Waiting for data (the first load, or a seek into what is not buffered yet). */
@@ -556,7 +560,7 @@ type MediaElementState = {
556
560
  toggle: () => void;
557
561
  /** Seeks; before the metadata has loaded, remembers the time and applies it when it has. */
558
562
  seek: (time: number) => void;
559
- /** 0 to 100. 0 mutes; more unmutes at that level. */
563
+ /** 0 to `maxVolume`. 0 mutes; more unmutes at that level; past 100 is the `boost`. */
560
564
  setVolume: (volume: number) => void;
561
565
  setRate: (rate: number) => void;
562
566
  /** Loads again, and plays if it was playing. For the error state's "Try again". */
@@ -594,6 +598,10 @@ type MediaElementOptions = {
594
598
  progressEvery?: number;
595
599
  /** Names what is being played, so the count starts again when it changes. Default the element's `src` attribute; give it for a stream attached by an engine. */
596
600
  progressKey?: string;
601
+ /** A factor on the sound, played through Web Audio: an app's loudness normalisation (2 is twice as loud, 0.5 half), so 100% on the volume is the level the app chose. A change glides there over a second or two. Peaks past full scale are held by a limiter. `null` or 1 leaves the sound alone. Only for a same-origin source (or one served with CORS): a browser gives Web Audio silence from another site's file. See `media-sound.ts`. */
602
+ gain?: number | null;
603
+ /** Let the volume go past 100%, to this many percent (200 is twice as loud), through Web Audio with the same limiter. Where the browser has no Web Audio the volume stops at 100. */
604
+ boost?: number;
597
605
  };
598
606
  /** Follows an `<audio>` or `<video>` and returns its state and the requests a player makes. Works with the browser's own controls too. */
599
607
  declare function useMediaElement(ref: React.RefObject<HTMLMediaElement | null>, options?: MediaElementOptions): MediaElementState;
@@ -740,6 +748,12 @@ type MediaPlayerProps = {
740
748
  status?: React.ReactNode;
741
749
  /** A transient warning from `usePlayerWarnings`, shown independently of the controls. */
742
750
  warning?: PlayerWarningEvent;
751
+ /** A factor on the sound, so 100% on the volume is the level the app chose: its loudness normalisation (a quiet file made as loud as the others, a loud one brought down). Played through Web Audio with a limiter that holds peaks under full scale; a change glides there. `null` or 1 leaves the sound alone. Same-origin sources only (or CORS): a browser gives Web Audio silence from another site's file. */
752
+ gain?: number | null;
753
+ /** How the element asks for its file (`crossOrigin`): set it for a file on another site served with CORS, so `gain` and `boost` can reach its sound. Without it such a file plays at its own level. */
754
+ crossOrigin?: "anonymous" | "use-credentials";
755
+ /** Let the volume go past 100%, to this many percent (200 is twice as loud), behind a Louder toggle beside the slider; the wheel goes on past 100 only once the volume is there. Through Web Audio with the same limiter; where the browser has none, no toggle. */
756
+ boost?: number;
743
757
  /** The picture's shape before its metadata loads (and after, when given): a width over a height, or "16/9". Default "16/9" until the video says its own. */
744
758
  aspect?: number | `${number}/${number}`;
745
759
  /** A video has a Full screen button (and the `f` key) beside the speed and volume. Default true; `false` for a picture that must stay in its place. Only where the browser has the Fullscreen API (the window-filling fallback would mount the video again and lose its place). Not drawn with the browser's own controls (`controls="native"`, or `"auto"` on a touch device), which have their own. */
@@ -753,6 +767,6 @@ declare const SPEECH_RATES: readonly number[];
753
767
  * a touch device), with the failure to load shown and retried. For an editor or a replay, use the
754
768
  * parts and `useMediaElement` directly.
755
769
  */
756
- declare function MediaPlayer({ label, kind, src, sources, index: controlledIndex, onIndexChange, autoAdvance, controls, autoPlay, poster, session, rates, shortcuts, attach, growing, window: bound, loop, showFull, group, onTimeUpdate, onWindowEnd, onEnded, onTimeChange, spans, spanKinds, marks, onSpan, spanWords, start, resumeWords, onProgress, progressEvery, mediaRef, heading, overlay, status, warning, aspect, fullscreen, skip, fps, float, className }: MediaPlayerProps): React.JSX.Element;
770
+ declare function MediaPlayer({ label, kind, src, sources, index: controlledIndex, onIndexChange, autoAdvance, controls, autoPlay, poster, session, rates, shortcuts, attach, growing, window: bound, loop, showFull, group, onTimeUpdate, onWindowEnd, onEnded, onTimeChange, spans, spanKinds, marks, onSpan, spanWords, start, resumeWords, onProgress, progressEvery, mediaRef, heading, overlay, status, warning, gain, boost, crossOrigin, aspect, fullscreen, skip, fps, float, className }: MediaPlayerProps): React.JSX.Element;
757
771
  export { LineChartGroupProps as $, RateChoice as A, VolumeControlProps as B, SpanBehaviour as C, useMediaSpans as D, SpanWords as E, StageGuides as F, isTypingTarget as G, HotkeysOptions as H, TimeReadout as I, ChartMark as J, keyName as K, Transport as L, SeekBarProps as M, SeekBarSpan as N, MediaStage as O, SpanStrip as P, LineChartGroup as Q, TransportProps as R, SpanActionsNotice as S, SpanOutcome as T, KeysLegend as U, transportShortcuts as V, Shortcut as W, GroupedChart as X, ChartSpan as Y, LineChart as Z, MediaProgress as _, skipAction as _t, MediaPlayerProps as a, valueAt as at, PlayerNotice as b, usePlayerWarnings as bt, MediaSource as c, CursorScope as ct, SPEECH_RATES as d, useSharedCursor as dt, LineChartProps as et, SourceAttacher as f, MediaMark as ft, useMediaElement as g, marksFor as gt, useAttachedSource as h, SkipSteps as ht, MediaPlayer as i, logScale as it, SeekBar as j, Precision as k, MediaWindow as l, CursorScopeProps as lt, StreamContext as m, SkipLevel as mt, MediaElementState as n, SpanTone as nt, MediaProblem as o, CursorMapping as ot, StreamAttachment as p, SkipAction as pt, useHotkeys as q, MediaHeading as r, YScale as rt, MediaSession as s, CursorOwner as st, MediaElementOptions as t, Point as tt, ResumeWords as u, SharedCursor as ut, MediaSpanData as v, PlayerWarning as vt, SpanKind as w, SpanActions as x, MediaSpansState as y, PlayerWarningEvent as yt, VolumeControl as z };
758
- //# sourceMappingURL=media-player-BETa3P7K.d.ts.map
772
+ //# sourceMappingURL=media-player-Buvu2l7R.d.ts.map
@@ -1,6 +1,6 @@
1
1
  import { r as cn } from "./tooltip-BosfsWYh.js";
2
2
  import { f as format } from "./field-DBCsFIng.js";
3
- import { a as isDev, o as useInView, t as Button$1 } from "./button-CYXjU-fs.js";
3
+ import { a as isDev, o as useInView, t as Button$1 } from "./button-CjnotDTb.js";
4
4
  import { o as readErrorBody, r as describeHttpError, t as HttpError } from "./errors-CmuwcWlb.js";
5
5
  import * as React from "react";
6
6
  import { Button, Text, UNSTABLE_Toast, UNSTABLE_ToastContent, UNSTABLE_ToastQueue, UNSTABLE_ToastRegion } from "react-aria-components";
@@ -707,4 +707,4 @@ const MicrophoneContext = React.createContext(browserMicrophone);
707
707
  const useMicrophone = () => React.useContext(MicrophoneContext);
708
708
 
709
709
  export { StrataQueryProvider as A, toast as C, LoadError as D, EmptyState as E, useLoad as F, usePoll as I, overlaySurface as L, fetchJson as M, staleOf as N, Skeleton as O, toLoad as P, StrataToastRegion as S, DataView as T, clampViewport as _, useMicrophone as a, viewportTransform as b, forgetLoadedThumbnails as c, zoomToBox as d, FIT as f, boxViewport as g, actualPixelsScale as h, explainMicrophoneError as i, createQueryClient as j, StaleNotice as k, readingOrder as l, MIN_SCALE as m, MicrophoneError as n, Thumbnail as o, MAX_SCALE as p, browserMicrophone as r, ThumbnailSkeleton as s, MicrophoneContext as t, regionStyle as u, frameBoxToShares as v, toastTimeout as w, zoomAt as x, regionShares as y };
710
- //# sourceMappingURL=microphone-76skMt6i.js.map
710
+ //# sourceMappingURL=microphone-D3sbBVka.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"microphone-76skMt6i.js","names":["Button","ToastQueue","ToastRegion","AriaToast","ToastContent","Button","AriaButton"],"sources":["../src/lib/overlay.ts","../src/query/poll.ts","../src/query/index.tsx","../src/components/data-view.tsx","../src/components/toast.tsx","../src/lib/viewport.ts","../src/lib/boxes.ts","../src/components/thumbnail.tsx","../src/lib/microphone.ts"],"sourcesContent":["// 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","import * as React from \"react\";\nimport type { UseQueryResult } from \"@tanstack/react-query\";\n\n// Pausing a polled read (strata-react issue #344, from the status page in jburnhams/homepage). A\n// screen that re-reads every few seconds needs the same three parts every time: whether it is\n// paused, a button that says so, and when the readings were taken. A person reading a table while\n// it re-sorts under them needs the pause (ux-research `patterns.md` on live data: the person, not\n// the poll, decides when the view moves); a page whose readings may be minutes old needs the time.\n// Written by hand it was a `useState`, a button with `aria-pressed`, `refetchInterval: paused ?\n// false : ms` and an \"updated 12:00\" line, in every live screen.\n//\n// - `usePoll({ every })` holds the state and is passed to `useLoad({ poll })`, which polls at its\n// interval while it is not paused, notes when each read arrived, and reads once at once when the\n// poll is resumed (what was on screen is as old as the pause).\n// - `PauseButton` (components/pause-button.tsx) takes the same object, with its words fixed.\n// - One `Poll` may serve several reads: the page pauses together. The time is the latest read's. A read\n// with its own pace takes `poll.with({ every })`: same pause and time, other interval (#349).\n// - `useJob` keeps its own interval: a job is polled only while it runs, which is not the person's\n// to pause.\n\n/** The state of a polled read: its interval, whether the person paused it and when it last read. Made by `usePoll`. */\nexport type Poll = {\n /** Milliseconds between reads while not paused. */\n every: number;\n paused: boolean;\n /** Pause or resume. Resuming reads at once. */\n toggle: () => void;\n /** When the last read arrived, or `null` before the first. */\n updatedAt: Date | null;\n /** Used by `useLoad`: records the time of the read that just arrived (TanStack's `dataUpdatedAt`; 0 is none). */\n note: (dataUpdatedAt: number) => void;\n /** The same poll at another pace: a read that must be slower (or faster) than the page's keeps the shared pause, resume and \"updated\" time (`useLoad({ poll: poll.with({ every: 60_000 }) })`). */\n with: (override: { every: number }) => Poll;\n};\n\n/** The pause state and last-read time of a polled screen: pass it to `useLoad({ poll })` and to `PauseButton`. */\nexport function usePoll({ every, paused: initiallyPaused = false }: { every: number; paused?: boolean }): Poll {\n const [paused, setPaused] = React.useState(initiallyPaused);\n const [at, setAt] = React.useState(0);\n const toggle = React.useCallback(() => setPaused((p) => !p), []);\n const note = React.useCallback((dataUpdatedAt: number) => setAt((previous) => Math.max(previous, dataUpdatedAt)), []);\n return React.useMemo(() => {\n const poll: Poll = {\n every,\n paused,\n toggle,\n updatedAt: at ? new Date(at) : null,\n note,\n with: (override) => ({ ...poll, every: override.every, with: (again) => poll.with(again) }),\n };\n return poll;\n }, [every, paused, toggle, at, note]);\n}\n\n/** Wires a query to its `Poll`: the time of each read, and one read when the poll is resumed. */\nexport function usePollBinding(poll: Poll | undefined, query: Pick<UseQueryResult, \"dataUpdatedAt\" | \"refetch\">) {\n const note = poll?.note;\n React.useEffect(() => {\n if (note && query.dataUpdatedAt) note(query.dataUpdatedAt);\n }, [note, query.dataUpdatedAt]);\n const paused = poll?.paused;\n const wasPaused = React.useRef(paused);\n React.useEffect(() => {\n if (wasPaused.current && paused === false) void query.refetch();\n wasPaused.current = paused;\n // `refetch` is stable per query; only the pause changing should read.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [paused]);\n}\n","import * as React from \"react\";\nimport {\n QueryClient,\n QueryClientProvider,\n useQuery,\n type QueryKey,\n type UseQueryOptions,\n type UseQueryResult,\n} from \"@tanstack/react-query\";\nimport type { Load, Stale } from \"../components/data-view\";\nimport { usePollBinding, type Poll } from \"./poll\";\nimport {\n HttpError,\n describeHttpError,\n errorPayload,\n readErrorBody,\n type DescribeError,\n type ErrorBody,\n} from \"../lib/errors\";\n\nexport { HttpError, describeHttpError, errorPayload, readErrorBody, type DescribeError, type ErrorBody };\n\n// Data loading, the Strata way: TanStack Query fetches and caches, and every view of the result\n// goes through DataView, which takes a Load<T>. `toLoad` is the one bridge between them, so a\n// screen never re-derives loading/error/ready from a query's flags and never forgets one.\n//\n// Opinions in createQueryClient: one retry (a second failure is real and the person should see\n// it with a \"Try again\"), 30 s stale time (dashboards are read many times a minute but change\n// over minutes), and no refetch on window focus (a table that reorders itself while someone reads\n// it is worse than one that is 30 s old). Override per query when the data says otherwise.\n\n/** A QueryClient with Strata's defaults: one retry, 30 s stale time, no refetch on window focus. */\nexport function createQueryClient(overrides?: ConstructorParameters<typeof QueryClient>[0]) {\n return new QueryClient({\n ...overrides,\n defaultOptions: {\n ...overrides?.defaultOptions,\n queries: { retry: 1, staleTime: 30_000, refetchOnWindowFocus: false, ...overrides?.defaultOptions?.queries },\n },\n });\n}\n\n/** Provides a query client (Strata's defaults unless one is passed) to the app. */\nexport function StrataQueryProvider({ client, children }: { client?: QueryClient; children: React.ReactNode }) {\n const [fallback] = React.useState(() => client ?? createQueryClient());\n return <QueryClientProvider client={client ?? fallback}>{children}</QueryClientProvider>;\n}\n\n/**\n * Turns a TanStack query result into the `Load<T>` that `DataView` takes; errors are described for a person by `describe`.\n * A refetch that fails after data arrived stays `ready`, with `stale` saying why and when the data was read.\n */\nexport function toLoad<T>(query: UseQueryResult<T>, describe: DescribeError = describeHttpError): Load<T> {\n if (query.status === \"success\") return { status: \"ready\", data: query.data };\n // TanStack keeps the last good data when a refetch fails and sets status \"error\" (isRefetchError).\n // That is old data, not no data: keep it on screen and say how old it is.\n if (query.status === \"error\" && query.data !== undefined)\n return { status: \"ready\", data: query.data, stale: staleOf(query, describe) };\n if (query.status === \"error\")\n return { status: \"error\", message: describe(query.error), retry: () => void query.refetch() };\n return { status: \"loading\" };\n}\n\n/** The `Stale` of a query whose refetch failed after a good read. Shared by `toLoad` and `useInfiniteLoad`. */\nexport function staleOf(\n query: { error: unknown; dataUpdatedAt: number; isFetching: boolean; refetch: () => unknown },\n describe: DescribeError = describeHttpError,\n): Stale {\n return {\n message: describe(query.error),\n readAt: new Date(query.dataUpdatedAt),\n retry: () => void query.refetch(),\n retrying: query.isFetching,\n };\n}\n\n/** `useQuery`, returned as a `Load<T>` for `DataView`. With `poll` (from `usePoll`) it reads again every `poll.every` ms until the person pauses it. */\nexport function useLoad<T, K extends QueryKey = QueryKey>(\n options: UseQueryOptions<T, Error, T, K> & {\n describeError?: DescribeError;\n /** Read again on this poll's interval unless it is paused; see `usePoll` and `PauseButton`. Replaces `refetchInterval`. */\n poll?: Poll;\n },\n): Load<T> {\n const { describeError, poll, ...rest } = options;\n const query = useQuery(poll ? { ...rest, refetchInterval: poll.paused ? false : poll.every } : rest);\n usePollBinding(poll, query);\n return toLoad(query, describeError);\n}\n\n/** What `fetchJson` takes as `fetch`'s init, plus `json`. */\nexport type FetchJsonInit = RequestInit & {\n /**\n * A value sent as the JSON body: `Content-Type: application/json` is set unless the caller gave one, and the method is `POST` unless given.\n * Replaces `body`; an app never builds the `RequestInit` for a write by hand.\n */\n json?: unknown;\n};\n\n/** Options for `fetchJson` beyond `fetch`'s own. */\nexport type FetchJsonOptions = {\n /** Finds the server's reason and per-field messages in an error body. Default `readErrorBody` (FastAPI's `detail`, `message`, `error`). */\n readError?: (body: unknown) => ErrorBody;\n};\n\n/**\n * fetch() that throws an HttpError on a non-2xx response and parses JSON: the queryFn default, and the usual commit for a write.\n * `init.json` sends a JSON body without building the headers. A 204 or empty body resolves to undefined. An error response's body is read onto the HttpError (`body`, `reason`, `fieldErrors`).\n */\nexport async function fetchJson<T>(\n input: string | URL,\n init?: FetchJsonInit,\n { readError = readErrorBody }: FetchJsonOptions = {},\n): Promise<T> {\n const { json, ...rest } = init ?? {};\n // Headers, tuple arrays and plain objects are all valid HeadersInit; normalise before adding the\n // default so a caller's Authorization (or their own Accept) is never dropped.\n const headers = new Headers(rest.headers);\n if (!headers.has(\"Accept\")) headers.set(\"Accept\", \"application/json\");\n if (json !== undefined) {\n if (!headers.has(\"Content-Type\")) headers.set(\"Content-Type\", \"application/json\");\n rest.body = JSON.stringify(json);\n rest.method ??= \"POST\";\n }\n const res = await fetch(input, { ...rest, headers });\n if (!res.ok) {\n // The body is read as text and parsed only when it parses: a proxy's HTML 502 page or an empty\n // body must still throw the HttpError, never a JSON SyntaxError in its place.\n const raw = await res.text().catch(() => \"\");\n let body: unknown = raw || undefined;\n try {\n if (raw) body = JSON.parse(raw);\n } catch {\n // Not JSON: keep the text.\n }\n throw new HttpError(res.status, res.statusText, String(input), body, readError(body));\n }\n // Writes (DELETE, a PUT that returns nothing) answer 204 or an empty body; that is success, not a\n // JSON parse error.\n const text = res.status === 204 ? \"\" : await res.text();\n return (text ? JSON.parse(text) : undefined) as T;\n}\n\nexport { usePoll, type Poll } from \"./poll\";\nexport { createApi, type Api, type ApiOptions } from \"./api\";\nexport { createTypedApi, type TypedApi } from \"./typed-api\";\nexport {\n useInfiniteLoad,\n apiPage,\n type ApiPage,\n type InfiniteLoad,\n type InfiniteLoadOptions,\n type More,\n} from \"./infinite\";\nexport { useJob, isTaskRunning, type Job, type JobOptions } from \"./job\";\nexport { useWorkflowRun, isWorkflowRunning, type WorkflowRunLike, type WorkflowRunOptions } from \"./workflow\";\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\n role=\"status\"\n className={cn(\n \"mb-4 flex flex-wrap items-start gap-3 rounded-surface bg-warning-subtle p-3 text-warning\",\n className,\n )}\n >\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({\n title,\n children,\n action,\n}: {\n title: string;\n children?: React.ReactNode;\n action?: React.ReactNode;\n}) {\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","import * as React from \"react\";\nimport {\n UNSTABLE_Toast as AriaToast,\n UNSTABLE_ToastContent as ToastContent,\n UNSTABLE_ToastQueue as ToastQueue,\n UNSTABLE_ToastRegion as ToastRegion,\n Button as AriaButton,\n Text,\n} 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\";\nimport { isDev } from \"../lib/dev\";\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// - One region at a time, enforced (issue #230): the first mounted owns the queue and a second one draws nothing and\n// says so in development, naming the fix. Two regions on one queue show every toast twice, which looks like a bug in\n// the toast and (in a test) fails `findByText` with \"Found multiple elements\"; the usual cause is a route tree that\n// draws the region in its root layout while a test helper draws one too (`renderRoutes(..., { toasts: false })`),\n// or an app with a region in a layout and another in a page. Ownership is held by a mounted-order list, not by the\n// queue, so unmounting the owner hands it to the next region.\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 // Nothing appears without a region, and nothing says so: in development the first such call does (issue #249).\n if (mounted.length === 0 && !warnedNoRegion && isDev()) {\n warnedNoRegion = true;\n console.warn(\n \"strata-react: toast.show() was called but no StrataToastRegion is mounted, so nothing will appear. Render <StrataToastRegion /> once at the app root.\",\n );\n }\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 = {\n info: { icon: Info, color: \"text-info\" },\n success: { icon: CircleCheck, color: \"text-success\" },\n warning: { icon: TriangleAlert, color: \"text-warning\" },\n} 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 regions mounted now, oldest first: the first draws, the rest stay empty.\nconst mounted: string[] = [];\nlet warnedNoRegion = false;\n/** For tests: forget that the missing-region warning was given. */\nexport function resetToastWarnings() {\n warnedNoRegion = false;\n}\nconst watchers = new Set<() => void>();\nconst changed = () => watchers.forEach((w) => w());\nconst watch = (w: () => void) => {\n watchers.add(w);\n return () => void watchers.delete(w);\n};\n\n/** True while this region is the one that draws. The server and the first client render say yes, so hydration matches. */\nfunction useOwnsQueue(): boolean {\n const id = React.useId();\n React.useLayoutEffect(() => {\n mounted.push(id);\n changed();\n return () => {\n mounted.splice(mounted.indexOf(id), 1);\n changed();\n };\n }, [id]);\n const owns = React.useSyncExternalStore(\n watch,\n () => mounted[0] === id,\n () => true,\n );\n const [warned, setWarned] = React.useState(false);\n React.useEffect(() => {\n if (owns || warned || mounted.indexOf(id) < 1) return;\n setWarned(true);\n if (isDev()) {\n console.warn(\n \"strata-react: a StrataToastRegion is already mounted, so this one draws nothing. Render it once at the app root; in a test of a route tree that draws its own, pass `toasts: false` to renderRoutes.\",\n );\n }\n }, [owns, warned, id]);\n return owns;\n}\n\n/** The one place toasts appear. Render it once at the app root; a second one mounted at the same time draws nothing and warns in development. A labelled landmark (F6), polite, above panes and the undo bar. */\nexport function StrataToastRegion({ label = \"Notifications\", className }: StrataToastRegionProps) {\n const owns = useOwnsQueue();\n if (!owns) return null;\n return (\n <ToastRegion\n queue={queue}\n aria-label={label}\n className={cn(\n \"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\",\n className,\n )}\n >\n {({ toast: t }) => (\n <AriaToast\n toast={t}\n className={cn(\n \"flex w-full max-w-sm items-start gap-3 p-3 outline-none focus-visible:outline-2 focus-visible:outline-ring\",\n overlaySurface,\n )}\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 && (\n <Text slot=\"description\" className=\"type-body-sm text-muted-foreground\">\n {t.content.description}\n </Text>\n )}\n </ToastContent>\n {t.content.action && (\n <Button\n size=\"sm\"\n onPress={() => {\n t.content.action?.onPress();\n queue.close(t.key);\n }}\n >\n {t.content.action.label}\n </Button>\n )}\n <AriaButton\n slot=\"close\"\n aria-label=\"Dismiss\"\n 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 >\n <X aria-hidden className=\"size-4\" />\n </AriaButton>\n </AriaToast>\n )}\n </ToastRegion>\n );\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(\n v: Viewport,\n nextScale: number,\n at: { x: number; y: number },\n frame: { width: number; height: number },\n): 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\n/** A box in a picture, as shares (0 to 1) of its width and height from the top left: `[x, y, width, height]`. */\nexport type ShareBox = readonly [number, number, number, number];\n\n/** A named box in the source's coordinates: `of` is the reference size in pixels, and without it the box is already shares. */\nexport type Region = {\n id: string;\n label: string;\n box: readonly [number, number, number, number];\n of?: readonly [number, number];\n};\n\n/** A region as shares of the frame, so it lands on the same part of every candidate whatever its pixel size. */\nexport function regionShares(region: Region): ShareBox {\n const [x, y, w, h] = region.box;\n if (!region.of) return [x, y, w, h];\n const [ow, oh] = region.of;\n return [x / ow, y / oh, w / ow, h / oh];\n}\n\n/** The viewport that fills the frame with a box (as much of it as fits, centred): the scale that fits the box, the offset that puts its centre at the frame's centre. */\nexport function boxViewport(box: ShareBox, frame: { width: number; height: number }): Viewport {\n const [x, y, w, h] = box;\n const scale = Math.min(MAX_SCALE, Math.max(MIN_SCALE, Math.min(1 / Math.max(w, 1e-6), 1 / Math.max(h, 1e-6))));\n return clampViewport(\n { scale, x: -scale * (x + w / 2 - 0.5) * frame.width, y: -scale * (y + h / 2 - 0.5) * frame.height },\n frame,\n );\n}\n\n/** A rectangle drawn on the frame (pixels from its top left) as shares of the picture under the viewport now. */\nexport function frameBoxToShares(\n rect: { x0: number; y0: number; x1: number; y1: number },\n v: Viewport,\n frame: { width: number; height: number },\n): ShareBox {\n const toShare = (p: number, offset: number, size: number) =>\n size ? (p - size / 2 - offset) / v.scale / size + 0.5 : 0;\n const clamp = (n: number) => Math.min(1, Math.max(0, n));\n const xa = clamp(toShare(Math.min(rect.x0, rect.x1), v.x, frame.width));\n const xb = clamp(toShare(Math.max(rect.x0, rect.x1), v.x, frame.width));\n const ya = clamp(toShare(Math.min(rect.y0, rect.y1), v.y, frame.height));\n const yb = clamp(toShare(Math.max(rect.y0, rect.y1), v.y, frame.height));\n return [xa, ya, xb - xa, yb - ya];\n}\n","// The geometry behind `BoxOverlay` (issue #237): boxes in a picture's own pixel units, the order a\n// person reads them in, and the viewport that zooms to one. No DOM, so the rules are tested without\n// a pointer. `Rect` is the same rectangle `RegionEditor` edits (`lib/region.ts`).\nimport { boxViewport, type ShareBox, type Viewport } from \"./viewport\";\nimport type { Rect } from \"./region\";\n\n/** A box on a picture, in the picture's own pixels. `label` names it for assistive technology and the list beside it. */\nexport type PictureBox = Rect & { id: string; label: string; tone?: BoxTone };\n\n/** The status role a box is drawn in. `neutral` is the foreground. Outline only, so the type underneath stays readable. */\nexport type BoxTone = \"neutral\" | \"info\" | \"success\" | \"warning\" | \"danger\";\n\n/**\n * The boxes in reading order: top to bottom in rows, left to right within a row. A box joins the\n * row above when its centre falls inside that row's first box vertically, so lines of text that\n * wobble a few pixels still read in order and two columns read row by row, not column by column.\n * Returns ids, so a caller keeps its own objects.\n */\nexport function readingOrder(boxes: readonly Rect[] & readonly { id: string }[]): string[] {\n const byTop = [...boxes].sort((a, b) => a.y + a.h / 2 - (b.y + b.h / 2) || a.x - b.x);\n const rows: (typeof byTop)[] = [];\n for (const box of byTop) {\n const row = rows[rows.length - 1];\n const centre = box.y + box.h / 2;\n if (row && centre >= row[0].y && centre <= row[0].y + row[0].h) row.push(box);\n else rows.push([box]);\n }\n return rows.flatMap((row) => row.sort((a, b) => a.x - b.x).map((b) => b.id));\n}\n\n/**\n * The viewport that fills a frame with one box of the picture. The picture sits in the frame the way\n * `object-fit: contain` puts it (a frame of another shape leaves bars), which is also how\n * `BoxOverlay` draws it, so the same numbers agree. `margin` is the share of the box added on every\n * side so the box is not touching the frame (default 0.25).\n */\nexport function zoomToBox(\n box: Rect,\n of: { w: number; h: number },\n frame: { width: number; height: number },\n margin = 0.25,\n): Viewport {\n const s = Math.min(frame.width / of.w, frame.height / of.h);\n const ox = (frame.width - of.w * s) / 2;\n const oy = (frame.height - of.h * s) / 2;\n const mx = box.w * margin;\n const my = box.h * margin;\n const shares: ShareBox = [\n (ox + (box.x - mx) * s) / frame.width,\n (oy + (box.y - my) * s) / frame.height,\n ((box.w + 2 * mx) * s) / frame.width,\n ((box.h + 2 * my) * s) / frame.height,\n ];\n return boxViewport(shares, frame);\n}\n\n/** One box of a picture to show on its own, as `Thumbnail`'s `region` takes it: the picture's size, the box in its pixels, and `pad`, how many times the box's size the crop is (default 1.6, a face with its hair and chin). */\nexport type PictureRegion = { of: { w: number; h: number }; box: Rect; pad?: number };\n\n/**\n * Where the whole picture goes so that one box of it fills a frame of `aspect` (width over height), as\n * percentages of the frame: the crop is the box grown `pad` times about its centre, then widened or\n * heightened to the frame's shape, so the box is never squashed and stays in the middle. A crop that\n * runs past the picture's edge shows the frame's own ground there, as a face at the edge of a photo\n * is shown by a server crop that pads. No canvas and no second request: the browser draws the one\n * picture, which a list of faces from the same photo shares from its cache.\n */\nexport function regionStyle(\n { of, box, pad = 1.6 }: PictureRegion,\n aspect: number,\n): { left: string; top: string; width: string; height: string } {\n let cw = Math.max(box.w * pad, 1);\n let ch = Math.max(box.h * pad, 1);\n if (cw / ch < aspect) cw = ch * aspect;\n else ch = cw / aspect;\n const x0 = box.x + box.w / 2 - cw / 2;\n const y0 = box.y + box.h / 2 - ch / 2;\n const pct = (n: number) => `${+(n * 100).toFixed(4) || 0}%`; // `|| 0`: never \"-0%\"\n return { left: pct(-x0 / cw), top: pct(-y0 / ch), width: pct(of.w / cw), height: pct(of.h / ch) };\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\";\nimport { regionStyle, type PictureRegion } from \"../lib/boxes\";\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\"`. With `alt=\"\"` and no `missing` words (a decorative avatar beside a\n// name that already says it) there is nothing to name, so the missing state is not an image role at all\n// (strata-react issue #209: an `img` named \"\" is flagged by axe, and the `<img alt=\"\">` it replaces is\n// presentational).\n//\n// What a third party's pictures need from the app (issue #209, from Tubes), which made it draw its own\n// `<img>` and lose everything above:\n//\n// - `src` may be a list, tried in order: the next one when a request fails or is rejected, the missing\n// state after the last (`maxres`, then `hq`).\n// - `onLoad(img)` sees each loaded image and may return `false` to reject it: a host that answers a\n// missing item with a 200 and a small grey placeholder is recognised by its `naturalWidth`, and the\n// next source is tried as if it had failed.\n// - `onMissing()` is called once when the thumbnail ends in its missing state after asking for\n// something (not for `src={null}`), so an app can record that the item behind it has gone.\n\n// One box of a bigger picture (strata-models' face store, where every app shows faces cut from photos):\n// `region` draws the whole picture placed so that the box fills the thumbnail, so an app shows a face,\n// or an OCR line, from the photo it already has, with the loading, missing and lazy rules above,\n// without a crop endpoint. A server crop (a smaller file) is still better for a grid of hundreds from\n// different photos; `region` is for a few faces of one photo, or before the server has cut one.\n\n// A picture the page has already loaded is shown at once when a `Thumbnail` for it mounts again (issue\n// #352, from strata-reels): a `FilmStrip` that re-fits after the window changes size, a list that\n// re-sorts or a row that remounts used to start every thumbnail as a skeleton that waited to be near the\n// screen, although the browser had the picture in its cache and a request would cost nothing. The\n// request key and the source index that loaded are remembered for the life of the page (bounded, oldest\n// forgotten first), and a new `Thumbnail` for the same request asks at once, at the source that loaded.\n// It is not trusted to be loaded: the image element says so (it is `complete` with a size when it\n// mounts from the cache, so there is no skeleton frame; otherwise its load event does), so a picture\n// that has left the cache or must be fetched again (`no-store`) keeps its skeleton while it comes, and\n// one that now fails goes through the usual missing path.\nconst loadedBefore = new Map<string, number>();\nconst LOADED_LIMIT = 2000;\n\nfunction remember(key: string, index: number) {\n loadedBefore.delete(key);\n loadedBefore.set(key, index);\n if (loadedBefore.size > LOADED_LIMIT) loadedBefore.delete(loadedBefore.keys().next().value!);\n}\n\n/** Forgets which pictures `Thumbnail` has loaded, so a test that checks the loading state starts from nothing. `renderWithStrata` and `renderRoutes` call it. */\nexport function forgetLoadedThumbnails() {\n loadedBefore.clear();\n}\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, or a list of them tried in order (the next one when a request fails or `onLoad` rejects it). `null` or an empty list when the record has no photo: the `missing` words show without a request. */\n src: string | readonly 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 /** Sees each image that loaded, with the index of its source. Return `false` to reject it (a host's grey placeholder answered with a 200): the next source is tried, or the missing state shows. */\n onLoad?: (image: HTMLImageElement, index: number) => boolean | void;\n /** Called once when the thumbnail ends in its missing state after a request failed or was rejected, never for a record with no source. */\n onMissing?: () => void;\n /** Show one box of the picture, filling the thumbnail (a face from a photo): the picture's size, the box in its pixels and `pad`, how many times the box the crop is (default 1.6). `fit` does not apply. */\n region?: PictureRegion;\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\";\ntype Outcome = { key: string; index: number; done: \"loaded\" | \"missing\" | null };\n\nconst ratioNumber = (aspect: AspectRatio) => {\n if (typeof aspect === \"number\") return aspect;\n const [w, h] = aspect.split(\"/\").map(Number);\n return w! / h!;\n};\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 onLoad,\n onMissing,\n region,\n children,\n}: ThumbnailProps) {\n // The outcome is kept with the request it belongs to (the sources 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. `index` is the source being tried.\n const sources = React.useMemo(\n () => (src === null ? [] : typeof src === \"string\" ? (src ? [src] : []) : src.filter(Boolean)),\n [src],\n );\n const key = sources.length ? `${sources.join(\"\\n\")} ${srcSet ?? \"\"}` : null;\n const [outcome, setOutcome] = React.useState<Outcome | null>(null);\n const before = key === null ? undefined : loadedBefore.get(key);\n const mine = key !== null && outcome?.key === key ? outcome : null;\n // A remembered request starts at the source that loaded, but stays \"loading\" until this image says it has.\n const index = mine?.index ?? before ?? 0;\n const phase: Phase = key === null ? \"missing\" : (mine?.done ?? \"loading\");\n const current = sources[index];\n const near = useInView({ active: !eager && sources.length > 0, rootMargin, once: true, unsupported: true });\n const requested = eager || near.inView || before !== undefined;\n // The next source, or the end of the list.\n const fail = () =>\n setOutcome(\n index + 1 < sources.length ? { key: key!, index: index + 1, done: null } : { key: key!, index, done: \"missing\" },\n );\n // An app that records what is gone is told once per request that ended without a picture.\n const told = React.useRef<string | null>(null);\n const tell = React.useRef(onMissing);\n tell.current = onMissing;\n React.useEffect(() => {\n // Any state but \"missing\" ends the last telling, so the same request failing again later is told again.\n if (phase !== \"missing\") told.current = null;\n else if (key !== null && told.current !== key) {\n told.current = key;\n tell.current?.();\n }\n }, [key, phase]);\n\n const name = [alt, missing].filter(Boolean).join(\": \");\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 {key !== null && phase !== \"missing\" && requested && (\n <img\n key={`${key}#${index}`}\n ref={(el) => {\n // From the cache the image is complete as it mounts: loaded now, with no skeleton frame (the load event also follows, and agrees).\n if (el && phase === \"loading\" && before !== undefined && el.complete && el.naturalWidth > 0)\n setOutcome({ key: key!, index, done: \"loaded\" });\n }}\n src={current}\n // The candidates are the first source's: a fallback would otherwise be replaced by the set that just failed.\n srcSet={index === 0 ? srcSet : undefined}\n sizes={sizes}\n alt={alt}\n decoding=\"async\"\n onLoad={(e) =>\n onLoad?.(e.currentTarget, index) === false\n ? fail()\n : (remember(key!, index), setOutcome({ key: key!, index, done: \"loaded\" }))\n }\n onError={fail}\n style={region ? regionStyle(region, ratioNumber(aspect)) : undefined}\n className={cn(\n \"absolute\",\n region ? \"max-w-none\" : [\"inset-0 size-full\", fit === \"cover\" ? \"object-cover\" : \"object-contain\"],\n phase === \"loading\" && \"opacity-0\",\n )}\n />\n )}\n {phase === \"missing\" && (\n <div\n {...(name ? { role: \"img\", \"aria-label\": name } : { \"aria-hidden\": true })}\n className={cn(\n \"absolute inset-0 grid\",\n fallback === undefined &&\n \"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\n aria-hidden\n className={cn(\"relative overflow-hidden rounded-control bg-muted\", className)}\n style={{ aspectRatio: ratio(aspect) }}\n >\n <Skeleton className=\"absolute inset-0\" />\n </div>\n );\n}\n","import * as React from \"react\";\n\n// The microphone as raw samples, for an app that records speech (strata-voice's studio). What an app would\n// otherwise write each time:\n// - MediaRecorder only writes compressed audio, so the samples come through an AudioWorklet (loaded from a\n// Blob URL, so the app ships no worklet file) that posts 2048 frames at a time (~43 ms at 48 kHz): about\n// 23 messages a second instead of one per 128-frame render quantum.\n// - Echo cancellation, noise suppression and automatic gain are off: each reshapes a voice, and a take is\n// meant to be the voice as it was. The worklet feeds a silent gain into the output, because a worklet\n// nothing pulls does not run.\n// - getUserMedia exists only on a secure page (https:// or http://localhost), and its refusals are\n// DOMExceptions by name; `explainMicrophoneError` turns both into a sentence a person can act on.\n// - The device is behind `MicrophoneContext`, so a screen takes it from `useMicrophone()` and a test or\n// story gives it `fakeMicrophone()` (strata-react/testing) instead: hardware is the one true external.\n// Not a React Aria part: there is none for capture, and nothing here is a control.\n// `browserMicrophone` is covered by the stories in Chromium only: jsdom has no audio graph.\n\n/** A microphone that is open and sending samples. */\nexport type MicrophoneStream = {\n sampleRate: number;\n /** What the browser calls the device (\"USB Audio Device\"), or null when it says nothing. */\n device: string | null;\n /** Stops the device (the browser's recording light goes out). */\n close: () => void;\n};\n\n/** Something that can be opened to send mono samples (-1 to 1) a chunk at a time. */\nexport type Microphone = {\n open: (onSamples: (chunk: Float32Array) => void) => Promise<MicrophoneStream>;\n};\n\n/** A microphone that would not open, with a sentence a person can act on. */\nexport class MicrophoneError extends Error {}\n\n/** The sentence for what getUserMedia threw. */\nexport function explainMicrophoneError(e: unknown): MicrophoneError {\n const name = e instanceof DOMException ? e.name : \"\";\n if (name === \"NotAllowedError\")\n return new MicrophoneError(\n \"The browser was not allowed to use the microphone. Allow it from the address bar, then try again.\",\n );\n if (name === \"NotFoundError\") return new MicrophoneError(\"No microphone was found. Plug one in, then try again.\");\n if (name === \"NotReadableError\")\n return new MicrophoneError(\"The microphone is in use by another program. Close it, then try again.\");\n // DOMException is checked apart from Error: it is an Error in browsers but not in every runtime (jsdom).\n const said = e instanceof DOMException || e instanceof Error ? e.message : String(e);\n return new MicrophoneError(`The microphone could not be opened (${said}).`);\n}\n\nconst WORKLET = `\nclass StrataTap extends AudioWorkletProcessor {\n constructor() { super(); this.buf = new Float32Array(2048); this.n = 0 }\n process(inputs) {\n const ch = inputs[0] && inputs[0][0]\n if (ch) for (let i = 0; i < ch.length; i++) {\n this.buf[this.n++] = ch[i]\n if (this.n === this.buf.length) { this.port.postMessage(this.buf.slice()); this.n = 0 }\n }\n return true\n }\n}\nregisterProcessor('strata-tap', StrataTap)\n`;\n\n/** The browser's own microphone, with its processing off. */\nexport const browserMicrophone: Microphone = {\n async open(onSamples) {\n if (typeof navigator === \"undefined\" || !navigator.mediaDevices?.getUserMedia)\n throw new MicrophoneError(\"The microphone needs a secure page: open the app at http://localhost or over https.\");\n let media: MediaStream;\n try {\n media = await navigator.mediaDevices.getUserMedia({\n audio: { channelCount: 1, echoCancellation: false, noiseSuppression: false, autoGainControl: false },\n });\n } catch (e) {\n throw explainMicrophoneError(e);\n }\n let context: AudioContext | undefined;\n const close = () => {\n for (const t of media.getTracks()) t.stop();\n void context?.close();\n };\n // Once the device is open, any failure building the graph closes it again: the caller gets no stream to\n // close, and the browser's recording light would otherwise stay on.\n try {\n context = new AudioContext();\n const url = URL.createObjectURL(new Blob([WORKLET], { type: \"text/javascript\" }));\n try {\n await context.audioWorklet.addModule(url);\n } finally {\n URL.revokeObjectURL(url);\n }\n const tap = new AudioWorkletNode(context, \"strata-tap\");\n tap.port.onmessage = (event: MessageEvent<Float32Array>) => onSamples(event.data);\n const mute = context.createGain();\n mute.gain.value = 0;\n context.createMediaStreamSource(media).connect(tap).connect(mute).connect(context.destination);\n return { sampleRate: context.sampleRate, device: media.getAudioTracks()[0]?.label || null, close };\n } catch (e) {\n close();\n throw explainMicrophoneError(e);\n }\n },\n};\n\n/** The microphone screens record from: the browser's, unless a provider gives another (a fake in tests and stories). */\nexport const MicrophoneContext = React.createContext<Microphone>(browserMicrophone);\n\n/** The microphone from the nearest `MicrophoneContext`. */\nexport const useMicrophone = (): Microphone => React.useContext(MicrophoneContext);\n"],"mappings":";;;;;;;;;;;AAGA,MAAa,iBACX;;;;ACgCF,SAAgB,QAAQ,EAAE,OAAO,QAAQ,kBAAkB,SAAoD;CAC7G,MAAM,CAAC,QAAQ,aAAa,MAAM,SAAS,eAAe;CAC1D,MAAM,CAAC,IAAI,SAAS,MAAM,SAAS,CAAC;CACpC,MAAM,SAAS,MAAM,kBAAkB,WAAW,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC;CAC/D,MAAM,OAAO,MAAM,aAAa,kBAA0B,OAAO,aAAa,KAAK,IAAI,UAAU,aAAa,CAAC,GAAG,CAAC,CAAC;CACpH,OAAO,MAAM,cAAc;EACzB,MAAM,OAAa;GACjB;GACA;GACA;GACA,WAAW,KAAK,IAAI,KAAK,EAAE,IAAI;GAC/B;GACA,OAAO,cAAc;IAAE,GAAG;IAAM,OAAO,SAAS;IAAO,OAAO,UAAU,KAAK,KAAK,KAAK;GAAE;EAC3F;EACA,OAAO;CACT,GAAG;EAAC;EAAO;EAAQ;EAAQ;EAAI;CAAI,CAAC;AACtC;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;EAChF,IAAI;GACF,MAAM,QAAQ,aAAa,UAAU,GAAG;EAC1C,UAAU;GACR,IAAI,gBAAgB,GAAG;EACzB;EACA,MAAM,MAAM,IAAI,iBAAiB,SAAS,YAAY;EACtD,IAAI,KAAK,aAAa,UAAsC,UAAU,MAAM,IAAI;EAChF,MAAM,OAAO,QAAQ,WAAW;EAChC,KAAK,KAAK,QAAQ;EAClB,QAAQ,wBAAwB,KAAK,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,QAAQ,IAAI,CAAC,CAAC,QAAQ,QAAQ,WAAW;EAC7F,OAAO;GAAE,YAAY,QAAQ;GAAY,QAAQ,MAAM,eAAe,CAAC,CAAC,EAAE,EAAE,SAAS;GAAM;EAAM;CACnG,SAAS,GAAG;EACV,MAAM;EACN,MAAM,uBAAuB,CAAC;CAChC;AACF,EACF;;AAGA,MAAa,oBAAoB,MAAM,cAA0B,iBAAiB;;AAGlF,MAAa,sBAAkC,MAAM,WAAW,iBAAiB"}
1
+ {"version":3,"file":"microphone-D3sbBVka.js","names":["Button","ToastQueue","ToastRegion","AriaToast","ToastContent","Button","AriaButton"],"sources":["../src/lib/overlay.ts","../src/query/poll.ts","../src/query/index.tsx","../src/components/data-view.tsx","../src/components/toast.tsx","../src/lib/viewport.ts","../src/lib/boxes.ts","../src/components/thumbnail.tsx","../src/lib/microphone.ts"],"sourcesContent":["// 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","import * as React from \"react\";\nimport type { UseQueryResult } from \"@tanstack/react-query\";\n\n// Pausing a polled read (strata-react issue #344, from the status page in jburnhams/homepage). A\n// screen that re-reads every few seconds needs the same three parts every time: whether it is\n// paused, a button that says so, and when the readings were taken. A person reading a table while\n// it re-sorts under them needs the pause (ux-research `patterns.md` on live data: the person, not\n// the poll, decides when the view moves); a page whose readings may be minutes old needs the time.\n// Written by hand it was a `useState`, a button with `aria-pressed`, `refetchInterval: paused ?\n// false : ms` and an \"updated 12:00\" line, in every live screen.\n//\n// - `usePoll({ every })` holds the state and is passed to `useLoad({ poll })`, which polls at its\n// interval while it is not paused, notes when each read arrived, and reads once at once when the\n// poll is resumed (what was on screen is as old as the pause).\n// - `PauseButton` (components/pause-button.tsx) takes the same object, with its words fixed.\n// - One `Poll` may serve several reads: the page pauses together. The time is the latest read's. A read\n// with its own pace takes `poll.with({ every })`: same pause and time, other interval (#349).\n// - `useJob` keeps its own interval: a job is polled only while it runs, which is not the person's\n// to pause.\n\n/** The state of a polled read: its interval, whether the person paused it and when it last read. Made by `usePoll`. */\nexport type Poll = {\n /** Milliseconds between reads while not paused. */\n every: number;\n paused: boolean;\n /** Pause or resume. Resuming reads at once. */\n toggle: () => void;\n /** When the last read arrived, or `null` before the first. */\n updatedAt: Date | null;\n /** Used by `useLoad`: records the time of the read that just arrived (TanStack's `dataUpdatedAt`; 0 is none). */\n note: (dataUpdatedAt: number) => void;\n /** The same poll at another pace: a read that must be slower (or faster) than the page's keeps the shared pause, resume and \"updated\" time (`useLoad({ poll: poll.with({ every: 60_000 }) })`). */\n with: (override: { every: number }) => Poll;\n};\n\n/** The pause state and last-read time of a polled screen: pass it to `useLoad({ poll })` and to `PauseButton`. */\nexport function usePoll({ every, paused: initiallyPaused = false }: { every: number; paused?: boolean }): Poll {\n const [paused, setPaused] = React.useState(initiallyPaused);\n const [at, setAt] = React.useState(0);\n const toggle = React.useCallback(() => setPaused((p) => !p), []);\n const note = React.useCallback((dataUpdatedAt: number) => setAt((previous) => Math.max(previous, dataUpdatedAt)), []);\n return React.useMemo(() => {\n const poll: Poll = {\n every,\n paused,\n toggle,\n updatedAt: at ? new Date(at) : null,\n note,\n with: (override) => ({ ...poll, every: override.every, with: (again) => poll.with(again) }),\n };\n return poll;\n }, [every, paused, toggle, at, note]);\n}\n\n/** Wires a query to its `Poll`: the time of each read, and one read when the poll is resumed. */\nexport function usePollBinding(poll: Poll | undefined, query: Pick<UseQueryResult, \"dataUpdatedAt\" | \"refetch\">) {\n const note = poll?.note;\n React.useEffect(() => {\n if (note && query.dataUpdatedAt) note(query.dataUpdatedAt);\n }, [note, query.dataUpdatedAt]);\n const paused = poll?.paused;\n const wasPaused = React.useRef(paused);\n React.useEffect(() => {\n if (wasPaused.current && paused === false) void query.refetch();\n wasPaused.current = paused;\n // `refetch` is stable per query; only the pause changing should read.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [paused]);\n}\n","import * as React from \"react\";\nimport {\n QueryClient,\n QueryClientProvider,\n useQuery,\n type QueryKey,\n type UseQueryOptions,\n type UseQueryResult,\n} from \"@tanstack/react-query\";\nimport type { Load, Stale } from \"../components/data-view\";\nimport { usePollBinding, type Poll } from \"./poll\";\nimport {\n HttpError,\n describeHttpError,\n errorPayload,\n readErrorBody,\n type DescribeError,\n type ErrorBody,\n} from \"../lib/errors\";\n\nexport { HttpError, describeHttpError, errorPayload, readErrorBody, type DescribeError, type ErrorBody };\n\n// Data loading, the Strata way: TanStack Query fetches and caches, and every view of the result\n// goes through DataView, which takes a Load<T>. `toLoad` is the one bridge between them, so a\n// screen never re-derives loading/error/ready from a query's flags and never forgets one.\n//\n// Opinions in createQueryClient: one retry (a second failure is real and the person should see\n// it with a \"Try again\"), 30 s stale time (dashboards are read many times a minute but change\n// over minutes), and no refetch on window focus (a table that reorders itself while someone reads\n// it is worse than one that is 30 s old). Override per query when the data says otherwise.\n\n/** A QueryClient with Strata's defaults: one retry, 30 s stale time, no refetch on window focus. */\nexport function createQueryClient(overrides?: ConstructorParameters<typeof QueryClient>[0]) {\n return new QueryClient({\n ...overrides,\n defaultOptions: {\n ...overrides?.defaultOptions,\n queries: { retry: 1, staleTime: 30_000, refetchOnWindowFocus: false, ...overrides?.defaultOptions?.queries },\n },\n });\n}\n\n/** Provides a query client (Strata's defaults unless one is passed) to the app. */\nexport function StrataQueryProvider({ client, children }: { client?: QueryClient; children: React.ReactNode }) {\n const [fallback] = React.useState(() => client ?? createQueryClient());\n return <QueryClientProvider client={client ?? fallback}>{children}</QueryClientProvider>;\n}\n\n/**\n * Turns a TanStack query result into the `Load<T>` that `DataView` takes; errors are described for a person by `describe`.\n * A refetch that fails after data arrived stays `ready`, with `stale` saying why and when the data was read.\n */\nexport function toLoad<T>(query: UseQueryResult<T>, describe: DescribeError = describeHttpError): Load<T> {\n if (query.status === \"success\") return { status: \"ready\", data: query.data };\n // TanStack keeps the last good data when a refetch fails and sets status \"error\" (isRefetchError).\n // That is old data, not no data: keep it on screen and say how old it is.\n if (query.status === \"error\" && query.data !== undefined)\n return { status: \"ready\", data: query.data, stale: staleOf(query, describe) };\n if (query.status === \"error\")\n return { status: \"error\", message: describe(query.error), retry: () => void query.refetch() };\n return { status: \"loading\" };\n}\n\n/** The `Stale` of a query whose refetch failed after a good read. Shared by `toLoad` and `useInfiniteLoad`. */\nexport function staleOf(\n query: { error: unknown; dataUpdatedAt: number; isFetching: boolean; refetch: () => unknown },\n describe: DescribeError = describeHttpError,\n): Stale {\n return {\n message: describe(query.error),\n readAt: new Date(query.dataUpdatedAt),\n retry: () => void query.refetch(),\n retrying: query.isFetching,\n };\n}\n\n/** `useQuery`, returned as a `Load<T>` for `DataView`. With `poll` (from `usePoll`) it reads again every `poll.every` ms until the person pauses it. */\nexport function useLoad<T, K extends QueryKey = QueryKey>(\n options: UseQueryOptions<T, Error, T, K> & {\n describeError?: DescribeError;\n /** Read again on this poll's interval unless it is paused; see `usePoll` and `PauseButton`. Replaces `refetchInterval`. */\n poll?: Poll;\n },\n): Load<T> {\n const { describeError, poll, ...rest } = options;\n const query = useQuery(poll ? { ...rest, refetchInterval: poll.paused ? false : poll.every } : rest);\n usePollBinding(poll, query);\n return toLoad(query, describeError);\n}\n\n/** What `fetchJson` takes as `fetch`'s init, plus `json`. */\nexport type FetchJsonInit = RequestInit & {\n /**\n * A value sent as the JSON body: `Content-Type: application/json` is set unless the caller gave one, and the method is `POST` unless given.\n * Replaces `body`; an app never builds the `RequestInit` for a write by hand.\n */\n json?: unknown;\n};\n\n/** Options for `fetchJson` beyond `fetch`'s own. */\nexport type FetchJsonOptions = {\n /** Finds the server's reason and per-field messages in an error body. Default `readErrorBody` (FastAPI's `detail`, `message`, `error`). */\n readError?: (body: unknown) => ErrorBody;\n};\n\n/**\n * fetch() that throws an HttpError on a non-2xx response and parses JSON: the queryFn default, and the usual commit for a write.\n * `init.json` sends a JSON body without building the headers. A 204 or empty body resolves to undefined. An error response's body is read onto the HttpError (`body`, `reason`, `fieldErrors`).\n */\nexport async function fetchJson<T>(\n input: string | URL,\n init?: FetchJsonInit,\n { readError = readErrorBody }: FetchJsonOptions = {},\n): Promise<T> {\n const { json, ...rest } = init ?? {};\n // Headers, tuple arrays and plain objects are all valid HeadersInit; normalise before adding the\n // default so a caller's Authorization (or their own Accept) is never dropped.\n const headers = new Headers(rest.headers);\n if (!headers.has(\"Accept\")) headers.set(\"Accept\", \"application/json\");\n if (json !== undefined) {\n if (!headers.has(\"Content-Type\")) headers.set(\"Content-Type\", \"application/json\");\n rest.body = JSON.stringify(json);\n rest.method ??= \"POST\";\n }\n const res = await fetch(input, { ...rest, headers });\n if (!res.ok) {\n // The body is read as text and parsed only when it parses: a proxy's HTML 502 page or an empty\n // body must still throw the HttpError, never a JSON SyntaxError in its place.\n const raw = await res.text().catch(() => \"\");\n let body: unknown = raw || undefined;\n try {\n if (raw) body = JSON.parse(raw);\n } catch {\n // Not JSON: keep the text.\n }\n throw new HttpError(res.status, res.statusText, String(input), body, readError(body));\n }\n // Writes (DELETE, a PUT that returns nothing) answer 204 or an empty body; that is success, not a\n // JSON parse error.\n const text = res.status === 204 ? \"\" : await res.text();\n return (text ? JSON.parse(text) : undefined) as T;\n}\n\nexport { usePoll, type Poll } from \"./poll\";\nexport { createApi, type Api, type ApiOptions } from \"./api\";\nexport { createTypedApi, type TypedApi } from \"./typed-api\";\nexport {\n useInfiniteLoad,\n apiPage,\n type ApiPage,\n type InfiniteLoad,\n type InfiniteLoadOptions,\n type More,\n} from \"./infinite\";\nexport { useJob, isTaskRunning, type Job, type JobOptions } from \"./job\";\nexport { useWorkflowRun, isWorkflowRunning, type WorkflowRunLike, type WorkflowRunOptions } from \"./workflow\";\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\n role=\"status\"\n className={cn(\n \"mb-4 flex flex-wrap items-start gap-3 rounded-surface bg-warning-subtle p-3 text-warning\",\n className,\n )}\n >\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({\n title,\n children,\n action,\n}: {\n title: string;\n children?: React.ReactNode;\n action?: React.ReactNode;\n}) {\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","import * as React from \"react\";\nimport {\n UNSTABLE_Toast as AriaToast,\n UNSTABLE_ToastContent as ToastContent,\n UNSTABLE_ToastQueue as ToastQueue,\n UNSTABLE_ToastRegion as ToastRegion,\n Button as AriaButton,\n Text,\n} 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\";\nimport { isDev } from \"../lib/dev\";\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// - One region at a time, enforced (issue #230): the first mounted owns the queue and a second one draws nothing and\n// says so in development, naming the fix. Two regions on one queue show every toast twice, which looks like a bug in\n// the toast and (in a test) fails `findByText` with \"Found multiple elements\"; the usual cause is a route tree that\n// draws the region in its root layout while a test helper draws one too (`renderRoutes(..., { toasts: false })`),\n// or an app with a region in a layout and another in a page. Ownership is held by a mounted-order list, not by the\n// queue, so unmounting the owner hands it to the next region.\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 // Nothing appears without a region, and nothing says so: in development the first such call does (issue #249).\n if (mounted.length === 0 && !warnedNoRegion && isDev()) {\n warnedNoRegion = true;\n console.warn(\n \"strata-react: toast.show() was called but no StrataToastRegion is mounted, so nothing will appear. Render <StrataToastRegion /> once at the app root.\",\n );\n }\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 = {\n info: { icon: Info, color: \"text-info\" },\n success: { icon: CircleCheck, color: \"text-success\" },\n warning: { icon: TriangleAlert, color: \"text-warning\" },\n} 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 regions mounted now, oldest first: the first draws, the rest stay empty.\nconst mounted: string[] = [];\nlet warnedNoRegion = false;\n/** For tests: forget that the missing-region warning was given. */\nexport function resetToastWarnings() {\n warnedNoRegion = false;\n}\nconst watchers = new Set<() => void>();\nconst changed = () => watchers.forEach((w) => w());\nconst watch = (w: () => void) => {\n watchers.add(w);\n return () => void watchers.delete(w);\n};\n\n/** True while this region is the one that draws. The server and the first client render say yes, so hydration matches. */\nfunction useOwnsQueue(): boolean {\n const id = React.useId();\n React.useLayoutEffect(() => {\n mounted.push(id);\n changed();\n return () => {\n mounted.splice(mounted.indexOf(id), 1);\n changed();\n };\n }, [id]);\n const owns = React.useSyncExternalStore(\n watch,\n () => mounted[0] === id,\n () => true,\n );\n const [warned, setWarned] = React.useState(false);\n React.useEffect(() => {\n if (owns || warned || mounted.indexOf(id) < 1) return;\n setWarned(true);\n if (isDev()) {\n console.warn(\n \"strata-react: a StrataToastRegion is already mounted, so this one draws nothing. Render it once at the app root; in a test of a route tree that draws its own, pass `toasts: false` to renderRoutes.\",\n );\n }\n }, [owns, warned, id]);\n return owns;\n}\n\n/** The one place toasts appear. Render it once at the app root; a second one mounted at the same time draws nothing and warns in development. A labelled landmark (F6), polite, above panes and the undo bar. */\nexport function StrataToastRegion({ label = \"Notifications\", className }: StrataToastRegionProps) {\n const owns = useOwnsQueue();\n if (!owns) return null;\n return (\n <ToastRegion\n queue={queue}\n aria-label={label}\n className={cn(\n \"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\",\n className,\n )}\n >\n {({ toast: t }) => (\n <AriaToast\n toast={t}\n className={cn(\n \"flex w-full max-w-sm items-start gap-3 p-3 outline-none focus-visible:outline-2 focus-visible:outline-ring\",\n overlaySurface,\n )}\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 && (\n <Text slot=\"description\" className=\"type-body-sm text-muted-foreground\">\n {t.content.description}\n </Text>\n )}\n </ToastContent>\n {t.content.action && (\n <Button\n size=\"sm\"\n onPress={() => {\n t.content.action?.onPress();\n queue.close(t.key);\n }}\n >\n {t.content.action.label}\n </Button>\n )}\n <AriaButton\n slot=\"close\"\n aria-label=\"Dismiss\"\n 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 >\n <X aria-hidden className=\"size-4\" />\n </AriaButton>\n </AriaToast>\n )}\n </ToastRegion>\n );\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(\n v: Viewport,\n nextScale: number,\n at: { x: number; y: number },\n frame: { width: number; height: number },\n): 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\n/** A box in a picture, as shares (0 to 1) of its width and height from the top left: `[x, y, width, height]`. */\nexport type ShareBox = readonly [number, number, number, number];\n\n/** A named box in the source's coordinates: `of` is the reference size in pixels, and without it the box is already shares. */\nexport type Region = {\n id: string;\n label: string;\n box: readonly [number, number, number, number];\n of?: readonly [number, number];\n};\n\n/** A region as shares of the frame, so it lands on the same part of every candidate whatever its pixel size. */\nexport function regionShares(region: Region): ShareBox {\n const [x, y, w, h] = region.box;\n if (!region.of) return [x, y, w, h];\n const [ow, oh] = region.of;\n return [x / ow, y / oh, w / ow, h / oh];\n}\n\n/** The viewport that fills the frame with a box (as much of it as fits, centred): the scale that fits the box, the offset that puts its centre at the frame's centre. */\nexport function boxViewport(box: ShareBox, frame: { width: number; height: number }): Viewport {\n const [x, y, w, h] = box;\n const scale = Math.min(MAX_SCALE, Math.max(MIN_SCALE, Math.min(1 / Math.max(w, 1e-6), 1 / Math.max(h, 1e-6))));\n return clampViewport(\n { scale, x: -scale * (x + w / 2 - 0.5) * frame.width, y: -scale * (y + h / 2 - 0.5) * frame.height },\n frame,\n );\n}\n\n/** A rectangle drawn on the frame (pixels from its top left) as shares of the picture under the viewport now. */\nexport function frameBoxToShares(\n rect: { x0: number; y0: number; x1: number; y1: number },\n v: Viewport,\n frame: { width: number; height: number },\n): ShareBox {\n const toShare = (p: number, offset: number, size: number) =>\n size ? (p - size / 2 - offset) / v.scale / size + 0.5 : 0;\n const clamp = (n: number) => Math.min(1, Math.max(0, n));\n const xa = clamp(toShare(Math.min(rect.x0, rect.x1), v.x, frame.width));\n const xb = clamp(toShare(Math.max(rect.x0, rect.x1), v.x, frame.width));\n const ya = clamp(toShare(Math.min(rect.y0, rect.y1), v.y, frame.height));\n const yb = clamp(toShare(Math.max(rect.y0, rect.y1), v.y, frame.height));\n return [xa, ya, xb - xa, yb - ya];\n}\n","// The geometry behind `BoxOverlay` (issue #237): boxes in a picture's own pixel units, the order a\n// person reads them in, and the viewport that zooms to one. No DOM, so the rules are tested without\n// a pointer. `Rect` is the same rectangle `RegionEditor` edits (`lib/region.ts`).\nimport { boxViewport, type ShareBox, type Viewport } from \"./viewport\";\nimport type { Rect } from \"./region\";\n\n/** A box on a picture, in the picture's own pixels. `label` names it for assistive technology and the list beside it. */\nexport type PictureBox = Rect & { id: string; label: string; tone?: BoxTone };\n\n/** The status role a box is drawn in. `neutral` is the foreground. Outline only, so the type underneath stays readable. */\nexport type BoxTone = \"neutral\" | \"info\" | \"success\" | \"warning\" | \"danger\";\n\n/**\n * The boxes in reading order: top to bottom in rows, left to right within a row. A box joins the\n * row above when its centre falls inside that row's first box vertically, so lines of text that\n * wobble a few pixels still read in order and two columns read row by row, not column by column.\n * Returns ids, so a caller keeps its own objects.\n */\nexport function readingOrder(boxes: readonly Rect[] & readonly { id: string }[]): string[] {\n const byTop = [...boxes].sort((a, b) => a.y + a.h / 2 - (b.y + b.h / 2) || a.x - b.x);\n const rows: (typeof byTop)[] = [];\n for (const box of byTop) {\n const row = rows[rows.length - 1];\n const centre = box.y + box.h / 2;\n if (row && centre >= row[0].y && centre <= row[0].y + row[0].h) row.push(box);\n else rows.push([box]);\n }\n return rows.flatMap((row) => row.sort((a, b) => a.x - b.x).map((b) => b.id));\n}\n\n/**\n * The viewport that fills a frame with one box of the picture. The picture sits in the frame the way\n * `object-fit: contain` puts it (a frame of another shape leaves bars), which is also how\n * `BoxOverlay` draws it, so the same numbers agree. `margin` is the share of the box added on every\n * side so the box is not touching the frame (default 0.25).\n */\nexport function zoomToBox(\n box: Rect,\n of: { w: number; h: number },\n frame: { width: number; height: number },\n margin = 0.25,\n): Viewport {\n const s = Math.min(frame.width / of.w, frame.height / of.h);\n const ox = (frame.width - of.w * s) / 2;\n const oy = (frame.height - of.h * s) / 2;\n const mx = box.w * margin;\n const my = box.h * margin;\n const shares: ShareBox = [\n (ox + (box.x - mx) * s) / frame.width,\n (oy + (box.y - my) * s) / frame.height,\n ((box.w + 2 * mx) * s) / frame.width,\n ((box.h + 2 * my) * s) / frame.height,\n ];\n return boxViewport(shares, frame);\n}\n\n/** One box of a picture to show on its own, as `Thumbnail`'s `region` takes it: the picture's size, the box in its pixels, and `pad`, how many times the box's size the crop is (default 1.6, a face with its hair and chin). */\nexport type PictureRegion = { of: { w: number; h: number }; box: Rect; pad?: number };\n\n/**\n * Where the whole picture goes so that one box of it fills a frame of `aspect` (width over height), as\n * percentages of the frame: the crop is the box grown `pad` times about its centre, then widened or\n * heightened to the frame's shape, so the box is never squashed and stays in the middle. A crop that\n * runs past the picture's edge shows the frame's own ground there, as a face at the edge of a photo\n * is shown by a server crop that pads. No canvas and no second request: the browser draws the one\n * picture, which a list of faces from the same photo shares from its cache.\n */\nexport function regionStyle(\n { of, box, pad = 1.6 }: PictureRegion,\n aspect: number,\n): { left: string; top: string; width: string; height: string } {\n let cw = Math.max(box.w * pad, 1);\n let ch = Math.max(box.h * pad, 1);\n if (cw / ch < aspect) cw = ch * aspect;\n else ch = cw / aspect;\n const x0 = box.x + box.w / 2 - cw / 2;\n const y0 = box.y + box.h / 2 - ch / 2;\n const pct = (n: number) => `${+(n * 100).toFixed(4) || 0}%`; // `|| 0`: never \"-0%\"\n return { left: pct(-x0 / cw), top: pct(-y0 / ch), width: pct(of.w / cw), height: pct(of.h / ch) };\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\";\nimport { regionStyle, type PictureRegion } from \"../lib/boxes\";\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\"`. With `alt=\"\"` and no `missing` words (a decorative avatar beside a\n// name that already says it) there is nothing to name, so the missing state is not an image role at all\n// (strata-react issue #209: an `img` named \"\" is flagged by axe, and the `<img alt=\"\">` it replaces is\n// presentational).\n//\n// What a third party's pictures need from the app (issue #209, from Tubes), which made it draw its own\n// `<img>` and lose everything above:\n//\n// - `src` may be a list, tried in order: the next one when a request fails or is rejected, the missing\n// state after the last (`maxres`, then `hq`).\n// - `onLoad(img)` sees each loaded image and may return `false` to reject it: a host that answers a\n// missing item with a 200 and a small grey placeholder is recognised by its `naturalWidth`, and the\n// next source is tried as if it had failed.\n// - `onMissing()` is called once when the thumbnail ends in its missing state after asking for\n// something (not for `src={null}`), so an app can record that the item behind it has gone.\n\n// One box of a bigger picture (strata-models' face store, where every app shows faces cut from photos):\n// `region` draws the whole picture placed so that the box fills the thumbnail, so an app shows a face,\n// or an OCR line, from the photo it already has, with the loading, missing and lazy rules above,\n// without a crop endpoint. A server crop (a smaller file) is still better for a grid of hundreds from\n// different photos; `region` is for a few faces of one photo, or before the server has cut one.\n\n// A picture the page has already loaded is shown at once when a `Thumbnail` for it mounts again (issue\n// #352, from strata-reels): a `FilmStrip` that re-fits after the window changes size, a list that\n// re-sorts or a row that remounts used to start every thumbnail as a skeleton that waited to be near the\n// screen, although the browser had the picture in its cache and a request would cost nothing. The\n// request key and the source index that loaded are remembered for the life of the page (bounded, oldest\n// forgotten first), and a new `Thumbnail` for the same request asks at once, at the source that loaded.\n// It is not trusted to be loaded: the image element says so (it is `complete` with a size when it\n// mounts from the cache, so there is no skeleton frame; otherwise its load event does), so a picture\n// that has left the cache or must be fetched again (`no-store`) keeps its skeleton while it comes, and\n// one that now fails goes through the usual missing path.\nconst loadedBefore = new Map<string, number>();\nconst LOADED_LIMIT = 2000;\n\nfunction remember(key: string, index: number) {\n loadedBefore.delete(key);\n loadedBefore.set(key, index);\n if (loadedBefore.size > LOADED_LIMIT) loadedBefore.delete(loadedBefore.keys().next().value!);\n}\n\n/** Forgets which pictures `Thumbnail` has loaded, so a test that checks the loading state starts from nothing. `renderWithStrata` and `renderRoutes` call it. */\nexport function forgetLoadedThumbnails() {\n loadedBefore.clear();\n}\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, or a list of them tried in order (the next one when a request fails or `onLoad` rejects it). `null` or an empty list when the record has no photo: the `missing` words show without a request. */\n src: string | readonly 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 /** Sees each image that loaded, with the index of its source. Return `false` to reject it (a host's grey placeholder answered with a 200): the next source is tried, or the missing state shows. */\n onLoad?: (image: HTMLImageElement, index: number) => boolean | void;\n /** Called once when the thumbnail ends in its missing state after a request failed or was rejected, never for a record with no source. */\n onMissing?: () => void;\n /** Show one box of the picture, filling the thumbnail (a face from a photo): the picture's size, the box in its pixels and `pad`, how many times the box the crop is (default 1.6). `fit` does not apply. */\n region?: PictureRegion;\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\";\ntype Outcome = { key: string; index: number; done: \"loaded\" | \"missing\" | null };\n\nconst ratioNumber = (aspect: AspectRatio) => {\n if (typeof aspect === \"number\") return aspect;\n const [w, h] = aspect.split(\"/\").map(Number);\n return w! / h!;\n};\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 onLoad,\n onMissing,\n region,\n children,\n}: ThumbnailProps) {\n // The outcome is kept with the request it belongs to (the sources 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. `index` is the source being tried.\n const sources = React.useMemo(\n () => (src === null ? [] : typeof src === \"string\" ? (src ? [src] : []) : src.filter(Boolean)),\n [src],\n );\n const key = sources.length ? `${sources.join(\"\\n\")} ${srcSet ?? \"\"}` : null;\n const [outcome, setOutcome] = React.useState<Outcome | null>(null);\n const before = key === null ? undefined : loadedBefore.get(key);\n const mine = key !== null && outcome?.key === key ? outcome : null;\n // A remembered request starts at the source that loaded, but stays \"loading\" until this image says it has.\n const index = mine?.index ?? before ?? 0;\n const phase: Phase = key === null ? \"missing\" : (mine?.done ?? \"loading\");\n const current = sources[index];\n const near = useInView({ active: !eager && sources.length > 0, rootMargin, once: true, unsupported: true });\n const requested = eager || near.inView || before !== undefined;\n // The next source, or the end of the list.\n const fail = () =>\n setOutcome(\n index + 1 < sources.length ? { key: key!, index: index + 1, done: null } : { key: key!, index, done: \"missing\" },\n );\n // An app that records what is gone is told once per request that ended without a picture.\n const told = React.useRef<string | null>(null);\n const tell = React.useRef(onMissing);\n tell.current = onMissing;\n React.useEffect(() => {\n // Any state but \"missing\" ends the last telling, so the same request failing again later is told again.\n if (phase !== \"missing\") told.current = null;\n else if (key !== null && told.current !== key) {\n told.current = key;\n tell.current?.();\n }\n }, [key, phase]);\n\n const name = [alt, missing].filter(Boolean).join(\": \");\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 {key !== null && phase !== \"missing\" && requested && (\n <img\n key={`${key}#${index}`}\n ref={(el) => {\n // From the cache the image is complete as it mounts: loaded now, with no skeleton frame (the load event also follows, and agrees).\n if (el && phase === \"loading\" && before !== undefined && el.complete && el.naturalWidth > 0)\n setOutcome({ key: key!, index, done: \"loaded\" });\n }}\n src={current}\n // The candidates are the first source's: a fallback would otherwise be replaced by the set that just failed.\n srcSet={index === 0 ? srcSet : undefined}\n sizes={sizes}\n alt={alt}\n decoding=\"async\"\n onLoad={(e) =>\n onLoad?.(e.currentTarget, index) === false\n ? fail()\n : (remember(key!, index), setOutcome({ key: key!, index, done: \"loaded\" }))\n }\n onError={fail}\n style={region ? regionStyle(region, ratioNumber(aspect)) : undefined}\n className={cn(\n \"absolute\",\n region ? \"max-w-none\" : [\"inset-0 size-full\", fit === \"cover\" ? \"object-cover\" : \"object-contain\"],\n phase === \"loading\" && \"opacity-0\",\n )}\n />\n )}\n {phase === \"missing\" && (\n <div\n {...(name ? { role: \"img\", \"aria-label\": name } : { \"aria-hidden\": true })}\n className={cn(\n \"absolute inset-0 grid\",\n fallback === undefined &&\n \"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\n aria-hidden\n className={cn(\"relative overflow-hidden rounded-control bg-muted\", className)}\n style={{ aspectRatio: ratio(aspect) }}\n >\n <Skeleton className=\"absolute inset-0\" />\n </div>\n );\n}\n","import * as React from \"react\";\n\n// The microphone as raw samples, for an app that records speech (strata-voice's studio). What an app would\n// otherwise write each time:\n// - MediaRecorder only writes compressed audio, so the samples come through an AudioWorklet (loaded from a\n// Blob URL, so the app ships no worklet file) that posts 2048 frames at a time (~43 ms at 48 kHz): about\n// 23 messages a second instead of one per 128-frame render quantum.\n// - Echo cancellation, noise suppression and automatic gain are off: each reshapes a voice, and a take is\n// meant to be the voice as it was. The worklet feeds a silent gain into the output, because a worklet\n// nothing pulls does not run.\n// - getUserMedia exists only on a secure page (https:// or http://localhost), and its refusals are\n// DOMExceptions by name; `explainMicrophoneError` turns both into a sentence a person can act on.\n// - The device is behind `MicrophoneContext`, so a screen takes it from `useMicrophone()` and a test or\n// story gives it `fakeMicrophone()` (strata-react/testing) instead: hardware is the one true external.\n// Not a React Aria part: there is none for capture, and nothing here is a control.\n// `browserMicrophone` is covered by the stories in Chromium only: jsdom has no audio graph.\n\n/** A microphone that is open and sending samples. */\nexport type MicrophoneStream = {\n sampleRate: number;\n /** What the browser calls the device (\"USB Audio Device\"), or null when it says nothing. */\n device: string | null;\n /** Stops the device (the browser's recording light goes out). */\n close: () => void;\n};\n\n/** Something that can be opened to send mono samples (-1 to 1) a chunk at a time. */\nexport type Microphone = {\n open: (onSamples: (chunk: Float32Array) => void) => Promise<MicrophoneStream>;\n};\n\n/** A microphone that would not open, with a sentence a person can act on. */\nexport class MicrophoneError extends Error {}\n\n/** The sentence for what getUserMedia threw. */\nexport function explainMicrophoneError(e: unknown): MicrophoneError {\n const name = e instanceof DOMException ? e.name : \"\";\n if (name === \"NotAllowedError\")\n return new MicrophoneError(\n \"The browser was not allowed to use the microphone. Allow it from the address bar, then try again.\",\n );\n if (name === \"NotFoundError\") return new MicrophoneError(\"No microphone was found. Plug one in, then try again.\");\n if (name === \"NotReadableError\")\n return new MicrophoneError(\"The microphone is in use by another program. Close it, then try again.\");\n // DOMException is checked apart from Error: it is an Error in browsers but not in every runtime (jsdom).\n const said = e instanceof DOMException || e instanceof Error ? e.message : String(e);\n return new MicrophoneError(`The microphone could not be opened (${said}).`);\n}\n\nconst WORKLET = `\nclass StrataTap extends AudioWorkletProcessor {\n constructor() { super(); this.buf = new Float32Array(2048); this.n = 0 }\n process(inputs) {\n const ch = inputs[0] && inputs[0][0]\n if (ch) for (let i = 0; i < ch.length; i++) {\n this.buf[this.n++] = ch[i]\n if (this.n === this.buf.length) { this.port.postMessage(this.buf.slice()); this.n = 0 }\n }\n return true\n }\n}\nregisterProcessor('strata-tap', StrataTap)\n`;\n\n/** The browser's own microphone, with its processing off. */\nexport const browserMicrophone: Microphone = {\n async open(onSamples) {\n if (typeof navigator === \"undefined\" || !navigator.mediaDevices?.getUserMedia)\n throw new MicrophoneError(\"The microphone needs a secure page: open the app at http://localhost or over https.\");\n let media: MediaStream;\n try {\n media = await navigator.mediaDevices.getUserMedia({\n audio: { channelCount: 1, echoCancellation: false, noiseSuppression: false, autoGainControl: false },\n });\n } catch (e) {\n throw explainMicrophoneError(e);\n }\n let context: AudioContext | undefined;\n const close = () => {\n for (const t of media.getTracks()) t.stop();\n void context?.close();\n };\n // Once the device is open, any failure building the graph closes it again: the caller gets no stream to\n // close, and the browser's recording light would otherwise stay on.\n try {\n context = new AudioContext();\n const url = URL.createObjectURL(new Blob([WORKLET], { type: \"text/javascript\" }));\n try {\n await context.audioWorklet.addModule(url);\n } finally {\n URL.revokeObjectURL(url);\n }\n const tap = new AudioWorkletNode(context, \"strata-tap\");\n tap.port.onmessage = (event: MessageEvent<Float32Array>) => onSamples(event.data);\n const mute = context.createGain();\n mute.gain.value = 0;\n context.createMediaStreamSource(media).connect(tap).connect(mute).connect(context.destination);\n return { sampleRate: context.sampleRate, device: media.getAudioTracks()[0]?.label || null, close };\n } catch (e) {\n close();\n throw explainMicrophoneError(e);\n }\n },\n};\n\n/** The microphone screens record from: the browser's, unless a provider gives another (a fake in tests and stories). */\nexport const MicrophoneContext = React.createContext<Microphone>(browserMicrophone);\n\n/** The microphone from the nearest `MicrophoneContext`. */\nexport const useMicrophone = (): Microphone => React.useContext(MicrophoneContext);\n"],"mappings":";;;;;;;;;;;AAGA,MAAa,iBACX;;;;ACgCF,SAAgB,QAAQ,EAAE,OAAO,QAAQ,kBAAkB,SAAoD;CAC7G,MAAM,CAAC,QAAQ,aAAa,MAAM,SAAS,eAAe;CAC1D,MAAM,CAAC,IAAI,SAAS,MAAM,SAAS,CAAC;CACpC,MAAM,SAAS,MAAM,kBAAkB,WAAW,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC;CAC/D,MAAM,OAAO,MAAM,aAAa,kBAA0B,OAAO,aAAa,KAAK,IAAI,UAAU,aAAa,CAAC,GAAG,CAAC,CAAC;CACpH,OAAO,MAAM,cAAc;EACzB,MAAM,OAAa;GACjB;GACA;GACA;GACA,WAAW,KAAK,IAAI,KAAK,EAAE,IAAI;GAC/B;GACA,OAAO,cAAc;IAAE,GAAG;IAAM,OAAO,SAAS;IAAO,OAAO,UAAU,KAAK,KAAK,KAAK;GAAE;EAC3F;EACA,OAAO;CACT,GAAG;EAAC;EAAO;EAAQ;EAAQ;EAAI;CAAI,CAAC;AACtC;;AAGA,SAAgB,eAAe,MAAwB,OAA0D;CAC/G,MAAM,OAAO,MAAM;CACnB,MAAM,gBAAgB;EACpB,IAAI,QAAQ,MAAM,eAAe,KA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I,iBAAiB,SAAS,YAAY;EACtD,IAAI,KAAK,aAAa,UAAsC,UAAU,MAAM,IAAI;EAChF,MAAM,OAAO,QAAQ,WAAW;EAChC,KAAK,KAAK,QAAQ;EAClB,QAAQ,wBAAwB,KAAK,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,QAAQ,IAAI,CAAC,CAAC,QAAQ,QAAQ,WAAW;EAC7F,OAAO;GAAE,YAAY,QAAQ;GAAY,QAAQ,MAAM,eAAe,CAAC,CAAC,EAAE,EAAE,SAAS;GAAM;EAAM;CACnG,SAAS,GAAG;EACV,MAAM;EACN,MAAM,uBAAuB,CAAC;CAChC;AACF,EACF;;AAGA,MAAa,oBAAoB,MAAM,cAA0B,iBAAiB;;AAGlF,MAAa,sBAAkC,MAAM,WAAW,iBAAiB"}
@@ -10,7 +10,7 @@ type IconComponent = React.ComponentType<{
10
10
  type ControlSize = "default" | "sm";
11
11
  declare const buttonVariants: (props?: ({
12
12
  variant?: "link" | "default" | "outline" | "secondary" | "ghost" | "destructive" | null | undefined;
13
- size?: "default" | "sm" | "icon" | "icon-sm" | null | undefined;
13
+ size?: "default" | "icon" | "sm" | "icon-sm" | "lg" | null | undefined;
14
14
  } & import("class-variance-authority/types").ClassProp) | undefined) => string;
15
15
  type ButtonProps = Omit<React.ComponentProps<"button">, "className" | "style" | "title"> & VariantProps<typeof buttonVariants> & {
16
16
  className?: string;
@@ -234,4 +234,4 @@ declare const MicrophoneContext: React.Context<Microphone>;
234
234
  /** The microphone from the nearest `MicrophoneContext`. */
235
235
  declare const useMicrophone: () => Microphone;
236
236
  export { AsyncActionOptions as A, RowAction as B, useColorScheme as C, DensityName as D, Density as E, useAsyncAction as F, buttonVariants as H, Button$1 as I, ButtonProps as L, AsyncLabels as M, FieldErrors as N, DensityProps as O, Phase as P, IconButton as R, palettes as S, useSystemColorScheme as T, ControlSize as U, RowActionProps as V, IconComponent as W, PaletteOption as _, browserMicrophone as a, colorSchemeScript as b, COLOR_SCHEME_STORAGE_KEY as c, ColorSchemeLabels as d, ColorSchemePreference as f, PaletteChoice as g, PALETTE_STORAGE_KEY as h, MicrophoneStream as i, AsyncButton as j, AsyncAction as k, ColorScheme as l, DEFAULT_PALETTE as m, MicrophoneContext as n, explainMicrophoneError as o, ColorSchemeState as p, MicrophoneError as r, useMicrophone as s, Microphone as t, ColorSchemeChoice as u, PaletteState as v, usePalette as w, paletteScript as x, ThemeProvider as y, IconButtonProps as z };
237
- //# sourceMappingURL=microphone-DDOnQHxf.d.ts.map
237
+ //# sourceMappingURL=microphone-xGKxcK6p.d.ts.map
package/dist/panorama.js CHANGED
@@ -1,7 +1,7 @@
1
- import { o as useInView } from "./button-CYXjU-fs.js";
1
+ import { o as useInView } from "./button-CjnotDTb.js";
2
2
  import { n as useViewPointers, r as useWheelZoom, t as useSettledStatus } from "./viewer-input-3Qa-o35k.js";
3
3
  import { r as cn } from "./tooltip-BosfsWYh.js";
4
- import { r as Slider } from "./value-controls-5u7sD_wG.js";
4
+ import { r as Slider } from "./value-controls-ColD28Pp.js";
5
5
  import * as React from "react";
6
6
  import { jsx, jsxs } from "react/jsx-runtime";
7
7
  import { VisuallyHidden } from "react-aria";
package/dist/scene.js CHANGED
@@ -1,4 +1,4 @@
1
- import { o as useInView, t as Button } from "./button-CYXjU-fs.js";
1
+ import { o as useInView, t as Button } from "./button-CjnotDTb.js";
2
2
  import { n as useViewPointers, r as useWheelZoom, t as useSettledStatus } from "./viewer-input-3Qa-o35k.js";
3
3
  import { r as cn } from "./tooltip-BosfsWYh.js";
4
4
  import { t as followAim } from "./follow-CXQsL86O.js";
@@ -103,6 +103,10 @@
103
103
  --control-px: 1rem;
104
104
  --control-px-sm: 0.75rem;
105
105
  --control-icon: 1rem;
106
+ /* Button size="lg": one big action for small fingers (a round's Check), the same in every density. */
107
+ --control-h-lg: 5rem;
108
+ --control-px-lg: 2.5rem;
109
+ --control-icon-lg: 2rem;
106
110
 
107
111
  --motion-effects: 200ms;
108
112
  --motion-spatial: 350ms;
package/dist/strata.css CHANGED
@@ -98,6 +98,10 @@
98
98
  --control-px: 1rem;
99
99
  --control-px-sm: 0.75rem;
100
100
  --control-icon: 1rem;
101
+ /* Button size="lg": one big action for small fingers (a round's Check), the same in every density. */
102
+ --control-h-lg: 5rem;
103
+ --control-px-lg: 2.5rem;
104
+ --control-icon-lg: 2rem;
101
105
 
102
106
  --motion-effects: 200ms;
103
107
  --motion-spatial: 350ms;
@@ -94,6 +94,10 @@
94
94
  --control-px: 1rem;
95
95
  --control-px-sm: 0.75rem;
96
96
  --control-icon: 1rem;
97
+ /* Button size="lg": one big action for small fingers (a round's Check), the same in every density. */
98
+ --control-h-lg: 5rem;
99
+ --control-px-lg: 2.5rem;
100
+ --control-icon-lg: 2rem;
97
101
 
98
102
  --motion-effects: 200ms;
99
103
  --motion-spatial: 350ms;
package/dist/testing.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { P as Phase, f as ColorSchemePreference, t as Microphone } from "./microphone-DDOnQHxf.js";
1
+ import { P as Phase, f as ColorSchemePreference, t as Microphone } from "./microphone-xGKxcK6p.js";
2
2
  import * as React from "react";
3
3
  import { RouteObject, To } from "react-router";
4
4
  import { QueryClient } from "@tanstack/react-query";
package/dist/testing.js CHANGED
@@ -1,4 +1,4 @@
1
- import { A as StrataQueryProvider, C as toast, S as StrataToastRegion, c as forgetLoadedThumbnails, j as createQueryClient, n as MicrophoneError, t as MicrophoneContext } from "./microphone-76skMt6i.js";
1
+ import { A as StrataQueryProvider, C as toast, S as StrataToastRegion, c as forgetLoadedThumbnails, j as createQueryClient, n as MicrophoneError, t as MicrophoneContext } from "./microphone-D3sbBVka.js";
2
2
  import { o as ThemeProvider } from "./theme-1oOSMj_D.js";
3
3
  import * as React from "react";
4
4
  import { jsx, jsxs } from "react/jsx-runtime";
@@ -1,5 +1,5 @@
1
1
  import { f as format, o as useFieldControl, s as controlHeight, u as NBSP } from "./field-DBCsFIng.js";
2
- import { t as Button$1 } from "./button-CYXjU-fs.js";
2
+ import { t as Button$1 } from "./button-CjnotDTb.js";
3
3
  import { a as fieldErrorsOf, n as describeActionError } from "./errors-CmuwcWlb.js";
4
4
  import { n as KeyText, r as cn } from "./tooltip-BosfsWYh.js";
5
5
  import * as React from "react";
@@ -747,4 +747,4 @@ function ColorField({ value, onChange, suggestions, against, againstLabel = "the
747
747
  }
748
748
 
749
749
  export { useAsyncAction as a, KeysLegend as c, useHotkeys as d, AsyncButton as i, isTypingTarget as l, NumberField$1 as n, Toolbar$1 as o, Slider$1 as r, ToolbarSeparator as s, ColorField as t, keyName as u };
750
- //# sourceMappingURL=value-controls-5u7sD_wG.js.map
750
+ //# sourceMappingURL=value-controls-ColD28Pp.js.map