strata-react 1.3.2 → 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.
Files changed (46) hide show
  1. package/README.md +20 -2
  2. package/UPGRADING.md +4 -0
  3. package/dist/api-types/generate.d.ts +2 -0
  4. package/dist/api-types-cli.js +1 -1
  5. package/dist/api-types.js +1 -1
  6. package/dist/components/field.d.ts +28 -5
  7. package/dist/components/link.d.ts +43 -0
  8. package/dist/components/recorder.d.ts +73 -0
  9. package/dist/components/say-again.d.ts +11 -0
  10. package/dist/components/toggle.d.ts +12 -4
  11. package/dist/{errors-DqezYZgy.js → errors-D99YX4XL.js} +2 -2
  12. package/dist/{errors-DqezYZgy.js.map → errors-D99YX4XL.js.map} +1 -1
  13. package/dist/{field-CTd1l3md.js → field-QCCmWTuY.js} +77 -4
  14. package/dist/field-QCCmWTuY.js.map +1 -0
  15. package/dist/{generate-DCRYZPJs.js → generate-CjTHKJ39.js} +21 -3
  16. package/dist/generate-CjTHKJ39.js.map +1 -0
  17. package/dist/index.d.ts +10 -2
  18. package/dist/index.js +447 -15
  19. package/dist/index.js.map +1 -1
  20. package/dist/lib/base.d.ts +10 -0
  21. package/dist/lib/microphone.d.ts +24 -0
  22. package/dist/lib/recording.d.ts +16 -0
  23. package/dist/lib/search-param.d.ts +16 -0
  24. package/dist/lib/speech.d.ts +37 -0
  25. package/dist/map.js +2 -2
  26. package/dist/{query-CgoGqE0T.js → microphone-BZXMKTCM.js} +84 -7
  27. package/dist/microphone-BZXMKTCM.js.map +1 -0
  28. package/dist/panorama.js +2 -2
  29. package/dist/query/api.d.ts +23 -0
  30. package/dist/query/index.d.ts +12 -2
  31. package/dist/query/typed-api.d.ts +78 -0
  32. package/dist/testing/index.d.ts +10 -8
  33. package/dist/testing/layout.d.ts +1 -1
  34. package/dist/testing/microphone.d.ts +20 -0
  35. package/dist/testing/speech.d.ts +32 -0
  36. package/dist/testing/storage.d.ts +7 -0
  37. package/dist/testing.js +175 -8
  38. package/dist/testing.js.map +1 -1
  39. package/dist/{theme-DB0Km2m2.js → theme-By3DSUTs.js} +2 -2
  40. package/dist/{theme-DB0Km2m2.js.map → theme-By3DSUTs.js.map} +1 -1
  41. package/dist/{value-controls-CiwdvJeH.js → value-controls-B7iNh4WO.js} +3 -3
  42. package/dist/{value-controls-CiwdvJeH.js.map → value-controls-B7iNh4WO.js.map} +1 -1
  43. package/package.json +1 -1
  44. package/dist/field-CTd1l3md.js.map +0 -1
  45. package/dist/generate-DCRYZPJs.js.map +0 -1
  46. package/dist/query-CgoGqE0T.js.map +0 -1
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Where the app is mounted: the path of the page's `<base href>` without its trailing slash, `""` at the root or where there is no base (SSR, a plain page).
3
+ * Give it to React Router as `createBrowserRouter(routes, { basename: appBase() || "/" })`.
4
+ */
5
+ export declare function appBase(doc?: Document | undefined): string;
6
+ /**
7
+ * Puts the app's base in front of a root-relative path (`/api/learners` becomes `/proxy/api/learners` behind a proxy).
8
+ * Anything else (a relative path, a full URL, a protocol-relative `//host`) is returned as it is. Use it for every `fetch`, `<img src>` and download link the app builds; in-app links are router paths and need none.
9
+ */
10
+ export declare function withBase(path: string, base?: string): string;
@@ -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;
@@ -0,0 +1,16 @@
1
+ /** Options of `useSearchParam`. */
2
+ export type SearchParamOptions<T extends string> = {
3
+ /** Read when the param is missing or invalid; setting it removes the param. */
4
+ default: T;
5
+ /** Says whether a raw value is allowed: a type guard (`isMode`), or a function that returns the typed value or `undefined`. */
6
+ parse?: (raw: string) => T | boolean | undefined;
7
+ /** Replace the history entry instead of adding one. Default `true`, since most params are filters. */
8
+ replace?: boolean;
9
+ };
10
+ /** What `useSearchParam` returns: the value, and a setter that takes the next value or `null` for the default. */
11
+ export type SearchParam<T extends string> = readonly [T, (next: T | null) => void];
12
+ /**
13
+ * One value held in a URL search parameter (React Router): `const [mode, setMode] = useSearchParam("mode", { default: "all", parse: isMode })`.
14
+ * Reads and validates it, drops the param when set to the default or `null`, keeps the others, and replaces the history entry by default.
15
+ */
16
+ export declare function useSearchParam<T extends string = string>(key: string, { default: fallback, parse, replace }: SearchParamOptions<T>): SearchParam<T>;
@@ -0,0 +1,37 @@
1
+ /** How a prompt is said. */
2
+ export type SpeakOptions = {
3
+ /** BCP 47 language of the text ("en-GB", "sv"). Picks the voice; when omitted the browser's default voice is used. */
4
+ lang?: string;
5
+ /** 1 is normal speed. Default 0.9. */
6
+ rate?: number;
7
+ /** Called when the browser has finished saying it, or was stopped. */
8
+ onEnd?: () => void;
9
+ };
10
+ /** Whether this browser can say text aloud. */
11
+ export declare function canSpeak(): boolean;
12
+ /** The voice that fits a language: exact match, else the same base language, else none (the browser then uses its default for `lang`). */
13
+ export declare function pickVoice(voices: readonly SpeechSynthesisVoice[], lang: string | undefined): SpeechSynthesisVoice | undefined;
14
+ /** Says `text` aloud now, cancelling what is still being said. Does nothing where there is no speech. Returns whether it was handed to the browser. */
15
+ export declare function speak(text: string, { lang, rate, onEnd }?: SpeakOptions): boolean;
16
+ /** Stops whatever is being said. */
17
+ export declare function stopSpeaking(): void;
18
+ /** Options for `useSpeech`. */
19
+ export type UseSpeechOptions = Pick<SpeakOptions, "lang" | "rate"> & {
20
+ /** The person has turned speech off: `say` does nothing. Keep the choice where the app keeps its settings. */
21
+ muted?: boolean;
22
+ };
23
+ /** What `useSpeech` returns. */
24
+ export type Speech = {
25
+ /** The browser can speak and the person has not muted it: show the control only then. */
26
+ supported: boolean;
27
+ /** True while something is being said. */
28
+ speaking: boolean;
29
+ /** Says the text now (cancelling what is being said). Returns whether it was spoken. */
30
+ say: (text: string) => boolean;
31
+ stop: () => void;
32
+ };
33
+ /**
34
+ * Speech for a screen: `const { say, supported } = useSpeech({ lang })`. Waits for voices that load late (`voiceschanged`), cancels on unmount so a
35
+ * prompt does not keep talking after its screen is gone, and does nothing where there is no speech or the person muted it.
36
+ */
37
+ export declare function useSpeech({ lang, rate, muted }?: UseSpeechOptions): Speech;
package/dist/map.js CHANGED
@@ -1,5 +1,5 @@
1
- import { a as useColorScheme } from "./theme-DB0Km2m2.js";
2
- import { c as Tooltip$1, u as cn } from "./field-CTd1l3md.js";
1
+ import { a as useColorScheme } from "./theme-By3DSUTs.js";
2
+ import { d as cn, l as Tooltip$1 } from "./field-QCCmWTuY.js";
3
3
  import { i as format } from "./format-B32-PVi2.js";
