strata-react 1.3.14 → 1.3.16

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 (52) hide show
  1. package/README.md +52 -11
  2. package/UPGRADING.md +16 -0
  3. package/dist/components/data-table.d.ts +6 -0
  4. package/dist/components/field.d.ts +2 -0
  5. package/dist/components/hotkeys.d.ts +1 -1
  6. package/dist/components/link-card.d.ts +4 -2
  7. package/dist/components/pause-button.d.ts +7 -0
  8. package/dist/components/schedule-table.d.ts +24 -0
  9. package/dist/components/system-panel.d.ts +58 -0
  10. package/dist/components/theme.d.ts +46 -1
  11. package/dist/{errors-D99YX4XL.js → errors-D0TsKLwJ.js} +2 -2
  12. package/dist/{errors-D99YX4XL.js.map → errors-D0TsKLwJ.js.map} +1 -1
  13. package/dist/{field-QCCmWTuY.js → field-jfhLD5XX.js} +22 -15
  14. package/dist/{field-QCCmWTuY.js.map → field-jfhLD5XX.js.map} +1 -1
  15. package/dist/{format-B32-PVi2.js → format-BNkXVwFx.js} +67 -6
  16. package/dist/format-BNkXVwFx.js.map +1 -0
  17. package/dist/index.d.ts +6 -3
  18. package/dist/index.js +796 -409
  19. package/dist/index.js.map +1 -1
  20. package/dist/lib/breakpoint.d.ts +4 -0
  21. package/dist/lib/format.d.ts +59 -6
  22. package/dist/map.js +3 -3
  23. package/dist/{microphone-BZXMKTCM.js → microphone-CZy0bNEx.js} +138 -91
  24. package/dist/microphone-CZy0bNEx.js.map +1 -0
  25. package/dist/panorama.js +2 -2
  26. package/dist/query/index.d.ts +5 -1
  27. package/dist/query/poll.d.ts +24 -0
  28. package/dist/reading.css +11 -0
  29. package/dist/{run-hR9neQHM.js → run-BT2WKzMz.js} +83 -17
  30. package/dist/run-BT2WKzMz.js.map +1 -0
  31. package/dist/strata.bare.css +279 -0
  32. package/dist/strata.css +845 -7
  33. package/dist/strata.migrate.css +25 -8
  34. package/dist/testing/index.d.ts +4 -2
  35. package/dist/testing.js +32 -6
  36. package/dist/testing.js.map +1 -1
  37. package/dist/{theme-By3DSUTs.js → theme-CFBAYaiu.js} +147 -6
  38. package/dist/theme-CFBAYaiu.js.map +1 -0
  39. package/dist/{value-controls-B7iNh4WO.js → value-controls-WRXbtUp6.js} +21 -6
  40. package/dist/value-controls-WRXbtUp6.js.map +1 -0
  41. package/dist/visual/capture.d.ts +2 -0
  42. package/dist/visual/fonts.d.ts +18 -0
  43. package/dist/visual/index.d.ts +1 -0
  44. package/dist/visual/types.d.ts +7 -1
  45. package/dist/visual-cli.js +1 -1
  46. package/dist/visual.js +1 -1
  47. package/package.json +13 -3
  48. package/dist/format-B32-PVi2.js.map +0 -1
  49. package/dist/microphone-BZXMKTCM.js.map +0 -1
  50. package/dist/run-hR9neQHM.js.map +0 -1
  51. package/dist/theme-By3DSUTs.js.map +0 -1
  52. package/dist/value-controls-B7iNh4WO.js.map +0 -1
@@ -1,19 +1,33 @@
1
- /* strata-react: the token contract, the namespace reset, the type steps, motion utilities and the
2
- base layer. It ships no colours. A product imports it between Tailwind and its own theme:
1
+ /* strata-react, the contract alone (`strata-react/strata.bare.css`): the token contract, the namespace
2
+ reset, the type steps, motion utilities and the base layer. It ships no colours and no look. This is
3
+ what an app that brings its own look imports, between Tailwind and its own theme:
3
4
 
4
5
  @import "tailwindcss";
5
- @import "strata-react/strata.css";
6
+ @import "strata-react/strata.bare.css";
6
7
  @import "./theme.generated.css"; (palette.mjs output: shadcn roles + 12-step ramps)
7
8
  @import "./theme.css"; (status roles, fonts, any subject colours, with reasons)
8
9
 
10
+ `strata-react/strata.css` is this file plus Strata's default look (src/styles/theme.css); apps that
11
+ want the default import that one and override what they like (CLAUDE.md, "The stance").
12
+
9
13
  An app that already has its own Tailwind colours and sizes imports "strata-react/strata.migrate.css"
10
14
  instead: this file without the reset below, so its stock classes keep compiling while it moves
11
15
  screens over (the build writes it from this file: scripts/copy-css.mjs). The README says when.
12
16
 
13
17
  The research behind every value is in jburnhams/ux-research, ui-library/tokens.md. */
