strata-react 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,345 @@
1
+ import { clsx } from "clsx";
2
+ import { extendTailwindMerge } from "tailwind-merge";
3
+ import * as React from "react";
4
+ import { jsx, jsxs } from "react/jsx-runtime";
5
+ import { CircleAlert } from "lucide-react";
6
+ import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";
7
+ // src/lib/utils.ts
8
+ var typeSteps = [
9
+ "caption",
10
+ "label",
11
+ "body-sm",
12
+ "body",
13
+ "heading",
14
+ "title",
15
+ "figure",
16
+ "display"
17
+ ];
18
+ var twMerge = extendTailwindMerge({ extend: { classGroups: { "font-size": [{ type: [...typeSteps] }] } } });
19
+ /** clsx + tailwind-merge, taught that `type-*` utilities are font sizes. */
20
+ function cn(...inputs) {
21
+ return twMerge(clsx(inputs));
22
+ }
23
+ // src/lib/errors.ts
24
+ /** Thrown by `fetchJson` on a non-2xx response; carries the status for `describeHttpError` and `describeActionError`. */
25
+ var HttpError = class extends Error {
26
+ status;
27
+ statusText;
28
+ url;
29
+ constructor(status, statusText, url) {
30
+ super(`${status} ${statusText} from ${url}`);
31
+ this.status = status;
32
+ this.statusText = statusText;
33
+ this.url = url;
34
+ this.name = "HttpError";
35
+ }
36
+ };
37
+ function refused(error) {
38
+ return `The request was refused (${error.status}): ${error.statusText || "no reason given"}.`;
39
+ }
40
+ /** The default `DescribeError` for loads: the HTTP status in a sentence, else the error's message, else a plain fallback. */
41
+ var describeHttpError = (error) => error instanceof HttpError ? error.status >= 500 ? `The server could not answer (${error.status}). Nothing was changed.` : refused(error) : error instanceof Error && error.message ? error.message : "The data could not be loaded. Nothing was changed.";
42
+ /** The default for `useAsyncAction`: the HTTP status in a sentence, else the thrown Error's message, else undefined (the retry label alone). */
43
+ var describeActionError = (error) => error instanceof HttpError ? error.status >= 500 ? `The server could not answer (${error.status}).` : refused(error) : error instanceof Error && error.message ? error.message : void 0;
44
+ // src/components/field.tsx
45
+ var FieldContext = React.createContext(null);
46
+ function useField(id) {
47
+ const field = React.useContext(FieldContext);
48
+ return {
49
+ id: field?.id ?? id,
50
+ "aria-describedby": field?.describedBy,
51
+ "aria-invalid": field?.invalid || void 0
52
+ };
53
+ }
54
+ /** A labelled form field: wires the label, hint, error, `aria-describedby` and `aria-invalid` into the one control it wraps. */
55
+ function Field({ label, id: idProp, hint, error, children, className }) {
56
+ const generated = React.useId();
57
+ const id = idProp ?? generated;
58
+ const hintId = hint ? `${id}-hint` : void 0;
59
+ const errorId = error ? `${id}-error` : void 0;
60
+ const describedBy = [errorId, hintId].filter(Boolean).join(" ") || void 0;
61
+ return /* @__PURE__ */ jsx(FieldContext.Provider, {
62
+ value: {
63
+ id,
64
+ describedBy,
65
+ invalid: Boolean(error)
66
+ },
67
+ children: /* @__PURE__ */ jsxs("div", {
68
+ className: cn("grid min-w-0 content-start gap-1.5", className),
69
+ children: [
70
+ /* @__PURE__ */ jsx("label", {
71
+ htmlFor: id,
72
+ className: "type-label text-foreground",
73
+ children: label
74
+ }),
75
+ children,
76
+ error && /* @__PURE__ */ jsxs("p", {
77
+ id: errorId,
78
+ className: "flex items-start gap-1.5 type-body-sm text-danger",
79
+ children: [/* @__PURE__ */ jsx(CircleAlert, {
80
+ "aria-hidden": true,
81
+ className: "mt-0.5 size-4 shrink-0"
82
+ }), error]
83
+ }),
84
+ hint && /* @__PURE__ */ jsx("p", {
85
+ id: hintId,
86
+ className: "type-body-sm text-muted-foreground",
87
+ children: hint
88
+ })
89
+ ]
90
+ })
91
+ });
92
+ }
93
+ var control = "w-full min-w-0 rounded-control border border-input bg-background px-3 type-body text-foreground transition-state placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:bg-muted disabled:opacity-70 aria-invalid:border-danger";
94
+ /** A text input that picks up its id and descriptions from the surrounding `Field`. */
95
+ function Input({ className, id, ...props }) {
96
+ return /* @__PURE__ */ jsx("input", {
97
+ ...useField(id),
98
+ className: cn(control, "h-(--control-h)", className),
99
+ ...props
100
+ });
101
+ }
102
+ /** A multi-line input that picks up its id and descriptions from the surrounding `Field`. */
103
+ function Textarea({ className, id, ...props }) {
104
+ return /* @__PURE__ */ jsx("textarea", {
105
+ ...useField(id),
106
+ className: cn(control, "min-h-24 py-2", className),
107
+ ...props
108
+ });
109
+ }
110
+ /** The platform select, styled. The default for short lists, especially on touch screens. */
111
+ function NativeSelect({ className, id, ...props }) {
112
+ return /* @__PURE__ */ jsx("select", {
113
+ ...useField(id),
114
+ className: cn(control, "h-(--control-h) pr-8", className),
115
+ ...props
116
+ });
117
+ }
118
+ /** Radio choices in a fieldset with a legend; each whole row is the hit target. For 2 to 5 options that each need a sentence. */
119
+ function ChoiceGroup({ legend, name, choices, value, onChange, error }) {
120
+ const errorId = React.useId();
121
+ return /* @__PURE__ */ jsxs("fieldset", {
122
+ className: "grid gap-2",
123
+ "aria-describedby": error ? errorId : void 0,
124
+ children: [
125
+ /* @__PURE__ */ jsx("legend", {
126
+ className: "mb-1.5 type-label text-foreground",
127
+ children: legend
128
+ }),
129
+ choices.map((c) => /* @__PURE__ */ jsxs("label", {
130
+ className: "flex min-h-(--control-h-sm) cursor-pointer items-start gap-3 py-1",
131
+ children: [/* @__PURE__ */ jsx("input", {
132
+ type: "radio",
133
+ name,
134
+ value: c.value,
135
+ checked: value === c.value,
136
+ onChange: () => onChange(c.value),
137
+ className: "mt-1 size-4 shrink-0 accent-primary"
138
+ }), /* @__PURE__ */ jsxs("span", {
139
+ className: "grid",
140
+ children: [/* @__PURE__ */ jsx("span", {
141
+ className: "type-body",
142
+ children: c.label
143
+ }), c.detail && /* @__PURE__ */ jsx("span", {
144
+ className: "type-body-sm text-muted-foreground",
145
+ children: c.detail
146
+ })]
147
+ })]
148
+ }, c.value)),
149
+ error && /* @__PURE__ */ jsxs("p", {
150
+ id: errorId,
151
+ className: "flex items-start gap-1.5 type-body-sm text-danger",
152
+ children: [/* @__PURE__ */ jsx(CircleAlert, {
153
+ "aria-hidden": true,
154
+ className: "mt-0.5 size-4 shrink-0"
155
+ }), error]
156
+ })
157
+ ]
158
+ });
159
+ }
160
+ // src/components/theme.tsx
161
+ /** The localStorage key `ThemeProvider` uses unless given another. */
162
+ var COLOR_SCHEME_STORAGE_KEY = "strata-color-scheme";
163
+ var QUERY = "(prefers-color-scheme: dark)";
164
+ var PREFERENCES = [
165
+ "system",
166
+ "light",
167
+ "dark"
168
+ ];
169
+ function isPreference(value) {
170
+ return typeof value === "string" && PREFERENCES.includes(value);
171
+ }
172
+ function readStored(key) {
173
+ if (key === null) return null;
174
+ try {
175
+ const value = window.localStorage.getItem(key);
176
+ return isPreference(value) ? value : null;
177
+ } catch {
178
+ return null;
179
+ }
180
+ }
181
+ function writeStored(key, value) {
182
+ if (key === null) return;
183
+ try {
184
+ window.localStorage.setItem(key, value);
185
+ } catch {}
186
+ }
187
+ function media() {
188
+ return typeof window !== "undefined" && typeof window.matchMedia === "function" ? window.matchMedia(QUERY) : null;
189
+ }
190
+ function subscribeSystem(onChange) {
191
+ const list = media();
192
+ if (!list) return () => void 0;
193
+ list.addEventListener("change", onChange);
194
+ return () => list.removeEventListener("change", onChange);
195
+ }
196
+ var systemSnapshot = () => media()?.matches ? "dark" : "light";
197
+ var serverSnapshot = () => "light";
198
+ /** The operating system's colour scheme, kept current as it changes. Light where it cannot be read (the server, jsdom). */
199
+ function useSystemColorScheme() {
200
+ return React.useSyncExternalStore(subscribeSystem, systemSnapshot, serverSnapshot);
201
+ }
202
+ var Context = React.createContext(null);
203
+ /** Sets the `.dark` class strata.css keys on, from a system, light or dark preference that persists in localStorage when it can. */
204
+ function ThemeProvider({ children, defaultPreference = "system", storageKey = COLOR_SCHEME_STORAGE_KEY, target }) {
205
+ const [preference, setState] = React.useState(defaultPreference);
206
+ React.useLayoutEffect(() => {
207
+ const stored = readStored(storageKey);
208
+ if (stored) setState(stored);
209
+ }, [storageKey]);
210
+ const system = useSystemColorScheme();
211
+ const scheme = preference === "system" ? system : preference;
212
+ const setPreference = React.useCallback((next) => {
213
+ setState(next);
214
+ writeStored(storageKey, next);
215
+ }, [storageKey]);
216
+ React.useEffect(() => {
217
+ if (storageKey === null) return;
218
+ const onStorage = (event) => {
219
+ if (event.key !== storageKey && event.key !== null) return;
220
+ const value = event.key === null ? null : event.newValue;
221
+ setState(isPreference(value) ? value : defaultPreference);
222
+ };
223
+ window.addEventListener("storage", onStorage);
224
+ return () => window.removeEventListener("storage", onStorage);
225
+ }, [storageKey, defaultPreference]);
226
+ React.useLayoutEffect(() => {
227
+ const element = target === void 0 ? document.documentElement : target;
228
+ if (!element) return;
229
+ element.classList.toggle("dark", scheme === "dark");
230
+ return () => element.classList.remove("dark");
231
+ }, [scheme, target]);
232
+ const value = React.useMemo(() => ({
233
+ preference,
234
+ scheme,
235
+ setPreference
236
+ }), [
237
+ preference,
238
+ scheme,
239
+ setPreference
240
+ ]);
241
+ return /* @__PURE__ */ jsx(Context.Provider, {
242
+ value,
243
+ children
244
+ });
245
+ }
246
+ /** The person's colour-scheme preference, the scheme in effect, and a setter that persists it. Must be inside `ThemeProvider`. */
247
+ function useColorScheme() {
248
+ const value = React.useContext(Context);
249
+ if (!value) throw new Error("useColorScheme must be used inside a ThemeProvider.");
250
+ return value;
251
+ }
252
+ /**
253
+ * The body of an inline `<script>` for the page's `<head>` that sets `.dark` before the first
254
+ * paint, from the stored choice or the operating system, so a dark page does not flash light while
255
+ * the bundle loads. Pass the same key and default as the `ThemeProvider`.
256
+ */
257
+ function colorSchemeScript(storageKey = COLOR_SCHEME_STORAGE_KEY, defaultPreference = "system") {
258
+ const key = JSON.stringify(storageKey);
259
+ return `(function(){var p=${JSON.stringify(defaultPreference)};try{var s=localStorage.getItem(${key});if(s==="system"||s==="light"||s==="dark")p=s}catch(e){}var d=p==="dark"||(p==="system"&&window.matchMedia&&matchMedia(${JSON.stringify(QUERY)}).matches);document.documentElement.classList.toggle("dark",!!d)})()`;
260
+ }
261
+ var defaultLabels = {
262
+ system: {
263
+ label: "Match this device",
264
+ detail: "Light or dark as your system setting changes"
265
+ },
266
+ light: { label: "Light" },
267
+ dark: { label: "Dark" }
268
+ };
269
+ /** The three colour-scheme preferences as radio buttons, bound to the nearest `ThemeProvider`. For a settings page. */
270
+ function ColorSchemeChoice({ legend = "Theme", labels = defaultLabels }) {
271
+ const { preference, setPreference } = useColorScheme();
272
+ const name = React.useId();
273
+ const words = {
274
+ ...defaultLabels,
275
+ ...labels
276
+ };
277
+ return /* @__PURE__ */ jsx(ChoiceGroup, {
278
+ legend,
279
+ name,
280
+ value: preference,
281
+ onChange: (value) => {
282
+ if (isPreference(value)) setPreference(value);
283
+ },
284
+ choices: PREFERENCES.map((value) => ({
285
+ value,
286
+ ...words[value]
287
+ }))
288
+ });
289
+ }
290
+ // src/query/index.tsx
291
+ /** A QueryClient with Strata's defaults: one retry, 30 s stale time, no refetch on window focus. */
292
+ function createQueryClient(overrides) {
293
+ return new QueryClient({
294
+ ...overrides,
295
+ defaultOptions: {
296
+ ...overrides?.defaultOptions,
297
+ queries: {
298
+ retry: 1,
299
+ staleTime: 3e4,
300
+ refetchOnWindowFocus: false,
301
+ ...overrides?.defaultOptions?.queries
302
+ }
303
+ }
304
+ });
305
+ }
306
+ /** Provides a query client (Strata's defaults unless one is passed) to the app. */
307
+ function StrataQueryProvider({ client, children }) {
308
+ const [fallback] = React.useState(() => client ?? createQueryClient());
309
+ return /* @__PURE__ */ jsx(QueryClientProvider, {
310
+ client: client ?? fallback,
311
+ children
312
+ });
313
+ }
314
+ /** Turns a TanStack query result into the `Load<T>` that `DataView` takes; errors are described for a person by `describe`. */
315
+ function toLoad(query, describe = describeHttpError) {
316
+ if (query.status === "success") return {
317
+ status: "ready",
318
+ data: query.data
319
+ };
320
+ if (query.status === "error") return {
321
+ status: "error",
322
+ message: describe(query.error),
323
+ retry: () => void query.refetch()
324
+ };
325
+ return { status: "loading" };
326
+ }
327
+ /** `useQuery`, returned as a `Load<T>` for `DataView`. */
328
+ function useLoad(options) {
329
+ const { describeError, ...rest } = options;
330
+ return toLoad(useQuery(rest), describeError);
331
+ }
332
+ /** fetch() that throws an HttpError on a non-2xx response and parses JSON: the queryFn default. */
333
+ async function fetchJson(input, init) {
334
+ const headers = new Headers(init?.headers);
335
+ if (!headers.has("Accept")) headers.set("Accept", "application/json");
336
+ const res = await fetch(input, {
337
+ ...init,
338
+ headers
339
+ });
340
+ if (!res.ok) throw new HttpError(res.status, res.statusText, String(input));
341
+ return await res.json();
342
+ }
343
+ export { HttpError as _, useLoad as a, cn as b, ThemeProvider as c, useSystemColorScheme as d, ChoiceGroup as f, Textarea as g, NativeSelect as h, toLoad as i, colorSchemeScript as l, Input as m, createQueryClient as n, COLOR_SCHEME_STORAGE_KEY as o, Field as p, fetchJson as r, ColorSchemeChoice as s, StrataQueryProvider as t, useColorScheme as u, describeActionError as v, typeSteps as x, describeHttpError as y };
344
+
345
+ //# sourceMappingURL=query-CmdlXVW_.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-CmdlXVW_.js","names":[],"sources":["../src/lib/utils.ts","../src/lib/errors.ts","../src/components/field.tsx","../src/components/theme.tsx","../src/query/index.tsx"],"sourcesContent":["import { clsx, type ClassValue } from \"clsx\";\nimport { extendTailwindMerge } from \"tailwind-merge\";\n\n// Teach tailwind-merge that `type-*` utilities are font sizes. Without this, cn() cannot tell\n// `type-label` from a colour and may drop one of two classes that both survive in CSS; with stock\n// shadcn the same bug drops `text-muted-foreground` next to a custom `text-*` size.\nexport const typeSteps = [\"caption\", \"label\", \"body-sm\", \"body\", \"heading\", \"title\", \"figure\", \"display\"] as const;\n\nconst twMerge = extendTailwindMerge({\n extend: {\n classGroups: {\n \"font-size\": [{ type: [...typeSteps] }],\n },\n },\n});\n\n/** clsx + tailwind-merge, taught that `type-*` utilities are font sizes. */\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n","// Errors, described for a person. Anything that fails in front of someone (a load in DataView, an\n// action in AsyncButton) says what happened in a sentence, in the product's words, not the\n// developer's: `HttpError`'s own message (\"409 Conflict from /api/bookings\") is for logs. Loads\n// and actions share HttpError's status sentences, so the same failure reads the same everywhere,\n// and differ only in what is true afterwards: a failed load changed nothing, while a failed action\n// may have reached the server, so its sentence does not promise that.\n\n/** Thrown by `fetchJson` on a non-2xx response; carries the status for `describeHttpError` and `describeActionError`. */\nexport class HttpError extends Error {\n constructor(\n readonly status: number,\n readonly statusText: string,\n readonly url: string,\n ) {\n super(`${status} ${statusText} from ${url}`);\n this.name = \"HttpError\";\n }\n}\n\n/** Writes an error for a person: what happened, in a sentence. A product passes its own words. */\nexport type DescribeError = (error: unknown) => string;\n\nfunction refused(error: HttpError) {\n return `The request was refused (${error.status}): ${error.statusText || \"no reason given\"}.`;\n}\n\n/** The default `DescribeError` for loads: the HTTP status in a sentence, else the error's message, else a plain fallback. */\nexport const describeHttpError: DescribeError = (error) =>\n error instanceof HttpError\n ? error.status >= 500\n ? `The server could not answer (${error.status}). Nothing was changed.`\n : refused(error)\n : error instanceof Error && error.message\n ? error.message\n : \"The data could not be loaded. Nothing was changed.\";\n\n/** The default for `useAsyncAction`: the HTTP status in a sentence, else the thrown Error's message, else undefined (the retry label alone). */\nexport const describeActionError = (error: unknown): string | undefined =>\n error instanceof HttpError\n ? error.status >= 500\n ? `The server could not answer (${error.status}).`\n : refused(error)\n : error instanceof Error && error.message\n ? error.message\n : undefined;\n","import * as React from \"react\";\nimport { CircleAlert } from \"lucide-react\";\nimport { cn } from \"../lib/utils\";\n\n// Field owns the wiring a generated form usually forgets: the label's htmlFor, aria-describedby\n// pointing at the hint and the error, and aria-invalid. Controls read it from context, so a control\n// inside a Field cannot end up unlabelled or silently invalid.\n\ntype FieldState = { id: string; describedBy?: string; invalid: boolean };\nconst FieldContext = React.createContext<FieldState | null>(null);\n\nfunction useField(id?: string) {\n const field = React.useContext(FieldContext);\n return {\n // Inside a Field the Field's id wins, so the label always points at the control. To choose the\n // id yourself, pass it to Field.\n id: field?.id ?? id,\n \"aria-describedby\": field?.describedBy,\n \"aria-invalid\": field?.invalid || undefined,\n };\n}\n\nexport type FieldProps = {\n label: string;\n /** The control's id, when the page needs a known one (an anchor, a test). Generated otherwise. */\n id?: string;\n /** What the person needs to know before typing, such as limits or units. */\n hint?: React.ReactNode;\n /** What went wrong and how to fix it, in one sentence. Shown under the control, never in a toast. */\n error?: string;\n children: React.ReactNode;\n className?: string;\n};\n\n/** A labelled form field: wires the label, hint, error, `aria-describedby` and `aria-invalid` into the one control it wraps. */\nexport function Field({ label, id: idProp, hint, error, children, className }: FieldProps) {\n const generated = React.useId();\n const id = idProp ?? generated;\n const hintId = hint ? `${id}-hint` : undefined;\n const errorId = error ? `${id}-error` : undefined;\n const describedBy = [errorId, hintId].filter(Boolean).join(\" \") || undefined;\n\n return (\n <FieldContext.Provider value={{ id, describedBy, invalid: Boolean(error) }}>\n <div className={cn(\"grid min-w-0 content-start gap-1.5\", className)}>\n <label htmlFor={id} className=\"type-label text-foreground\">\n {label}\n </label>\n {children}\n {error && (\n <p id={errorId} className=\"flex items-start gap-1.5 type-body-sm text-danger\">\n <CircleAlert aria-hidden className=\"mt-0.5 size-4 shrink-0\" />\n {error}\n </p>\n )}\n {hint && (\n <p id={hintId} className=\"type-body-sm text-muted-foreground\">\n {hint}\n </p>\n )}\n </div>\n </FieldContext.Provider>\n );\n}\n\nconst control =\n \"w-full min-w-0 rounded-control border border-input bg-background px-3 type-body text-foreground transition-state placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:bg-muted disabled:opacity-70 aria-invalid:border-danger\";\n\n/** A text input that picks up its id and descriptions from the surrounding `Field`. */\nexport function Input({ className, id, ...props }: React.ComponentProps<\"input\">) {\n return <input {...useField(id)} className={cn(control, \"h-(--control-h)\", className)} {...props} />;\n}\n\n/** A multi-line input that picks up its id and descriptions from the surrounding `Field`. */\nexport function Textarea({ className, id, ...props }: React.ComponentProps<\"textarea\">) {\n return <textarea {...useField(id)} className={cn(control, \"min-h-24 py-2\", className)} {...props} />;\n}\n\n// A native select, styled. For short option lists on a touch screen it beats a custom listbox:\n// the platform picker, typeahead and form autofill all work with no code.\n/** The platform select, styled. The default for short lists, especially on touch screens. */\nexport function NativeSelect({ className, id, ...props }: React.ComponentProps<\"select\">) {\n return <select {...useField(id)} className={cn(control, \"h-(--control-h) pr-8\", className)} {...props} />;\n}\n\n// Radio choices: a fieldset with a legend, and each label wrapping its control so the whole row is\n// one hit target. accent-color carries the theme into the native control.\nexport type Choice = { value: string; label: string; detail?: string };\n\n/** Radio choices in a fieldset with a legend; each whole row is the hit target. For 2 to 5 options that each need a sentence. */\nexport function ChoiceGroup({\n legend,\n name,\n choices,\n value,\n onChange,\n error,\n}: {\n legend: string;\n name: string;\n choices: Choice[];\n value: string;\n onChange: (value: string) => void;\n error?: string;\n}) {\n const errorId = React.useId();\n return (\n <fieldset className=\"grid gap-2\" aria-describedby={error ? errorId : undefined}>\n <legend className=\"mb-1.5 type-label text-foreground\">{legend}</legend>\n {choices.map((c) => (\n <label key={c.value} className=\"flex min-h-(--control-h-sm) cursor-pointer items-start gap-3 py-1\">\n <input\n type=\"radio\"\n name={name}\n value={c.value}\n checked={value === c.value}\n onChange={() => onChange(c.value)}\n className=\"mt-1 size-4 shrink-0 accent-primary\"\n />\n <span className=\"grid\">\n <span className=\"type-body\">{c.label}</span>\n {c.detail && <span className=\"type-body-sm text-muted-foreground\">{c.detail}</span>}\n </span>\n </label>\n ))}\n {error && (\n <p id={errorId} className=\"flex items-start gap-1.5 type-body-sm text-danger\">\n <CircleAlert aria-hidden className=\"mt-0.5 size-4 shrink-0\" />\n {error}\n </p>\n )}\n </fieldset>\n );\n}\n","import * as React from \"react\";\nimport { ChoiceGroup } from \"./field\";\n\n// strata.css keys dark mode on a `.dark` ancestor (`@custom-variant dark (&:is(.dark *))`) and\n// gives `.dark` its `color-scheme`, but nothing in the library set the class, so every app wrote\n// the same matchMedia listener by hand (strata-listory did, in web/src/main.tsx). This is that\n// listener, once:\n// - Three choices, not two. \"system\" follows the operating system and keeps following it when it\n// changes at dusk; \"light\" and \"dark\" are a person's override. A toggle with only light and dark\n// loses the system setting the first time it is pressed.\n// - The choice persists in localStorage, read and written inside try/catch. Storage throws in\n// private windows, with blocked site data and in sandboxed frames; the theme then simply does\n// not persist, and the page still renders. A stored value that is not one of the three is\n// ignored.\n// - Another tab changing the choice changes this one too (the `storage` event).\n// - The first render uses the default preference, as a server render would, and the stored choice\n// is applied in a layout effect, so server-rendered markup hydrates cleanly and nothing paints\n// with the wrong scheme (found in review).\n// - The class is set in a layout effect, before paint. A page that must not flash light on first\n// load before React runs puts `colorSchemeScript()` in an inline script in its `<head>`.\n// - `ColorSchemeChoice` is the picker for a settings page: a `ChoiceGroup` of the three, with\n// \"Match this device\" first because it is the default and the one most people should keep. A\n// product that wants the choice elsewhere (a menu item, a header button) builds it from\n// `useColorScheme`. Changing theme is rare, so the picker has no motion and no icon flourish.\n// - Storybook's decorator and `renderWithStrata({ colorScheme })` run through this provider, so\n// stories and tests see the same class, in the same place, as an app.\n\n/** What a person chose: follow the operating system, or a fixed light or dark theme. */\nexport type ColorSchemePreference = \"system\" | \"light\" | \"dark\";\n/** The scheme in effect after \"system\" is resolved. */\nexport type ColorScheme = \"light\" | \"dark\";\n\n/** The localStorage key `ThemeProvider` uses unless given another. */\nexport const COLOR_SCHEME_STORAGE_KEY = \"strata-color-scheme\";\n\nconst QUERY = \"(prefers-color-scheme: dark)\";\nconst PREFERENCES: readonly ColorSchemePreference[] = [\"system\", \"light\", \"dark\"];\n\nfunction isPreference(value: unknown): value is ColorSchemePreference {\n return typeof value === \"string\" && (PREFERENCES as readonly string[]).includes(value);\n}\n\nfunction readStored(key: string | null): ColorSchemePreference | null {\n if (key === null) return null;\n try {\n const value = window.localStorage.getItem(key);\n return isPreference(value) ? value : null;\n } catch {\n return null;\n }\n}\n\nfunction writeStored(key: string | null, value: ColorSchemePreference) {\n if (key === null) return;\n try {\n window.localStorage.setItem(key, value);\n } catch {\n // Storage unavailable (private window, blocked site data): the choice lasts this visit only.\n }\n}\n\nfunction media(): MediaQueryList | null {\n return typeof window !== \"undefined\" && typeof window.matchMedia === \"function\" ? window.matchMedia(QUERY) : null;\n}\n\nfunction subscribeSystem(onChange: () => void) {\n const list = media();\n if (!list) return () => undefined;\n list.addEventListener(\"change\", onChange);\n return () => list.removeEventListener(\"change\", onChange);\n}\n\nconst systemSnapshot = (): ColorScheme => (media()?.matches ? \"dark\" : \"light\");\nconst serverSnapshot = (): ColorScheme => \"light\";\n\n/** The operating system's colour scheme, kept current as it changes. Light where it cannot be read (the server, jsdom). */\nexport function useSystemColorScheme(): ColorScheme {\n return React.useSyncExternalStore(subscribeSystem, systemSnapshot, serverSnapshot);\n}\n\n/** What `useColorScheme` returns: the chosen preference, the scheme in effect, and a setter that persists the choice. */\nexport type ColorSchemeState = {\n preference: ColorSchemePreference;\n scheme: ColorScheme;\n setPreference: (preference: ColorSchemePreference) => void;\n};\n\nconst Context = React.createContext<ColorSchemeState | null>(null);\n\n/** Sets the `.dark` class strata.css keys on, from a system, light or dark preference that persists in localStorage when it can. */\nexport function ThemeProvider({\n children,\n defaultPreference = \"system\",\n storageKey = COLOR_SCHEME_STORAGE_KEY,\n target,\n}: {\n children: React.ReactNode;\n /** The preference before a person has chosen one. */\n defaultPreference?: ColorSchemePreference;\n /** Where the choice is kept in localStorage; `null` keeps it for this visit only. */\n storageKey?: string | null;\n /**\n * The element that gets the `.dark` class; the document's root element when left out. A nested\n * target can turn a light page's panel dark, not the reverse: strata.css keys dark on any\n * `.dark` ancestor. Pass the element itself (keep it in state with a callback ref, since a\n * wrapping element's ref is not attached yet when this provider's effect first runs); `null`\n * means it has not mounted yet, and nothing is set until it has.\n */\n target?: HTMLElement | null;\n}) {\n // The first render uses the default, as the server does, so a server-rendered tree hydrates\n // without a mismatch; the stored choice is read in a layout effect, which re-renders before the\n // browser paints, so a client-only app still never shows the default first.\n const [preference, setState] = React.useState<ColorSchemePreference>(defaultPreference);\n React.useLayoutEffect(() => {\n const stored = readStored(storageKey);\n if (stored) setState(stored);\n }, [storageKey]);\n const system = useSystemColorScheme();\n const scheme: ColorScheme = preference === \"system\" ? system : preference;\n\n const setPreference = React.useCallback(\n (next: ColorSchemePreference) => {\n setState(next);\n writeStored(storageKey, next);\n },\n [storageKey],\n );\n\n // Another tab changed the choice. A cleared key (`newValue` null) falls back to the default.\n React.useEffect(() => {\n if (storageKey === null) return;\n const onStorage = (event: StorageEvent) => {\n if (event.key !== storageKey && event.key !== null) return;\n const value = event.key === null ? null : event.newValue;\n setState(isPreference(value) ? value : defaultPreference);\n };\n window.addEventListener(\"storage\", onStorage);\n return () => window.removeEventListener(\"storage\", onStorage);\n }, [storageKey, defaultPreference]);\n\n React.useLayoutEffect(() => {\n const element = target === undefined ? document.documentElement : target;\n if (!element) return;\n element.classList.toggle(\"dark\", scheme === \"dark\");\n return () => element.classList.remove(\"dark\");\n }, [scheme, target]);\n\n const value = React.useMemo(() => ({ preference, scheme, setPreference }), [preference, scheme, setPreference]);\n return <Context.Provider value={value}>{children}</Context.Provider>;\n}\n\n/** The person's colour-scheme preference, the scheme in effect, and a setter that persists it. Must be inside `ThemeProvider`. */\nexport function useColorScheme(): ColorSchemeState {\n const value = React.useContext(Context);\n if (!value) throw new Error(\"useColorScheme must be used inside a ThemeProvider.\");\n return value;\n}\n\n/**\n * The body of an inline `<script>` for the page's `<head>` that sets `.dark` before the first\n * paint, from the stored choice or the operating system, so a dark page does not flash light while\n * the bundle loads. Pass the same key and default as the `ThemeProvider`.\n */\nexport function colorSchemeScript(\n storageKey: string = COLOR_SCHEME_STORAGE_KEY,\n defaultPreference: ColorSchemePreference = \"system\",\n): string {\n const key = JSON.stringify(storageKey);\n const fallback = JSON.stringify(defaultPreference);\n return (\n `(function(){var p=${fallback};try{var s=localStorage.getItem(${key});` +\n `if(s===\"system\"||s===\"light\"||s===\"dark\")p=s}catch(e){}` +\n `var d=p===\"dark\"||(p===\"system\"&&window.matchMedia&&matchMedia(${JSON.stringify(QUERY)}).matches);` +\n `document.documentElement.classList.toggle(\"dark\",!!d)})()`\n );\n}\n\n/** The words `ColorSchemeChoice` shows for each preference. */\nexport type ColorSchemeLabels = Record<ColorSchemePreference, { label: string; detail?: string }>;\n\nconst defaultLabels: ColorSchemeLabels = {\n system: { label: \"Match this device\", detail: \"Light or dark as your system setting changes\" },\n light: { label: \"Light\" },\n dark: { label: \"Dark\" },\n};\n\n/** The three colour-scheme preferences as radio buttons, bound to the nearest `ThemeProvider`. For a settings page. */\nexport function ColorSchemeChoice({\n legend = \"Theme\",\n labels = defaultLabels,\n}: {\n /** The group's name, as the settings page words it. */\n legend?: string;\n /** Overrides the words for each choice, in the product's voice. */\n labels?: Partial<ColorSchemeLabels>;\n}) {\n const { preference, setPreference } = useColorScheme();\n const name = React.useId();\n const words = { ...defaultLabels, ...labels };\n return (\n <ChoiceGroup\n legend={legend}\n name={name}\n value={preference}\n onChange={(value) => {\n if (isPreference(value)) setPreference(value);\n }}\n choices={PREFERENCES.map((value) => ({ value, ...words[value] }))}\n />\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 } from \"../components/data-view\";\nimport { HttpError, describeHttpError, type DescribeError } from \"../lib/errors\";\n\nexport { HttpError, describeHttpError, type DescribeError };\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/** Turns a TanStack query result into the `Load<T>` that `DataView` takes; errors are described for a person by `describe`. */\nexport function toLoad<T>(query: UseQueryResult<T>, describe: DescribeError = describeHttpError): Load<T> {\n if (query.status === \"success\") return { status: \"ready\", data: query.data };\n if (query.status === \"error\") return { status: \"error\", message: describe(query.error), retry: () => void query.refetch() };\n return { status: \"loading\" };\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/** fetch() that throws an HttpError on a non-2xx response and parses JSON: the queryFn default. */\nexport async function fetchJson<T>(input: string | URL, init?: RequestInit): 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) throw new HttpError(res.status, res.statusText, String(input));\n return (await res.json()) as T;\n}\n"],"mappings":";;;;;;;AAMA,IAAa,YAAY;CAAC;CAAW;CAAS;CAAW;CAAQ;CAAW;CAAS;CAAU;AAAS;AAExG,IAAM,UAAU,oBAAoB,EAClC,QAAQ,EACN,aAAa,EACX,aAAa,CAAC,EAAE,MAAM,CAAC,GAAG,SAAS,EAAE,CA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e,UAAU,kBAAkB,CAAC;CACrE,OAAO,oBAAC,qBAAD;EAAqB,QAAQ,UAAU;EAAW;CAA8B,CAAA;AACzF;;AAGA,SAAgB,OAAU,OAA0B,WAA0B,mBAA4B;CACxG,IAAI,MAAM,WAAW,WAAW,OAAO;EAAE,QAAQ;EAAS,MAAM,MAAM;CAAK;CAC3E,IAAI,MAAM,WAAW,SAAS,OAAO;EAAE,QAAQ;EAAS,SAAS,SAAS,MAAM,KAAK;EAAG,aAAa,KAAK,MAAM,QAAQ;CAAE;CAC1H,OAAO,EAAE,QAAQ,UAAU;AAC7B;;AAGA,SAAgB,QACd,SACS;CACT,MAAM,EAAE,eAAe,GAAG,SAAS;CACnC,OAAO,OAAO,SAAS,IAAI,GAAG,aAAa;AAC7C;;AAGA,eAAsB,UAAa,OAAqB,MAAgC;CAGtF,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,MAAM,IAAI,UAAU,IAAI,QAAQ,IAAI,YAAY,OAAO,KAAK,CAAC;CAC1E,OAAQ,MAAM,IAAI,KAAK;AACzB"}
@@ -1,16 +1,23 @@
1
1
  import { RenderOptions } from '@testing-library/react';
