strata-react 1.3.3 → 1.3.4

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.
@@ -0,0 +1,24 @@
1
+ import * as React from "react";
2
+ /** A microphone that is open and sending samples. */
3
+ export type MicrophoneStream = {
4
+ sampleRate: number;
5
+ /** What the browser calls the device ("USB Audio Device"), or null when it says nothing. */
6
+ device: string | null;
7
+ /** Stops the device (the browser's recording light goes out). */
8
+ close: () => void;
9
+ };
10
+ /** Something that can be opened to send mono samples (-1 to 1) a chunk at a time. */
11
+ export type Microphone = {
12
+ open: (onSamples: (chunk: Float32Array) => void) => Promise<MicrophoneStream>;
13
+ };
14
+ /** A microphone that would not open, with a sentence a person can act on. */
15
+ export declare class MicrophoneError extends Error {
16
+ }
17
+ /** The sentence for what getUserMedia threw. */
18
+ export declare function explainMicrophoneError(e: unknown): MicrophoneError;
19
+ /** The browser's own microphone, with its processing off. */
20
+ export declare const browserMicrophone: Microphone;
21
+ /** The microphone screens record from: the browser's, unless a provider gives another (a fake in tests and stories). */
22
+ export declare const MicrophoneContext: React.Context<Microphone>;
23
+ /** The microphone from the nearest `MicrophoneContext`. */
24
+ export declare const useMicrophone: () => Microphone;
@@ -0,0 +1,16 @@
1
+ /** The quietest level a speech meter draws, in dBFS: below it is silence for speech. */
2
+ export declare const LEVEL_FLOOR_DB = -60;
3
+ /** Joins chunks of samples into one buffer, in order. */
4
+ export declare function joinSamples(chunks: readonly Float32Array[]): Float32Array;
5
+ /** A mono 16-bit PCM WAV of `samples` (-1 to 1; beyond full scale is clipped). */
6
+ export declare function encodeWav(samples: Float32Array, sampleRate: number): Blob;
7
+ /** The highest sample in dBFS, never below `LEVEL_FLOOR_DB` (silence reads as the floor, not minus infinity). */
8
+ export declare function peakDb(samples: Float32Array): number;
9
+ /** How a take's level reads for speech, in words a speaker can act on. */
10
+ export type SpeechLevel = {
11
+ tone: "success" | "warning" | "danger";
12
+ word: string;
13
+ advice: string;
14
+ };
15
+ /** Judges a take by its peak (dBFS). */
16
+ export declare function speechLevel(peak: number): SpeechLevel;
@@ -216,6 +216,77 @@ async function fetchJson(input, init, { readError = readErrorBody } = {}) {
216
216
  const text = res.status === 204 ? "" : await res.text();
217
217
  return text ? JSON.parse(text) : void 0;
218
218
  }
219
- export { toLoad as a, toast as c, staleOf as i, toastTimeout as l, createQueryClient as n, useLoad as o, fetchJson as r, StrataToastRegion as s, StrataQueryProvider as t, overlaySurface as u };
219
+ // src/lib/microphone.ts
220
+ /** A microphone that would not open, with a sentence a person can act on. */
221
+ var MicrophoneError = class extends Error {};
222
+ /** The sentence for what getUserMedia threw. */
223
+ function explainMicrophoneError(e) {
224
+ const name = e instanceof DOMException ? e.name : "";
225
+ if (name === "NotAllowedError") return new MicrophoneError("The browser was not allowed to use the microphone. Allow it from the address bar, then try again.");
226
+ if (name === "NotFoundError") return new MicrophoneError("No microphone was found. Plug one in, then try again.");
227
+ if (name === "NotReadableError") return new MicrophoneError("The microphone is in use by another program. Close it, then try again.");
228
+ return new MicrophoneError(`The microphone could not be opened (${e instanceof DOMException || e instanceof Error ? e.message : String(e)}).`);
229
+ }
230
+ var WORKLET = `
231
+ class StrataTap extends AudioWorkletProcessor {
232
+ constructor() { super(); this.buf = new Float32Array(2048); this.n = 0 }
233
+ process(inputs) {
234
+ const ch = inputs[0] && inputs[0][0]
235
+ if (ch) for (let i = 0; i < ch.length; i++) {
236
+ this.buf[this.n++] = ch[i]
237
+ if (this.n === this.buf.length) { this.port.postMessage(this.buf.slice()); this.n = 0 }
238
+ }
239
+ return true
240
+ }
241
+ }
242
+ registerProcessor('strata-tap', StrataTap)
243
+ `;
244
+ /** The browser's own microphone, with its processing off. */
245
+ var browserMicrophone = { async open(onSamples) {
246
+ if (typeof navigator === "undefined" || !navigator.mediaDevices?.getUserMedia) throw new MicrophoneError("The microphone needs a secure page: open the app at http://localhost or over https.");
247
+ let media;
248
+ try {
249
+ media = await navigator.mediaDevices.getUserMedia({ audio: {
250
+ channelCount: 1,
251
+ echoCancellation: false,
252
+ noiseSuppression: false,
253
+ autoGainControl: false
254
+ } });
255
+ } catch (e) {
256
+ throw explainMicrophoneError(e);
257
+ }
258
+ let context;
259
+ const close = () => {
260
+ for (const t of media.getTracks()) t.stop();
261
+ context?.close();
262
+ };
263
+ try {
264
+ context = new AudioContext();
265
+ const url = URL.createObjectURL(new Blob([WORKLET], { type: "text/javascript" }));
266
+ try {
267
+ await context.audioWorklet.addModule(url);
268
+ } finally {
269
+ URL.revokeObjectURL(url);
270
+ }
271
+ const tap = new AudioWorkletNode(context, "strata-tap");
272
+ tap.port.onmessage = (event) => onSamples(event.data);
273
+ const mute = context.createGain();
274
+ mute.gain.value = 0;
275
+ context.createMediaStreamSource(media).connect(tap).connect(mute).connect(context.destination);
276
+ return {
277
+ sampleRate: context.sampleRate,
278
+ device: media.getAudioTracks()[0]?.label || null,
279
+ close
280
+ };
281
+ } catch (e) {
282
+ close();
283
+ throw explainMicrophoneError(e);
284
+ }
285
+ } };
286
+ /** The microphone screens record from: the browser's, unless a provider gives another (a fake in tests and stories). */
287
+ var MicrophoneContext = React.createContext(browserMicrophone);
288
+ /** The microphone from the nearest `MicrophoneContext`. */
289
+ var useMicrophone = () => React.useContext(MicrophoneContext);
290
+ export { useMicrophone as a, fetchJson as c, useLoad as d, StrataToastRegion as f, overlaySurface as h, explainMicrophoneError as i, staleOf as l, toastTimeout as m, MicrophoneError as n, StrataQueryProvider as o, toast as p, browserMicrophone as r, createQueryClient as s, MicrophoneContext as t, toLoad as u };
220
291
 
221
- //# sourceMappingURL=query-CfonqUzU.js.map
292
+ //# sourceMappingURL=microphone-BZXMKTCM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"microphone-BZXMKTCM.js","names":["ToastQueue","ToastRegion","AriaToast","ToastContent","Button","AriaButton"],"sources":["../src/lib/overlay.ts","../src/components/toast.tsx","../src/query/index.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 { UNSTABLE_Toast as AriaToast, UNSTABLE_ToastContent as ToastContent, UNSTABLE_ToastQueue as ToastQueue, UNSTABLE_ToastRegion as ToastRegion, Button as AriaButton, Text } from \"react-aria-components\";\nimport { CircleCheck, Info, TriangleAlert, X } from \"lucide-react\";\nimport { Button } from \"./button\";\nimport { cn } from \"../lib/utils\";\nimport { overlaySurface } from \"../lib/overlay\";\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(\"strata-react: toast.show() was called but no StrataToastRegion is mounted, so nothing will appear. Render <StrataToastRegion /> once at the app root.\");\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 = { info: { icon: Info, color: \"text-info\" }, success: { icon: CircleCheck, color: \"text-success\" }, warning: { icon: TriangleAlert, color: \"text-warning\" } } as const;\n\n/** Props for `ToastRegion`. */\nexport type StrataToastRegionProps = {\n /** Names the landmark. Default \"Notifications\". */\n label?: string;\n className?: string;\n};\n\n// The 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(watch, () => mounted[0] === id, () => true);\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(\"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 }, [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(\"layer-bar fixed inset-x-4 top-4 grid justify-items-end gap-2 outline-none sm:inset-x-auto sm:top-auto sm:right-4 sm:bottom-4\", className)}\n >\n {({ toast: t }) => (\n <AriaToast\n toast={t}\n className={cn(\"flex w-full max-w-sm items-start gap-3 p-3 outline-none focus-visible:outline-2 focus-visible:outline-ring\", overlaySurface)}\n >\n {(() => {\n const { icon: Icon, color } = marks[t.content.tone ?? \"info\"];\n return <Icon aria-hidden className={cn(\"mt-0.5 size-4 shrink-0\", color)} />;\n })()}\n <ToastContent className=\"grid min-w-0 flex-1 gap-0.5\">\n <Text slot=\"title\" className=\"type-label\">\n {t.content.title}\n </Text>\n {t.content.description && <Text slot=\"description\" className=\"type-body-sm text-muted-foreground\">{t.content.description}</Text>}\n </ToastContent>\n {t.content.action && (\n <Button size=\"sm\" onPress={() => { t.content.action?.onPress(); queue.close(t.key); }}>\n {t.content.action.label}\n </Button>\n )}\n <AriaButton slot=\"close\" aria-label=\"Dismiss\" className=\"grid size-6 shrink-0 cursor-pointer place-items-center rounded-control text-muted-foreground transition-state hover:bg-muted hover:text-foreground\">\n <X aria-hidden className=\"size-4\" />\n </AriaButton>\n </AriaToast>\n )}\n </ToastRegion>\n );\n}\n","import * as React from \"react\";\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 { HttpError, describeHttpError, errorPayload, readErrorBody, type DescribeError, type ErrorBody } 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) return { status: \"ready\", data: query.data, stale: staleOf(query, describe) };\n if (query.status === \"error\") 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 { message: describe(query.error), readAt: new Date(query.dataUpdatedAt), retry: () => void query.refetch(), retrying: query.isFetching };\n}\n\n/** `useQuery`, returned as a `Load<T>` for `DataView`. */\nexport function useLoad<T, K extends QueryKey = QueryKey>(\n options: UseQueryOptions<T, Error, T, K> & { describeError?: DescribeError },\n): Load<T> {\n const { describeError, ...rest } = options;\n return toLoad(useQuery(rest), 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>(input: string | URL, init?: FetchJsonInit, { readError = readErrorBody }: FetchJsonOptions = {}): 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 { createApi, type Api, type ApiOptions } from \"./api\";\nexport { createTypedApi, type TypedApi } from \"./typed-api\";\nexport { useInfiniteLoad, apiPage, type ApiPage, type InfiniteLoad, type InfiniteLoadOptions, type More } from \"./infinite\";\nexport { useJob, isTaskRunning, type Job, type JobOptions } from \"./job\";\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(\"The browser was not allowed to use the microphone. Allow it from the address bar, then try again.\");\n if (name === \"NotFoundError\") return new MicrophoneError(\"No microphone was found. Plug one in, then try again.\");\n if (name === \"NotReadableError\") 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,IAAa,iBACX;;AC0CF,IAAM,QAAQ,IA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K,WAAW;CACpB,IAAI,OAAO,cAAc,eAAe,CAAC,UAAU,cAAc,cAC/D,MAAM,IAAI,gBAAgB,qFAAqF;CACjH,IAAI;CACJ,IAAI;EACF,QAAQ,MAAM,UAAU,aAAa,aAAa,EAChD,OAAO;GAAE,cAAc;GAAG,kBAAkB;GAAO,kBAAkB;GAAO,iBAAiB;EAAM,EACrG,CAAC;CACH,SAAS,GAAG;EACV,MAAM,uBAAuB,CAAC;CAChC;CACA,IAAI;CACJ,MAAM,cAAc;EAClB,KAAK,MAAM,KAAK,MAAM,UAAU,GAAG,EAAE,KAAK;EAC1C,SAAc,MAAM;CACtB;CAGA,IAAI;EACF,UAAU,IAAI,aAAa;EAC3B,MAAM,MAAM,IAAI,gBAAgB,IAAI,KAAK,CAAC,OAAO,GAAG,EAAE,MAAM,kBAAkB,CAAC,CAAC;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,IAAa,oBAAoB,MAAM,cAA0B,iBAAiB;;AAGlF,IAAa,sBAAkC,MAAM,WAAW,iBAAiB"}
@@ -2,6 +2,7 @@ import { RenderOptions } from '@testing-library/react';
2
2
  import { RouteObject, To } from 'react-router';