14
18
 
19
+ /* strata:geist-begin */
20
+ /* The face of the contract on its own, bundled so no screen is drawn in whatever the machine has (Jonathan, 2026-11-25):
21
+ Geist Variable from Fontsource, a dependency of this package, so an app installs nothing. The
22
+ @font-face rules carry unicode-range, so a browser downloads only the subset a page uses (about
23
+ 32 KB for Latin). A product that names its own face in `--font-sans` still wins; this only
24
+ replaces the system fallback. Vite resolves the files, as it does for any imported CSS. */
25
+ @import "@fontsource-variable/geist";
26
+ /* strata:geist-end */
27
+
15
28
  /* MIGRATION MODE (strata.migrate.css): Tailwind's stock colours, sizes, radii, shadows and fonts are NOT cleared here, so an
16
- app's own `bg-stone-100` and `text-sm` keep compiling beside Strata's roles. Switch the import to strata.css once
29
+ app's own `bg-stone-100` and `text-sm` keep compiling beside Strata's roles. It is the bare contract (no default look), so an app
30
+ keeps its own colours while it moves over. Switch the import to strata.css or strata.bare.css once
17
31
  `strata-stock-classes` finds nothing left. */
18
32
 
19
33
  /* React Aria's state variants (`selected:`, `pressed:`, `hover:`, `focus-visible:`, `disabled:`, `open:`,
@@ -42,9 +56,10 @@
42
56
  }
43
57
 
44
58
  @theme {
45
- /* System faces until the product names its own (a later @theme block wins). One family on an
46
- Operate surface; --font-display is for page titles only. */
47
- --font-sans: ui-sans-serif, system-ui, sans-serif;
59
+ /* Geist Variable until the product names its own (a later @theme block wins), then the system
60
+ faces only for the instant before it loads. One family on an Operate surface; --font-display
61
+ is for page titles only. Mono stays a system face: Strata draws little code. */
62
+ --font-sans: "Geist Variable", ui-sans-serif, system-ui, sans-serif;
48
63
  --font-mono: ui-monospace, "SFMono-Regular", Menlo, monospace;
49
64
  --font-display: var(--font-sans);
50
65
 
@@ -118,6 +133,8 @@
118
133
  /* Type steps as utilities, not --text-* keys: a compound of size, line height and weight that
119
134
  cn() can tell apart from text colours. Operate scale, ratio about 1.2, fixed rem; nothing above
120
135
  28px except `type-display`, which is for Persuade surfaces only. */
136
+ /* `type-figure` also reads `--figure-font` and `--figure-stretch` (defaults: inherit, 100%), so a theme can set its big numbers in the
137
+ title voice (the default theme does) without every app that names a display face getting it. */
121
138
  /* Each step reads its own variables and falls back to today's value, so a product with another scale (or a
122
139
  region with a second look) sets `--type-body-size`, `--type-body-leading`, `--type-heading-weight`… on a
123
140
  class and every component with that step follows (issue #210). Names: --type-<step>-size, -leading, -weight. */
@@ -134,7 +151,7 @@
134
151
  font-stretch: var(--title-stretch);
135
152
  letter-spacing: var(--title-tracking);
136
153
  }
