strata-react 1.3.2 → 1.3.3

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 (41) hide show
  1. package/README.md +19 -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/say-again.d.ts +11 -0
  9. package/dist/components/toggle.d.ts +12 -4
  10. package/dist/{errors-DqezYZgy.js → errors-D99YX4XL.js} +2 -2
  11. package/dist/{errors-DqezYZgy.js.map → errors-D99YX4XL.js.map} +1 -1
  12. package/dist/{field-CTd1l3md.js → field-QCCmWTuY.js} +77 -4
  13. package/dist/field-QCCmWTuY.js.map +1 -0
  14. package/dist/{generate-DCRYZPJs.js → generate-CjTHKJ39.js} +21 -3
  15. package/dist/generate-CjTHKJ39.js.map +1 -0
  16. package/dist/index.d.ts +7 -2
  17. package/dist/index.js +251 -12
  18. package/dist/index.js.map +1 -1
  19. package/dist/lib/base.d.ts +10 -0
  20. package/dist/lib/search-param.d.ts +16 -0
  21. package/dist/lib/speech.d.ts +37 -0
  22. package/dist/map.js +2 -2
  23. package/dist/panorama.js +2 -2
  24. package/dist/query/api.d.ts +23 -0
  25. package/dist/query/index.d.ts +12 -2
  26. package/dist/query/typed-api.d.ts +78 -0
  27. package/dist/{query-CgoGqE0T.js → query-CfonqUzU.js} +12 -6
  28. package/dist/{query-CgoGqE0T.js.map → query-CfonqUzU.js.map} +1 -1
  29. package/dist/testing/index.d.ts +4 -6
  30. package/dist/testing/layout.d.ts +1 -1
  31. package/dist/testing/speech.d.ts +32 -0
  32. package/dist/testing/storage.d.ts +7 -0
  33. package/dist/testing.js +145 -4
  34. package/dist/testing.js.map +1 -1
  35. package/dist/{theme-DB0Km2m2.js → theme-By3DSUTs.js} +2 -2
  36. package/dist/{theme-DB0Km2m2.js.map → theme-By3DSUTs.js.map} +1 -1
  37. package/dist/{value-controls-CiwdvJeH.js → value-controls-B7iNh4WO.js} +3 -3
  38. package/dist/{value-controls-CiwdvJeH.js.map → value-controls-B7iNh4WO.js.map} +1 -1
  39. package/package.json +1 -1
  40. package/dist/field-CTd1l3md.js.map +0 -1
  41. package/dist/generate-DCRYZPJs.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,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";
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 {};
@@ -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) {
@@ -212,4 +218,4 @@ async function fetchJson(input, init, { readError = readErrorBody } = {}) {
212
218
  }
213
219
  export { toLoad as a, toast as c, staleOf as i, toastTimeout as l, createQueryClient as n, useLoad as o, fetchJson as r, StrataToastRegion as s, StrataQueryProvider as t, overlaySurface as u };
214
220
 
215
- //# sourceMappingURL=query-CgoGqE0T.js.map
221
+ //# sourceMappingURL=query-CfonqUzU.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"query-CgoGqE0T.js","names":["ToastQueue","ToastRegion","AriaToast","ToastContent","Button","AriaButton"],"sources":["../src/lib/overlay.ts","../src/components/toast.tsx","../src/query/index.tsx"],"sourcesContent":["// The look every floating surface shares (Dialog, Popover, and later Menu and Toast): the popover\n// role pair, an overlay radius, one hairline and the one shadow that exists for what floats\n// (components.md §3.11). One string, so a menu and a popover cannot drift apart.\nexport const overlaySurface =\n \"rounded-overlay border border-border bg-popover text-popover-foreground shadow-overlay enter-overlay\";\n","import * as React from \"react\";\nimport { UNSTABLE_Toast as AriaToast, UNSTABLE_ToastContent as ToastContent, UNSTABLE_ToastQueue as ToastQueue, UNSTABLE_ToastRegion as ToastRegion, Button as AriaButton, Text } from \"react-aria-components\";\nimport { CircleCheck, Info, TriangleAlert, X } from \"lucide-react\";\nimport { Button } from \"./button\";\nimport { cn } from \"../lib/utils\";\nimport { overlaySurface } from \"../lib/overlay\";\nimport { isDev } from \"../lib/dev\";\n\n// A toast confirms background work that finished (\"Export finished\", \"3 pieces synced\"). It is a\n// polite live region; it never carries an error a person must act on, which goes inline as an\n// `Alert` with its recovery (components.md §3.13, patterns.md §7), so there is no danger tone:\n// the type refuses it. `warning` is for a fact worth a glance (\"Kiln 2 is 40 min behind\").\n//\n// Rules the component owns so an app does not have to:\n// - One region, once, at the app root (`ToastRegion`), on the `layer-bar` layer: bottom end of the\n// window on a wide screen, the top on a phone, so it does not sit on the undo bar or cover the\n// focused control. It is a labelled landmark the keyboard reaches with F6 (React Aria).\n// - It stays long enough to read: 5 s plus 40 ms a character, up to 15 s, at least 8 s with an\n// action. The timer pauses while the pointer or focus is on it. There is always a dismiss control.\n// - At most one action, a button (\"Open file\"); content is words, not a form.\n// - Announcements are React Aria's: the toast's text is read when it appears and not again.\n// - The queue is module-level, so `toast.show()` works from a mutation's `onSuccess` outside any\n// component; `toast.clear()` empties it for a test. React Aria marks its toast API unstable; it\n// is used only here, behind this small surface, so a change upstream stays in this file.\n// - One region at a time, enforced (issue #230): the first mounted owns the queue and a second one draws nothing and\n// says so in development, naming the fix. Two regions on one queue show every toast twice, which looks like a bug in\n// the toast and (in a test) fails `findByText` with \"Found multiple elements\"; the usual cause is a route tree that\n// draws the region in its root layout while a test helper draws one too (`renderRoutes(..., { toasts: false })`),\n// or an app with a region in a layout and another in a page. Ownership is held by a mounted-order list, not by the\n// queue, so unmounting the owner hands it to the next region.\n// Toasts are rare and brief, so they get the overlay entrance and nothing else (character.md §3).\n\n/** What a toast says. */\nexport type ToastContentProps = {\n /** What finished, past tense, in the product's words: \"Export finished\". */\n title: string;\n /** One more sentence: what and where (\"run.mp4, 2:31 at 1080p, in your Downloads folder.\"). */\n description?: string;\n /** `info` by default. There is no danger tone: an error the person must act on is an `Alert`. */\n tone?: \"info\" | \"success\" | \"warning\";\n /** One action beside the words. */\n action?: { label: string; onPress: () => void };\n /** Milliseconds before it goes. Defaults to enough to read the words. */\n timeout?: number;\n};\n\nconst queue = new ToastQueue<ToastContentProps>({ maxVisibleToasts: 3 });\n\n/** Milliseconds a toast stays: 5 s plus 40 ms a character, to at most 15 s, and at least 8 s with an action. */\nexport function toastTimeout(content: Pick<ToastContentProps, \"title\" | \"description\" | \"action\" | \"timeout\">): number {\n if (content.timeout !== undefined) return content.timeout;\n const chars = content.title.length + (content.description?.length ?? 0) + (content.action?.label.length ?? 0);\n return Math.max(content.action ? 8000 : 0, Math.min(15000, 5000 + 40 * chars));\n}\n\n/** The toast queue: `toast.show({ title })` from anywhere; `toast.close(key)`; `toast.clear()`. */\nexport const toast = {\n /** Shows a toast and returns its key. */\n show(content: ToastContentProps): string {\n // Nothing appears without a region, and nothing says so: in development the first such call does (issue #249).\n if (mounted.length === 0 && !warnedNoRegion && isDev()) {\n warnedNoRegion = true;\n console.warn(\"strata-react: toast.show() was called but no StrataToastRegion is mounted, so nothing will appear. Render <StrataToastRegion /> once at the app root.\");\n }\n return queue.add(content, { timeout: toastTimeout(content) });\n },\n close(key: string) {\n queue.close(key);\n },\n clear() {\n queue.clear();\n },\n};\n\nconst marks = { info: { icon: Info, color: \"text-info\" }, success: { icon: CircleCheck, color: \"text-success\" }, warning: { icon: TriangleAlert, color: \"text-warning\" } } as const;\n\n/** Props for `ToastRegion`. */\nexport type StrataToastRegionProps = {\n /** Names the landmark. Default \"Notifications\". */\n label?: string;\n className?: string;\n};\n\n// The regions mounted now, oldest first: the first draws, the rest stay empty.\nconst mounted: string[] = [];\nlet warnedNoRegion = false;\n/** For tests: forget that the missing-region warning was given. */\nexport function resetToastWarnings() {\n warnedNoRegion = false;\n}\nconst watchers = new Set<() => void>();\nconst changed = () => watchers.forEach((w) => w());\nconst watch = (w: () => void) => {\n watchers.add(w);\n return () => void watchers.delete(w);\n};\n\n/** True while this region is the one that draws. The server and the first client render say yes, so hydration matches. */\nfunction useOwnsQueue(): boolean {\n const id = React.useId();\n React.useLayoutEffect(() => {\n mounted.push(id);\n changed();\n return () => {\n mounted.splice(mounted.indexOf(id), 1);\n changed();\n };\n }, [id]);\n const owns = React.useSyncExternalStore(watch, () => mounted[0] === id, () => true);\n const [warned, setWarned] = React.useState(false);\n React.useEffect(() => {\n if (owns || warned || mounted.indexOf(id) < 1) return;\n setWarned(true);\n if (isDev()) {\n console.warn(\"strata-react: a StrataToastRegion is already mounted, so this one draws nothing. Render it once at the app root; in a test of a route tree that draws its own, pass `toasts: false` to renderRoutes.\");\n }\n }, [owns, warned, id]);\n return owns;\n}\n\n/** The one place toasts appear. Render it once at the app root; a second one mounted at the same time draws nothing and warns in development. A labelled landmark (F6), polite, above panes and the undo bar. */\nexport function StrataToastRegion({ label = \"Notifications\", className }: StrataToastRegionProps) {\n const owns = useOwnsQueue();\n if (!owns) return null;\n return (\n <ToastRegion\n queue={queue}\n aria-label={label}\n className={cn(\"layer-bar fixed inset-x-4 top-4 grid justify-items-end gap-2 outline-none sm:inset-x-auto sm:top-auto sm:right-4 sm:bottom-4\", className)}\n >\n {({ toast: t }) => (\n <AriaToast\n toast={t}\n className={cn(\"flex w-full max-w-sm items-start gap-3 p-3 outline-none focus-visible:outline-2 focus-visible:outline-ring\", overlaySurface)}\n >\n {(() => {\n const { icon: Icon, color } = marks[t.content.tone ?? \"info\"];\n return <Icon aria-hidden className={cn(\"mt-0.5 size-4 shrink-0\", color)} />;\n })()}\n <ToastContent className=\"grid min-w-0 flex-1 gap-0.5\">\n <Text slot=\"title\" className=\"type-label\">\n {t.content.title}\n </Text>\n {t.content.description && <Text slot=\"description\" className=\"type-body-sm text-muted-foreground\">{t.content.description}</Text>}\n </ToastContent>\n {t.content.action && (\n <Button size=\"sm\" onPress={() => { t.content.action?.onPress(); queue.close(t.key); }}>\n {t.content.action.label}\n </Button>\n )}\n <AriaButton slot=\"close\" aria-label=\"Dismiss\" className=\"grid size-6 shrink-0 cursor-pointer place-items-center rounded-control text-muted-foreground transition-state hover:bg-muted hover:text-foreground\">\n <X aria-hidden className=\"size-4\" />\n </AriaButton>\n </AriaToast>\n )}\n </ToastRegion>\n );\n}\n","import * as React from \"react\";\nimport {\n QueryClient,\n QueryClientProvider,\n useQuery,\n type QueryKey,\n type UseQueryOptions,\n type UseQueryResult,\n} from \"@tanstack/react-query\";\nimport type { Load, Stale } from \"../components/data-view\";\nimport { HttpError, describeHttpError, errorPayload, readErrorBody, type DescribeError, type ErrorBody } from \"../lib/errors\";\n\nexport { HttpError, describeHttpError, errorPayload, readErrorBody, type DescribeError, type ErrorBody };\n\n// Data loading, the Strata way: TanStack Query fetches and caches, and every view of the result\n// goes through DataView, which takes a Load<T>. `toLoad` is the one bridge between them, so a\n// screen never re-derives loading/error/ready from a query's flags and never forgets one.\n//\n// Opinions in createQueryClient: one retry (a second failure is real and the person should see\n// it with a \"Try again\"), 30 s stale time (dashboards are read many times a minute but change\n// over minutes), and no refetch on window focus (a table that reorders itself while someone reads\n// it is worse than one that is 30 s old). Override per query when the data says otherwise.\n\n/** A QueryClient with Strata's defaults: one retry, 30 s stale time, no refetch on window focus. */\nexport function createQueryClient(overrides?: ConstructorParameters<typeof QueryClient>[0]) {\n return new QueryClient({\n ...overrides,\n defaultOptions: {\n ...overrides?.defaultOptions,\n queries: { retry: 1, staleTime: 30_000, refetchOnWindowFocus: false, ...overrides?.defaultOptions?.queries },\n },\n });\n}\n\n/** Provides a query client (Strata's defaults unless one is passed) to the app. */\nexport function StrataQueryProvider({ client, children }: { client?: QueryClient; children: React.ReactNode }) {\n const [fallback] = React.useState(() => client ?? createQueryClient());\n return <QueryClientProvider client={client ?? fallback}>{children}</QueryClientProvider>;\n}\n\n/**\n * Turns a TanStack query result into the `Load<T>` that `DataView` takes; errors are described for a person by `describe`.\n * A refetch that fails after data arrived stays `ready`, with `stale` saying why and when the data was read.\n */\nexport function toLoad<T>(query: UseQueryResult<T>, describe: DescribeError = describeHttpError): Load<T> {\n if (query.status === \"success\") return { status: \"ready\", data: query.data };\n // TanStack keeps the last good data when a refetch fails and sets status \"error\" (isRefetchError).\n // That is old data, not no data: keep it on screen and say how old it is.\n if (query.status === \"error\" && query.data !== undefined) return { status: \"ready\", data: query.data, stale: staleOf(query, describe) };\n if (query.status === \"error\") return { status: \"error\", message: describe(query.error), retry: () => void query.refetch() };\n return { status: \"loading\" };\n}\n\n/** The `Stale` of a query whose refetch failed after a good read. Shared by `toLoad` and `useInfiniteLoad`. */\nexport function staleOf(\n query: { error: unknown; dataUpdatedAt: number; isFetching: boolean; refetch: () => unknown },\n describe: DescribeError = describeHttpError,\n): Stale {\n return { message: describe(query.error), readAt: new Date(query.dataUpdatedAt), retry: () => void query.refetch(), retrying: query.isFetching };\n}\n\n/** `useQuery`, returned as a `Load<T>` for `DataView`. */\nexport function useLoad<T, K extends QueryKey = QueryKey>(\n options: UseQueryOptions<T, Error, T, K> & { describeError?: DescribeError },\n): Load<T> {\n const { describeError, ...rest } = options;\n return toLoad(useQuery(rest), describeError);\n}\n\n/** 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 * 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?: RequestInit, { readError = readErrorBody }: FetchJsonOptions = {}): Promise<T> {\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(init?.headers);\n if (!headers.has(\"Accept\")) headers.set(\"Accept\", \"application/json\");\n const res = await fetch(input, { ...init, 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 { useInfiniteLoad, apiPage, type ApiPage, type InfiniteLoad, type InfiniteLoadOptions, type More } from \"./infinite\";\nexport { useJob, isTaskRunning, type Job, type J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AqB,MAAoB,EAAE,YAAY,kBAAoC,CAAC,GAAe;CAG5I,MAAM,UAAU,IAAI,QAAQ,MAAM,OAAO;CACzC,IAAI,CAAC,QAAQ,IAAI,QAAQ,GAAG,QAAQ,IAAI,UAAU,kBAAkB;CACpE,MAAM,MAAM,MAAM,MAAM,OAAO;EAAE,GAAG;EAAM;CAAQ,CAAC;CACnD,IAAI,CAAC,IAAI,IAAI;EAGX,MAAM,MAAM,MAAM,IAAI,KAAK,CAAC,CAAC,YAAY,EAAE;EAC3C,IAAI,OAAgB,OAAO,KAAA;EAC3B,IAAI;GACF,IAAI,KAAK,OAAO,KAAK,MAAM,GAAG;EAChC,QAAQ,CAER;EACA,MAAM,IAAI,UAAU,IAAI,QAAQ,IAAI,YAAY,OAAO,KAAK,GAAG,MAAM,UAAU,IAAI,CAAC;CACtF;CAGA,MAAM,OAAO,IAAI,WAAW,MAAM,KAAK,MAAM,IAAI,KAAK;CACtD,OAAQ,OAAO,KAAK,MAAM,IAAI,IAAI,KAAA;AACpC"}
1
+ {"version":3,"file":"query-CfonqUzU.js","names":["ToastQueue","ToastRegion","AriaToast","ToastContent","Button","AriaButton"],"sources":["../src/lib/overlay.ts","../src/components/toast.tsx","../src/query/index.tsx"],"sourcesContent":["// The look every floating surface shares (Dialog, Popover, and later Menu and Toast): the popover\n// role pair, an overlay radius, one hairline and the one shadow that exists for what floats\n// (components.md §3.11). One string, so a menu and a popover cannot drift apart.\nexport const overlaySurface =\n \"rounded-overlay border border-border bg-popover text-popover-foreground shadow-overlay enter-overlay\";\n","import * as React from \"react\";\nimport { UNSTABLE_Toast as AriaToast, UNSTABLE_ToastContent as ToastContent, UNSTABLE_ToastQueue as ToastQueue, UNSTABLE_ToastRegion as ToastRegion, Button as AriaButton, Text } from \"react-aria-components\";\nimport { CircleCheck, Info, TriangleAlert, X } from \"lucide-react\";\nimport { Button } from \"./button\";\nimport { cn } from \"../lib/utils\";\nimport { overlaySurface } from \"../lib/overlay\";\nimport { isDev } from \"../lib/dev\";\n\n// A toast confirms background work that finished (\"Export finished\", \"3 pieces synced\"). It is a\n// polite live region; it never carries an error a person must act on, which goes inline as an\n// `Alert` with its recovery (components.md §3.13, patterns.md §7), so there is no danger tone:\n// the type refuses it. `warning` is for a fact worth a glance (\"Kiln 2 is 40 min behind\").\n//\n// Rules the component owns so an app does not have to:\n// - One region, once, at the app root (`ToastRegion`), on the `layer-bar` layer: bottom end of the\n// window on a wide screen, the top on a phone, so it does not sit on the undo bar or cover the\n// focused control. It is a labelled landmark the keyboard reaches with F6 (React Aria).\n// - It stays long enough to read: 5 s plus 40 ms a character, up to 15 s, at least 8 s with an\n// action. The timer pauses while the pointer or focus is on it. There is always a dismiss control.\n// - At most one action, a button (\"Open file\"); content is words, not a form.\n// - Announcements are React Aria's: the toast's text is read when it appears and not again.\n// - The queue is module-level, so `toast.show()` works from a mutation's `onSuccess` outside any\n// component; `toast.clear()` empties it for a test. React Aria marks its toast API unstable; it\n// is used only here, behind this small surface, so a change upstream stays in this file.\n// - One region at a time, enforced (issue #230): the first mounted owns the queue and a second one draws nothing and\n// says so in development, naming the fix. Two regions on one queue show every toast twice, which looks like a bug in\n// the toast and (in a test) fails `findByText` with \"Found multiple elements\"; the usual cause is a route tree that\n// draws the region in its root layout while a test helper draws one too (`renderRoutes(..., { toasts: false })`),\n// or an app with a region in a layout and another in a page. Ownership is held by a mounted-order list, not by the\n// queue, so unmounting the owner hands it to the next region.\n// Toasts are rare and brief, so they get the overlay entrance and nothing else (character.md §3).\n\n/** What a toast says. */\nexport type ToastContentProps = {\n /** What finished, past tense, in the product's words: \"Export finished\". */\n title: string;\n /** One more sentence: what and where (\"run.mp4, 2:31 at 1080p, in your Downloads folder.\"). */\n description?: string;\n /** `info` by default. There is no danger tone: an error the person must act on is an `Alert`. */\n tone?: \"info\" | \"success\" | \"warning\";\n /** One action beside the words. */\n action?: { label: string; onPress: () => void };\n /** Milliseconds before it goes. Defaults to enough to read the words. */\n timeout?: number;\n};\n\nconst queue = new ToastQueue<ToastContentProps>({ maxVisibleToasts: 3 });\n\n/** Milliseconds a toast stays: 5 s plus 40 ms a character, to at most 15 s, and at least 8 s with an action. */\nexport function toastTimeout(content: Pick<ToastContentProps, \"title\" | \"description\" | \"action\" | \"timeout\">): number {\n if (content.timeout !== undefined) return content.timeout;\n const chars = content.title.length + (content.description?.length ?? 0) + (content.action?.label.length ?? 0);\n return Math.max(content.action ? 8000 : 0, Math.min(15000, 5000 + 40 * chars));\n}\n\n/** The toast queue: `toast.show({ title })` from anywhere; `toast.close(key)`; `toast.clear()`. */\nexport const toast = {\n /** Shows a toast and returns its key. */\n show(content: ToastContentProps): string {\n // Nothing appears without a region, and nothing says so: in development the first such call does (issue #249).\n if (mounted.length === 0 && !warnedNoRegion && isDev()) {\n warnedNoRegion = true;\n console.warn(\"strata-react: toast.show() was called but no StrataToastRegion is mounted, so nothing will appear. Render <StrataToastRegion /> once at the app root.\");\n }\n return queue.add(content, { timeout: toastTimeout(content) });\n },\n close(key: string) {\n queue.close(key);\n },\n clear() {\n queue.clear();\n },\n};\n\nconst marks = { info: { icon: Info, color: \"text-info\" }, success: { icon: CircleCheck, color: \"text-success\" }, warning: { icon: TriangleAlert, color: \"text-warning\" } } as const;\n\n/** Props for `ToastRegion`. */\nexport type StrataToastRegionProps = {\n /** Names the landmark. Default \"Notifications\". */\n label?: string;\n className?: string;\n};\n\n// The regions mounted now, oldest first: the first draws, the rest stay empty.\nconst mounted: string[] = [];\nlet warnedNoRegion = false;\n/** For tests: forget that the missing-region warning was given. */\nexport function resetToastWarnings() {\n warnedNoRegion = false;\n}\nconst watchers = new Set<() => void>();\nconst changed = () => watchers.forEach((w) => w());\nconst watch = (w: () => void) => {\n watchers.add(w);\n return () => void watchers.delete(w);\n};\n\n/** True while this region is the one that draws. The server and the first client render say yes, so hydration matches. */\nfunction useOwnsQueue(): boolean {\n const id = React.useId();\n React.useLayoutEffect(() => {\n mounted.push(id);\n changed();\n return () => {\n mounted.splice(mounted.indexOf(id), 1);\n changed();\n };\n }, [id]);\n const owns = React.useSyncExternalStore(watch, () => mounted[0] === id, () => true);\n const [warned, setWarned] = React.useState(false);\n React.useEffect(() => {\n if (owns || warned || mounted.indexOf(id) < 1) return;\n setWarned(true);\n if (isDev()) {\n console.warn(\"strata-react: a StrataToastRegion is already mounted, so this one draws nothing. Render it once at the app root; in a test of a route tree that draws its own, pass `toasts: false` to renderRoutes.\");\n }\n }, [owns, warned, id]);\n return owns;\n}\n\n/** The one place toasts appear. Render it once at the app root; a second one mounted at the same time draws nothing and warns in development. A labelled landmark (F6), polite, above panes and the undo bar. */\nexport function StrataToastRegion({ label = \"Notifications\", className }: StrataToastRegionProps) {\n const owns = useOwnsQueue();\n if (!owns) return null;\n return (\n <ToastRegion\n queue={queue}\n aria-label={label}\n className={cn(\"layer-bar fixed inset-x-4 top-4 grid justify-items-end gap-2 outline-none sm:inset-x-auto sm:top-auto sm:right-4 sm:bottom-4\", className)}\n >\n {({ toast: t }) => (\n <AriaToast\n toast={t}\n className={cn(\"flex w-full max-w-sm items-start gap-3 p-3 outline-none focus-visible:outline-2 focus-visible:outline-ring\", overlaySurface)}\n >\n {(() => {\n const { icon: Icon, color } = marks[t.content.tone ?? \"info\"];\n return <Icon aria-hidden className={cn(\"mt-0.5 size-4 shrink-0\", color)} />;\n })()}\n <ToastContent className=\"grid min-w-0 flex-1 gap-0.5\">\n <Text slot=\"title\" className=\"type-label\">\n {t.content.title}\n </Text>\n {t.content.description && <Text slot=\"description\" className=\"type-body-sm text-muted-foreground\">{t.content.description}</Text>}\n </ToastContent>\n {t.content.action && (\n <Button size=\"sm\" onPress={() => { t.content.action?.onPress(); queue.close(t.key); }}>\n {t.content.action.label}\n </Button>\n )}\n <AriaButton slot=\"close\" aria-label=\"Dismiss\" className=\"grid size-6 shrink-0 cursor-pointer place-items-center rounded-control text-muted-foreground transition-state hover:bg-muted hover:text-foreground\">\n <X aria-hidden className=\"size-4\" />\n </AriaButton>\n </AriaToast>\n )}\n </ToastRegion>\n );\n}\n","import * as React from \"react\";\nimport {\n QueryClient,\n QueryClientProvider,\n useQuery,\n type QueryKey,\n type UseQueryOptions,\n type UseQueryResult,\n} from \"@tanstack/react-query\";\nimport type { Load, Stale } from \"../components/data-view\";\nimport { HttpError, describeHttpError, errorPayload, readErrorBody, type DescribeError, type ErrorBody } from \"../lib/errors\";\n\nexport { HttpError, describeHttpError, errorPayload, readErrorBody, type DescribeError, type ErrorBody };\n\n// Data loading, the Strata way: TanStack Query fetches and caches, and every view of the result\n// goes through DataView, which takes a Load<T>. `toLoad` is the one bridge between them, so a\n// screen never re-derives loading/error/ready from a query's flags and never forgets one.\n//\n// Opinions in createQueryClient: one retry (a second failure is real and the person should see\n// it with a \"Try again\"), 30 s stale time (dashboards are read many times a minute but change\n// over minutes), and no refetch on window focus (a table that reorders itself while someone reads\n// it is worse than one that is 30 s old). Override per query when the data says otherwise.\n\n/** A QueryClient with Strata's defaults: one retry, 30 s stale time, no refetch on window focus. */\nexport function createQueryClient(overrides?: ConstructorParameters<typeof QueryClient>[0]) {\n return new QueryClient({\n ...overrides,\n defaultOptions: {\n ...overrides?.defaultOptions,\n queries: { retry: 1, staleTime: 30_000, refetchOnWindowFocus: false, ...overrides?.defaultOptions?.queries },\n },\n });\n}\n\n/** Provides a query client (Strata's defaults unless one is passed) to the app. */\nexport function StrataQueryProvider({ client, children }: { client?: QueryClient; children: React.ReactNode }) {\n const [fallback] = React.useState(() => client ?? createQueryClient());\n return <QueryClientProvider client={client ?? fallback}>{children}</QueryClientProvider>;\n}\n\n/**\n * Turns a TanStack query result into the `Load<T>` that `DataView` takes; errors are described for a person by `describe`.\n * A refetch that fails after data arrived stays `ready`, with `stale` saying why and when the data was read.\n */\nexport function toLoad<T>(query: UseQueryResult<T>, describe: DescribeError = describeHttpError): Load<T> {\n if (query.status === \"success\") return { status: \"ready\", data: query.data };\n // TanStack keeps the last good data when a refetch fails and sets status \"error\" (isRefetchError).\n // That is old data, not no data: keep it on screen and say how old it is.\n if (query.status === \"error\" && query.data !== undefined) return { status: \"ready\", data: query.data, stale: staleOf(query, describe) };\n if (query.status === \"error\") return { status: \"error\", message: describe(query.error), retry: () => void query.refetch() };\n return { status: \"loading\" };\n}\n\n/** The `Stale` of a query whose refetch failed after a good read. Shared by `toLoad` and `useInfiniteLoad`. */\nexport function staleOf(\n query: { error: unknown; dataUpdatedAt: number; isFetching: boolean; refetch: () => unknown },\n describe: DescribeError = describeHttpError,\n): Stale {\n return { message: describe(query.error), readAt: new Date(query.dataUpdatedAt), retry: () => void query.refetch(), retrying: query.isFetching };\n}\n\n/** `useQuery`, returned as a `Load<T>` for `DataView`. */\nexport function useLoad<T, K extends QueryKey = QueryKey>(\n options: UseQueryOptions<T, Error, T, K> & { describeError?: DescribeError },\n): Load<T> {\n const { describeError, ...rest } = options;\n return toLoad(useQuery(rest), describeError);\n}\n\n/** What `fetchJson` takes as `fetch`'s init, plus `json`. */\nexport type FetchJsonInit = RequestInit & {\n /**\n * A value sent as the JSON body: `Content-Type: application/json` is set unless the caller gave one, and the method is `POST` unless given.\n * Replaces `body`; an app never builds the `RequestInit` for a write by hand.\n */\n json?: unknown;\n};\n\n/** Options for `fetchJson` beyond `fetch`'s own. */\nexport type FetchJsonOptions = {\n /** Finds the server's reason and per-field messages in an error body. Default `readErrorBody` (FastAPI's `detail`, `message`, `error`). */\n readError?: (body: unknown) => ErrorBody;\n};\n\n/**\n * fetch() that throws an HttpError on a non-2xx response and parses JSON: the queryFn default, and the usual commit for a write.\n * `init.json` sends a JSON body without building the headers. A 204 or empty body resolves to undefined. An error response's body is read onto the HttpError (`body`, `reason`, `fieldErrors`).\n */\nexport async function fetchJson<T>(input: string | URL, init?: FetchJsonInit, { readError = readErrorBody }: FetchJsonOptions = {}): Promise<T> {\n const { json, ...rest } = init ?? {};\n // Headers, tuple arrays and plain objects are all valid HeadersInit; normalise before adding the\n // default so a caller's Authorization (or their own Accept) is never dropped.\n const headers = new Headers(rest.headers);\n if (!headers.has(\"Accept\")) headers.set(\"Accept\", \"application/json\");\n if (json !== undefined) {\n if (!headers.has(\"Content-Type\")) headers.set(\"Content-Type\", \"application/json\");\n rest.body = JSON.stringify(json);\n rest.method ??= \"POST\";\n }\n const res = await fetch(input, { ...rest, headers });\n if (!res.ok) {\n // The body is read as text and parsed only when it parses: a proxy's HTML 502 page or an empty\n // body must still throw the HttpError, never a JSON SyntaxError in its place.\n const raw = await res.text().catch(() => \"\");\n let body: unknown = raw || undefined;\n try {\n if (raw) body = JSON.parse(raw);\n } catch {\n // Not JSON: keep the text.\n }\n throw new HttpError(res.status, res.statusText, String(input), body, readError(body));\n }\n // Writes (DELETE, a PUT that returns nothing) answer 204 or an empty body; that is success, not a\n // JSON parse error.\n const text = res.status === 204 ? \"\" : await res.text();\n return (text ? JSON.parse(text) : undefined) as T;\n}\n\nexport { createApi, type Api, type ApiOptions } from \"./api\";\nexport { createTypedApi, type TypedApi } from \"./typed-api\";\nexport { useInfiniteLoad, apiPage, type ApiPage, type InfiniteLoad, type InfiniteLoadOptions, type More } from \"./infinite\";\nexport { useJob, isTaskRunning, type Job, type JobOptions } from \"./job\";\n"],"mappings":";;;;;;;;AAGA,IAAa,iBACX;;AC0CF,IAAM,QAAQ,IAAIA,oBAA8B,EAAE,kBAAkB,EAAE,CAAC;;AAGvE,SAAgB,aAAa,SAA0F;CACrH,IAAI,QAAQ,YAAY,KAAA,GAAW,OAAO,QAAQ;CAClD,MAAM,QAAQ,QAAQ,MAAM,UAAU,QAAQ,aAAa,UAAU,MAAM,QAAQ,QAAQ,MAAM,UAAU;CAC3G,OAAO,KAAK,IAAI,QAAQ,SAAS,MAAO,GAAG,KAAK,IAAI,MAAO,MAAO,KAAK,KAAK,CAAC;AAC/E;;AAGA,IAAa,QAAQ;;CAEnB,KAAK,SAAoC;EAEvC,IAAI,QAAQ,WAAW,KAAK,CAAC,kBAAkB,MAAM,GAAG;GACtD,iBAAiB;GACjB,QAAQ,KAAK,uJAAuJ;EACtK;EACA,OAAO,MAA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gB,OAAO,KAAA;EAC3B,IAAI;GACF,IAAI,KAAK,OAAO,KAAK,MAAM,GAAG;EAChC,QAAQ,CAER;EACA,MAAM,IAAI,UAAU,IAAI,QAAQ,IAAI,YAAY,OAAO,KAAK,GAAG,MAAM,UAAU,IAAI,CAAC;CACtF;CAGA,MAAM,OAAO,IAAI,WAAW,MAAM,KAAK,MAAM,IAAI,KAAK;CACtD,OAAQ,OAAO,KAAK,MAAM,IAAI,IAAI,KAAA;AACpC"}
@@ -12,6 +12,8 @@ import { ColorSchemePreference } from '../components/theme';
12
12
  */
13
13
  import * as React from "react";
14
14
  export { installLayoutShims, type LayoutBox } from './layout';
15
+ export { installStorageShim, memoryStorage } from './storage';
16
+ export { installFakeSpeech, type FakeSpeech, type Spoken } from './speech';
15
17
  export { filledButtons, expectOneFilledButton, asyncButtonPhase } from './buttons';
16
18
  export { installFakeIntersectionObserver, type FakeIntersectionObserverControls, type FakeObserver, } from './intersection-observer';
17
19
  /** A query client for tests: no retries, and nothing goes stale or is collected mid-test. */
@@ -31,9 +33,7 @@ export type StrataRenderOptions = Omit<RenderOptions, "wrapper"> & {
31
33
  export declare function renderWithStrata(ui: React.ReactElement, { route, client, colorScheme, toasts, ...options }?: StrataRenderOptions): {
32
34
  container: HTMLElement;
33
35
  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;
36
+ 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
37
  rerender: (ui: React.ReactNode) => void;
38
38
  unmount: () => void;
39
39
  asFragment: () => DocumentFragment;
@@ -96,9 +96,7 @@ export type RenderRoutesOptions = StrataRenderOptions & {
96
96
  export declare function renderRoutes(routes: RouteObject[], { route, basename, client, colorScheme, toasts, ...options }?: RenderRoutesOptions): {
97
97
  container: HTMLElement;
98
98
  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;
99
+ 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
100
  rerender: (ui: React.ReactNode) => void;
103
101
  unmount: () => void;
104
102
  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,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;
package/dist/testing.js CHANGED
@@ -1,9 +1,59 @@
1
- import { c as toast, n as createQueryClient, s as StrataToastRegion, t as StrataQueryProvider } from "./query-CgoGqE0T.js";
2
- import { r as ThemeProvider } from "./theme-DB0Km2m2.js";
1
+ import { c as toast, n as createQueryClient, s as StrataToastRegion, t as StrataQueryProvider } from "./query-CfonqUzU.js";
2
+ import { r as ThemeProvider } from "./theme-By3DSUTs.js";
3
3
  import "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";
7
+ // src/testing/storage.ts
8
+ /** An in-memory `Storage`, with the platform's behaviour (values are strings, `key` and `length` work). */
9
+ function memoryStorage() {
10
+ const data = /* @__PURE__ */ new Map();
11
+ return {
12
+ get length() {
13
+ return data.size;
14
+ },
15
+ clear: () => data.clear(),
16
+ getItem: (key) => data.get(String(key)) ?? null,
17
+ key: (index) => [...data.keys()][index] ?? null,
18
+ removeItem: (key) => void data.delete(String(key)),
19
+ setItem: (key, value) => void data.set(String(key), String(value))
20
+ };
21
+ }
22
+ function usable(name) {
23
+ try {
24
+ return typeof globalThis[name]?.getItem === "function";
25
+ } catch {
26
+ return false;
27
+ }
28
+ }
29
+ /**
30
+ * 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`.
31
+ * Does nothing where storage works. Returns a function that puts the originals back. Called by `installLayoutShims`.
32
+ */
33
+ function installStorageShim() {
34
+ const restore = [];
35
+ for (const name of ["localStorage", "sessionStorage"]) {
36
+ if (usable(name)) continue;
37
+ const storage = memoryStorage();
38
+ const targets = [globalThis, typeof window !== "undefined" ? window : void 0].filter((t) => t !== void 0);
39
+ for (const target of new Set(targets)) {
40
+ const before = Object.getOwnPropertyDescriptor(target, name);
41
+ Object.defineProperty(target, name, {
42
+ configurable: true,
43
+ value: storage
44
+ });
45
+ restore.push(() => {
46
+ if (before) Object.defineProperty(target, name, before);
47
+ else delete target[name];
48
+ });
49
+ }
50
+ const after = globalThis.afterEach;
51
+ if (typeof after === "function") after(() => storage.clear());
52
+ }
53
+ return () => {
54
+ for (const undo of restore.reverse()) undo();
55
+ };
56
+ }
7
57
  // src/testing/layout.ts
8
58
  /** A DOMRect-shaped object, for stand-ins that report geometry. */
9
59
  function box(x, y, width, height) {
@@ -23,7 +73,7 @@ function box(x, y, width, height) {
23
73
  }
24
74
  /**
25
75
  * Give jsdom a fixed box for every element (`getBoundingClientRect`, `offset*`, `client*`) and a
26
- * ResizeObserver that reports it on observe, so measuring components render. Defaults to 640×280.
76
+ * 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.
27
77
  * Call once in a Vitest setup file; returns a function that puts the originals back.
28
78
  */
29
79
  function installLayoutShims({ width = 640, height = 280 } = {}) {
@@ -70,10 +120,101 @@ function installLayoutShims({ width = 640, height = 280 } = {}) {
70
120
  ["clientWidth", width],
71
121
  ["clientHeight", height]
72
122
  ]) replace(HTMLElement.prototype, prop, { get: () => value });
123
+ restore.push(installStorageShim());
73
124
  return () => {
74
125
  for (const undo of restore.reverse()) undo();
75
126
  };
76
127
  }
128
+ // src/testing/speech.ts
129
+ /**
130
+ * Installs a recording `speechSynthesis` and `SpeechSynthesisUtterance` on `window` and returns what was said.
131
+ * `uninstall()` after each test. `const speech = installFakeSpeech(); … expect(speech.texts()).toEqual(["Which one is the cat?"])`.
132
+ */
133
+ function installFakeSpeech(voices = []) {
134
+ const hadSynth = Object.getOwnPropertyDescriptor(window, "speechSynthesis");
135
+ const hadUtterance = Object.getOwnPropertyDescriptor(globalThis, "SpeechSynthesisUtterance");
136
+ let current;
137
+ let installed = voices.map((v) => ({
138
+ ...v,
139
+ default: false,
140
+ localService: true,
141
+ voiceURI: v.name
142
+ }));
143
+ const listeners = /* @__PURE__ */ new Set();
144
+ const said = [];
145
+ class FakeUtterance {
146
+ text;
147
+ lang = "";
148
+ rate = 1;
149
+ voice = null;
150
+ onend = null;
151
+ onerror = null;
152
+ constructor(text) {
153
+ this.text = text;
154
+ }
155
+ }
156
+ Object.defineProperty(window, "speechSynthesis", {
157
+ configurable: true,
158
+ value: {
159
+ get speaking() {
160
+ return current !== void 0;
161
+ },
162
+ speak(utterance) {
163
+ const entry = {
164
+ text: utterance.text,
165
+ lang: utterance.lang,
166
+ rate: utterance.rate,
167
+ voice: utterance.voice?.name ?? null,
168
+ cancelled: false
169
+ };
170
+ said.push(entry);
171
+ current = {
172
+ entry,
173
+ utterance
174
+ };
175
+ },
176
+ cancel() {
177
+ if (!current) return;
178
+ const { entry, utterance } = current;
179
+ current = void 0;
180
+ entry.cancelled = true;
181
+ utterance.onerror?.();
182
+ },
183
+ getVoices: () => installed,
184
+ addEventListener: (_, l) => void listeners.add(l),
185
+ removeEventListener: (_, l) => void listeners.delete(l)
186
+ }
187
+ });
188
+ Object.defineProperty(globalThis, "SpeechSynthesisUtterance", {
189
+ configurable: true,
190
+ writable: true,
191
+ value: FakeUtterance
192
+ });
193
+ return {
194
+ said,
195
+ texts: () => said.filter((s) => !s.cancelled).map((s) => s.text),
196
+ finish() {
197
+ const done = current;
198
+ current = void 0;
199
+ done?.utterance.onend?.();
200
+ },
201
+ setVoices(next) {
202
+ installed = next.map((v) => ({
203
+ ...v,
204
+ default: false,
205
+ localService: true,
206
+ voiceURI: v.name
207
+ }));
208
+ for (const l of listeners) l(new Event("voiceschanged"));
209
+ },
210
+ uninstall() {
211
+ if (hadSynth) Object.defineProperty(window, "speechSynthesis", hadSynth);
212
+ else delete window.speechSynthesis;
213
+ if (hadUtterance) Object.defineProperty(globalThis, "SpeechSynthesisUtterance", hadUtterance);
214
+ else delete globalThis.SpeechSynthesisUtterance;
215
+ }
216
+ };
217
+ }
77
218
  // src/testing/buttons.ts
78
219
  /** Whether an element is out of the view: hidden, inert or aria-hidden, itself or by an ancestor. */
79
220
  function outOfView(el) {
@@ -255,6 +396,6 @@ function renderRoutes(routes, { route, basename, client = createTestQueryClient(
255
396
  ...result
256
397
  };
257
398
  }
258
- export { asyncButtonPhase, createTestQueryClient, expectOneFilledButton, filledButtons, installFakeIntersectionObserver, installLayoutShims, renderRoutes, renderWithStrata };
399
+ export { asyncButtonPhase, createTestQueryClient, expectOneFilledButton, filledButtons, installFakeIntersectionObserver, installFakeSpeech, installLayoutShims, installStorageShim, memoryStorage, renderRoutes, renderWithStrata };
259
400
 
260
401
  //# sourceMappingURL=testing.js.map