3
3
  import { QueryClient } from '@tanstack/react-query';
4
4
  import { ColorSchemePreference } from '../components/theme';
5
+ import { Microphone } from '../lib/microphone';
5
6
  /**
6
7
  * Test helpers: render a component, or a whole route tree, inside a router and a query client, as
7
8
  * a Strata app runs it,
@@ -14,6 +15,7 @@ import * as React from "react";
14
15
  export { installLayoutShims, type LayoutBox } from './layout';
15
16
  export { installStorageShim, memoryStorage } from './storage';
16
17
  export { installFakeSpeech, type FakeSpeech, type Spoken } from './speech';
18
+ export { fakeMicrophone, type FakeMicrophoneOptions } from './microphone';
17
19
  export { filledButtons, expectOneFilledButton, asyncButtonPhase } from './buttons';
18
20
  export { installFakeIntersectionObserver, type FakeIntersectionObserverControls, type FakeObserver, } from './intersection-observer';
19
21
  /** A query client for tests: no retries, and nothing goes stale or is collected mid-test. */
@@ -28,9 +30,11 @@ export type StrataRenderOptions = Omit<RenderOptions, "wrapper"> & {
28
30
  colorScheme?: ColorSchemePreference;
29
31
  /** Render the one `StrataToastRegion`, so `toast.show(...)` has somewhere to appear and a test can find it. Default true; pass `false` when the app's own route tree renders the region (a root layout route), or a test would see every toast twice. The queue is cleared at the start of each render, so a toast never carries into the next test. */
30
32
  toasts?: boolean;
33
+ /** The microphone a recording screen gets from `useMicrophone()`, such as `fakeMicrophone()`; the browser's when left out (which jsdom cannot open). */
34
+ microphone?: Microphone;
31
35
  };
32
36
  /** Testing Library's `render` inside `StrataQueryProvider` and a `MemoryRouter` at `route`. */
33
- export declare function renderWithStrata(ui: React.ReactElement, { route, client, colorScheme, toasts, ...options }?: StrataRenderOptions): {
37
+ export declare function renderWithStrata(ui: React.ReactElement, { route, client, colorScheme, toasts, microphone, ...options }?: StrataRenderOptions): {
34
38
  container: HTMLElement;
35
39
  baseElement: HTMLElement;
36
40
  debug: (baseElement?: import('react-dom/client').Container | (Element | Document) | Array<import('react-dom/client').Container | (Element | Document)> | undefined, maxLength?: number | undefined, options?: import('pretty-format').OptionsReceived | undefined) => void;
@@ -93,7 +97,7 @@ export type RenderRoutesOptions = StrataRenderOptions & {
93
97
  basename?: string;
94
98
  };
95
99
  /** Testing Library's `render` of an app's route tree in a memory data router at `route`, with Strata's providers. */
96
- export declare function renderRoutes(routes: RouteObject[], { route, basename, client, colorScheme, toasts, ...options }?: RenderRoutesOptions): {
100
+ export declare function renderRoutes(routes: RouteObject[], { route, basename, client, colorScheme, toasts, microphone, ...options }?: RenderRoutesOptions): {
97
101
  container: HTMLElement;
98
102
  baseElement: HTMLElement;
99
103
  debug: (baseElement?: import('react-dom/client').Container | (Element | Document) | Array<import('react-dom/client').Container | (Element | Document)> | undefined, maxLength?: number | undefined, options?: import('pretty-format').OptionsReceived | undefined) => void;
@@ -0,0 +1,20 @@
1
+ import { Microphone } from '../lib/microphone';
2
+ /** `fakeMicrophone`'s options. */
3
+ export type FakeMicrophoneOptions = {
4
+ /** Peak of the tone, 0 to 1. Default 0.3 (about -10 dBFS, a good level for speech). */
5
+ amplitude?: number;
6
+ /** Refuse to open with this sentence, as a `MicrophoneError` (what a screen shows). */
7
+ refuse?: string;
8
+ /** Throw something that is not a `MicrophoneError` (an audio graph that failed). */
9
+ crash?: boolean;
10
+ /** What the browser calls the device. Default "Fake USB microphone". */
11
+ device?: string | null;
12
+ /** Open but never send a sample: a take held in its first moment, for a screenshot. */
13
+ silent?: boolean;
14
+ /** Samples a second. Default 16 000. */
15
+ sampleRate?: number;
16
+ /** How many times faster than real time the samples arrive. Default 10. */
17
+ speed?: number;
18
+ };
19
+ /** A microphone that sends a tone (or refuses), for tests and stories; hardware is never touched. */
20
+ export declare function fakeMicrophone({ amplitude, refuse, crash, device, silent, sampleRate, speed, }?: FakeMicrophoneOptions): Microphone;
package/dist/testing.js CHANGED
@@ -1,4 +1,4 @@
1
- import { c as toast, n as createQueryClient, s as StrataToastRegion, t as StrataQueryProvider } from "./query-CfonqUzU.js";
1
+ import { f as StrataToastRegion, n as MicrophoneError, o as StrataQueryProvider, p as toast, s as createQueryClient, t as MicrophoneContext } from "./microphone-BZXMKTCM.js";
2
2
  import { r as ThemeProvider } from "./theme-By3DSUTs.js";
3
3
  import "react";
4
4
  import { jsx, jsxs } from "react/jsx-runtime";
@@ -215,6 +215,26 @@ function installFakeSpeech(voices = []) {
215
215
  }
216
216
  };
217
217
  }
218
+ // src/testing/microphone.ts
219
+ /** A microphone that sends a tone (or refuses), for tests and stories; hardware is never touched. */
220
+ function fakeMicrophone({ amplitude = .3, refuse, crash, device = "Fake USB microphone", silent, sampleRate = 16e3, speed = 10 } = {}) {
221
+ return { open(onSamples) {
222
+ if (crash) return Promise.reject(/* @__PURE__ */ new TypeError("audio graph exploded"));
223
+ if (refuse) return Promise.reject(new MicrophoneError(refuse));
224
+ let t = 0;
225
+ const frames = Math.round(sampleRate / 10);
226
+ const timer = silent ? void 0 : setInterval(() => {
227
+ const chunk = new Float32Array(frames);
228
+ for (let i = 0; i < frames; i++) chunk[i] = amplitude * Math.sin(2 * Math.PI * 220 * t++ / sampleRate);
229
+ onSamples(chunk);
230
+ }, 100 / speed);
231
+ return Promise.resolve({
232
+ sampleRate,
233
+ device,
234
+ close: () => clearInterval(timer)
235
+ });
236
+ } };
237
+ }
218
238
  // src/testing/buttons.ts
219
239
  /** Whether an element is out of the view: hidden, inert or aria-hidden, itself or by an ancestor. */
220
240
  function outOfView(el) {
@@ -343,8 +363,8 @@ function createTestQueryClient() {
343
363
  gcTime: Infinity
344
364
  } } });
345
365
  }