4
4
  import { n as useSharedCursor, r as geo } from "./cursor-DDGBPiTJ.js";
5
5
  import * as React from "react";
@@ -1,5 +1,5 @@
1
- import { u as cn } from "./field-CTd1l3md.js";
2
- import { d as isDev, o as readErrorBody, r as describeHttpError, s as Button$1, t as HttpError } from "./errors-DqezYZgy.js";
1
+ import { d as cn } from "./field-QCCmWTuY.js";
2
+ import { d as isDev, o as readErrorBody, r as describeHttpError, s as Button$1, t as HttpError } from "./errors-D99YX4XL.js";
3
3
  import * as React from "react";
4
4
  import { Button, Text, UNSTABLE_Toast, UNSTABLE_ToastContent, UNSTABLE_ToastQueue, UNSTABLE_ToastRegion } from "react-aria-components";
5
5
  import { CircleCheck, Info, TriangleAlert, X } from "lucide-react";
@@ -190,13 +190,19 @@ function useLoad(options) {
190
190
  }
191
191
  /**
192
192
  * fetch() that throws an HttpError on a non-2xx response and parses JSON: the queryFn default, and the usual commit for a write.
193
- * A 204 or empty body resolves to undefined. An error response's body is read onto the HttpError (`body`, `reason`, `fieldErrors`).
193
+ * `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`).
194
194
  */