2
2
  import { QueryClient } from '@tanstack/react-query';
3
+ import { ColorSchemePreference } from '../components/theme';
3
4
  /**
4
- * Test helpers: render a component inside a router and a query client, as a Strata app runs it.
5
- * Use with MSW for the network, never module mocks.
5
+ * Test helpers: render a component inside a router and a query client, as a Strata app runs it,
6
+ * and fill the gaps jsdom leaves (layout, ResizeObserver, IntersectionObserver). Use with MSW for
7
+ * the network, never module mocks.
6
8
  *
7
9
  * @module strata-react/testing
8
10
  */
9
11
  import * as React from "react";
12
+ export { installLayoutShims, type LayoutBox } from './layout';
13
+ export { installFakeIntersectionObserver, type FakeIntersectionObserverControls, type FakeObserver, } from './intersection-observer';
14
+ /** A query client for tests: no retries, and nothing goes stale or is collected mid-test. */
10
15
  export declare function createTestQueryClient(): QueryClient;
11
- export declare function renderWithStrata(ui: React.ReactElement, { route, client, ...options }?: RenderOptions & {
16
+ /** Testing Library's `render` inside `StrataQueryProvider` and a `MemoryRouter` at `route`. */
17
+ export declare function renderWithStrata(ui: React.ReactElement, { route, client, colorScheme, ...options }?: RenderOptions & {
12
18
  route?: string;
13
19
  client?: QueryClient;
20
+ colorScheme?: ColorSchemePreference;
14
21
  }): {
15
22
  container: HTMLElement;
16
23
  baseElement: HTMLElement;
@@ -0,0 +1,34 @@
1
+ /** One stand-in observer: its callback, options and the elements it currently watches. */
2
+ export interface FakeObserver {
3
+ readonly callback: IntersectionObserverCallback;
4
+ readonly options: IntersectionObserverInit;
5
+ readonly targets: ReadonlySet<Element>;
6
+ }
7
+ /** The controls `installFakeIntersectionObserver` returns. */
8
+ export interface FakeIntersectionObserverControls {
9
+ /** Every observer created since install, including disconnected ones (their target sets are empty). */
10
+ readonly observers: readonly FakeObserver[];
11
+ /** Report `el` to every observer watching it: in view by default, or out of view with `false`. Returns how many observers were told. */
12
+ intersect(el: Element, isIntersecting?: boolean): number;
13
+ /** Report every watched element as in view, as if the person scrolled to the end of the list. Returns how many elements were reported. */
14
+ scrollToEnd(): number;
15
+ /** Put back whatever `IntersectionObserver` was there before install. */
16
+ uninstall(): void;
17
+ }
18
+ /**
19
+ * Replace `globalThis.IntersectionObserver` with a stand-in the test fires by hand. Call it in
20
+ * `beforeEach` and call `uninstall()` in `afterEach`.
21
+ *
22
+ * @example
23
+ * let io: FakeIntersectionObserverControls;
24
+ * beforeEach(() => { io = installFakeIntersectionObserver(); });
25
+ * afterEach(() => io.uninstall());
26
+ *
27
+ * it("loads the next page at the end of the list", async () => {
28
+ * renderWithStrata(<Pieces />);
29
+ * await screen.findByRole("list", { name: "Pieces" });
30
+ * io.scrollToEnd();
31
+ * expect(await screen.findByText("Celadon bowl")).toBeInTheDocument();
32
+ * });
33
+ */
34
+ export declare function installFakeIntersectionObserver(): FakeIntersectionObserverControls;
@@ -0,0 +1,13 @@
1
+ /** A DOMRect-shaped object, for stand-ins that report geometry. */
2
+ export declare function box(x: number, y: number, width: number, height: number): DOMRect;
3
+ /** The box every element reports while the shims are installed. */
4
+ export interface LayoutBox {
5
+ width: number;
6
+ height: number;
7
+ }
8
+ /**
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.
11
+ * Call once in a Vitest setup file; returns a function that puts the originals back.
12
+ */
13
+ export declare function installLayoutShims({ width, height }?: Partial<LayoutBox>): () => void;