346
- function StrataProviders({ client, colorScheme, toasts, children }) {
347
- return /* @__PURE__ */ jsx(ThemeProvider, {
366
+ function StrataProviders({ client, colorScheme, toasts, microphone, children }) {
367
+ const tree = /* @__PURE__ */ jsx(ThemeProvider, {
348
368
  defaultPreference: colorScheme,
349
369
  storageKey: null,
350
370
  children: /* @__PURE__ */ jsxs(StrataQueryProvider, {
@@ -352,14 +372,19 @@ function StrataProviders({ client, colorScheme, toasts, children }) {
352
372
  children: [children, toasts && /* @__PURE__ */ jsx(StrataToastRegion, {})]
353
373
  })
354
374
  });
375
+ return microphone ? /* @__PURE__ */ jsx(MicrophoneContext.Provider, {
376
+ value: microphone,
377
+ children: tree
378
+ }) : tree;
355
379
  }
356
380
  /** Testing Library's `render` inside `StrataQueryProvider` and a `MemoryRouter` at `route`. */
357
- function renderWithStrata(ui, { route = "/", client = createTestQueryClient(), colorScheme = "light", toasts = true, ...options } = {}) {
381
+ function renderWithStrata(ui, { route = "/", client = createTestQueryClient(), colorScheme = "light", toasts = true, microphone, ...options } = {}) {
358
382
  toast.clear();
359
383
  const Wrapper = ({ children }) => /* @__PURE__ */ jsx(StrataProviders, {
360
384
  client,
361
385
  colorScheme,
362
386
  toasts,
387
+ microphone,
363
388
  children: /* @__PURE__ */ jsx(MemoryRouter, {
364
389
  initialEntries: [route],
365
390
  children
@@ -374,7 +399,7 @@ function renderWithStrata(ui, { route = "/", client = createTestQueryClient(), c
374
399
  };
375
400
  }
376
401
  /** Testing Library's `render` of an app's route tree in a memory data router at `route`, with Strata's providers. */
377
- function renderRoutes(routes, { route, basename, client = createTestQueryClient(), colorScheme = "light", toasts = true, ...options } = {}) {
402
+ function renderRoutes(routes, { route, basename, client = createTestQueryClient(), colorScheme = "light", toasts = true, microphone, ...options } = {}) {
378
403
  toast.clear();
379
404
  const router = createMemoryRouter(routes, {
380
405
  initialEntries: [route ?? basename ?? "/"],
@@ -384,6 +409,7 @@ function renderRoutes(routes, { route, basename, client = createTestQueryClient(
384
409
  client,
385
410
  colorScheme,
386
411
  toasts,
412
+ microphone,
387
413
  children: /* @__PURE__ */ jsx(RouterProvider, { router })
388
414
  }), options);
389
415
  const navigate = (to) => act(async () => {
@@ -396,6 +422,6 @@ function renderRoutes(routes, { route, basename, client = createTestQueryClient(
396
422
  ...result
397
423
  };
398
424
  }
399
- export { asyncButtonPhase, createTestQueryClient, expectOneFilledButton, filledButtons, installFakeIntersectionObserver, installFakeSpeech, installLayoutShims, installStorageShim, memoryStorage, renderRoutes, renderWithStrata };
425
+ export { asyncButtonPhase, createTestQueryClient, expectOneFilledButton, fakeMicrophone, filledButtons, installFakeIntersectionObserver, installFakeSpeech, installLayoutShims, installStorageShim, memoryStorage, renderRoutes, renderWithStrata };
400
426
 
401
427
  //# sourceMappingURL=testing.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"testing.js","names":[],"sources":["../src/testing/storage.ts","../src/testing/layout.ts","../src/testing/speech.ts","../src/testing/buttons.ts","../src/testing/intersection-observer.ts","../src/testing/index.tsx"],"sourcesContent":["// Node 25 and later define a global `localStorage` that is undefined unless Node runs with\n// `--localstorage-file`, and it shadows jsdom's. In a Vitest jsdom project on Node 26 (Strata's floor)\n// `localStorage.getItem` then throws, so any app code that reads storage (a remembered choice, a\n// `ColorSchemeChoice` on a settings screen tested with storage on) fails in its tests. Strata's own\n// tests never hit it because `renderWithStrata` turns theme storage off. Every app would have copied\n// the same dozen lines (issue #298), so `installLayoutShims` installs this when, and only when, the\n// platform's storage is unusable; where it works nothing is replaced.\n\n/** An in-memory `Storage`, with the platform's behaviour (values are strings, `key` and `length` work). */\nexport function memoryStorage(): Storage {\n const data = new Map<string, string>();\n return {\n get length() {\n return data.size;\n },\n clear: () => data.clear(),\n getItem: (key) => data.get(String(key)) ?? null,\n key: (index) => [...data.keys()][index] ?? null,\n removeItem: (key) => void data.delete(String(key)),\n setItem: (key, value) => void data.set(String(key), String(value)),\n };\n}\n\nfunction usable(name: \"localStorage\" | \"sessionStorage\"): boolean {\n try {\n return typeof (globalThis as unknown as Record<string, Storage | undefined>)[name]?.getItem === \"function\";\n } catch {\n return false;\n }\n}\n\n/**\n * Replaces `localStorage` and `sessionStorage` with in-memory ones where the runtime's are missing or throw (Node 25+ under jsdom), and empties them after each test when the test runner has a global `afterEach`.\n * Does nothing where storage works. Returns a function that puts the originals back. Called by `installLayoutShims`.\n */\nexport function installStorageShim(): () => void {\n const restore: (() => void)[] = [];\n for (const name of [\"localStorage\", \"sessionStorage\"] as const) {\n if (usable(name)) continue;\n const storage = memoryStorage();\n const targets = [globalThis, typeof window !== \"undefined\" ? window : undefined].filter((t): t is typeof globalThis => t !== undefined);\n for (const target of new Set(targets)) {\n const before = Object.getOwnPropertyDescriptor(target, name);\n Object.defineProperty(target, name, { configurable: true, value: storage });\n restore.push(() => {\n if (before) Object.defineProperty(target, name, before);\n else delete (target as unknown as Record<string, unknown>)[name];\n });\n }\n const after = (globalThis as { afterEach?: (fn: () => void) => void }).afterEach;\n if (typeof after === \"function\") after(() => storage.clear());\n }\n return () => {\n for (const undo of restore.reverse()) undo();\n };\n}\n","// jsdom does no layout: every box is 0×0 and there is no ResizeObserver. Components that measure\n// (LineChart's width; React Aria's Virtualizer draws every row of a list in a test unless the box is mocked, which these shims do not make smaller. A virtualised table with detail rows, or a virtualised grid of tiles, measures each row by its scroll size, which jsdom reports as 0: a test of one gives `Element.prototype.scrollHeight` a value) then render nothing to\n// assert on, so an app testing a screen built from them hits the same wall Strata's own suite did.\n// These shims give every element one fixed box and a ResizeObserver that reports it once on\n// observe (and, on Node 25+, a working in-memory localStorage: see storage.ts). Real layout is checked by the visual suite in Chromium, never here.\n\nimport { installStorageShim } from \"./storage\";\n\n// jsdom has no DOMRect constructor in every version, so rects are plain objects of the same shape.\n/** A DOMRect-shaped object, for stand-ins that report geometry. */\nexport function box(x: number, y: number, width: number, height: number): DOMRect {\n return { x, y, width, height, top: y, left: x, right: x + width, bottom: y + height, toJSON() { return this; } } as DOMRect;\n}\n\n/** The box every element reports while the shims are installed. */\nexport interface LayoutBox {\n width: number;\n height: number;\n}\n\n/**\n * Give jsdom a fixed box for every element (`getBoundingClientRect`, `offset*`, `client*`) and a\n * ResizeObserver that reports it on observe, so measuring components render, and an in-memory `localStorage` and `sessionStorage` where the runtime's throw (Node 25+). Defaults to 640×280.\n * Call once in a Vitest setup file; returns a function that puts the originals back.\n */\nexport function installLayoutShims({ width = 640, height = 280 }: Partial<LayoutBox> = {}): () => void {\n const restore: (() => void)[] = [];\n const replace = (target: object, prop: string, descriptor: PropertyDescriptor) => {\n const before = Object.getOwnPropertyDescriptor(target, prop);\n Object.defineProperty(target, prop, { configurable: true, ...descriptor });\n restore.push(() => {\n if (before) Object.defineProperty(target, prop, before);\n else delete (target as Record<string, unknown>)[prop];\n });\n };\n\n class FixedResizeObserver implements ResizeObserver {\n constructor(private readonly callback: ResizeObserverCallback) {}\n observe(target: Element) {\n this.callback([{ target, contentRect: { width, height } } as unknown as ResizeObserverEntry], this);\n }\n unobserve() {}\n disconnect() {}\n }\n if (!globalThis.ResizeObserver) replace(globalThis, \"ResizeObserver\", { writable: true, value: FixedResizeObserver });\n\n replace(Element.prototype, \"getBoundingClientRect\", {\n writable: true,\n value: () => box(0, 0, width, height),\n });\n for (const [prop, value] of [[\"offsetWidth\", width], [\"offsetHeight\", height], [\"clientWidth\", width], [\"clientHeight\", height]] as const) {\n replace(HTMLElement.prototype, prop, { get: () => value });\n }\n\n restore.push(installStorageShim());\n\n return () => {\n for (const undo of restore.reverse()) undo();\n };\n}\n","// jsdom has no `speechSynthesis`, and the device's voices are a true external, so a test of a screen\n// that speaks needs a stand-in that records what was said (strata-react issue #299). This is the one\n// stand-in an app would otherwise write: it has `speak`, `cancel`, `getVoices`, `speaking` and the\n// voiceschanged event, it ends an utterance when the test says so (`finish()`), and it never makes a sound.\n\n/** One thing said aloud. */\nexport type Spoken = { text: string; lang: string; rate: number; voice: string | null; cancelled: boolean };\n\n/** The recording stand-in `installFakeSpeech` puts on `window`. */\nexport type FakeSpeech = {\n /** Everything said so far, in order; an utterance cut off by a later one has `cancelled: true`. */\n said: Spoken[];\n /** The texts said so far that were not cancelled. */\n texts(): string[];\n /** Ends the utterance being said, as the browser does when it has finished. */\n finish(): void;\n /** Makes these voices the device's, and fires `voiceschanged` (the late arrival some browsers have). */\n setVoices(voices: { name: string; lang: string }[]): void;\n /** Puts the browser's own back (or none). */\n uninstall(): void;\n};\n\n/**\n * Installs a recording `speechSynthesis` and `SpeechSynthesisUtterance` on `window` and returns what was said.\n * `uninstall()` after each test. `const speech = installFakeSpeech(); … expect(speech.texts()).toEqual([\"Which one is the cat?\"])`.\n */\nexport function installFakeSpeech(voices: { name: string; lang: string }[] = []): FakeSpeech {\n const hadSynth = Object.getOwnPropertyDescriptor(window, \"speechSynthesis\");\n const hadUtterance = Object.getOwnPropertyDescriptor(globalThis, \"SpeechSynthesisUtterance\");\n let current: { entry: Spoken; utterance: FakeUtterance } | undefined;\n let installed = voices.map((v) => ({ ...v, default: false, localService: true, voiceURI: v.name }) as SpeechSynthesisVoice);\n const listeners = new Set<EventListener>();\n const said: Spoken[] = [];\n\n class FakeUtterance {\n lang = \"\";\n rate = 1;\n voice: SpeechSynthesisVoice | null = null;\n onend: (() => void) | null = null;\n onerror: (() => void) | null = null;\n constructor(public text: string) {}\n }\n\n const synth = {\n get speaking() {\n return current !== undefined;\n },\n speak(utterance: FakeUtterance) {\n const entry: Spoken = { text: utterance.text, lang: utterance.lang, rate: utterance.rate, voice: utterance.voice?.name ?? null, cancelled: false };\n said.push(entry);\n current = { entry, utterance };\n },\n cancel() {\n if (!current) return;\n const { entry, utterance } = current;\n current = undefined;\n entry.cancelled = true;\n utterance.onerror?.();\n },\n getVoices: () => installed,\n addEventListener: (_: string, l: EventListener) => void listeners.add(l),\n removeEventListener: (_: string, l: EventListener) => void listeners.delete(l),\n };\n\n Object.defineProperty(window, \"speechSynthesis\", { configurable: true, value: synth });\n Object.defineProperty(globalThis, \"SpeechSynthesisUtterance\", { configurable: true, writable: true, value: FakeUtterance });\n\n return {\n said,\n texts: () => said.filter((s) => !s.cancelled).map((s) => s.text),\n finish() {\n const done = current;\n current = undefined;\n done?.utterance.onend?.();\n },\n setVoices(next) {\n installed = next.map((v) => ({ ...v, default: false, localService: true, voiceURI: v.name }) as SpeechSynthesisVoice);\n for (const l of listeners) l(new Event(\"voiceschanged\"));\n },\n uninstall() {\n if (hadSynth) Object.defineProperty(window, \"speechSynthesis\", hadSynth);\n else delete (window as unknown as Record<string, unknown>).speechSynthesis;\n if (hadUtterance) Object.defineProperty(globalThis, \"SpeechSynthesisUtterance\", hadUtterance);\n else delete (globalThis as unknown as Record<string, unknown>).SpeechSynthesisUtterance;\n },\n };\n}\n","import type { Phase } from \"../components/async-button\";\n\n// Assertions for the rules a screen keeps, read from what the components draw rather than from\n// their class names (strata-react issue #48, from the Tubes Library test, which matched\n// `bg-primary`). `Button` marks its variant (`data-variant`), so \"one filled button per view\"\n// (ux-research patterns.md §2, with the BulkBar hand-over: while rows are chosen the bulk action is\n// the filled one) is a check a screen test can make after every interaction. `AsyncButton` marks\n// its phase (`data-phase`), because it keeps every phase's label in the DOM to hold its width, so\n// its text reads \"AddAdding…AddedTry again\" and only the phase says which one shows.\n\n/** Whether an element is out of the view: hidden, inert or aria-hidden, itself or by an ancestor. */\nfunction outOfView(el: Element) {\n return Boolean(el.closest('[hidden], [inert], [aria-hidden=\"true\"]'));\n}\n\n/** An element's name as a person reads it: its `aria-label`, else its text without the parts hidden from screen readers. */\nfunction nameOf(el: Element): string {\n const label = el.getAttribute(\"aria-label\");\n if (label) return label;\n const walk = (node: Node): string =>\n node.nodeType === 3\n ? (node.textContent ?? \"\")\n : node instanceof Element && node.getAttribute(\"aria-hidden\") === \"true\"\n ? \"\"\n : [...node.childNodes].map(walk).join(\"\");\n return walk(el).replace(/\\s+/g, \" \").trim();\n}\n\n/** The filled (`variant=\"default\"`) buttons and links in `container` (default the whole document) that are in view. */\nexport function filledButtons(container: ParentNode = document.body): HTMLElement[] {\n return [...container.querySelectorAll<HTMLElement>('[data-variant=\"default\"]')].filter((el) => !outOfView(el));\n}\n\n/** Throws unless `container` (default the whole document) has exactly one filled button in view; the message names the ones found. */\nexport function expectOneFilledButton(container: ParentNode = document.body): HTMLElement {\n const found = filledButtons(container);\n if (found.length === 1) return found[0];\n const names = found.map((el) => `\"${nameOf(el)}\"`).join(\", \");\n throw new Error(`Expected one filled button in the view, found ${found.length}${names ? `: ${names}` : \"\"}.`);\n}\n\n/** The phase an `AsyncButton` is in (`idle`, `pending`, `done`, `error`), from the button or any element inside it. */\nexport function asyncButtonPhase(el: Element): Phase {\n const phase = el.closest(\"[data-phase]\")?.getAttribute(\"data-phase\");\n if (phase === \"idle\" || phase === \"pending\" || phase === \"done\" || phase === \"error\") return phase;\n throw new Error(`Not an AsyncButton: ${el.outerHTML.slice(0, 120)}`);\n}\n","// jsdom has no IntersectionObserver and does no layout, so nothing a component observes ever comes\n// into view in a unit test. Infinite lists load the next page when a sentinel at the end of the\n// list intersects, and before this helper every app wrote its own firable fake to test that\n// (strata-react issue #12, from strata-listory). This one stands in for the global, records what\n// each observer watches, and lets the test say when something scrolls into view: `scrollToEnd()`\n// for the common case, `intersect(el)` for one element. Entries are delivered inside `act` so the\n// state updates they cause are flushed before the next assertion, as a real scroll would be.\n\nimport { act } from \"@testing-library/react\";\nimport { box } from \"./layout\";\n\n/** One stand-in observer: its callback, options and the elements it currently watches. */\nexport interface FakeObserver {\n readonly callback: IntersectionObserverCallback;\n readonly options: IntersectionObserverInit;\n readonly targets: ReadonlySet<Element>;\n}\n\n/** The controls `installFakeIntersectionObserver` returns. */\nexport interface FakeIntersectionObserverControls {\n /** Every observer created since install, including disconnected ones (their target sets are empty). */\n readonly observers: readonly FakeObserver[];\n /** Report `el` to every observer watching it: in view by default, or out of view with `false`. Returns how many observers were told. */\n intersect(el: Element, isIntersecting?: boolean): number;\n /** Report every watched element as in view, as if the person scrolled to the end of the list. Returns how many elements were reported. */\n scrollToEnd(): number;\n /** Put back whatever `IntersectionObserver` was there before install. */\n uninstall(): void;\n}\n\nfunction entryFor(target: Element, isIntersecting: boolean): IntersectionObserverEntry {\n const rect = target.getBoundingClientRect();\n return {\n target,\n isIntersecting,\n intersectionRatio: isIntersecting ? 1 : 0,\n boundingClientRect: rect,\n intersectionRect: isIntersecting ? rect : box(0, 0, 0, 0),\n rootBounds: null,\n time: performance.now(),\n };\n}\n\n/**\n * Replace `globalThis.IntersectionObserver` with a stand-in the test fires by hand. Call it in\n * `beforeEach` and call `uninstall()` in `afterEach`.\n *\n * @example\n * let io: FakeIntersectionObserverControls;\n * beforeEach(() => { io = installFakeIntersectionObserver(); });\n * afterEach(() => io.uninstall());\n *\n * it(\"loads the next page at the end of the list\", async () => {\n * renderWithStrata(<Pieces />);\n * await screen.findByRole(\"list\", { name: \"Pieces\" });\n * io.scrollToEnd();\n * expect(await screen.findByText(\"Celadon bowl\")).toBeInTheDocument();\n * });\n */\nexport function installFakeIntersectionObserver(): FakeIntersectionObserverControls {\n const previous = Object.getOwnPropertyDescriptor(globalThis, \"IntersectionObserver\");\n const observers: (FakeObserver & { targets: Set<Element>; self: IntersectionObserver })[] = [];\n\n class FakeIntersectionObserver implements IntersectionObserver {\n readonly root: Element | Document | null;\n readonly rootMargin: string;\n readonly thresholds: readonly number[];\n readonly scrollMargin = \"0px\";\n private readonly record: (typeof observers)[number];\n\n constructor(callback: IntersectionObserverCallback, options: IntersectionObserverInit = {}) {\n this.root = options.root ?? null;\n this.rootMargin = options.rootMargin ?? \"0px\";\n const threshold = options.threshold ?? 0;\n this.thresholds = Array.isArray(threshold) ? threshold : [threshold];\n this.record = { callback, options, targets: new Set(), self: this };\n observers.push(this.record);\n }\n observe(target: Element) {\n this.record.targets.add(target);\n }\n unobserve(target: Element) {\n this.record.targets.delete(target);\n }\n disconnect() {\n this.record.targets.clear();\n }\n takeRecords(): IntersectionObserverEntry[] {\n return [];\n }\n }\n\n Object.defineProperty(globalThis, \"IntersectionObserver\", {\n configurable: true,\n writable: true,\n value: FakeIntersectionObserver,\n });\n\n const deliver = (observer: (typeof observers)[number], targets: readonly Element[], isIntersecting: boolean) => {\n act(() => observer.callback(targets.map((t) => entryFor(t, isIntersecting)), observer.self));\n };\n\n return {\n observers,\n intersect(el, isIntersecting = true) {\n const watching = observers.filter((o) => o.targets.has(el));\n for (const o of watching) deliver(o, [el], isIntersecting);\n return watching.length;\n },\n scrollToEnd() {\n // Snapshot every observer's targets before any callback runs: a callback that loads more\n // may observe a new sentinel, on this observer or another, which the person has not\n // scrolled to yet.\n const batches = observers.map((o) => [o, [...o.targets]] as const).filter(([, targets]) => targets.length > 0);\n for (const [o, targets] of batches) deliver(o, targets, true);\n return batches.reduce((n, [, targets]) => n + targets.length, 0);\n },\n uninstall() {\n if (previous) Object.defineProperty(globalThis, \"IntersectionObserver\", previous);\n else delete (globalThis as { IntersectionObserver?: unknown }).IntersectionObserver;\n },\n };\n}\n","/**\n * Test helpers: render a component, or a whole route tree, inside a router and a query client, as\n * a Strata app runs it,\n * and fill the gaps jsdom leaves (layout, ResizeObserver, IntersectionObserver). Use with MSW for\n * the network, never module mocks.\n *\n * @module strata-react/testing\n */\nimport * as React from \"react\";\nimport { act, render, type RenderOptions } from \"@testing-library/react\";\nimport { MemoryRouter, RouterProvider, createMemoryRouter, type RouteObject, type To } from \"react-router\";\nimport { QueryClient } from \"@tanstack/react-query\";\nimport { StrataQueryProvider, createQueryClient } from \"../query\";\nimport { ThemeProvider, type ColorSchemePreference } from \"../components/theme\";\nimport { StrataToastRegion, toast } from \"../components/toast\";\n\nexport { installLayoutShims, type LayoutBox } from \"./layout\";\nexport { installStorageShim, memoryStorage } from \"./storage\";\nexport { installFakeSpeech, type FakeSpeech, type Spoken } from \"./speech\";\nexport { filledButtons, expectOneFilledButton, asyncButtonPhase } from \"./buttons\";\nexport {\n installFakeIntersectionObserver,\n type FakeIntersectionObserverControls,\n type FakeObserver,\n} from \"./intersection-observer\";\n\n// Render a component the way a Strata app runs it: inside a router and a query client. Tests use\n// MSW for the network (see CLAUDE.md), never module mocks, so the real fetch/query/DataView path\n// runs. Each call gets a fresh QueryClient with retries off, so a test that serves a 500 sees the\n// error at once instead of after the retry delay. It also runs inside a ThemeProvider with\n// storage off, so `useColorScheme` works and a test can render the dark scheme with\n// `colorScheme: \"dark\"` without touching localStorage or leaking state into the next test.\n\n/** A query client for tests: no retries, and nothing goes stale or is collected mid-test. */\nexport function createTestQueryClient() {\n return createQueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity, gcTime: Infinity } } });\n}\n\n/** The options `renderWithStrata` and `renderRoutes` share, beside Testing Library's own. */\nexport type StrataRenderOptions = Omit<RenderOptions, \"wrapper\"> & {\n /** The URL the test starts at, with its search and hash (`/bookings?sort=pieces.desc`). Defaults to `/`. */\n route?: string;\n /** The query client; a fresh `createTestQueryClient()` when left out. */\n client?: QueryClient;\n /** The colour scheme to render; `light` when left out. */\n colorScheme?: ColorSchemePreference;\n /** Render the one `StrataToastRegion`, so `toast.show(...)` has somewhere to appear and a test can find it. Default true; pass `false` when the app's own route tree renders the region (a root layout route), or a test would see every toast twice. The queue is cleared at the start of each render, so a toast never carries into the next test. */\n toasts?: boolean;\n};\n\n// The providers every Strata app has above its router, in the order an app nests them.\nfunction StrataProviders({\n client,\n colorScheme,\n toasts,\n children,\n}: {\n client: QueryClient;\n colorScheme: ColorSchemePreference;\n toasts: boolean;\n children: React.ReactNode;\n}) {\n return (\n <ThemeProvider defaultPreference={colorScheme} storageKey={null}>\n <StrataQueryProvider client={client}>\n {children}\n {toasts && <StrataToastRegion />}\n </StrataQueryProvider>\n </ThemeProvider>\n );\n}\n\n/** Testing Library's `render` inside `StrataQueryProvider` and a `MemoryRouter` at `route`. */\nexport function renderWithStrata(\n ui: React.ReactElement,\n { route = \"/\", client = createTestQueryClient(), colorScheme = \"light\", toasts = true, ...options }: StrataRenderOptions = {},\n) {\n toast.clear(); // module state: a toast from the last test must not show in this one\n const Wrapper = ({ children }: { children: React.ReactNode }) => (\n <StrataProviders client={client} colorScheme={colorScheme} toasts={toasts}>\n <MemoryRouter initialEntries={[route]}>{children}</MemoryRouter>\n </StrataProviders>\n );\n return { client, ...render(ui, { wrapper: Wrapper, ...options }) };\n}\n\n// Render an app's own route tree: its layout routes and <Outlet />s, index routes, redirects\n// (<Navigate /> or a loader's redirect()), loaders, actions and error elements. Those only run in\n// a data router, which <MemoryRouter> is not, so renderWithStrata cannot show them; this builds\n// the memory twin of the app's createBrowserRouter from the same RouteObject[] the app exports,\n// so the test and the app cannot drift. The providers and options are renderWithStrata's.\n// `basename` is the app's own (the kiln app runs under /kiln), and `route` is the full URL,\n// basename included, as the browser would show it. The router is returned so a test can assert\n// where a redirect landed (`router.state.location`), and `navigate` moves it inside act().\n\n/** `renderRoutes`'s options: `renderWithStrata`'s, plus the app's `basename`. */\nexport type RenderRoutesOptions = StrataRenderOptions & {\n /** The base path the app is served under, as passed to `createBrowserRouter`. */\n basename?: string;\n};\n\n/** Testing Library's `render` of an app's route tree in a memory data router at `route`, with Strata's providers. */\nexport function renderRoutes(\n routes: RouteObject[],\n {\n route,\n basename,\n client = createTestQueryClient(),\n colorScheme = \"light\",\n toasts = true,\n ...options\n }: RenderRoutesOptions = {},\n) {\n toast.clear();\n const router = createMemoryRouter(routes, { initialEntries: [route ?? basename ?? \"/\"], basename });\n const result = render(\n <StrataProviders client={client} colorScheme={colorScheme} toasts={toasts}>\n <RouterProvider router={router} />\n </StrataProviders>,\n options,\n );\n const navigate = (to: To | number) =>\n act(async () => {\n await (typeof to === \"number\" ? router.navigate(to) : router.navigate(to));\n });\n return { client, router, navigate, ...result };\n}\n"],"mappings":";;;;;;;;AASA,SAAgB,gBAAyB;CACvC,MAAM,uBAAO,IAAI,IAAoB;CACrC,OAAO;EACL,IAAI,SAAS;GACX,OAAO,KAAK;EACd;EACA,aAAa,KAAK,MAAM;EACxB,UAAU,QAAQ,KAAK,IAAI,OAAO,GAAG,CAAC,KAAK;EAC3C,MAAM,UAAU,CAAC,GAAG,KAAK,KAAK,CAAC,CAAC,CAAC,UAAU;EAC3C,aAAa,QAAQ,KAAK,KAAK,OAAO,OAAO,GAAG,CAAC;EACjD,UAAU,KAAK,UAAU,KAAK,KAAK,IAAI,OAAO,GAAG,GAAG,OAAO,KAAK,CAAC;CACnE;AACF;AAEA,SAAS,OAAO,MAAkD;CAChE,IAAI;EACF,OAAO,OAAQ,WAA8D,KAAK,EAAE,YAAY;CAClG,QAAQ;EACN,OAAO;CACT;AACF;;;;;AAMA,SAAgB,qBAAiC;CAC/C,MAAM,UAA0B,CAAC;CACjC,KAAK,MAAM,QAAQ,CA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;EAAqB;EACjE,UAAA,oBAAC,gBAAD,EAAwB,OAAS,CAAA;CAClB,CAAA,GACjB,OACF;CACA,MAAM,YAAY,OAChB,IAAI,YAAY;EACd,OAAO,OAAO,OAAO,WAAW,OAAO,SAAS,EAAE,IAAI,OAAO,SAAS,EAAE;CAC1E,CAAC;CACH,OAAO;EAAE;EAAQ;EAAQ;EAAU,GAAG;CAAO;AAC/C"}
1
+ {"version":3,"file":"testing.js","names":[],"sources":["../src/testing/storage.ts","../src/testing/layout.ts","../src/testing/speech.ts","../src/testing/microphone.ts","../src/testing/buttons.ts","../src/testing/intersection-observer.ts","../src/testing/index.tsx"],"sourcesContent":["// Node 25 and later define a global `localStorage` that is undefined unless Node runs with\n// `--localstorage-file`, and it shadows jsdom's. In a Vitest jsdom project on Node 26 (Strata's floor)\n// `localStorage.getItem` then throws, so any app code that reads storage (a remembered choice, a\n// `ColorSchemeChoice` on a settings screen tested with storage on) fails in its tests. Strata's own\n// tests never hit it because `renderWithStrata` turns theme storage off. Every app would have copied\n// the same dozen lines (issue #298), so `installLayoutShims` installs this when, and only when, the\n// platform's storage is unusable; where it works nothing is replaced.\n\n/** An in-memory `Storage`, with the platform's behaviour (values are strings, `key` and `length` work). */\nexport function memoryStorage(): Storage {\n const data = new Map<string, string>();\n return {\n get length() {\n return data.size;\n },\n clear: () => data.clear(),\n getItem: (key) => data.get(String(key)) ?? null,\n key: (index) => [...data.keys()][index] ?? null,\n removeItem: (key) => void data.delete(String(key)),\n setItem: (key, value) => void data.set(String(key), String(value)),\n };\n}\n\nfunction usable(name: \"localStorage\" | \"sessionStorage\"): boolean {\n try {\n return typeof (globalThis as unknown as Record<string, Storage | undefined>)[name]?.getItem === \"function\";\n } catch {\n return false;\n }\n}\n\n/**\n * Replaces `localStorage` and `sessionStorage` with in-memory ones where the runtime's are missing or throw (Node 25+ under jsdom), and empties them after each test when the test runner has a global `afterEach`.\n * Does nothing where storage works. Returns a function that puts the originals back. Called by `installLayoutShims`.\n */\nexport function installStorageShim(): () => void {\n const restore: (() => void)[] = [];\n for (const name of [\"localStorage\", \"sessionStorage\"] as const) {\n if (usable(name)) continue;\n const storage = memoryStorage();\n const targets = [globalThis, typeof window !== \"undefined\" ? window : undefined].filter((t): t is typeof globalThis => t !== undefined);\n for (const target of new Set(targets)) {\n const before = Object.getOwnPropertyDescriptor(target, name);\n Object.defineProperty(target, name, { configurable: true, value: storage });\n restore.push(() => {\n if (before) Object.defineProperty(target, name, before);\n else delete (target as unknown as Record<string, unknown>)[name];\n });\n }\n const after = (globalThis as { afterEach?: (fn: () => void) => void }).afterEach;\n if (typeof after === \"function\") after(() => storage.clear());\n }\n return () => {\n for (const undo of restore.reverse()) undo();\n };\n}\n","// jsdom does no layout: every box is 0×0 and there is no ResizeObserver. Components that measure\n// (LineChart's width; React Aria's Virtualizer draws every row of a list in a test unless the box is mocked, which these shims do not make smaller. A virtualised table with detail rows, or a virtualised grid of tiles, measures each row by its scroll size, which jsdom reports as 0: a test of one gives `Element.prototype.scrollHeight` a value) then render nothing to\n// assert on, so an app testing a screen built from them hits the same wall Strata's own suite did.\n// These shims give every element one fixed box and a ResizeObserver that reports it once on\n// observe (and, on Node 25+, a working in-memory localStorage: see storage.ts). Real layout is checked by the visual suite in Chromium, never here.\n\nimport { installStorageShim } from \"./storage\";\n\n// jsdom has no DOMRect constructor in every version, so rects are plain objects of the same shape.\n/** A DOMRect-shaped object, for stand-ins that report geometry. */\nexport function box(x: number, y: number, width: number, height: number): DOMRect {\n return { x, y, width, height, top: y, left: x, right: x + width, bottom: y + height, toJSON() { return this; } } as DOMRect;\n}\n\n/** The box every element reports while the shims are installed. */\nexport interface LayoutBox {\n width: number;\n height: number;\n}\n\n/**\n * Give jsdom a fixed box for every element (`getBoundingClientRect`, `offset*`, `client*`) and a\n * ResizeObserver that reports it on observe, so measuring components render, and an in-memory `localStorage` and `sessionStorage` where the runtime's throw (Node 25+). Defaults to 640×280.\n * Call once in a Vitest setup file; returns a function that puts the originals back.\n */\nexport function installLayoutShims({ width = 640, height = 280 }: Partial<LayoutBox> = {}): () => void {\n const restore: (() => void)[] = [];\n const replace = (target: object, prop: string, descriptor: PropertyDescriptor) => {\n const before = Object.getOwnPropertyDescriptor(target, prop);\n Object.defineProperty(target, prop, { configurable: true, ...descriptor });\n restore.push(() => {\n if (before) Object.defineProperty(target, prop, before);\n else delete (target as Record<string, unknown>)[prop];\n });\n };\n\n class FixedResizeObserver implements ResizeObserver {\n constructor(private readonly callback: ResizeObserverCallback) {}\n observe(target: Element) {\n this.callback([{ target, contentRect: { width, height } } as unknown as ResizeObserverEntry], this);\n }\n unobserve() {}\n disconnect() {}\n }\n if (!globalThis.ResizeObserver) replace(globalThis, \"ResizeObserver\", { writable: true, value: FixedResizeObserver });\n\n replace(Element.prototype, \"getBoundingClientRect\", {\n writable: true,\n value: () => box(0, 0, width, height),\n });\n for (const [prop, value] of [[\"offsetWidth\", width], [\"offsetHeight\", height], [\"clientWidth\", width], [\"clientHeight\", height]] as const) {\n replace(HTMLElement.prototype, prop, { get: () => value });\n }\n\n restore.push(installStorageShim());\n\n return () => {\n for (const undo of restore.reverse()) undo();\n };\n}\n","// jsdom has no `speechSynthesis`, and the device's voices are a true external, so a test of a screen\n// that speaks needs a stand-in that records what was said (strata-react issue #299). This is the one\n// stand-in an app would otherwise write: it has `speak`, `cancel`, `getVoices`, `speaking` and the\n// voiceschanged event, it ends an utterance when the test says so (`finish()`), and it never makes a sound.\n\n/** One thing said aloud. */\nexport type Spoken = { text: string; lang: string; rate: number; voice: string | null; cancelled: boolean };\n\n/** The recording stand-in `installFakeSpeech` puts on `window`. */\nexport type FakeSpeech = {\n /** Everything said so far, in order; an utterance cut off by a later one has `cancelled: true`. */\n said: Spoken[];\n /** The texts said so far that were not cancelled. */\n texts(): string[];\n /** Ends the utterance being said, as the browser does when it has finished. */\n finish(): void;\n /** Makes these voices the device's, and fires `voiceschanged` (the late arrival some browsers have). */\n setVoices(voices: { name: string; lang: string }[]): void;\n /** Puts the browser's own back (or none). */\n uninstall(): void;\n};\n\n/**\n * Installs a recording `speechSynthesis` and `SpeechSynthesisUtterance` on `window` and returns what was said.\n * `uninstall()` after each test. `const speech = installFakeSpeech(); … expect(speech.texts()).toEqual([\"Which one is the cat?\"])`.\n */\nexport function installFakeSpeech(voices: { name: string; lang: string }[] = []): FakeSpeech {\n const hadSynth = Object.getOwnPropertyDescriptor(window, \"speechSynthesis\");\n const hadUtterance = Object.getOwnPropertyDescriptor(globalThis, \"SpeechSynthesisUtterance\");\n let current: { entry: Spoken; utterance: FakeUtterance } | undefined;\n let installed = voices.map((v) => ({ ...v, default: false, localService: true, voiceURI: v.name }) as SpeechSynthesisVoice);\n const listeners = new Set<EventListener>();\n const said: Spoken[] = [];\n\n class FakeUtterance {\n lang = \"\";\n rate = 1;\n voice: SpeechSynthesisVoice | null = null;\n onend: (() => void) | null = null;\n onerror: (() => void) | null = null;\n constructor(public text: string) {}\n }\n\n const synth = {\n get speaking() {\n return current !== undefined;\n },\n speak(utterance: FakeUtterance) {\n const entry: Spoken = { text: utterance.text, lang: utterance.lang, rate: utterance.rate, voice: utterance.voice?.name ?? null, cancelled: false };\n said.push(entry);\n current = { entry, utterance };\n },\n cancel() {\n if (!current) return;\n const { entry, utterance } = current;\n current = undefined;\n entry.cancelled = true;\n utterance.onerror?.();\n },\n getVoices: () => installed,\n addEventListener: (_: string, l: EventListener) => void listeners.add(l),\n removeEventListener: (_: string, l: EventListener) => void listeners.delete(l),\n };\n\n Object.defineProperty(window, \"speechSynthesis\", { configurable: true, value: synth });\n Object.defineProperty(globalThis, \"SpeechSynthesisUtterance\", { configurable: true, writable: true, value: FakeUtterance });\n\n return {\n said,\n texts: () => said.filter((s) => !s.cancelled).map((s) => s.text),\n finish() {\n const done = current;\n current = undefined;\n done?.utterance.onend?.();\n },\n setVoices(next) {\n installed = next.map((v) => ({ ...v, default: false, localService: true, voiceURI: v.name }) as SpeechSynthesisVoice);\n for (const l of listeners) l(new Event(\"voiceschanged\"));\n },\n uninstall() {\n if (hadSynth) Object.defineProperty(window, \"speechSynthesis\", hadSynth);\n else delete (window as unknown as Record<string, unknown>).speechSynthesis;\n if (hadUtterance) Object.defineProperty(globalThis, \"SpeechSynthesisUtterance\", hadUtterance);\n else delete (globalThis as unknown as Record<string, unknown>).SpeechSynthesisUtterance;\n },\n };\n}\n","import { MicrophoneError, type Microphone } from \"../lib/microphone\";\n\n// The microphone is hardware, the one true external a recording screen has, and jsdom, Storybook and\n// the visual suite have none. This stand-in sends a sine tone at a chosen level, `speed` times faster\n// than real time (ten by default, so a test of a two-second take waits a fifth of a second), or refuses\n// to open with a sentence as the browser's refusals become (`explainMicrophoneError`). Give it to the\n// screen through `MicrophoneContext`, or `renderWithStrata(ui, { microphone })`.\n\n/** `fakeMicrophone`'s options. */\nexport type FakeMicrophoneOptions = {\n /** Peak of the tone, 0 to 1. Default 0.3 (about -10 dBFS, a good level for speech). */\n amplitude?: number;\n /** Refuse to open with this sentence, as a `MicrophoneError` (what a screen shows). */\n refuse?: string;\n /** Throw something that is not a `MicrophoneError` (an audio graph that failed). */\n crash?: boolean;\n /** What the browser calls the device. Default \"Fake USB microphone\". */\n device?: string | null;\n /** Open but never send a sample: a take held in its first moment, for a screenshot. */\n silent?: boolean;\n /** Samples a second. Default 16 000. */\n sampleRate?: number;\n /** How many times faster than real time the samples arrive. Default 10. */\n speed?: number;\n};\n\n/** A microphone that sends a tone (or refuses), for tests and stories; hardware is never touched. */\nexport function fakeMicrophone({\n amplitude = 0.3,\n refuse,\n crash,\n device = \"Fake USB microphone\",\n silent,\n sampleRate = 16_000,\n speed = 10,\n}: FakeMicrophoneOptions = {}): Microphone {\n return {\n open(onSamples) {\n if (crash) return Promise.reject(new TypeError(\"audio graph exploded\"));\n if (refuse) return Promise.reject(new MicrophoneError(refuse));\n let t = 0;\n // A tenth of a second of sound each tick, every 100 / speed ms of real time.\n const frames = Math.round(sampleRate / 10);\n const timer = silent\n ? undefined\n : setInterval(() => {\n const chunk = new Float32Array(frames);\n for (let i = 0; i < frames; i++) chunk[i] = amplitude * Math.sin((2 * Math.PI * 220 * t++) / sampleRate);\n onSamples(chunk);\n }, 100 / speed);\n return Promise.resolve({ sampleRate, device, close: () => clearInterval(timer) });\n },\n };\n}\n","import type { Phase } from \"../components/async-button\";\n\n// Assertions for the rules a screen keeps, read from what the components draw rather than from\n// their class names (strata-react issue #48, from the Tubes Library test, which matched\n// `bg-primary`). `Button` marks its variant (`data-variant`), so \"one filled button per view\"\n// (ux-research patterns.md §2, with the BulkBar hand-over: while rows are chosen the bulk action is\n// the filled one) is a check a screen test can make after every interaction. `AsyncButton` marks\n// its phase (`data-phase`), because it keeps every phase's label in the DOM to hold its width, so\n// its text reads \"AddAdding…AddedTry again\" and only the phase says which one shows.\n\n/** Whether an element is out of the view: hidden, inert or aria-hidden, itself or by an ancestor. */\nfunction outOfView(el: Element) {\n return Boolean(el.closest('[hidden], [inert], [aria-hidden=\"true\"]'));\n}\n\n/** An element's name as a person reads it: its `aria-label`, else its text without the parts hidden from screen readers. */\nfunction nameOf(el: Element): string {\n const label = el.getAttribute(\"aria-label\");\n if (label) return label;\n const walk = (node: Node): string =>\n node.nodeType === 3\n ? (node.textContent ?? \"\")\n : node instanceof Element && node.getAttribute(\"aria-hidden\") === \"true\"\n ? \"\"\n : [...node.childNodes].map(walk).join(\"\");\n return walk(el).replace(/\\s+/g, \" \").trim();\n}\n\n/** The filled (`variant=\"default\"`) buttons and links in `container` (default the whole document) that are in view. */\nexport function filledButtons(container: ParentNode = document.body): HTMLElement[] {\n return [...container.querySelectorAll<HTMLElement>('[data-variant=\"default\"]')].filter((el) => !outOfView(el));\n}\n\n/** Throws unless `container` (default the whole document) has exactly one filled button in view; the message names the ones found. */\nexport function expectOneFilledButton(container: ParentNode = document.body): HTMLElement {\n const found = filledButtons(container);\n if (found.length === 1) return found[0];\n const names = found.map((el) => `\"${nameOf(el)}\"`).join(\", \");\n throw new Error(`Expected one filled button in the view, found ${found.length}${names ? `: ${names}` : \"\"}.`);\n}\n\n/** The phase an `AsyncButton` is in (`idle`, `pending`, `done`, `error`), from the button or any element inside it. */\nexport function asyncButtonPhase(el: Element): Phase {\n const phase = el.closest(\"[data-phase]\")?.getAttribute(\"data-phase\");\n if (phase === \"idle\" || phase === \"pending\" || phase === \"done\" || phase === \"error\") return phase;\n throw new Error(`Not an AsyncButton: ${el.outerHTML.slice(0, 120)}`);\n}\n","// jsdom has no IntersectionObserver and does no layout, so nothing a component observes ever comes\n// into view in a unit test. Infinite lists load the next page when a sentinel at the end of the\n// list intersects, and before this helper every app wrote its own firable fake to test that\n// (strata-react issue #12, from strata-listory). This one stands in for the global, records what\n// each observer watches, and lets the test say when something scrolls into view: `scrollToEnd()`\n// for the common case, `intersect(el)` for one element. Entries are delivered inside `act` so the\n// state updates they cause are flushed before the next assertion, as a real scroll would be.\n\nimport { act } from \"@testing-library/react\";\nimport { box } from \"./layout\";\n\n/** One stand-in observer: its callback, options and the elements it currently watches. */\nexport interface FakeObserver {\n readonly callback: IntersectionObserverCallback;\n readonly options: IntersectionObserverInit;\n readonly targets: ReadonlySet<Element>;\n}\n\n/** The controls `installFakeIntersectionObserver` returns. */\nexport interface FakeIntersectionObserverControls {\n /** Every observer created since install, including disconnected ones (their target sets are empty). */\n readonly observers: readonly FakeObserver[];\n /** Report `el` to every observer watching it: in view by default, or out of view with `false`. Returns how many observers were told. */\n intersect(el: Element, isIntersecting?: boolean): number;\n /** Report every watched element as in view, as if the person scrolled to the end of the list. Returns how many elements were reported. */\n scrollToEnd(): number;\n /** Put back whatever `IntersectionObserver` was there before install. */\n uninstall(): void;\n}\n\nfunction entryFor(target: Element, isIntersecting: boolean): IntersectionObserverEntry {\n const rect = target.getBoundingClientRect();\n return {\n target,\n isIntersecting,\n intersectionRatio: isIntersecting ? 1 : 0,\n boundingClientRect: rect,\n intersectionRect: isIntersecting ? rect : box(0, 0, 0, 0),\n rootBounds: null,\n time: performance.now(),\n };\n}\n\n/**\n * Replace `globalThis.IntersectionObserver` with a stand-in the test fires by hand. Call it in\n * `beforeEach` and call `uninstall()` in `afterEach`.\n *\n * @example\n * let io: FakeIntersectionObserverControls;\n * beforeEach(() => { io = installFakeIntersectionObserver(); });\n * afterEach(() => io.uninstall());\n *\n * it(\"loads the next page at the end of the list\", async () => {\n * renderWithStrata(<Pieces />);\n * await screen.findByRole(\"list\", { name: \"Pieces\" });\n * io.scrollToEnd();\n * expect(await screen.findByText(\"Celadon bowl\")).toBeInTheDocument();\n * });\n */\nexport function installFakeIntersectionObserver(): FakeIntersectionObserverControls {\n const previous = Object.getOwnPropertyDescriptor(globalThis, \"IntersectionObserver\");\n const observers: (FakeObserver & { targets: Set<Element>; self: IntersectionObserver })[] = [];\n\n class FakeIntersectionObserver implements IntersectionObserver {\n readonly root: Element | Document | null;\n readonly rootMargin: string;\n readonly thresholds: readonly number[];\n readonly scrollMargin = \"0px\";\n private readonly record: (typeof observers)[number];\n\n constructor(callback: IntersectionObserverCallback, options: IntersectionObserverInit = {}) {\n this.root = options.root ?? null;\n this.rootMargin = options.rootMargin ?? \"0px\";\n const threshold = options.threshold ?? 0;\n this.thresholds = Array.isArray(threshold) ? threshold : [threshold];\n this.record = { callback, options, targets: new Set(), self: this };\n observers.push(this.record);\n }\n observe(target: Element) {\n this.record.targets.add(target);\n }\n unobserve(target: Element) {\n this.record.targets.delete(target);\n }\n disconnect() {\n this.record.targets.clear();\n }\n takeRecords(): IntersectionObserverEntry[] {\n return [];\n }\n }\n\n Object.defineProperty(globalThis, \"IntersectionObserver\", {\n configurable: true,\n writable: true,\n value: FakeIntersectionObserver,\n });\n\n const deliver = (observer: (typeof observers)[number], targets: readonly Element[], isIntersecting: boolean) => {\n act(() => observer.callback(targets.map((t) => entryFor(t, isIntersecting)), observer.self));\n };\n\n return {\n observers,\n intersect(el, isIntersecting = true) {\n const watching = observers.filter((o) => o.targets.has(el));\n for (const o of watching) deliver(o, [el], isIntersecting);\n return watching.length;\n },\n scrollToEnd() {\n // Snapshot every observer's targets before any callback runs: a callback that loads more\n // may observe a new sentinel, on this observer or another, which the person has not\n // scrolled to yet.\n const batches = observers.map((o) => [o, [...o.targets]] as const).filter(([, targets]) => targets.length > 0);\n for (const [o, targets] of batches) deliver(o, targets, true);\n return batches.reduce((n, [, targets]) => n + targets.length, 0);\n },\n uninstall() {\n if (previous) Object.defineProperty(globalThis, \"IntersectionObserver\", previous);\n else delete (globalThis as { IntersectionObserver?: unknown }).IntersectionObserver;\n },\n };\n}\n","/**\n * Test helpers: render a component, or a whole route tree, inside a router and a query client, as\n * a Strata app runs it,\n * and fill the gaps jsdom leaves (layout, ResizeObserver, IntersectionObserver). Use with MSW for\n * the network, never module mocks.\n *\n * @module strata-react/testing\n */\nimport * as React from \"react\";\nimport { act, render, type RenderOptions } from \"@testing-library/react\";\nimport { MemoryRouter, RouterProvider, createMemoryRouter, type RouteObject, type To } from \"react-router\";\nimport { QueryClient } from \"@tanstack/react-query\";\nimport { StrataQueryProvider, createQueryClient } from \"../query\";\nimport { ThemeProvider, type ColorSchemePreference } from \"../components/theme\";\nimport { StrataToastRegion, toast } from \"../components/toast\";\nimport { MicrophoneContext, type Microphone } from \"../lib/microphone\";\n\nexport { installLayoutShims, type LayoutBox } from \"./layout\";\nexport { installStorageShim, memoryStorage } from \"./storage\";\nexport { installFakeSpeech, type FakeSpeech, type Spoken } from \"./speech\";\nexport { fakeMicrophone, type FakeMicrophoneOptions } from \"./microphone\";\nexport { filledButtons, expectOneFilledButton, asyncButtonPhase } from \"./buttons\";\nexport {\n installFakeIntersectionObserver,\n type FakeIntersectionObserverControls,\n type FakeObserver,\n} from \"./intersection-observer\";\n\n// Render a component the way a Strata app runs it: inside a router and a query client. Tests use\n// MSW for the network (see CLAUDE.md), never module mocks, so the real fetch/query/DataView path\n// runs. Each call gets a fresh QueryClient with retries off, so a test that serves a 500 sees the\n// error at once instead of after the retry delay. It also runs inside a ThemeProvider with\n// storage off, so `useColorScheme` works and a test can render the dark scheme with\n// `colorScheme: \"dark\"` without touching localStorage or leaking state into the next test.\n\n/** A query client for tests: no retries, and nothing goes stale or is collected mid-test. */\nexport function createTestQueryClient() {\n return createQueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity, gcTime: Infinity } } });\n}\n\n/** The options `renderWithStrata` and `renderRoutes` share, beside Testing Library's own. */\nexport type StrataRenderOptions = Omit<RenderOptions, \"wrapper\"> & {\n /** The URL the test starts at, with its search and hash (`/bookings?sort=pieces.desc`). Defaults to `/`. */\n route?: string;\n /** The query client; a fresh `createTestQueryClient()` when left out. */\n client?: QueryClient;\n /** The colour scheme to render; `light` when left out. */\n colorScheme?: ColorSchemePreference;\n /** Render the one `StrataToastRegion`, so `toast.show(...)` has somewhere to appear and a test can find it. Default true; pass `false` when the app's own route tree renders the region (a root layout route), or a test would see every toast twice. The queue is cleared at the start of each render, so a toast never carries into the next test. */\n toasts?: boolean;\n /** The microphone a recording screen gets from `useMicrophone()`, such as `fakeMicrophone()`; the browser's when left out (which jsdom cannot open). */\n microphone?: Microphone;\n};\n\n// The providers every Strata app has above its router, in the order an app nests them.\nfunction StrataProviders({\n client,\n colorScheme,\n toasts,\n microphone,\n children,\n}: {\n client: QueryClient;\n colorScheme: ColorSchemePreference;\n toasts: boolean;\n microphone?: Microphone;\n children: React.ReactNode;\n}) {\n const tree = (\n <ThemeProvider defaultPreference={colorScheme} storageKey={null}>\n <StrataQueryProvider client={client}>\n {children}\n {toasts && <StrataToastRegion />}\n </StrataQueryProvider>\n </ThemeProvider>\n );\n return microphone ? <MicrophoneContext.Provider value={microphone}>{tree}</MicrophoneContext.Provider> : tree;\n}\n\n/** Testing Library's `render` inside `StrataQueryProvider` and a `MemoryRouter` at `route`. */\nexport function renderWithStrata(\n ui: React.ReactElement,\n { route = \"/\", client = createTestQueryClient(), colorScheme = \"light\", toasts = true, microphone, ...options }: StrataRenderOptions = {},\n) {\n toast.clear(); // module state: a toast from the last test must not show in this one\n const Wrapper = ({ children }: { children: React.ReactNode }) => (\n <StrataProviders client={client} colorScheme={colorScheme} toasts={toasts} microphone={microphone}>\n <MemoryRouter initialEntries={[route]}>{children}</MemoryRouter>\n </StrataProviders>\n );\n return { client, ...render(ui, { wrapper: Wrapper, ...options }) };\n}\n\n// Render an app's own route tree: its layout routes and <Outlet />s, index routes, redirects\n// (<Navigate /> or a loader's redirect()), loaders, actions and error elements. Those only run in\n// a data router, which <MemoryRouter> is not, so renderWithStrata cannot show them; this builds\n// the memory twin of the app's createBrowserRouter from the same RouteObject[] the app exports,\n// so the test and the app cannot drift. The providers and options are renderWithStrata's.\n// `basename` is the app's own (the kiln app runs under /kiln), and `route` is the full URL,\n// basename included, as the browser would show it. The router is returned so a test can assert\n// where a redirect landed (`router.state.location`), and `navigate` moves it inside act().\n\n/** `renderRoutes`'s options: `renderWithStrata`'s, plus the app's `basename`. */\nexport type RenderRoutesOptions = StrataRenderOptions & {\n /** The base path the app is served under, as passed to `createBrowserRouter`. */\n basename?: string;\n};\n\n/** Testing Library's `render` of an app's route tree in a memory data router at `route`, with Strata's providers. */\nexport function renderRoutes(\n routes: RouteObject[],\n {\n route,\n basename,\n client = createTestQueryClient(),\n colorScheme = \"light\",\n toasts = true,\n microphone,\n ...options\n }: RenderRoutesOptions = {},\n) {\n toast.clear();\n const router = createMemoryRouter(routes, { initialEntries: [route ?? basename ?? \"/\"], basename });\n const result = render(\n <StrataProviders client={client} colorScheme={colorScheme} toasts={toasts} microphone={microphone}>\n <RouterProvider router={router} />\n </StrataProviders>,\n options,\n );\n const navigate = (to: To | number) =>\n act(async () => {\n await (typeof to === \"number\" ? router.navigate(to) : router.navigate(to));\n });\n return { client, router, navigate, ...result };\n}\n"],"mappings":";;;;;;;;AASA,SAAgB,gBAAyB;CACvC,MAAM,uBAAO,IAAI,IAAoB;CACrC,OAAO;EACL,IAAI,SAAS;GACX,OAAO,KAAK;EACd;EACA,aAAa,KAAK,MAAM;EACxB,UAAU,QAAQ,KAAK,IAAI,OAAO,GAAG,CAAC,KAAK;EAC3C,MAAM,UAAU,C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jB,OACF;CACA,MAAM,YAAY,OAChB,IAAI,YAAY;EACd,OAAO,OAAO,OAAO,WAAW,OAAO,SAAS,EAAE,IAAI,OAAO,SAAS,EAAE;CAC1E,CAAC;CACH,OAAO;EAAE;EAAQ;EAAQ;EAAU,GAAG;CAAO;AAC/C"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "strata-react",
3
- "version": "1.3.3",
3
+ "version": "1.3.4",
4
4
  "description": "React + Tailwind v4 components that ship structure, behaviour, states and a token contract, and no look: each product brings a theme generated from its own subject.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1 +0,0 @@
1
- {"version":3,"file":"query-CfonqUzU.js","names":["ToastQueue","ToastRegion","AriaToast","ToastContent","Button","AriaButton"],"sources":["../src/lib/overlay.ts","../src/components/toast.tsx","../src/query/index.tsx"],"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 { UNSTABLE_Toast as AriaToast, UNSTABLE_ToastContent as ToastContent, UNSTABLE_ToastQueue as ToastQueue, UNSTABLE_ToastRegion as ToastRegion, Button as AriaButton, Text } from \"react-aria-components\";\nimport { CircleCheck, Info, TriangleAlert, X } from \"lucide-react\";\nimport { Button } from \"./button\";\nimport { cn } from \"../lib/utils\";\nimport { overlaySurface } from \"../lib/overlay\";\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(\"strata-react: toast.show() was called but no StrataToastRegion is mounted, so nothing will appear. Render <StrataToastRegion /> once at the app root.\");\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 = { info: { icon: Info, color: \"text-info\" }, success: { icon: CircleCheck, color: \"text-success\" }, warning: { icon: TriangleAlert, color: \"text-warning\" } } as const;\n\n/** Props for `ToastRegion`. */\nexport type StrataToastRegionProps = {\n /** Names the landmark. Default \"Notifications\". */\n label?: string;\n className?: string;\n};\n\n// The 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(watch, () => mounted[0] === id, () => true);\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(\"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 }, [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(\"layer-bar fixed inset-x-4 top-4 grid justify-items-end gap-2 outline-none sm:inset-x-auto sm:top-auto sm:right-4 sm:bottom-4\", className)}\n >\n {({ toast: t }) => (\n <AriaToast\n toast={t}\n className={cn(\"flex w-full max-w-sm items-start gap-3 p-3 outline-none focus-visible:outline-2 focus-visible:outline-ring\", overlaySurface)}\n >\n {(() => {\n const { icon: Icon, color } = marks[t.content.tone ?? \"info\"];\n return <Icon aria-hidden className={cn(\"mt-0.5 size-4 shrink-0\", color)} />;\n })()}\n <ToastContent className=\"grid min-w-0 flex-1 gap-0.5\">\n <Text slot=\"title\" className=\"type-label\">\n {t.content.title}\n </Text>\n {t.content.description && <Text slot=\"description\" className=\"type-body-sm text-muted-foreground\">{t.content.description}</Text>}\n </ToastContent>\n {t.content.action && (\n <Button size=\"sm\" onPress={() => { t.content.action?.onPress(); queue.close(t.key); }}>\n {t.content.action.label}\n </Button>\n )}\n <AriaButton slot=\"close\" aria-label=\"Dismiss\" className=\"grid size-6 shrink-0 cursor-pointer place-items-center rounded-control text-muted-foreground transition-state hover:bg-muted hover:text-foreground\">\n <X aria-hidden className=\"size-4\" />\n </AriaButton>\n </AriaToast>\n )}\n </ToastRegion>\n );\n}\n","import * as React from \"react\";\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 { HttpError, describeHttpError, errorPayload, readErrorBody, type DescribeError, type ErrorBody } 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) return { status: \"ready\", data: query.data, stale: staleOf(query, describe) };\n if (query.status === \"error\") 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 { message: describe(query.error), readAt: new Date(query.dataUpdatedAt), retry: () => void query.refetch(), retrying: query.isFetching };\n}\n\n/** `useQuery`, returned as a `Load<T>` for `DataView`. */\nexport function useLoad<T, K extends QueryKey = QueryKey>(\n options: UseQueryOptions<T, Error, T, K> & { describeError?: DescribeError },\n): Load<T> {\n const { describeError, ...rest } = options;\n return toLoad(useQuery(rest), 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>(input: string | URL, init?: FetchJsonInit, { readError = readErrorBody }: FetchJsonOptions = {}): 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 { createApi, type Api, type ApiOptions } from \"./api\";\nexport { createTypedApi, type TypedApi } from \"./typed-api\";\nexport { useInfiniteLoad, apiPage, type ApiPage, type InfiniteLoad, type InfiniteLoadOptions, type More } from \"./infinite\";\nexport { useJob, isTaskRunning, type Job, type JobOptions } from \"./job\";\n"],"mappings":";;;;;;;;AAGA,IAAa,iBACX;;AC0CF,IAAM,QAAQ,IAAIA,oBAA8B,EAAE,kBAAkB,EAAE,CAAC;;AAGvE,SAAgB,aAAa,SAA0F;CACrH,IAAI,QAAQ,YAAY,KAAA,GAAW,OAAO,QAAQ;CAClD,MAAM,QAAQ,QAAQ,MAAM,UAAU,QAAQ,aAAa,UAAU,MAAM,QAAQ,QAAQ,MAAM,UAAU;CAC3G,OAAO,KAAK,IAAI,QAAQ,SAAS,MAAO,GAAG,KAAK,IAAI,MAAO,MAAO,KAAK,KAAK,CAAC;AAC/E;;AAGA,IAAa,QAAQ;;CAEnB,KAAK,SAAoC;EAEvC,IAAI,QAAQ,WAAW,KAAK,CAAC,kBAAkB,MAAM,GAAG;GACtD,iBAAiB;GACjB,QAAQ,KAAK,uJAAuJ;EACtK;EACA,OAAO,MAAM,IAAI,SAAS,EAAE,SAAS,aAAa,OAAO,EAAE,CAAC;CAC9D;CACA,MAAM,KAAa;EACjB,MAAM,MAAM,GAAG;CACjB;CACA,QAAQ;EACN,MAAM,MAAM;CACd;AACF;AAEA,IAAM,QAAQ;CAAE,MAAM;EAAE,MAAM;EAAM,OAAO;CAAY;CAAG,SAAS;EAAE,MAAM;EAAa,OAAO;CA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