195
195
  async function fetchJson(input, init, { readError = readErrorBody } = {}) {
196
- const headers = new Headers(init?.headers);
196
+ const { json, ...rest } = init ?? {};
197
+ const headers = new Headers(rest.headers);
197
198
  if (!headers.has("Accept")) headers.set("Accept", "application/json");
199
+ if (json !== void 0) {
200
+ if (!headers.has("Content-Type")) headers.set("Content-Type", "application/json");
201
+ rest.body = JSON.stringify(json);
202
+ rest.method ??= "POST";
203
+ }
198
204
  const res = await fetch(input, {
199
- ...init,
205
+ ...rest,
200
206
  headers
201
207
  });
202
208
  if (!res.ok) {
@@ -210,6 +216,77 @@ async function fetchJson(input, init, { readError = readErrorBody } = {}) {
210
216
  const text = res.status === 204 ? "" : await res.text();
211
217
  return text ? JSON.parse(text) : void 0;
212
218
  }
213
- 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 };
214
291
 
215
- //# sourceMappingURL=query-CgoGqE0T.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,IAAIA,oBAA8B,EAAE,kBAAkB,EAAE,CAAC;;AAGvE,SAA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AAc,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"}
package/dist/panorama.js CHANGED
@@ -1,5 +1,5 @@
1
- import { d as useInView, r as Slider } from "./value-controls-CiwdvJeH.js";
2
- import { u as cn } from "./field-CTd1l3md.js";
1
+ import { d as useInView, r as Slider } from "./value-controls-B7iNh4WO.js";
2
+ import { d as cn } from "./field-QCCmWTuY.js";
3
3
  import * as React from "react";
4
4
  import { jsx, jsxs } from "react/jsx-runtime";
5
5
  import { VisuallyHidden } from "react-aria";
@@ -0,0 +1,23 @@
1
+ import { FetchJsonInit, FetchJsonOptions } from './index';
2
+ /** Options for `createApi`. */
3
+ export type ApiOptions = FetchJsonOptions & {
4
+ /** The mount path put before a root-relative path. Default the page's own (`appBase()`), read when each request is made. */
5
+ base?: string;
6
+ };
7
+ type Init = Omit<FetchJsonInit, "method" | "json" | "body">;
8
+ /** The methods `createApi` returns: each applies the base and answers `fetchJson`'s `T`. */
9
+ export type Api = {
10
+ /** The path with the app's base: for an `<img src>`, a download link or an `EventSource`. */
11
+ url(path: string): string;
12
+ get<T>(path: string, init?: Init): Promise<T>;
13
+ post<T>(path: string, body?: unknown, init?: Init): Promise<T>;
14
+ put<T>(path: string, body?: unknown, init?: Init): Promise<T>;
15
+ patch<T>(path: string, body?: unknown, init?: Init): Promise<T>;
16
+ delete<T = void>(path: string, init?: Init): Promise<T>;
17
+ };
18
+ /**
19
+ * A small client over `fetchJson` for the app's own server: root-relative paths get the app's base (so it works behind a reverse proxy),
20
+ * and `post`, `put` and `patch` send their body as JSON. `api.post<Learner>("/api/learners", { nickname })`.
21
+ */
22
+ export declare function createApi({ base, ...options }?: ApiOptions): Api;
23
+ export {};
@@ -26,6 +26,14 @@ export declare function staleOf(query: {
26
26
  export declare function useLoad<T, K extends QueryKey = QueryKey>(options: UseQueryOptions<T, Error, T, K> & {
27
27
  describeError?: DescribeError;
28
28
  }): Load<T>;
29
+ /** What `fetchJson` takes as `fetch`'s init, plus `json`. */
30
+ export type FetchJsonInit = RequestInit & {
31
+ /**
32
+ * 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.
33
+ * Replaces `body`; an app never builds the `RequestInit` for a write by hand.
34
+ */
35
+ json?: unknown;
36
+ };
29
37
  /** Options for `fetchJson` beyond `fetch`'s own. */
30
38
  export type FetchJsonOptions = {
31
39
  /** Finds the server's reason and per-field messages in an error body. Default `readErrorBody` (FastAPI's `detail`, `message`, `error`). */
@@ -33,8 +41,10 @@ export type FetchJsonOptions = {
33
41
  };
34
42
  /**
35
43
  * fetch() that throws an HttpError on a non-2xx response and parses JSON: the queryFn default, and the usual commit for a write.
36
- * A 204 or empty body resolves to undefined. An error response's body is read onto the HttpError (`body`, `reason`, `fieldErrors`).
44
+ * `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`).
37
45
  */
38
- export declare function fetchJson<T>(input: string | URL, init?: RequestInit, { readError }?: FetchJsonOptions): Promise<T>;
46
+ export declare function fetchJson<T>(input: string | URL, init?: FetchJsonInit, { readError }?: FetchJsonOptions): Promise<T>;
47
+ export { createApi, type Api, type ApiOptions } from './api';
48
+ export { createTypedApi, type TypedApi } from './typed-api';
39
49
  export { useInfiniteLoad, apiPage, type ApiPage, type InfiniteLoad, type InfiniteLoadOptions, type More } from './infinite';
40
50
  export { useJob, isTaskRunning, type Job, type JobOptions } from './job';
@@ -0,0 +1,78 @@
1
+ import { ApiOptions } from './api';
2
+ type Method = "get" | "post" | "put" | "patch" | "delete";
3
+ type Json = "application/json";
4
+ type PathsWith<P, M extends Method> = {
5
+ [K in keyof P]: P[K] extends {
6
+ [m in M]: object;
7
+ } ? K : never;
8
+ }[keyof P] & string;
9
+ type Operation<P, K extends keyof P, M extends Method> = P[K] extends {
10
+ [m in M]: infer O;
11
+ } ? O : never;
12
+ type Params<O, Where extends "path" | "query"> = O extends {
13
+ parameters: {
14
+ [w in Where]?: infer V;
15
+ };
16
+ } ? Exclude<V, undefined | never> : never;
17
+ type Body<O> = O extends {
18
+ requestBody?: {
19
+ content: {
20
+ [j in Json]: infer B;
21
+ };
22
+ };
23
+ } ? B : never;
24
+ type Answer<O> = O extends {
25
+ responses: infer R;
26
+ } ? R extends {
27
+ 200: {
28
+ content: {
29
+ [j in Json]: infer T;
30
+ };
31
+ };
32
+ } ? T : R extends {
33
+ 201: {
34
+ content: {
35
+ [j in Json]: infer T;
36
+ };
37
+ };
38
+ } ? T : R extends {
39
+ 202: {
40
+ content: {
41
+ [j in Json]: infer T;
42
+ };
43
+ };
44
+ } ? T : void : void;
45
+ type HasKeys<T> = [T] extends [never] ? false : [keyof T] extends [never] ? false : true;
46
+ type RequiredKeys<T> = {
47
+ [K in keyof T]-?: object extends Pick<T, K> ? never : K;
48
+ }[keyof T];
49
+ /** `{ path, query }`, each present only where the operation has them, and required only where one of its values is. */
50
+ type Request<O> = (HasKeys<Params<O, "path">> extends true ? {
51
+ path: Params<O, "path">;
52
+ } : {
53
+ path?: undefined;
54
+ }) & (HasKeys<Params<O, "query">> extends true ? RequiredKeys<Params<O, "query">> extends never ? {
55
+ query?: Params<O, "query">;
56
+ } : {
57
+ query: Params<O, "query">;
58
+ } : {
59
+ query?: undefined;
60
+ }) & Omit<RequestInit, "method" | "body">;
61
+ type Args<O, WithBody extends boolean> = WithBody extends true ? [Body<O>] extends [never] ? [request?: Request<O>] : HasKeys<Params<O, "path">> extends true ? [request: Request<O> & {
62
+ json: Body<O>;
63
+ }] : [request: Request<O> & {
64
+ json: Body<O>;
65
+ }] : [request?: Request<O>];
66
+ /** A client whose paths, parameters, JSON bodies and answers come from `strata-api-types`' `paths`. */
67
+ export type TypedApi<P> = {
68
+ /** The path with the app's base: for an `<img src>`, a download link or an `EventSource`. */
69
+ url(path: string): string;
70
+ } & {
71
+ [M in Method]: <K extends PathsWith<P, M>>(path: K, ...args: Args<Operation<P, K, M>, M extends "get" | "delete" ? false : true>) => Promise<Answer<Operation<P, K, M>>>;
72
+ };
73
+ /**
74
+ * `createApi` typed by the server's schema: `const api = createTypedApi<paths>()`, then `api.post("/api/learners", { json: { nickname } })` and
75
+ * `api.get("/api/learners/{id}", { path: { id } })`; the path, `path` and `query` values, `json` and the answer are checked, and `{id}` is filled and escaped.
76
+ */
77
+ export declare function createTypedApi<P>(options?: ApiOptions): TypedApi<P>;
78
+ export {};
@@ -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,
@@ -12,6 +13,9 @@ import { ColorSchemePreference } from '../components/theme';
12
13
  */
13
14
  import * as React from "react";
14
15
  export { installLayoutShims, type LayoutBox } from './layout';
16
+ export { installStorageShim, memoryStorage } from './storage';
17
+ export { installFakeSpeech, type FakeSpeech, type Spoken } from './speech';
18
+ export { fakeMicrophone, type FakeMicrophoneOptions } from './microphone';
15
19
  export { filledButtons, expectOneFilledButton, asyncButtonPhase } from './buttons';
16
20
  export { installFakeIntersectionObserver, type FakeIntersectionObserverControls, type FakeObserver, } from './intersection-observer';
17
21
  /** A query client for tests: no retries, and nothing goes stale or is collected mid-test. */
@@ -26,14 +30,14 @@ export type StrataRenderOptions = Omit<RenderOptions, "wrapper"> & {
26
30
  colorScheme?: ColorSchemePreference;
27
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. */
28
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;
29
35
  };
30
36
  /** Testing Library's `render` inside `StrataQueryProvider` and a `MemoryRouter` at `route`. */
31
- 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): {
32
38
  container: HTMLElement;
33
39
  baseElement: HTMLElement;
34
- debug: (baseElement?: import('react-dom/client').Container | (Element | Document) | Array<import('react-dom/client').Container | (Element | Document)> | undefined, maxLength
35
- /** A query client for tests: no retries, and nothing goes stale or is collected mid-test. */
36
- ?: number | undefined, options?: import('pretty-format').OptionsReceived | undefined) => void;
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;
37
41
  rerender: (ui: React.ReactNode) => void;
38
42
  unmount: () => void;
39
43
  asFragment: () => DocumentFragment;
@@ -93,12 +97,10 @@ 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
- debug: (baseElement?: import('react-dom/client').Container | (Element | Document) | Array<import('react-dom/client').Container | (Element | Document)> | undefined, maxLength
100
- /** A query client for tests: no retries, and nothing goes stale or is collected mid-test. */
101
- ?: number | undefined, options?: import('pretty-format').OptionsReceived | undefined) => void;
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;
102
104
  rerender: (ui: React.ReactNode) => void;
103
105
  unmount: () => void;
104
106
  asFragment: () => DocumentFragment;
@@ -7,7 +7,7 @@ export interface LayoutBox {
7
7
  }
8
8
  /**
9
9
  * Give jsdom a fixed box for every element (`getBoundingClientRect`, `offset*`, `client*`) and a
10
- * ResizeObserver that reports it on observe, so measuring components render. Defaults to 640×280.
10
+ * 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.
11
11
  * Call once in a Vitest setup file; returns a function that puts the originals back.
12
12
  */
13
13
  export declare function installLayoutShims({ width, height }?: Partial<LayoutBox>): () => 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;
@@ -0,0 +1,32 @@
1
+ /** One thing said aloud. */
2
+ export type Spoken = {
3
+ text: string;
4
+ lang: string;
5
+ rate: number;
6
+ voice: string | null;
7
+ cancelled: boolean;
8
+ };
9
+ /** The recording stand-in `installFakeSpeech` puts on `window`. */
10
+ export type FakeSpeech = {
11
+ /** Everything said so far, in order; an utterance cut off by a later one has `cancelled: true`. */
12
+ said: Spoken[];
13
+ /** The texts said so far that were not cancelled. */
14
+ texts(): string[];
15
+ /** Ends the utterance being said, as the browser does when it has finished. */
16
+ finish(): void;
17
+ /** Makes these voices the device's, and fires `voiceschanged` (the late arrival some browsers have). */
18
+ setVoices(voices: {
19
+ name: string;
20
+ lang: string;
21
+ }[]): void;
22
+ /** Puts the browser's own back (or none). */
23
+ uninstall(): void;
24
+ };
25
+ /**
26
+ * Installs a recording `speechSynthesis` and `SpeechSynthesisUtterance` on `window` and returns what was said.
27
+ * `uninstall()` after each test. `const speech = installFakeSpeech(); … expect(speech.texts()).toEqual(["Which one is the cat?"])`.
28
+ */
29
+ export declare function installFakeSpeech(voices?: {
30
+ name: string;
31
+ lang: string;
32
+ }[]): FakeSpeech;
@@ -0,0 +1,7 @@
1
+ /** An in-memory `Storage`, with the platform's behaviour (values are strings, `key` and `length` work). */
2
+ export declare function memoryStorage(): Storage;
3
+ /**
4
+ * 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`.
5
+ * Does nothing where storage works. Returns a function that puts the originals back. Called by `installLayoutShims`.
6
+ */
7
+ export declare function installStorageShim(): () => void;