137
- @utility type-figure { font-size: var(--type-figure-size, 1.75rem); line-height: var(--type-figure-leading, 2.25rem); font-weight: var(--type-figure-weight, 500); font-variant-numeric: tabular-nums; }
154
+ @utility type-figure { font-size: var(--type-figure-size, 1.75rem); line-height: var(--type-figure-leading, 2.25rem); font-weight: var(--type-figure-weight, 500); font-variant-numeric: tabular-nums; font-family: var(--figure-font, inherit); font-stretch: var(--figure-stretch, 100%); }
138
155
  @utility type-display {
139
156
  font-family: var(--font-display);
140
157
  font-size: clamp(2.25rem, 1.5rem + 3vw, 4rem);
@@ -32,9 +32,11 @@ export type StrataRenderOptions = Omit<RenderOptions, "wrapper"> & {
32
32
  toasts?: boolean;
33
33
  /** The microphone a recording screen gets from `useMicrophone()`, such as `fakeMicrophone()`; the browser's when left out (which jsdom cannot open). */
34
34
  microphone?: Microphone;
35
+ /** The mount point of an app served behind a proxy (`"/_home/"`): a `<base href>` is in the document while the render lasts and removed when it unmounts, so `withBase`, `createApi` and `useSystemInfo` read what they read in production and in `strata-visual`. None when left out. */
36
+ base?: string;
35
37
  };
36
38
  /** Testing Library's `render` inside `StrataQueryProvider` and a `MemoryRouter` at `route`. */
37
- export declare function renderWithStrata(ui: React.ReactElement, { route, client, colorScheme, toasts, microphone, ...options }?: StrataRenderOptions): {
39
+ export declare function renderWithStrata(ui: React.ReactElement, { route, client, colorScheme, toasts, microphone, base, ...options }?: StrataRenderOptions): {
38
40
  container: HTMLElement;
39
41
  baseElement: HTMLElement;
40
42
  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;
@@ -97,7 +99,7 @@ export type RenderRoutesOptions = StrataRenderOptions & {
97
99
  basename?: string;
98
100
  };
99
101
  /** Testing Library's `render` of an app's route tree in a memory data router at `route`, with Strata's providers. */
100
- export declare function renderRoutes(routes: RouteObject[], { route, basename, client, colorScheme, toasts, microphone, ...options }?: RenderRoutesOptions): {
102
+ export declare function renderRoutes(routes: RouteObject[], { route, basename, client, colorScheme, toasts, microphone, base, ...options }?: RenderRoutesOptions): {
101
103
  container: HTMLElement;
102
104
  baseElement: HTMLElement;
103
105
  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;
package/dist/testing.js CHANGED
@@ -1,6 +1,6 @@
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
- import { r as ThemeProvider } from "./theme-By3DSUTs.js";
3
- import "react";
1
+ import { l as StrataQueryProvider, n as MicrophoneError, o as StrataToastRegion, s as toast, t as MicrophoneContext, u as createQueryClient } from "./microphone-CZy0bNEx.js";
2
+ import { o as ThemeProvider } from "./theme-CFBAYaiu.js";
3
+ import * as React from "react";
4
4
  import { jsx, jsxs } from "react/jsx-runtime";
5
5
  import { MemoryRouter, RouterProvider, createMemoryRouter } from "react-router";
6
6
  import { act, render } from "@testing-library/react";
@@ -423,6 +423,14 @@ function installFakeIntersectionObserver() {
423
423
  };
424
424
  }
425
425
  // src/testing/index.tsx
426
+ /**
427
+ * Test helpers: render a component, or a whole route tree, inside a router and a query client, as
428
+ * a Strata app runs it,
429
+ * and fill the gaps jsdom leaves (layout, ResizeObserver, IntersectionObserver). Use with MSW for
430
+ * the network, never module mocks.
431
+ *
432
+ * @module strata-react/testing
433
+ */
426
434
  /** A query client for tests: no retries, and nothing goes stale or is collected mid-test. */
427
435
  function createTestQueryClient() {
428
436
  return createQueryClient({ defaultOptions: { queries: {
@@ -431,7 +439,21 @@ function createTestQueryClient() {
431
439
  gcTime: Infinity
432
440
  } } });
433
441
  }
434
- function StrataProviders({ client, colorScheme, toasts, microphone, children }) {
442
+ function installBase(base) {
443
+ if (base === void 0 || typeof document === "undefined") return null;
444
+ const el = document.createElement("base");
445
+ el.setAttribute("href", base);
446
+ document.head.prepend(el);
447
+ return el;
448
+ }
449
+ function useBaseElement(element) {
450
+ React.useEffect(() => {
451
+ if (element && !element.isConnected) document.head.prepend(element);
452
+ return () => element?.remove();
453
+ }, [element]);
454
+ }
455
+ function StrataProviders({ client, colorScheme, toasts, microphone, base, children }) {
456
+ useBaseElement(base);
435
457
  const tree = /* @__PURE__ */ jsx(ThemeProvider, {
436
458
  defaultPreference: colorScheme,
437
459
  storageKey: null,
@@ -446,13 +468,15 @@ function StrataProviders({ client, colorScheme, toasts, microphone, children })
446
468
  }) : tree;
447
469
  }
448
470
  /** Testing Library's `render` inside `StrataQueryProvider` and a `MemoryRouter` at `route`. */
449
- function renderWithStrata(ui, { route = "/", client = createTestQueryClient(), colorScheme = "light", toasts = true, microphone, ...options } = {}) {
471
+ function renderWithStrata(ui, { route = "/", client = createTestQueryClient(), colorScheme = "light", toasts = true, microphone, base, ...options } = {}) {
450
472
  toast.clear();
473
+ const baseElement = installBase(base);
451
474
  const Wrapper = ({ children }) => /* @__PURE__ */ jsx(StrataProviders, {
452
475
  client,
453
476
  colorScheme,
454
477
  toasts,
455
478
  microphone,
479
+ base: baseElement,
456
480
  children: /* @__PURE__ */ jsx(MemoryRouter, {
457
481
  initialEntries: [route],
458
482
  children
@@ -467,8 +491,9 @@ function renderWithStrata(ui, { route = "/", client = createTestQueryClient(), c
467
491
  };
468
492
  }
469
493
  /** Testing Library's `render` of an app's route tree in a memory data router at `route`, with Strata's providers. */
470
- function renderRoutes(routes, { route, basename, client = createTestQueryClient(), colorScheme = "light", toasts = true, microphone, ...options } = {}) {
494
+ function renderRoutes(routes, { route, basename, client = createTestQueryClient(), colorScheme = "light", toasts = true, microphone, base, ...options } = {}) {
471
495
  toast.clear();
496
+ const baseElement = installBase(base);
472
497
  const router = createMemoryRouter(routes, {
473
498
  initialEntries: [route ?? basename ?? "/"],
474
499
  basename
@@ -478,6 +503,7 @@ function renderRoutes(routes, { route, basename, client = createTestQueryClient(
478
503
  colorScheme,
479
504
  toasts,
480
505
  microphone,
506
+ base: baseElement,
481
507
  children: /* @__PURE__ */ jsx(RouterProvider, { router })
482
508
  }), options);
483
509
  const navigate = (to) => act(async () => {
@@ -1 +1 @@
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// It stands in for `Audio` too (issue #310): a recorded clip that plays is said with its `clip`, `finish()`\n// ends it (the next part starts) and `failClip()` makes it fail, as a missing file or a refused autoplay does.\n\n/** One thing said aloud. */\nexport type Spoken = {\n text: string;\n lang: string;\n rate: number;\n voice: string | null;\n cancelled: boolean;\n /** The recording that was played, or null when the browser's voice said it. */\n clip: string | null;\n};\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 /** The clips played so far, in order (cut-off ones included). */\n clips(): string[];\n /** Ends the utterance or clip being said, as the browser does when it has finished. */\n finish(): void;\n /** Makes the clip playing now fail (a missing file, a refused autoplay): the rest of the prompt goes to the browser's voice. */\n failClip(): 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 const hadAudio = Object.getOwnPropertyDescriptor(window, \"Audio\");\n let clip: { entry: Spoken; audio: FakeAudio } | undefined;\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 // Only what `speak` uses of an audio element: src, title (the words), play, pause and the two events.\n class FakeAudio {\n src = \"\";\n title = \"\";\n onended: (() => void) | null = null;\n onerror: (() => void) | null = null;\n play() {\n const entry: Spoken = { text: this.title, lang: \"\", rate: 1, voice: null, cancelled: false, clip: this.src };\n said.push(entry);\n clip = { entry, audio: this };\n return Promise.resolve();\n }\n pause() {\n if (clip?.audio !== this) return;\n clip.entry.cancelled = true;\n clip = undefined;\n }\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, clip: null };\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 Object.defineProperty(window, \"Audio\", { configurable: true, writable: true, value: FakeAudio });\n\n return {\n said,\n texts: () => said.filter((s) => !s.cancelled).map((s) => s.text),\n clips: () => said.flatMap((s) => (s.clip === null ? [] : [s.clip])),\n finish() {\n if (clip) {\n const done = clip;\n clip = undefined;\n done.audio.onended?.();\n return;\n }\n const done = current;\n current = undefined;\n done?.utterance.onend?.();\n },\n failClip() {\n const failed = clip;\n clip = undefined;\n failed?.audio.onerror?.();\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 if (hadAudio) Object.defineProperty(window, \"Audio\", hadAudio);\n else delete (window as unknown as Record<string, unknown>).Audio;\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// For a hands-free screen (`useAutoRecorder`), `script` plays stretches of tone and quiet in turn, as a\n// speaker reading prompts with gaps between them would, once (then quiet) or over and over (`loop`).\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 /** Stretches of tone at their own `amplitude` (0 for quiet), played in order instead of one steady tone. */\n script?: readonly FakeSpeechStretch[];\n /** Play `script` again from the start when it ends, instead of falling quiet. */\n loop?: boolean;\n};\n\n/** One stretch of a fake microphone's `script`: so many seconds at a peak (0 is quiet). */\nexport type FakeSpeechStretch = { seconds: number; amplitude: number };\n\n/** A script of `takes` stretches of speech, each `speak` seconds after `gap` seconds of quiet, at `amplitude`. */\nexport function speechScript(takes: number, { speak = 1.5, gap = 1.5, amplitude = 0.3 }: { speak?: number; gap?: number; amplitude?: number } = {}): FakeSpeechStretch[] {\n return Array.from({ length: takes }, () => [\n { seconds: gap, amplitude: 0 },\n { seconds: speak, amplitude },\n ]).flat();\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 script,\n loop,\n}: FakeMicrophoneOptions = {}): Microphone {\n // The amplitude at sample `t`: the script's stretch it falls in, or the steady tone's.\n const ends = (script ?? []).reduce<number[]>((acc, s) => [...acc, (acc.at(-1) ?? 0) + Math.round(s.seconds * sampleRate)], []);\n const total = ends.at(-1) ?? 0;\n const at = (t: number): number => {\n if (!script) return amplitude;\n if (total === 0) return 0;\n const n = loop ? t % total : t;\n if (n >= total) return 0;\n const i = ends.findIndex((end) => n < end);\n return script[i].amplitude;\n };\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] = at(t) * 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, speechScript, type FakeMicrophoneOptions, type FakeSpeechStretch } 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,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,CAAC,gBAAgB,gBAAgB,GAAY;EAC9D,IAAI,OAAO,IAAI,GAAG;EAClB,MAAM,UAAU,cAAc;EAC9B,MAAM,UAAU,CAAC,YAAY,OAAO,WAAW,cAAc,SAAS,KAAA,CAAS,CAAC,CAAC,QAAQ,MA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ing/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// It stands in for `Audio` too (issue #310): a recorded clip that plays is said with its `clip`, `finish()`\n// ends it (the next part starts) and `failClip()` makes it fail, as a missing file or a refused autoplay does.\n\n/** One thing said aloud. */\nexport type Spoken = {\n text: string;\n lang: string;\n rate: number;\n voice: string | null;\n cancelled: boolean;\n /** The recording that was played, or null when the browser's voice said it. */\n clip: string | null;\n};\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 /** The clips played so far, in order (cut-off ones included). */\n clips(): string[];\n /** Ends the utterance or clip being said, as the browser does when it has finished. */\n finish(): void;\n /** Makes the clip playing now fail (a missing file, a refused autoplay): the rest of the prompt goes to the browser's voice. */\n failClip(): 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 const hadAudio = Object.getOwnPropertyDescriptor(window, \"Audio\");\n let clip: { entry: Spoken; audio: FakeAudio } | undefined;\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 // Only what `speak` uses of an audio element: src, title (the words), play, pause and the two events.\n class FakeAudio {\n src = \"\";\n title = \"\";\n onended: (() => void) | null = null;\n onerror: (() => void) | null = null;\n play() {\n const entry: Spoken = { text: this.title, lang: \"\", rate: 1, voice: null, cancelled: false, clip: this.src };\n said.push(entry);\n clip = { entry, audio: this };\n return Promise.resolve();\n }\n pause() {\n if (clip?.audio !== this) return;\n clip.entry.cancelled = true;\n clip = undefined;\n }\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, clip: null };\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 Object.defineProperty(window, \"Audio\", { configurable: true, writable: true, value: FakeAudio });\n\n return {\n said,\n texts: () => said.filter((s) => !s.cancelled).map((s) => s.text),\n clips: () => said.flatMap((s) => (s.clip === null ? [] : [s.clip])),\n finish() {\n if (clip) {\n const done = clip;\n clip = undefined;\n done.audio.onended?.();\n return;\n }\n const done = current;\n current = undefined;\n done?.utterance.onend?.();\n },\n failClip() {\n const failed = clip;\n clip = undefined;\n failed?.audio.onerror?.();\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 if (hadAudio) Object.defineProperty(window, \"Audio\", hadAudio);\n else delete (window as unknown as Record<string, unknown>).Audio;\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// For a hands-free screen (`useAutoRecorder`), `script` plays stretches of tone and quiet in turn, as a\n// speaker reading prompts with gaps between them would, once (then quiet) or over and over (`loop`).\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 /** Stretches of tone at their own `amplitude` (0 for quiet), played in order instead of one steady tone. */\n script?: readonly FakeSpeechStretch[];\n /** Play `script` again from the start when it ends, instead of falling quiet. */\n loop?: boolean;\n};\n\n/** One stretch of a fake microphone's `script`: so many seconds at a peak (0 is quiet). */\nexport type FakeSpeechStretch = { seconds: number; amplitude: number };\n\n/** A script of `takes` stretches of speech, each `speak` seconds after `gap` seconds of quiet, at `amplitude`. */\nexport function speechScript(takes: number, { speak = 1.5, gap = 1.5, amplitude = 0.3 }: { speak?: number; gap?: number; amplitude?: number } = {}): FakeSpeechStretch[] {\n return Array.from({ length: takes }, () => [\n { seconds: gap, amplitude: 0 },\n { seconds: speak, amplitude },\n ]).flat();\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 script,\n loop,\n}: FakeMicrophoneOptions = {}): Microphone {\n // The amplitude at sample `t`: the script's stretch it falls in, or the steady tone's.\n const ends = (script ?? []).reduce<number[]>((acc, s) => [...acc, (acc.at(-1) ?? 0) + Math.round(s.seconds * sampleRate)], []);\n const total = ends.at(-1) ?? 0;\n const at = (t: number): number => {\n if (!script) return amplitude;\n if (total === 0) return 0;\n const n = loop ? t % total : t;\n if (n >= total) return 0;\n const i = ends.findIndex((end) => n < end);\n return script[i].amplitude;\n };\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] = at(t) * 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, speechScript, type FakeMicrophoneOptions, type FakeSpeechStretch } 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 /** The mount point of an app served behind a proxy (`\"/_home/\"`): a `<base href>` is in the document while the render lasts and removed when it unmounts, so `withBase`, `createApi` and `useSystemInfo` read what they read in production and in `strata-visual`. None when left out. */\n base?: string;\n};\n\n// A <base href> for one render (#350): `appBase()` reads the page's <base>, which jsdom does not have.\n// It is installed before the render (and before `renderRoutes` creates its router, whose loaders run\n// at creation and may call `withBase`), first in <head> so it wins over one a setup file left. It is\n// made once per render call, outside React's render, so Strict Mode cannot leave a second one behind;\n// the provider removes it when the tree unmounts (Testing Library's cleanup does that after each\n// test) and puts it back if Strict Mode's rehearsal of the effect took it out.\nfunction installBase(base: string | undefined): HTMLBaseElement | null {\n if (base === undefined || typeof document === \"undefined\") return null;\n const el = document.createElement(\"base\");\n el.setAttribute(\"href\", base);\n document.head.prepend(el);\n return el;\n}\n\nfunction useBaseElement(element: HTMLBaseElement | null | undefined) {\n React.useEffect(() => {\n if (element && !element.isConnected) document.head.prepend(element);\n return () => element?.remove();\n }, [element]);\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 base,\n children,\n}: {\n base?: HTMLBaseElement | null;\n client: QueryClient;\n colorScheme: ColorSchemePreference;\n toasts: boolean;\n microphone?: Microphone;\n children: React.ReactNode;\n}) {\n useBaseElement(base);\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, base, ...options }: StrataRenderOptions = {},\n) {\n toast.clear(); // module state: a toast from the last test must not show in this one\n const baseElement = installBase(base);\n const Wrapper = ({ children }: { children: React.ReactNode }) => (\n <StrataProviders client={client} colorScheme={colorScheme} toasts={toasts} microphone={microphone} base={baseElement}>\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 base,\n ...options\n }: RenderRoutesOptions = {},\n) {\n toast.clear();\n const baseElement = installBase(base);\n const router = createMemoryRouter(routes, { initialEntries: [route ?? basename ?? \"/\"], basename });\n const result = render(\n <StrataProviders client={client} colorScheme={colorScheme} toasts={toasts} microphone={microphone} base={baseElement}>\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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GAAG,OAAO,IAAI;GAAE,SAAS;GAAS,GAAG;EAAQ,CAAC;CAAE;AACnE;;AAkBA,SAAgB,aACd,QACA,EACE,OACA,UACA,SAAS,sBAAsB,GAC/B,cAAc,SACd,SAAS,MACT,YACA,MACA,GAAG,YACoB,CAAC,GAC1B;CACA,MAAM,MAAM;CACZ,MAAM,cAAc,YAAY,IAAI;CACpC,MAAM,SAAS,mBAAmB,QAAQ;EAAE,gBAAgB,CAAC,SAAS,YAAY,GAAG;EAAG;CAAS,CAAC;CAClG,MAAM,SAAS,OACb,oBAAC,iBAAD;EAAyB;EAAqB;EAAqB;EAAoB;EAAY,MAAM;EACvG,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,8 +1,8 @@
1
- import { d as cn, l as Tooltip$1, t as ChoiceGroup } from "./field-QCCmWTuY.js";
1
+ import { d as cn, l as Tooltip$1, t as ChoiceGroup } from "./field-jfhLD5XX.js";
2
2
  import * as React from "react";
3
3
  import { Radio, RadioGroup } from "react-aria-components";
4
4
  import { Monitor, Moon, Sun } from "lucide-react";
5
- import { Fragment, jsx } from "react/jsx-runtime";
5
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
6
6
  // src/components/density.tsx
7
7
  /** The density attribute's page-level setter, shared by `ThemeProvider`. @internal */
8
8
  function useDensityOn(value, target) {
@@ -37,6 +37,53 @@ var PREFERENCES = [
37
37
  "light",
38
38
  "dark"
39
39
  ];
40
+ /** The palettes in `strata.css`: the default first, then four others. An app that adds its own in CSS passes its own list to `PaletteChoice`. */
41
+ var palettes = [
42
+ {
43
+ name: "petrol",
44
+ label: "Petrol and marigold",
45
+ detail: "The default"
46
+ },
47
+ {
48
+ name: "pine",
49
+ label: "Pine and coral"
50
+ },
51
+ {
52
+ name: "cobalt",
53
+ label: "Cobalt and tangerine"
54
+ },
55
+ {
56
+ name: "steel",
57
+ label: "Steel and mint"
58
+ },
59
+ {
60
+ name: "clay",
61
+ label: "Clay and teal"
62
+ }
63
+ ];
64
+ /** The default palette: the plain `:root` look, with no override. */
65
+ var DEFAULT_PALETTE = "petrol";
66
+ /** The localStorage key `ThemeProvider` keeps the palette under unless given another. */
67
+ var PALETTE_STORAGE_KEY = "strata-palette";
68
+ var PALETTE_NAME = /^[a-z][a-z0-9-]{0,31}$/;
69
+ function isPalette(value) {
70
+ return typeof value === "string" && PALETTE_NAME.test(value);
71
+ }
72
+ function readStoredPalette(key) {
73
+ if (key === null) return null;
74
+ try {
75
+ const value = window.localStorage.getItem(key);
76
+ return isPalette(value) ? value : null;
77
+ } catch {
78
+ return null;
79
+ }
80
+ }
81
+ function writeStoredPalette(key, value) {
82
+ if (key === null) return;
83
+ try {
84
+ window.localStorage.setItem(key, value);
85
+ } catch {}
86
+ }
40
87
  function isPreference(value) {
41
88
  return typeof value === "string" && PREFERENCES.includes(value);
42
89
  }
@@ -71,8 +118,9 @@ function useSystemColorScheme() {
71
118
  return React.useSyncExternalStore(subscribeSystem, systemSnapshot, serverSnapshot);
72
119
  }
73
120
  var Context = React.createContext(null);
121
+ var PaletteContext = React.createContext(null);
74
122
  /** Sets the `.dark` class strata.css keys on, from a system, light or dark preference that persists in localStorage when it can. */
75
- function ThemeProvider({ children, defaultPreference = "system", storageKey = COLOR_SCHEME_STORAGE_KEY, target, density }) {
123
+ function ThemeProvider({ children, defaultPreference = "system", storageKey = COLOR_SCHEME_STORAGE_KEY, defaultPalette = DEFAULT_PALETTE, paletteStorageKey = PALETTE_STORAGE_KEY, target, density }) {
76
124
  const [preference, setState] = React.useState(defaultPreference);
77
125
  React.useLayoutEffect(() => {
78
126
  const stored = readStored(storageKey);
@@ -100,6 +148,32 @@ function ThemeProvider({ children, defaultPreference = "system", storageKey = CO
100
148
  element.classList.toggle("dark", scheme === "dark");
101
149
  return () => element.classList.remove("dark");
102
150
  }, [scheme, target]);
151
+ const [palette, setPaletteState] = React.useState(defaultPalette);
152
+ React.useLayoutEffect(() => {
153
+ const stored = readStoredPalette(paletteStorageKey);
154
+ if (stored) setPaletteState(stored);
155
+ }, [paletteStorageKey]);
156
+ const setPalette = React.useCallback((next) => {
157
+ if (!isPalette(next)) return;
158
+ setPaletteState(next);
159
+ writeStoredPalette(paletteStorageKey, next);
160
+ }, [paletteStorageKey]);
161
+ React.useEffect(() => {
162
+ if (paletteStorageKey === null) return;
163
+ const onStorage = (event) => {
164
+ if (event.key !== paletteStorageKey && event.key !== null) return;
165
+ const value = event.key === null ? null : event.newValue;
166
+ setPaletteState(isPalette(value) ? value : defaultPalette);
167
+ };
168
+ window.addEventListener("storage", onStorage);
169
+ return () => window.removeEventListener("storage", onStorage);
170
+ }, [paletteStorageKey, defaultPalette]);
171
+ React.useLayoutEffect(() => {
172
+ const element = target === void 0 ? document.documentElement : target;
173
+ if (!element) return;
174
+ element.setAttribute("data-palette", palette);
175
+ return () => element.removeAttribute("data-palette");
176
+ }, [palette, target]);
103
177
  useDensityOn(density, target);
104
178
  const value = React.useMemo(() => ({
105
179
  preference,
@@ -110,9 +184,16 @@ function ThemeProvider({ children, defaultPreference = "system", storageKey = CO
110
184
  scheme,
111
185
  setPreference
112
186
  ]);
187
+ const paletteValue = React.useMemo(() => ({
188
+ palette,
189
+ setPalette
190
+ }), [palette, setPalette]);
113
191
  return /* @__PURE__ */ jsx(Context.Provider, {
114
192
  value,
115
- children
193
+ children: /* @__PURE__ */ jsx(PaletteContext.Provider, {
194
+ value: paletteValue,
195
+ children
196
+ })
116
197
  });
117
198
  }
118
199
  /** The person's colour-scheme preference, the scheme in effect, and a setter that persists it. Must be inside `ThemeProvider`. */
@@ -189,6 +270,66 @@ function ColorSchemeChoice({ legend, labels = defaultLabels, compact = false, cl
189
270
  }))
190
271
  });
191
272
  }
192
- export { useColorScheme as a, colorSchemeScript as i, ColorSchemeChoice as n, useSystemColorScheme as o, ThemeProvider as r, Density as s, COLOR_SCHEME_STORAGE_KEY as t };
273
+ /** The palette in effect and a setter that persists it. Must be inside `ThemeProvider`. */
274
+ function usePalette() {
275
+ const value = React.useContext(PaletteContext);
276
+ if (!value) throw new Error("usePalette must be used inside a ThemeProvider.");
277
+ return value;
278
+ }
279
+ /**
280
+ * The body of an inline `<script>` for the page's `<head>` that sets `data-palette` before the first paint
281
+ * from the stored choice, so a page does not flash the default palette while the bundle loads. Pass the
282
+ * same key and default as the `ThemeProvider`; put it beside `colorSchemeScript()`.
283
+ */
284
+ function paletteScript(storageKey = PALETTE_STORAGE_KEY, defaultPalette = DEFAULT_PALETTE) {
285
+ const key = JSON.stringify(storageKey);
286
+ return `(function(){var p=${JSON.stringify(defaultPalette)};try{var s=localStorage.getItem(${key});if(s&&/^[a-z][a-z0-9-]{0,31}$/.test(s))p=s}catch(e){}document.documentElement.setAttribute("data-palette",p)})()`;
287
+ }
288
+ /**
289
+ * The palettes as radio buttons, bound to the nearest `ThemeProvider`, each with a swatch drawn in its own
290
+ * palette (primary and the one warm accent) so the colours are seen before they are chosen. A list for a
291
+ * settings page, or `compact` swatches named "Palette" for a header. The words are always present (the
292
+ * list shows them, the compact form names each swatch and shows the same words as a tooltip).
293
+ */
294
+ function PaletteChoice({ legend, options = palettes, compact = false, className }) {
295
+ const { palette, setPalette } = usePalette();
296
+ const name = React.useId();
297
+ const swatch = (option) => /* @__PURE__ */ jsxs("span", {
298
+ "data-palette": option.name,
299
+ "aria-hidden": true,
300
+ className: "inline-flex size-5 shrink-0 overflow-hidden rounded-pill border border-border",
301
+ children: [/* @__PURE__ */ jsx("span", { className: "w-1/2 bg-primary" }), /* @__PURE__ */ jsx("span", { className: "w-1/2 bg-secondary-9" })]
302
+ });
303
+ if (compact) return /* @__PURE__ */ jsx(RadioGroup, {
304
+ "aria-label": legend ?? "Palette",
305
+ orientation: "horizontal",
306
+ name,
307
+ value: palette,
308
+ onChange: setPalette,
309
+ className: cn("inline-flex gap-0.5 rounded-surface border border-border bg-background p-0.5", className),
310
+ children: options.map((option) => /* @__PURE__ */ jsx(Tooltip$1, {
311
+ label: option.label,
312
+ children: /* @__PURE__ */ jsx(Radio, {
313
+ value: option.name,
314
+ "aria-label": option.label,
315
+ className: cn("grid size-(--control-h-sm) cursor-pointer place-items-center rounded-control transition-state", "hover:bg-muted selected:bg-muted selected:ring-1 selected:ring-border", "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"),
316
+ children: swatch(option)
317
+ })
318
+ }, option.name))
319
+ });
320
+ return /* @__PURE__ */ jsx(ChoiceGroup, {
321
+ legend: legend ?? "Palette",
322
+ name,
323
+ value: palette,
324
+ onChange: setPalette,
325
+ choices: options.map((option) => ({
326
+ value: option.name,
327
+ label: option.label,
328
+ detail: option.detail,
329
+ leading: swatch(option)
330
+ }))
331
+ });
332
+ }
333
+ export { PaletteChoice as a, paletteScript as c, usePalette as d, useSystemColorScheme as f, PALETTE_STORAGE_KEY as i, palettes as l, ColorSchemeChoice as n, ThemeProvider as o, Density as p, DEFAULT_PALETTE as r, colorSchemeScript as s, COLOR_SCHEME_STORAGE_KEY as t, useColorScheme as u };
193
334
 
194
- //# sourceMappingURL=theme-By3DSUTs.js.map
335
+ //# sourceMappingURL=theme-CFBAYaiu.js.map