strata-react 0.1.4 → 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.
package/README.md CHANGED
@@ -44,18 +44,27 @@ kiln-room fixture).
44
44
 
45
45
  ```tsx
46
46
  import { createBrowserRouter, RouterProvider } from "react-router";
47
- import { StrataQueryProvider } from "strata-react";
47
+ import { StrataQueryProvider, ThemeProvider } from "strata-react";
48
48
  import "./app.css";
49
49
 
50
50
  const router = createBrowserRouter([{ path: "/", element: <KilnRoom /> }]);
51
51
 
52
52
  createRoot(document.getElementById("root")!).render(
53
- <StrataQueryProvider>
54
- <RouterProvider router={router} />
55
- </StrataQueryProvider>,
53
+ <ThemeProvider>
54
+ <StrataQueryProvider>
55
+ <RouterProvider router={router} />
56
+ </StrataQueryProvider>
57
+ </ThemeProvider>,
56
58
  );
57
59
  ```
58
60
 
61
+ `ThemeProvider` sets the `.dark` class strata.css keys on. It follows the operating system until
62
+ a person chooses light or dark, keeps that choice in localStorage (and carries on without it when
63
+ storage is blocked), and follows a choice made in another tab. Put `<ColorSchemeChoice />` on the
64
+ settings page, or build your own control from `useColorScheme()`. So a dark page does not flash
65
+ light while the bundle loads, inline the pre-paint script in `index.html`'s `<head>`; generate it
66
+ once with `colorSchemeScript()` (it reads the same key the provider writes).
67
+
59
68
  ```tsx
60
69
  // One question: "Is my work out of the kiln yet?"
61
70
  function KilnRoom() {
@@ -86,9 +95,10 @@ function KilnRoom() {
86
95
  | Data | `DataView`, `Load<T>`, `EmptyState`, `Skeleton`, `DataTable`, `TableSkeleton`, `VirtualList`, `LineChart` | `DataView` requires skeleton and empty; tables and lists virtualise from 100 rows; charts label values directly |
87
96
  | Data loading | `StrataQueryProvider`, `createQueryClient`, `useLoad`, `toLoad`, `fetchJson`, `HttpError` | TanStack Query in, `Load<T>` out |
88
97
  | Page and navigation | `AppShell`, `SideNav`, `Breadcrumb`, `Tabs`, `PageHeader` | React Router; tab and sort state in the URL |
98
+ | Theme | `ThemeProvider`, `useColorScheme`, `useSystemColorScheme`, `ColorSchemeChoice`, `colorSchemeScript` | System, light or dark; sets `.dark`, persists in localStorage when it can; no picker beyond the settings-page radio group |
89
99
  | Feedback | `UndoBar`, `useUndoable`, `Done` | Undo before confirm; `Done` is the one celebration, and it must say what happens next |
90
- | Helpers | `cn`, `format`, `createFormat` | `cn` knows `type-*`; all numbers and dates through `Intl` |
91
- | Testing | `strata-react/testing`: `renderWithStrata`, `createTestQueryClient` | Router + query client around Testing Library's `render` |
100
+ | Helpers | `cn`, `format`, `createFormat`, `NBSP` | `cn` knows `type-*`; all numbers and dates through `Intl`; `format.integer(n)`, `.decimal(n)`, `.percent(n)` are callable and keep Intl's methods; units and counts join with a non-breaking space |
101
+ | Testing | `strata-react/testing`: `renderWithStrata`, `createTestQueryClient`, `installLayoutShims`, `installFakeIntersectionObserver` | Router + query client around Testing Library's `render`; a fixed box and ResizeObserver so measuring components render in jsdom; an IntersectionObserver the test fires with `scrollToEnd()` or `intersect(el)`. Role names keep the non-breaking space from `format.count`, so match them with the same call or a `\s` regex |
92
102
 
93
103
  Specs for the components not built yet (dialogs, sheets, menus, toasts, command menu, prose)
94
104
  are in ux-research `ui-library/components.md`.
@@ -0,0 +1,51 @@
1
+ import * as React from "react";
2
+ /** What a person chose: follow the operating system, or a fixed light or dark theme. */
3
+ export type ColorSchemePreference = "system" | "light" | "dark";
4
+ /** The scheme in effect after "system" is resolved. */
5
+ export type ColorScheme = "light" | "dark";
6
+ /** The localStorage key `ThemeProvider` uses unless given another. */
7
+ export declare const COLOR_SCHEME_STORAGE_KEY = "strata-color-scheme";
8
+ /** The operating system's colour scheme, kept current as it changes. Light where it cannot be read (the server, jsdom). */
9
+ export declare function useSystemColorScheme(): ColorScheme;
10
+ /** What `useColorScheme` returns: the chosen preference, the scheme in effect, and a setter that persists the choice. */
11
+ export type ColorSchemeState = {
12
+ preference: ColorSchemePreference;
13
+ scheme: ColorScheme;
14
+ setPreference: (preference: ColorSchemePreference) => void;
15
+ };
16
+ /** Sets the `.dark` class strata.css keys on, from a system, light or dark preference that persists in localStorage when it can. */
17
+ export declare function ThemeProvider({ children, defaultPreference, storageKey, target, }: {
18
+ children: React.ReactNode;
19
+ /** The preference before a person has chosen one. */
20
+ defaultPreference?: ColorSchemePreference;
21
+ /** Where the choice is kept in localStorage; `null` keeps it for this visit only. */
22
+ storageKey?: string | null;
23
+ /**
24
+ * The element that gets the `.dark` class; the document's root element when left out. A nested
25
+ * target can turn a light page's panel dark, not the reverse: strata.css keys dark on any
26
+ * `.dark` ancestor. Pass the element itself (keep it in state with a callback ref, since a
27
+ * wrapping element's ref is not attached yet when this provider's effect first runs); `null`
28
+ * means it has not mounted yet, and nothing is set until it has.
29
+ */
30
+ target?: HTMLElement | null;
31
+ }): React.JSX.Element;
32
+ /** The person's colour-scheme preference, the scheme in effect, and a setter that persists it. Must be inside `ThemeProvider`. */
33
+ export declare function useColorScheme(): ColorSchemeState;
34
+ /**
35
+ * The body of an inline `<script>` for the page's `<head>` that sets `.dark` before the first
36
+ * paint, from the stored choice or the operating system, so a dark page does not flash light while
37
+ * the bundle loads. Pass the same key and default as the `ThemeProvider`.
38
+ */
39
+ export declare function colorSchemeScript(storageKey?: string, defaultPreference?: ColorSchemePreference): string;
40
+ /** The words `ColorSchemeChoice` shows for each preference. */
41
+ export type ColorSchemeLabels = Record<ColorSchemePreference, {
42
+ label: string;
43
+ detail?: string;
44
+ }>;
45
+ /** The three colour-scheme preferences as radio buttons, bound to the nearest `ThemeProvider`. For a settings page. */
46
+ export declare function ColorSchemeChoice({ legend, labels, }: {
47
+ /** The group's name, as the settings page words it. */
48
+ legend?: string;
49
+ /** Overrides the words for each choice, in the product's voice. */
50
+ labels?: Partial<ColorSchemeLabels>;
51
+ }): React.JSX.Element;
package/dist/index.d.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  * @module strata-react
7
7
  */
8
8
  export { cn, typeSteps } from './lib/utils';
9
- export { createFormat, format, NBSP, type Format } from './lib/format';
9
+ export { createFormat, format, NBSP, type Format, type NumberFormatter } from './lib/format';
10
10
  export type { IconComponent } from './lib/icon';
11
11
  export { Button, IconButton, buttonVariants, type ButtonProps, type IconButtonProps } from './components/button';
12
12
  export { AsyncButton, useAsyncAction, type Phase, type AsyncLabels, type AsyncAction, type AsyncActionOptions } from './components/async-button';
@@ -22,5 +22,6 @@ export { UndoBar, useUndoable, type PendingRemoval } from './components/undo';
22
22
  export { Done } from './components/done';
23
23
  export { AppShell, SideNav, Breadcrumb, type NavItem } from './components/app-shell';
24
24
  export { Tabs, type TabItem } from './components/tabs';
25
+ export { ThemeProvider, useColorScheme, useSystemColorScheme, ColorSchemeChoice, colorSchemeScript, COLOR_SCHEME_STORAGE_KEY, type ColorScheme, type ColorSchemePreference, type ColorSchemeLabels, type ColorSchemeState, } from './components/theme';
25
26
  export { StrataQueryProvider, createQueryClient, toLoad, useLoad, fetchJson, HttpError, describeHttpError, type DescribeError, } from './query';
26
27
  export { describeActionError } from './lib/errors';
package/dist/index.js CHANGED
@@ -1,6 +1,4 @@
1
- import { a as useLoad, c as describeHttpError, i as toLoad, n as createQueryClient, o as HttpError, r as fetchJson, s as describeActionError, t as StrataQueryProvider } from "./query-Bi7rfvwp.js";
2
- import { clsx } from "clsx";
3
- import { extendTailwindMerge } from "tailwind-merge";
1
+ import { _ as HttpError, a as useLoad, b as cn, c as ThemeProvider, d as useSystemColorScheme, f as ChoiceGroup, g as Textarea, h as NativeSelect, i as toLoad, l as colorSchemeScript, m as Input, n as createQueryClient, o as COLOR_SCHEME_STORAGE_KEY, p as Field, r as fetchJson, s as ColorSchemeChoice, t as StrataQueryProvider, u as useColorScheme, v as describeActionError, x as typeSteps, y as describeHttpError } from "./query-CmdlXVW_.js";
4
2
  import * as React from "react";
5
3
  import { Slot } from "@radix-ui/react-slot";
6
4
  import { cva } from "class-variance-authority";
@@ -9,32 +7,24 @@ import { ArrowDown, ArrowUp, ArrowUpDown, Check, CircleAlert, LoaderCircle, Rota
9
7
  import { flexRender, getCoreRowModel, getSortedRowModel, useReactTable } from "@tanstack/react-table";
10
8
  import { useVirtualizer } from "@tanstack/react-virtual";
11
9
  import { Link, NavLink, useSearchParams } from "react-router";
12
- // src/lib/utils.ts
13
- var typeSteps = [
14
- "caption",
15
- "label",
16
- "body-sm",
17
- "body",
18
- "heading",
19
- "title",
20
- "figure",
21
- "display"
22
- ];
23
- var twMerge = extendTailwindMerge({ extend: { classGroups: { "font-size": [{ type: [...typeSteps] }] } } });
24
- /** clsx + tailwind-merge, taught that `type-*` utilities are font sizes. */
25
- function cn(...inputs) {
26
- return twMerge(clsx(inputs));
27
- }
28
10
  // src/lib/format.ts
29
11
  var NBSP = "\xA0";
12
+ function callable(nf) {
13
+ const format = (value) => nf.format(value);
14
+ return Object.assign(format, {
15
+ format,
16
+ formatToParts: (value) => nf.formatToParts(value),
17
+ resolvedOptions: () => nf.resolvedOptions()
18
+ });
19
+ }
30
20
  /** Intl formatters for one locale: integers, decimals, percent, times, days, units with a non-breaking space, and counted nouns. */
31
21
  function createFormat(locale) {
32
- const integer = new Intl.NumberFormat(locale, { maximumFractionDigits: 0 });
33
- const decimal = new Intl.NumberFormat(locale, { maximumFractionDigits: 1 });
34
- const percent = new Intl.NumberFormat(locale, {
22
+ const integer = callable(new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }));
23
+ const decimal = callable(new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }));
24
+ const percent = callable(new Intl.NumberFormat(locale, {
35
25
  style: "percent",
36
26
  maximumFractionDigits: 0
37
- });
27
+ }));
38
28
  const clock = new Intl.DateTimeFormat(locale, {
39
29
  hour: "2-digit",
40
30
  minute: "2-digit"
@@ -52,15 +42,24 @@ function createFormat(locale) {
52
42
  const withUnit = (value, unit, fmt = integer) => `${fmt.format(value)} ${unit}`;
53
43
  return {
54
44
  locale,
45
+ /** Whole numbers with grouping: `format.integer(1222)` is "1,222". */
55
46
  integer,
47
+ /** One decimal place at most: `format.decimal(3.14)` is "3.1". */
56
48
  decimal,
49
+ /** A ratio as a whole percent: `format.percent(0.42)` is "42%". */
57
50
  percent,
58
51
  clock,
59
52
  day,
60
53
  shortDay,
54
+ /** A figure and its unit joined by a non-breaking space (`NBSP`), so they never wrap apart. */
61
55
  withUnit,
56
+ /** A temperature in °C, joined by a non-breaking space. */
62
57
  celsius: (value) => withUnit(value, "°C"),
63
- /** "1 piece", "6 pieces": the count and its noun, so copy never reads "1 pieces". */
58
+ /**
59
+ * "1 piece", "6 pieces": the count and its noun, so copy never reads "1 pieces". They are
60
+ * joined by a non-breaking space (`NBSP`), not a plain one: in a test, match with the same
61
+ * call or a `\s` regex, not a typed "6 pieces" string in a role's `name`.
62
+ */
64
63
  count: (value, one, many = `${one}s`) => `${integer.format(value)} ${new Intl.PluralRules(locale).select(value) === "one" ? one : many}`
65
64
  };
66
65
  }
@@ -212,122 +211,6 @@ function useAsyncAction(action, { settleMs = 2e3, onError, describeError = descr
212
211
  error: state.error
213
212
  };
214
213
  }
215
- // src/components/field.tsx
216
- var FieldContext = React.createContext(null);
217
- function useField(id) {
218
- const field = React.useContext(FieldContext);
219
- return {
220
- id: field?.id ?? id,
221
- "aria-describedby": field?.describedBy,
222
- "aria-invalid": field?.invalid || void 0
223
- };
224
- }
225
- /** A labelled form field: wires the label, hint, error, `aria-describedby` and `aria-invalid` into the one control it wraps. */
226
- function Field({ label, id: idProp, hint, error, children, className }) {
227
- const generated = React.useId();
228
- const id = idProp ?? generated;
229
- const hintId = hint ? `${id}-hint` : void 0;
230
- const errorId = error ? `${id}-error` : void 0;
231
- const describedBy = [errorId, hintId].filter(Boolean).join(" ") || void 0;
232
- return /* @__PURE__ */ jsx(FieldContext.Provider, {
233
- value: {
234
- id,
235
- describedBy,
236
- invalid: Boolean(error)
237
- },
238
- children: /* @__PURE__ */ jsxs("div", {
239
- className: cn("grid min-w-0 content-start gap-1.5", className),
240
- children: [
241
- /* @__PURE__ */ jsx("label", {
242
- htmlFor: id,
243
- className: "type-label text-foreground",
244
- children: label
245
- }),
246
- children,
247
- error && /* @__PURE__ */ jsxs("p", {
248
- id: errorId,
249
- className: "flex items-start gap-1.5 type-body-sm text-danger",
250
- children: [/* @__PURE__ */ jsx(CircleAlert, {
251
- "aria-hidden": true,
252
- className: "mt-0.5 size-4 shrink-0"
253
- }), error]
254
- }),
255
- hint && /* @__PURE__ */ jsx("p", {
256
- id: hintId,
257
- className: "type-body-sm text-muted-foreground",
258
- children: hint
259
- })
260
- ]
261
- })
262
- });
263
- }
264
- 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";
265
- /** A text input that picks up its id and descriptions from the surrounding `Field`. */
266
- function Input({ className, id, ...props }) {
267
- return /* @__PURE__ */ jsx("input", {
268
- ...useField(id),
269
- className: cn(control, "h-(--control-h)", className),
270
- ...props
271
- });
272
- }
273
- /** A multi-line input that picks up its id and descriptions from the surrounding `Field`. */
274
- function Textarea({ className, id, ...props }) {
275
- return /* @__PURE__ */ jsx("textarea", {
276
- ...useField(id),
277
- className: cn(control, "min-h-24 py-2", className),
278
- ...props
279
- });
280
- }
281
- /** The platform select, styled. The default for short lists, especially on touch screens. */
282
- function NativeSelect({ className, id, ...props }) {
283
- return /* @__PURE__ */ jsx("select", {
284
- ...useField(id),
285
- className: cn(control, "h-(--control-h) pr-8", className),
286
- ...props
287
- });
288
- }
289
- /** 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. */
290
- function ChoiceGroup({ legend, name, choices, value, onChange, error }) {
291
- const errorId = React.useId();
292
- return /* @__PURE__ */ jsxs("fieldset", {
293
- className: "grid gap-2",
294
- "aria-describedby": error ? errorId : void 0,
295
- children: [
296
- /* @__PURE__ */ jsx("legend", {
297
- className: "mb-1.5 type-label text-foreground",
298
- children: legend
299
- }),
300
- choices.map((c) => /* @__PURE__ */ jsxs("label", {
301
- className: "flex min-h-(--control-h-sm) cursor-pointer items-start gap-3 py-1",
302
- children: [/* @__PURE__ */ jsx("input", {
303
- type: "radio",
304
- name,
305
- value: c.value,
306
- checked: value === c.value,
307
- onChange: () => onChange(c.value),
308
- className: "mt-1 size-4 shrink-0 accent-primary"
309
- }), /* @__PURE__ */ jsxs("span", {
310
- className: "grid",
311
- children: [/* @__PURE__ */ jsx("span", {
312
- className: "type-body",
313
- children: c.label
314
- }), c.detail && /* @__PURE__ */ jsx("span", {
315
- className: "type-body-sm text-muted-foreground",
316
- children: c.detail
317
- })]
318
- })]
319
- }, c.value)),
320
- error && /* @__PURE__ */ jsxs("p", {
321
- id: errorId,
322
- className: "flex items-start gap-1.5 type-body-sm text-danger",
323
- children: [/* @__PURE__ */ jsx(CircleAlert, {
324
- "aria-hidden": true,
325
- className: "mt-0.5 size-4 shrink-0"
326
- }), error]
327
- })
328
- ]
329
- });
330
- }
331
214
  // src/components/status.tsx
332
215
  var tones = {
333
216
  neutral: "bg-muted text-muted-foreground",
@@ -1154,6 +1037,6 @@ function Tabs({ param, items, label, children, className }) {
1154
1037
  })]
1155
1038
  });
1156
1039
  }
1157
- export { AppShell, AsyncButton, Breadcrumb, Button, ChoiceGroup, DataTable, DataView, Done, EmptyState, Field, HttpError, IconButton, Input, LineChart, Metric, MetricStrip, NBSP, NativeSelect, PageHeader, SideNav, Skeleton, Status, StrataQueryProvider, TableSkeleton, Tabs, Textarea, UndoBar, VirtualList, buttonVariants, cn, createFormat, createQueryClient, describeActionError, describeHttpError, fetchJson, format, parseSort, serialiseSort, toLoad, typeSteps, useAsyncAction, useLoad, useUndoable };
1040
+ export { AppShell, AsyncButton, Breadcrumb, Button, COLOR_SCHEME_STORAGE_KEY, ChoiceGroup, ColorSchemeChoice, DataTable, DataView, Done, EmptyState, Field, HttpError, IconButton, Input, LineChart, Metric, MetricStrip, NBSP, NativeSelect, PageHeader, SideNav, Skeleton, Status, StrataQueryProvider, TableSkeleton, Tabs, Textarea, ThemeProvider, UndoBar, VirtualList, buttonVariants, cn, colorSchemeScript, createFormat, createQueryClient, describeActionError, describeHttpError, fetchJson, format, parseSort, serialiseSort, toLoad, typeSteps, useAsyncAction, useColorScheme, useLoad, useSystemColorScheme, useUndoable };
1158
1041
 
1159
1042
  //# sourceMappingURL=index.js.map