strata-react 1.3.2 → 1.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -2
- package/UPGRADING.md +4 -0
- package/dist/api-types/generate.d.ts +2 -0
- package/dist/api-types-cli.js +1 -1
- package/dist/api-types.js +1 -1
- package/dist/components/field.d.ts +28 -5
- package/dist/components/link.d.ts +43 -0
- package/dist/components/recorder.d.ts +73 -0
- package/dist/components/say-again.d.ts +11 -0
- package/dist/components/toggle.d.ts +12 -4
- package/dist/{errors-DqezYZgy.js → errors-D99YX4XL.js} +2 -2
- package/dist/{errors-DqezYZgy.js.map → errors-D99YX4XL.js.map} +1 -1
- package/dist/{field-CTd1l3md.js → field-QCCmWTuY.js} +77 -4
- package/dist/field-QCCmWTuY.js.map +1 -0
- package/dist/{generate-DCRYZPJs.js → generate-CjTHKJ39.js} +21 -3
- package/dist/generate-CjTHKJ39.js.map +1 -0
- package/dist/index.d.ts +10 -2
- package/dist/index.js +447 -15
- package/dist/index.js.map +1 -1
- package/dist/lib/base.d.ts +10 -0
- package/dist/lib/microphone.d.ts +24 -0
- package/dist/lib/recording.d.ts +16 -0
- package/dist/lib/search-param.d.ts +16 -0
- package/dist/lib/speech.d.ts +37 -0
- package/dist/map.js +2 -2
- package/dist/{query-CgoGqE0T.js → microphone-BZXMKTCM.js} +84 -7
- package/dist/microphone-BZXMKTCM.js.map +1 -0
- package/dist/panorama.js +2 -2
- package/dist/query/api.d.ts +23 -0
- package/dist/query/index.d.ts +12 -2
- package/dist/query/typed-api.d.ts +78 -0
- package/dist/testing/index.d.ts +10 -8
- package/dist/testing/layout.d.ts +1 -1
- package/dist/testing/microphone.d.ts +20 -0
- package/dist/testing/speech.d.ts +32 -0
- package/dist/testing/storage.d.ts +7 -0
- package/dist/testing.js +175 -8
- package/dist/testing.js.map +1 -1
- package/dist/{theme-DB0Km2m2.js → theme-By3DSUTs.js} +2 -2
- package/dist/{theme-DB0Km2m2.js.map → theme-By3DSUTs.js.map} +1 -1
- package/dist/{value-controls-CiwdvJeH.js → value-controls-B7iNh4WO.js} +3 -3
- package/dist/{value-controls-CiwdvJeH.js.map → value-controls-B7iNh4WO.js.map} +1 -1
- package/package.json +1 -1
- package/dist/field-CTd1l3md.js.map +0 -1
- package/dist/generate-DCRYZPJs.js.map +0 -1
- package/dist/query-CgoGqE0T.js.map +0 -1
package/README.md
CHANGED
|
@@ -156,13 +156,16 @@ thousands of lines. Such an app imports the same stylesheet **without the reset*
|
|
|
156
156
|
| Compare | `Compare`, `PairVote`, `PairJudge`, `CompareAudio`, `CompareText`, `CompareGrid`, `CompareVideoGrid`, `ViewportFrame`, `useViewport`, `FullscreenFrame`, `useDifference`, `differences` | Two pictures judged together: side by side, swipe (a divider that moves from the keyboard), fade, blink (`x` flips) and difference (a live difference blend with amplify, or pixelmatch's changed pixels with a tolerance and the share that differ; pixels are read only when that view is open, at most 2048 px on the long side, and a picture the browser will not let the page read says so in words); `maxHeight="fit"` measures the window for the pair and its surroundings instead of the `"viewport"` guess; `CompareGrid` is every candidate at once with the same zoom and full screen, and `actions` for what a tile offers; one zoom and pan for both sides (buttons, `+` `-` `0`, Ctrl-wheel or trackpad pinch, drag, arrow keys, double click, `1:1`), and full screen (the browser's Fullscreen API, a modal where there is none). `blind` is required: a blind comparison names pictures by `label` only and never writes the variant `id`, `note` or `alt`. A picture that fails shows the required `missing` words in its place; the keys come from one `Shortcut[]` shared with `KeysLegend`, and `keys={false}` leaves them to a surrounding screen. `PairVote` wraps `Compare` for a blind pairwise judgment: answer keys `a` `b` `t` `s` in Compare's one legend, a vote bar with no filled button, `pending`, a flag menu, a progress line, preload and Undo, and click to choose (a click on the picture you prefer, not a drag or double click; in swipe the side of the divider, in blink the side showing, none in fade or difference; `onPick` on `Compare` and `CompareVideo`, `pick={false}` turns it off). `CompareAudio` is one transport for two clips with an A/B switch that keeps the playhead (same time, or the same share when the lengths differ), a loop range and loudness matching (the louder clip turned down to the quieter, by RMS); `CompareText` is two texts scrolled together with a word diff and an optional reference; `PairJudge` is the answering around any of them; `CompareVideo` is two videos on one clock (play, pause, seek and speed drive both, the follower kept within a frame, both held while either waits for data) in side by side, swipe, fade and blink, with zoom and pan locked and nearest-neighbour pixels past 1:1, candidates of different sizes drawn in one box, one soundtrack (`audio`), and the same slots as the rest. `autoPlay` starts the pair once both can play (muted; not with reduced motion unless `"always"`) and `loopWhole` loops the whole clip when no range is set (also on `CompareVideoGrid`). Frame by frame (`,` `.`), a loop range the app can hold (`i` `o` `c`), speeds down to 0.1 and named `moments` are in it; `CompareVideoGrid` is every candidate's video at once on that one clock (one transport, one zoom, regions, a loop, stepping), light on the browser (metadata only until the first play, cells out of sight paused and left out of the sync, sound off unless `audio` names a cell, a cell that falls behind marked "Catching up"), with an optional `reference` drawn first, never blind and nearest-neighbour. `regions` (on `Compare`, `CompareVideo` and `CompareGrid`) names boxes in the source's coordinates to look at enlarged: chips, keys `q` `w` `e` `r` `y` `u`, nearest-neighbour drawing, the box outlined while its chip is pointed at, and Shift-drag to make another |
|
|
157
157
|
| Selection | `useSelection`, `useChoices`, `BulkBar`, `SelectableGrid`, `DataTable`'s `selection` (`RowSelection<T>`) | Opt-in checkbox column with "Select all shown" that respects `isSelectable`; Shift-click or Shift+Space chooses or clears the run from the last row clicked, in the order shown; `initial` (keys or a test on the row) chooses a row the first time it appears, so it applies to data that loads later; the selection drops rows that are gone; `BulkBar` announces the count politely, and while it is up its one filled action is the view's only one (the screen's primary goes to `outline`); `SelectableGrid` is the same selection as a grid of pictures (`renderImage`), each tile one labelled target, virtualised from 100 tiles; as a photo grid it takes a pixel `tileSize` zoomed by Ctrl/Cmd+wheel, `+` and `-` and two-finger pinch (`onTileSizeChange`), `aspect="natural"` (rows of equal height, each picture at its `naturalAspect`), a marquee from between tiles, `selectionMode` and `selectionBehavior` (`replace` is the Finder's rules; `onAction` opens), `groupBy` (sticky headings with a group box and a fold), a corner `badge`, `unselectableReason`, and counts what a filter hides ("3 chosen are hidden by the filter"); `ViewOptions` with `useViewOptions` is the one toolbar for how it is looked at: sort (natural order, direction named for the key), group, size slider, aspect, grid or list and a filter with its count, kept in `localStorage` and optionally `?sort=…&group=…&size=…`, a "View" popover on a phone. A choice can imply others: `implies(key)` (on `useSelection`, and `useChoices` for a lazy tree) keeps what the person chose apart from what that brings in, follows it through, locks the implied keys (they only clear with what implied them), and gives `implied`, `because(key)`, `counts`, a `note` for the live region and `summary(noun, then)`, the line a destructive confirm can carry ("12 results will be forgotten: 8 chosen, 4 that depend on them") |
|
|
158
158
|
| Expansion | `Disclosure`, `useExpanded`, `DataTable`'s `expansion` (`RowExpansion<T>`) | Show more of one row in place. The toggle is a button with `aria-expanded`; the body is mounted only while open, so a request inside it runs on first open (unlike `<details>`, which mounts every closed body); `useExpanded({ param })` shares the open keys across a list or table and keeps them in the URL; a table's detail row spans the data columns and is measured when virtualised |
|
|
159
|
-
| Data loading | `StrataQueryProvider`, `createQueryClient`, `useLoad`, `useInfiniteLoad`, `useJob`, `toLoad`, `staleOf`, `fetchJson`, `HttpError`, `readErrorBody`, `fieldErrorsOf` | TanStack Query in, `Load<T>` out; a refetch that fails after a good read stays `ready` with `stale` set, never an error panel; `useInfiniteLoad` works out the cursor itself (after the last item held), merges pages by key and can `dismiss` an item at once; `useJob` polls a job's status only while it runs and invalidates the queries it changes once, when it ends; `fetchJson` reads an error response's body onto the `HttpError` (`body`, `reason`, `fieldErrors`, read by `readErrorBody` or the API's own `readError`); the strata apps' shared server shapes (`strata_python.contracts`): `apiPage<T>()` gives `useInfiniteLoad` the `Page<T>` items and its own `next` cursor (nothing held or dismissed changes it), `isTaskRunning(task, FINISHED)` is `useJob`'s `isRunning` for a `Task`, and an error body's `payload` (what is already running, on a 409) is on `HttpError.payload`, read typed with `errorPayload<T>(error)` |
|
|
159
|
+
| Data loading | `StrataQueryProvider`, `createQueryClient`, `useLoad`, `useInfiniteLoad`, `useJob`, `toLoad`, `staleOf`, `fetchJson`, `createApi`, `appBase`, `withBase`, `HttpError`, `readErrorBody`, `fieldErrorsOf` | TanStack Query in, `Load<T>` out; a refetch that fails after a good read stays `ready` with `stale` set, never an error panel; `useInfiniteLoad` works out the cursor itself (after the last item held), merges pages by key and can `dismiss` an item at once; `useJob` polls a job's status only while it runs and invalidates the queries it changes once, when it ends; `fetchJson(url, { json })` sends a JSON body (content type and `POST` set for you); `createTypedApi<paths>()` is the same typed by `strata-api-types`' `paths` (path, `{params}`, `query`, `json` and the answer are checked); `createApi({ base })` is `get`/`post`/`put`/`patch`/`delete` over it with the app's base put before root-relative paths (`appBase()` reads the page's `<base href>`, so the app works behind a reverse proxy; use `withBase` for an `<img src>` or a download link); `fetchJson` reads an error response's body onto the `HttpError` (`body`, `reason`, `fieldErrors`, read by `readErrorBody` or the API's own `readError`); the strata apps' shared server shapes (`strata_python.contracts`): `apiPage<T>()` gives `useInfiniteLoad` the `Page<T>` items and its own `next` cursor (nothing held or dismissed changes it), `isTaskRunning(task, FINISHED)` is `useJob`'s `isRunning` for a `Task`, and an error body's `payload` (what is already running, on a 409) is on `HttpError.payload`, read typed with `errorPayload<T>(error)` |
|
|
160
160
|
| Page and navigation | `AppShell`, `SideNav`, `Breadcrumb`, `Tabs`, `PageHeader`, `LinkCard`, `LinkCardList` | React Router; tab and sort state in the URL; a `LinkCard` is one link named by its title, described by its text and `Status` marks, with the whole card as the target (`to` a route, `href` elsewhere, marked with an arrow) |
|
|
161
161
|
| Keyboard | `useHotkeys`, `KeysLegend`, `Shortcut`, `useActiveItem`, `ActiveList`, `isTypingTarget` | For queues worked from the keyboard; one shortcut list drives the handler and the legend; keys never fire while typing; answering moves focus to the next item |
|
|
162
162
|
| Theme | `ThemeProvider`, `useColorScheme`, `useSystemColorScheme`, `ColorSchemeChoice`, `colorSchemeScript` | System, light or dark; sets `.dark`, persists in localStorage when it can; `ColorSchemeChoice` is a radio list for a settings page, or `compact` icon segments named "Appearance" for an app with no settings page |
|
|
163
163
|
| Density | `Density`, `DensityName`, `ThemeProvider`'s `density`, `ControlSize` (`size="sm"` on `Input`, `NativeSelect`, `NumberField`, `IconButton`) | Control height is two variables, `--control-h` and `--control-h-sm`. `<ThemeProvider density="compact">` or `<Density page value="compact">` sets them app-wide, including dialogs and menus, which portal out of the app's root; `<Density value="compact">` is one region (a toolbar, a dense panel) and does not reach its overlays. A coarse pointer (touch) always gets 44px targets, whatever the density A second look for a region is roles alone: set `--control-h`, `--control-h-sm`, `--control-px`, `--control-px-sm`, `--control-icon` and each type step's `--type-<step>-size`, `-leading` and `-weight` (`caption`, `label`, `body-sm`, `body`, `heading`, `title`, `figure`) on a class; the defaults are today's values. |
|
|
164
164
|
| Workspace | `Workspace`, `Split`, `Pane`, `useWorkspaceState`, `WorkspaceState` | One screen of panes for a tool: splits of panes with a growing stage, a header on every pane (name, actions, fold button), separators that resize by pointer and by keyboard (arrows, Shift, Home, End, Enter to restore) within each pane's `min` and `max`, panes that fold to a rail or header bar with a visible way back (and `state.toggle(id)` from a menu), sizes and folds remembered with `useWorkspaceState("name")`, and stacking below 720px. Each pane is a labelled region |
|
|
165
165
|
| History and save state | `useHistory`, `useHistoryState`, `History`, `useAutoSave`, `SaveStatus`, `SaveState`, `useLeaveGuard` | Undo and redo for a document edited over a session: a step is a name and an `undo`/`redo` pair, `begin(label)` groups a drag into one step, a `key` merges a slider's pushes, a `limit` drops the oldest. `history.commands` are Undo and Redo as `Command`s ("Undo move clip", Mod+Z, Mod+Shift+Z or Mod+Y) for `useCommands` and `Menu`. `useAutoSave` debounces and never overlaps saves; `SaveStatus` is the fixed-width sign ("Saved 10:42", "Saving…", "Unsaved changes", "Not saved" with the reason and "Try again"), quiet except for a failure and its recovery. For one removal that commits after a few seconds, use `useUndoable` |
|
|
166
|
+
| Links and URL choices | `ButtonLink`, `TextLink`, `useSearchParam`, `NativeSelect param=`, `ChoiceGroup param=`, `ToggleGroup param=` | `ButtonLink` is a link (`to` for a route, `href` for a download) drawn as a `Button` with its variants; it sets `data-variant`, so `variant="default"` is the view's one filled button for `expectOneFilledButton()`. `TextLink` is the house in-app link. Both are React Aria links with React Router navigation. A filter or choice a person would link to is `useSearchParam("mode", { default, parse })` (the default is never written, an invalid value reads as the default, other params are kept, history is replaced), or `param=` on the three controls, as `Tabs` does |
|
|
167
|
+
| Speech | `speak`, `useSpeech`, `SayAgain`, `installFakeSpeech` (`strata-react/testing`) | The browser's `speechSynthesis` with the voice picked by language once voices have loaded, what is being said cancelled by the next prompt, a slightly slow default rate, and nothing where there is no speech or the person muted it. `SayAgain`'s name is the sentence it says. `installFakeSpeech()` records what was said in a test |
|
|
168
|
+
| Recording | `useRecorder`, `InputLevel`, `TakeLevel`, `MicrophoneContext`, `encodeWav`, `fakeMicrophone` (`strata-react/testing`) | One take of speech from the microphone as a lossless 16-bit PCM WAV (an AudioWorklet, not MediaRecorder, which only writes compressed audio), with the browser's echo cancellation, noise suppression and gain off. `start()` resolves with the take when it stops, by `stop()` or at `maxSeconds`. `InputLevel` is the live peak in dBFS with a "Too loud" notch at -3; `TakeLevel` judges the finished take for speech in words. The device comes from `MicrophoneContext`, so tests pass `renderWithStrata(ui, { microphone: fakeMicrophone() })`. The microphone needs a secure page (https or localhost); the refusals read as sentences |
|
|
166
169
|
| Toolbar and toggles | `Toolbar`, `ToolbarSeparator`, `Toggle`, `ToggleGroup`, `Switch` | A toolbar is one tab stop with arrows, Home and End inside; needs a `label`. `Toggle` (`aria-pressed`) and `ToggleGroup` (one of 2 to 7, always one chosen) show chosen as an ink border on a tint, never the filled primary, so they do not break the one-filled-button rule; an icon-only toggle still needs its `label` (shown as a tooltip). `Switch` is only for a setting that applies at once, label and control one target |
|
|
167
170
|
| Commands | `Command`, `useCommands`, `Menu`, `ContextMenu`, `CommandMenu`, `CommandLegend`, `formatChord`, `matchesChord` | A command is declared once (label or label function, chords, `disabled` with a reason, `destructive`, `checked`) and drives the key handler, dropdown and menu-bar menus, the context menu, the searchable command menu (Mod+K) and the legend, so they cannot disagree. Chords are written once ("Mod+Shift+Z") and shown per platform (⇧⌘Z, Ctrl+Shift+Z); they never fire while typing or during IME composition, and a chord the browser keeps (Ctrl+S) needs `claim: true`. `useHotkeys` is unchanged for single keys |
|
|
168
171
|
| Overlays | `Dialog`, `DialogProps`, `AlertDialog`, `Popover`, `Tooltip` | React Aria underneath. A dialog always has a title and, via `actions`'s close render prop, a way out; `closable={false}` while work cannot stop; `placement="end"` is a sheet. `AlertDialog` is the only confirm: required verb on the confirm button, Cancel focused first, no outside dismiss, stays open with the reason when an async confirm fails. `Popover` needs a `label`. `Tooltip` opens on hover and focus and `IconButton` uses it. All portal onto the `layer-*` stacking utilities |
|
|
@@ -207,7 +210,22 @@ npx strata-api-types openapi.json -o src/api.generated.ts --check # CI: exits
|
|
|
207
210
|
|
|
208
211
|
The schema is a URL (a running server) or a JSON file the server's CLI wrote, so CI needs no server. Commit the output and never edit it, as with `theme.generated.css`; it holds nothing of the machine (no URL, no date), so `--check` is exact. The file exports `paths`, `components` and `Schema<"Task">`. Then use the shared shapes with the hooks made for them: `useInfiniteLoad({ …, ...apiPage<Item>() })` pages by `Page<T>`'s own `next` cursor, `useJob({ isRunning: (t) => isTaskRunning(t, FINISHED) })` ends when a `Task`'s state is a finished one, and `errorPayload<T>(error)` reads an error body's `payload` (what is already running, on a 409).
|
|
209
212
|
|
|
210
|
-
`openapi-typescript` does the reading (types only, nothing in the app's bundle) and is an optional peer, so an app that never runs the command installs nothing. It declares `typescript@^5` as a peer; an app on another TypeScript
|
|
213
|
+
`openapi-typescript` does the reading (types only, nothing in the app's bundle) and is an optional peer, so an app that never runs the command installs nothing. It declares `typescript@^5` as a peer; an app on another TypeScript points it at its own with an `overrides` entry, `"openapi-typescript": { "typescript": "$typescript" }`, as this repository does (the generator uses the TypeScript 6 API and is tested on it).
|
|
214
|
+
|
|
215
|
+
An app on **TypeScript 7** needs more than the override: TypeScript 7 ships no JavaScript API, so `$typescript` would hand openapi-typescript a package it cannot use, and an override that names the TypeScript 6 package directly fails `npm install` (openapi-typescript's peer must match the root `typescript`). Copy this repository's split: the name `typescript` is the TypeScript 6 package and TypeScript 7 has its own name, and `tsc` runs from that.
|
|
216
|
+
|
|
217
|
+
```json
|
|
218
|
+
{
|
|
219
|
+
"devDependencies": {
|
|
220
|
+
"typescript": "npm:@typescript/typescript6@~6.0.2",
|
|
221
|
+
"typescript7": "npm:typescript@~7.0.2"
|
|
222
|
+
},
|
|
223
|
+
"scripts": { "typecheck": "node node_modules/typescript7/bin/tsc --noEmit" },
|
|
224
|
+
"overrides": { "openapi-typescript": { "typescript": "$typescript" } }
|
|
225
|
+
}
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
When openapi-typescript cannot load, `strata-api-types` says why (and, if the `typescript` it finds is version 7 or later, this fix) instead of asking for an install that is already done.
|
|
211
229
|
|
|
212
230
|
## Visual regression for apps
|
|
213
231
|
|
package/UPGRADING.md
CHANGED
|
@@ -12,6 +12,10 @@ time. While the version is 0.x, any release may break.
|
|
|
12
12
|
Every PR that changes what an app sees adds a line here (see `CLAUDE.md`, "Changelog").
|
|
13
13
|
|
|
14
14
|
## 2026-11-23
|
|
15
|
+
- `installLayoutShims()` now also installs an in-memory `localStorage` and `sessionStorage` where the runtime's are unusable (Node 25+ under jsdom), emptied after each test. Apps that carried their own shim can delete it; one that tests "no storage" must replace it afterwards.
|
|
16
|
+
- `strata-api-types` reports why openapi-typescript failed to load instead of always asking for an install; a TypeScript 7 app needs the `typescript`/`typescript7` split in the README (new section text, no code change).
|
|
17
|
+
- `NativeSelect`, `ChoiceGroup` and `ToggleGroup` are now unions that also take `param` (URL-held choice); `ChoiceGroup` and `ToggleGroup` are function components with the same props, so nothing changes for existing callers. `fetchJson`'s init type is `FetchJsonInit` (`RequestInit` plus `json`).
|
|
18
|
+
|
|
15
19
|
- `FileDropZone` no longer takes a `DragSource` drag (or one of its new `refuseTypes`): a keyboard drag skips it and it does not offer "Drop to add". A test that Tabbed past the zone during a keyboard drag can drop that Tab.
|
|
16
20
|
- `strata-visual` gives a route's page, when taller than the window, a window as tall as itself before its shot, so lazy pictures (`Thumbnail`) below the fold are drawn in the baseline: re-record baselines that showed their grey loading boxes (`scrollThrough: false` in the config keeps the old behaviour). An app that passed `eager` to `Thumbnail` only for its screenshots can drop it.
|
|
17
21
|
- `MediaPlayer` with `controls="native"` (or `"auto"` on a touch device) and `spans` now draws a thin strip of the spans under the picture.
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
export type OpenApiDocument = Record<string, unknown>;
|
|
3
3
|
/** Reads an OpenAPI document from an `http(s)` URL (a running server) or a JSON file path. */
|
|
4
4
|
export declare function loadSchema(source: string, fetcher?: typeof fetch): Promise<OpenApiDocument>;
|
|
5
|
+
/** The message for a failed `import("openapi-typescript")`: absent, or present but unable to load (issue #293: a TypeScript 7 app was told to install what it had). */
|
|
6
|
+
export declare function explainImportFailure(cause: unknown, typescriptMajor?: number | undefined): string;
|
|
5
7
|
/**
|
|
6
8
|
* The TypeScript types for an OpenAPI document, as the text of the generated file. `source` is where the
|
|
7
9
|
* document was read from (a URL or file path): relative `$ref`s to other files resolve against it.
|
package/dist/api-types-cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as loadSchema, t as generateApiTypes } from "./generate-
|
|
1
|
+
import { n as loadSchema, t as generateApiTypes } from "./generate-CjTHKJ39.js";
|
|
2
2
|
import { existsSync } from "node:fs";
|
|
3
3
|
import { parseArgs } from "node:util";
|
|
4
4
|
import { readFile, writeFile } from "node:fs/promises";
|
package/dist/api-types.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as generateApiTypes, n as loadSchema } from "./generate-
|
|
1
|
+
export { t as generateApiTypes, n as loadSchema } from "./generate-CjTHKJ39.js";
|
|
@@ -34,21 +34,44 @@ export declare function Input({ className, id, size, ...props }: Omit<React.Comp
|
|
|
34
34
|
/** A multi-line input that picks up its id and descriptions from the surrounding `Field`. */
|
|
35
35
|
export declare function Textarea({ className, id, ...props }: React.ComponentProps<"textarea">): React.JSX.Element;
|
|
36
36
|
/** The platform select, styled. The default for short lists, especially on touch screens. `size="sm"` is --control-h-sm. */
|
|
37
|
-
export declare function NativeSelect(
|
|
37
|
+
export declare function NativeSelect(props: NativeSelectProps): React.JSX.Element;
|
|
38
|
+
type PlainSelectProps = Omit<React.ComponentProps<"select">, "size"> & {
|
|
38
39
|
size?: ControlSize;
|
|
39
|
-
}
|
|
40
|
+
};
|
|
41
|
+
/** Props of `NativeSelect`: a native select's own, or (with `param`) a choice held in the URL. */
|
|
42
|
+
export type NativeSelectProps = (PlainSelectProps & {
|
|
43
|
+
param?: undefined;
|
|
44
|
+
paramDefault?: undefined;
|
|
45
|
+
}) | (Omit<PlainSelectProps, "value" | "defaultValue" | "onChange"> & {
|
|
46
|
+
/** The search parameter that holds the choice (`?mode=…`), so it can be linked and survives a reload. */
|
|
47
|
+
param: string;
|
|
48
|
+
/** The option that is chosen when the URL says nothing; choosing it removes the param. */
|
|
49
|
+
paramDefault: string;
|
|
50
|
+
/** Called after the URL changes. */
|
|
51
|
+
onChange?: (value: string) => void;
|
|
52
|
+
});
|
|
40
53
|
export type Choice = {
|
|
41
54
|
value: string;
|
|
42
55
|
label: string;
|
|
43
56
|
detail?: string;
|
|
44
57
|
};
|
|
45
58
|
/** 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. */
|
|
46
|
-
export declare function ChoiceGroup(
|
|
59
|
+
export declare function ChoiceGroup(props: ChoiceGroupProps): React.JSX.Element;
|
|
60
|
+
/** Props of `ChoiceGroup`: the value and `onChange` are the caller's, or (with `param`) the URL's, the first choice being the default. */
|
|
61
|
+
export type ChoiceGroupProps = {
|
|
47
62
|
legend: string;
|
|
48
63
|
name: string;
|
|
49
64
|
choices: Choice[];
|
|
65
|
+
error?: string;
|
|
66
|
+
} & ({
|
|
50
67
|
value: string;
|
|
51
68
|
onChange: (value: string) => void;
|
|
52
|
-
|
|
53
|
-
}
|
|
69
|
+
param?: undefined;
|
|
70
|
+
} | {
|
|
71
|
+
/** The search parameter that holds the choice, so it can be linked and survives a reload. The first choice is the default and is not written. */
|
|
72
|
+
param: string;
|
|
73
|
+
value?: undefined;
|
|
74
|
+
/** Called after the URL changes. */
|
|
75
|
+
onChange?: (value: string) => void;
|
|
76
|
+
});
|
|
54
77
|
export {};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { IconComponent } from '../lib/icon';
|
|
2
|
+
import { ButtonProps } from './button';
|
|
3
|
+
import * as React from "react";
|
|
4
|
+
type Target = {
|
|
5
|
+
/** An app route (React Router): `"/learners/7"`, `"?tab=log"`. Client-side navigation, the basename applied. */
|
|
6
|
+
to: string;
|
|
7
|
+
href?: undefined;
|
|
8
|
+
} | {
|
|
9
|
+
/** A plain link: a download, a file or another site. */
|
|
10
|
+
href: string;
|
|
11
|
+
to?: undefined;
|
|
12
|
+
/** Offers the file for saving; `true` uses the server's name. */
|
|
13
|
+
download?: boolean | string;
|
|
14
|
+
};
|
|
15
|
+
type BaseProps = {
|
|
16
|
+
children: React.ReactNode;
|
|
17
|
+
className?: string;
|
|
18
|
+
/** Opens in a new tab; the link gets `rel="noreferrer"`. */
|
|
19
|
+
newTab?: boolean;
|
|
20
|
+
/** Names the link when its text alone does not. */
|
|
21
|
+
"aria-label"?: string;
|
|
22
|
+
id?: string;
|
|
23
|
+
onPress?: ButtonProps["onPress"];
|
|
24
|
+
};
|
|
25
|
+
/** Props of `ButtonLink`. */
|
|
26
|
+
export type ButtonLinkProps = BaseProps & Target & {
|
|
27
|
+
variant?: ButtonProps["variant"];
|
|
28
|
+
size?: ButtonProps["size"];
|
|
29
|
+
icon?: IconComponent;
|
|
30
|
+
};
|
|
31
|
+
/** Props of `TextLink`. */
|
|
32
|
+
export type TextLinkProps = BaseProps & Target & {
|
|
33
|
+
icon?: IconComponent;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* A link drawn as a `Button` (React Router `to`, or `href` for a download or another site): the same variants and heights, `variant="default"` is the filled one and counts for the one-filled-button rule (`data-variant` is set).
|
|
37
|
+
*/
|
|
38
|
+
export declare function ButtonLink(all: ButtonLinkProps): React.JSX.Element;
|
|
39
|
+
/**
|
|
40
|
+
* The house in-app link: accent ink, underlined, for a sentence, a table cell or an empty state's next step. `to` for a route, `href` for a file or another site.
|
|
41
|
+
*/
|
|
42
|
+
export declare function TextLink(all: TextLinkProps): React.JSX.Element;
|
|
43
|
+
export {};
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { Microphone } from '../lib/microphone';
|
|
2
|
+
import { MeterThreshold } from './meter';
|
|
3
|
+
import * as React from "react";
|
|
4
|
+
/** A finished take: the samples, the same as a WAV, and what was measured. */
|
|
5
|
+
export type Recording = {
|
|
6
|
+
samples: Float32Array;
|
|
7
|
+
sampleRate: number;
|
|
8
|
+
/** 16-bit PCM mono WAV of `samples`, ready to upload. */
|
|
9
|
+
wav: Blob;
|
|
10
|
+
seconds: number;
|
|
11
|
+
/** The highest sample in dBFS, never below `LEVEL_FLOOR_DB`. */
|
|
12
|
+
peak: number;
|
|
13
|
+
/** What the browser calls the microphone, or null. */
|
|
14
|
+
device: string | null;
|
|
15
|
+
};
|
|
16
|
+
/** Where a recorder is: idle, waiting for the browser to open the device, recording, or refused. */
|
|
17
|
+
export type RecorderState = {
|
|
18
|
+
phase: "idle";
|
|
19
|
+
} | {
|
|
20
|
+
phase: "opening";
|
|
21
|
+
} | {
|
|
22
|
+
phase: "recording";
|
|
23
|
+
seconds: number;
|
|
24
|
+
level: number;
|
|
25
|
+
} | {
|
|
26
|
+
phase: "failed";
|
|
27
|
+
reason: string;
|
|
28
|
+
};
|
|
29
|
+
/** `useRecorder`'s options. */
|
|
30
|
+
export type UseRecorderOptions = {
|
|
31
|
+
/** The longest take, in seconds: the recorder stops itself there. */
|
|
32
|
+
maxSeconds: number;
|
|
33
|
+
/** The microphone to record from; `useMicrophone()` (the nearest `MicrophoneContext`) when left out. */
|
|
34
|
+
microphone?: Microphone;
|
|
35
|
+
};
|
|
36
|
+
/** What `useRecorder` returns. */
|
|
37
|
+
export type Recorder = {
|
|
38
|
+
state: RecorderState;
|
|
39
|
+
/** Starts a take; resolves with it once it stops (`stop`, or `maxSeconds`), or null when the microphone would not open or a take is already running. */
|
|
40
|
+
start: () => Promise<Recording | null>;
|
|
41
|
+
/** Stops the take, which resolves `start`. Does nothing when nothing is recording. */
|
|
42
|
+
stop: () => void;
|
|
43
|
+
/** True while opening or recording: the moment Record becomes Stop. */
|
|
44
|
+
recording: boolean;
|
|
45
|
+
};
|
|
46
|
+
/** Records one take at a time from the microphone, with its live level, as a lossless WAV. */
|
|
47
|
+
export declare function useRecorder({ maxSeconds, microphone }: UseRecorderOptions): Recorder;
|
|
48
|
+
/** `InputLevel`'s "Too loud" notch: -3 dBFS on the meter's `LEVEL_FLOOR_DB`..0 scale. */
|
|
49
|
+
export declare const inputLevelThresholds: MeterThreshold[];
|
|
50
|
+
/** `InputLevel`'s props. */
|
|
51
|
+
export type InputLevelProps = {
|
|
52
|
+
/** The live peak in dBFS (`state.level` while recording). */
|
|
53
|
+
level: number;
|
|
54
|
+
/** How long the take has run. */
|
|
55
|
+
seconds: number;
|
|
56
|
+
/** The longest take, said beside the running time. */
|
|
57
|
+
maxSeconds: number;
|
|
58
|
+
/** The meter's name. Default "Input level". */
|
|
59
|
+
label?: string;
|
|
60
|
+
className?: string;
|
|
61
|
+
};
|
|
62
|
+
/** The microphone's live level while a take records: a peak meter in dBFS with a "Too loud" notch, and the take's running time. */
|
|
63
|
+
export declare function InputLevel({ level, seconds, maxSeconds, label, className }: InputLevelProps): React.JSX.Element;
|
|
64
|
+
/** `TakeLevel`'s props. */
|
|
65
|
+
export type TakeLevelProps = {
|
|
66
|
+
/** The take's peak in dBFS (`Recording.peak`). */
|
|
67
|
+
peak: number;
|
|
68
|
+
/** What comes before the peak in the sentence, such as "Kept 0:04". */
|
|
69
|
+
lead?: string;
|
|
70
|
+
className?: string;
|
|
71
|
+
};
|
|
72
|
+
/** How a finished take's level reads for speech: a status word, the peak, and what to do about it. */
|
|
73
|
+
export declare function TakeLevel({ peak, lead, className }: TakeLevelProps): React.JSX.Element;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { UseSpeechOptions } from '../lib/speech';
|
|
2
|
+
/** Props of `SayAgain`. */
|
|
3
|
+
export type SayAgainProps = UseSpeechOptions & {
|
|
4
|
+
/** The one sentence it speaks. Also names the button: "Say: Which one is the cat?". */
|
|
5
|
+
text: string;
|
|
6
|
+
/** Replaces "Say" in the name, for an app that words it differently ("Hear"). */
|
|
7
|
+
verb?: string;
|
|
8
|
+
className?: string;
|
|
9
|
+
};
|
|
10
|
+
/** An icon button that says one sentence aloud with the browser's voice; hidden where there is no speech or it is muted. */
|
|
11
|
+
export declare function SayAgain({ text, verb, className, ...options }: SayAgainProps): import('react').JSX.Element | null;
|
|
@@ -33,11 +33,19 @@ export type ToggleGroupProps = {
|
|
|
33
33
|
/** Names the group for screen readers: "Preview quality". Required. */
|
|
34
34
|
label: string;
|
|
35
35
|
options: readonly ToggleOption[];
|
|
36
|
-
value: string;
|
|
37
|
-
onChange: (value: string) => void;
|
|
38
36
|
size?: Size;
|
|
39
37
|
className?: string;
|
|
40
|
-
}
|
|
38
|
+
} & ({
|
|
39
|
+
value: string;
|
|
40
|
+
onChange: (value: string) => void;
|
|
41
|
+
param?: undefined;
|
|
42
|
+
} | {
|
|
43
|
+
/** The search parameter that holds the choice, so it can be linked and survives a reload. The first option is the default and is not written. */
|
|
44
|
+
param: string;
|
|
45
|
+
value?: undefined;
|
|
46
|
+
/** Called after the URL changes. */
|
|
47
|
+
onChange?: (value: string) => void;
|
|
48
|
+
});
|
|
41
49
|
/** A single-choice set of toggle buttons for 2 to 7 short options that switch a view. One is always chosen; arrow keys move between them. */
|
|
42
|
-
export declare function ToggleGroup(
|
|
50
|
+
export declare function ToggleGroup(props: ToggleGroupProps): React.JSX.Element;
|
|
43
51
|
export {};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { d as cn, l as Tooltip$1 } from "./field-QCCmWTuY.js";
|
|
2
2
|
import * as React from "react";
|
|
3
3
|
import { Button } from "react-aria-components";
|
|
4
4
|
import { cva } from "class-variance-authority";
|
|
@@ -198,4 +198,4 @@ function errorPayload(error) {
|
|
|
198
198
|
}
|
|
199
199
|
export { fieldErrorsOf as a, IconButton as c, isDev as d, errorPayload as i, RowAction as l, describeActionError as n, readErrorBody as o, describeHttpError as r, Button$1 as s, HttpError as t, buttonVariants as u };
|
|
200
200
|
|
|
201
|
-
//# sourceMappingURL=errors-
|
|
201
|
+
//# sourceMappingURL=errors-D99YX4XL.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors-DqezYZgy.js","names":["Button","AriaButton","Tooltip"],"sources":["../src/lib/dev.ts","../src/components/button.tsx","../src/lib/errors.ts"],"sourcesContent":["// Development-only checks (a warning for a mistake a type cannot catch). `import.meta.env.DEV` is\n// replaced by the library build itself, so in the published package it is always false and the check\n// never runs in an app's development. `process.env.NODE_ENV` is left for the app's bundler to replace\n// (Vite, webpack and the rest do, in dependencies too), so the app decides. Where nothing replaces it\n// `process` does not exist, and the check is off.\n\n/** Whether the app is running in development, decided by the app's bundler. */\nexport function isDev(): boolean {\n try {\n return process.env.NODE_ENV !== \"production\";\n } catch {\n return false;\n }\n}\n","import * as React from \"react\";\nimport { Button as AriaButton, type PressEvent } from \"react-aria-components\";\nimport { cva, type VariantProps } from \"class-variance-authority\";\nimport type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\nimport type { ControlSize } from \"../lib/control\";\nimport { Tooltip } from \"./tooltip\";\nimport { isDev } from \"../lib/dev\";\n\n// Variant names are shadcn's, so copied code and agents' prior knowledge still work. Two things\n// differ on purpose:\n// 1. The default variant is `outline`, not the filled accent. A bare <Button> is the restrained\n// one; the accent (`variant=\"default\"`) has to be asked for, once per view. Generated app screens\n// put the accent on every button; 12 of 23 real product screens had no filled primary at all.\n// 2. Heights come from --control-h, shared with Input and NativeSelect, so density changes move\n// every control together.\n// 3. React Aria is the primitives layer (CLAUDE.md, \"The stack\"): behaviour and accessibility come\n// from it, the look from our tokens. `asChild`/`Slot` is gone; a button that navigates is a link.\n// 4. `press`: the button gives 2% under a click or a finger, over 100ms. Buttons are used tens of\n// times a day, so that is all the motion they get (character.md, the frequency budget).\n// 5. `title` is refused, not passed through (issue #231). React Aria's `Button` does not forward it,\n// so a tip moved over from a native button vanished with nothing said. Passing it through would\n// give a tip that has no keyboard focus, no touch and a long, unstyled delay; the answer is a\n// `Tooltip` (and `IconButton`'s `label` and `hint`). The type says so (`title?: never`) and, for\n// an untyped caller, so does a development warning. A button whose only child is one symbol\n// (`✕`, `−`, `+`) has no accessible name from its text and gets a development warning too.\nexport const buttonVariants = cva(\n \"inline-flex max-w-full shrink-0 cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-control type-label transition-state press disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-(--control-icon) [&_svg]:shrink-0\",\n {\n variants: {\n variant: {\n default: \"bg-primary text-primary-foreground hover:bg-primary-10\",\n outline: \"border border-input bg-background text-foreground hover:bg-muted\",\n secondary: \"bg-muted text-foreground hover:bg-neutral-4\",\n ghost: \"text-foreground hover:bg-muted\",\n destructive: \"bg-destructive text-destructive-foreground hover:bg-danger\",\n link: \"h-auto px-0 text-primary-11 underline underline-offset-4 hover:text-primary-12\",\n },\n size: {\n default: \"h-(--control-h) px-(--control-px)\",\n sm: \"h-(--control-h-sm) px-(--control-px-sm)\",\n icon: \"size-(--control-h)\",\n \"icon-sm\": \"size-(--control-h-sm)\",\n },\n },\n defaultVariants: { variant: \"outline\", size: \"default\" },\n },\n);\n\nexport type ButtonProps = Omit<React.ComponentProps<\"button\">, \"className\" | \"style\" | \"title\"> &\n VariantProps<typeof buttonVariants> & {\n className?: string;\n /** Not accepted: a `title` is a poor tooltip (no keyboard focus, no touch) and React Aria's button drops it. Wrap the button in a `Tooltip`, or use `IconButton`'s `label` and `hint`. */\n title?: never;\n /** React Aria's press event (mouse, touch, pen and keyboard alike). `onClick` also works. */\n onPress?: (event: PressEvent) => void;\n /** When a press begins and ends: for a control that acts while held (a nudge that repeats). */\n onPressStart?: (event: PressEvent) => void;\n onPressEnd?: (event: PressEvent) => void;\n };\n\n/**\n * A button with shadcn's variant names, built on React Aria's `Button` (press handling that behaves\n * the same for mouse, touch, pen and keyboard, focus-visible and hover state). The default variant is\n * `outline`; ask for the filled accent (`variant=\"default\"`) once per view. `type` defaults to `button`.\n * `onClick` and `disabled` are the DOM names and keep working; `onPress` is also accepted.\n */\nexport function Button({ className, variant, size, type = \"button\", disabled, children, \"aria-busy\": ariaBusy, ...props }: ButtonProps) {\n // React Aria's button drops `aria-busy` (it forwards only the aria props it knows), so it is set\n // on the element here; a pending row action says it is busy to a screen reader (issue #248).\n const ref = React.useRef<HTMLButtonElement>(null);\n React.useEffect(() => {\n const el = ref.current;\n if (!el) return;\n if (ariaBusy) el.setAttribute(\"aria-busy\", String(ariaBusy));\n else el.removeAttribute(\"aria-busy\");\n }, [ariaBusy]);\n if (isDev()) warnOnLoss(props as Record<string, unknown>, children);\n // data-variant says which variant was drawn, so a test can check \"one filled button per view\"\n // without reading class names (strata-react issue #48, `filledButtons` in strata-react/testing).\n return (\n <AriaButton\n ref={ref}\n type={type}\n isDisabled={disabled}\n data-variant={variant ?? \"outline\"}\n className={cn(buttonVariants({ variant, size }), className)}\n {...(props as object)}\n >\n {/* A text label that cannot fit its column is cut with an ellipsis, not drawn past the button (issue #116). */}\n {typeof children === \"string\" ? <span className=\"min-w-0 truncate\">{children}</span> : children}\n </AriaButton>\n );\n}\n\n/** Development only: what a native button had that this one loses or cannot name (issue #231). */\nfunction warnOnLoss(props: Record<string, unknown>, children: React.ReactNode) {\n if (props.title !== undefined && !warned.has(\"title\")) {\n warned.add(\"title\");\n console.warn(\"strata-react: Button does not pass `title` through (React Aria's button drops it, and a title has no keyboard or touch). Wrap the button in a `Tooltip`, or use IconButton's `label` and `hint`.\");\n }\n const glyph = typeof children === \"string\" ? children.trim() : \"\";\n if (glyph && Array.from(glyph).length === 1 && !/[\\p{L}\\p{N}]/u.test(glyph) && !props[\"aria-label\"] && !props[\"aria-labelledby\"] && !warned.has(\"glyph\")) {\n warned.add(\"glyph\");\n console.warn(`strata-react: a Button whose only content is \"${glyph}\" has no accessible name. Give it an aria-label, or use an IconButton with a label.`);\n }\n}\nconst warned = new Set<string>();\n\n// An icon-only button cannot be written without a name: `label` is required by the type, becomes\n// the accessible name and is shown as a `Tooltip` on hover and keyboard focus, so the name and the\n// visible hint come from one string and cannot drift. This makes the most common generated\n// accessibility defect (an unlabelled icon button) a compile error instead of an audit finding.\nexport type IconButtonProps = Omit<ButtonProps, \"size\" | \"children\" | \"aria-label\"> & {\n /** `sm` is --control-h-sm, the height of a small `Toggle` or `Button`, for a toolbar or property row. Default --control-h. */\n size?: ControlSize;\n icon: IconComponent;\n label: string;\n /** Shown after the label in its tooltip, muted: \"Ctrl+Z\". */\n hint?: React.ReactNode;\n};\n\n/** An icon-only button. `label` is required and becomes the accessible name and the tooltip (hover and keyboard focus); `hint` adds a muted aside to it, such as a shortcut. */\nexport function IconButton({ icon: Icon, label, hint, variant = \"ghost\", size = \"default\", ...props }: IconButtonProps) {\n return (\n <Tooltip label={label} hint={hint}>\n <Button size={size === \"sm\" ? \"icon-sm\" : \"icon\"} variant={variant} aria-label={label} {...props}>\n <Icon aria-hidden />\n </Button>\n </Tooltip>\n );\n}\n\n// A row action says what it does in the row (\"Withdraw\") and whom it does it to in its name\n// (\"Withdraw Tom Ellery\"): a table of eight \"Withdraw\" buttons is eight identical names in a\n// screen reader's list of controls. The name is an aria-label that starts with the visible verb,\n// so it meets WCAG 2.5.3 (label in name) and voice control still finds it by \"Withdraw\". Visually\n// hidden suffix text is not used: a hidden span joined to the verb did not form a name with its\n// space in dom-testing-library (strata-react issue #11). Ghost and small, one per row, shown only\n// on the rows where it applies; an icon-only row action is an `IconButton` whose `label` names the\n// row the same way. It keeps the row's pitch: rows with and without the action are the same height.\nexport type RowActionProps = Omit<ButtonProps, \"children\" | \"aria-label\"> & {\n /** The visible verb, sentence case: \"Withdraw\", \"Remove\". */\n label: string;\n /** What the row is, as a person would say it: \"Tom Ellery\", \"Moonbeam\". Completes the accessible name. */\n subject: string;\n icon?: IconComponent;\n};\n\n/** A small ghost action for one table row: shows `label`, and is named \"`label` `subject`\" so every row's action has its own name. */\nexport function RowAction({ label, subject, icon: Icon, variant = \"ghost\", size = \"sm\", className, ...props }: RowActionProps) {\n // -my-1.5 lets the 32px button sit in the 20px line of a table row, inside the row's padding, so\n // rows with an action keep the same pitch as rows without one.\n return (\n <Button variant={variant} size={size} aria-label={`${label} ${subject}`} className={cn(\"-my-1.5\", className)} {...props}>\n {Icon && <Icon aria-hidden />}\n {label}\n </Button>\n );\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// A server's own reason beats the status text (strata-react issue #42, from python-app-template).\n// FastAPI and most JSON APIs say why a 4xx happened in the body (`{\"detail\": \"the data folder must\n// be an absolute path\"}`), and a client that drops it has to repeat every server rule to show the\n// person anything better than \"Bad Request\", which drifts and cannot cover rules only the server\n// can check. So `fetchJson` reads an error response's body, `HttpError` keeps it with the reason\n// and any per-field messages found in it, and the sentences below use the reason for a 4xx.\n// Per-field messages (FastAPI's 422 `detail: [{loc, msg}]`) are keyed by field name, so\n// `useAsyncAction`'s `fieldErrors` can put each under its `Field`, never in a toast. A 5xx body is\n// not shown: it is usually a stack trace or a proxy's HTML page, and is kept on `body` for logs.\n\n/** What `readErrorBody` finds in an error response: the server's sentence, and messages per field. */\nexport type ErrorBody = {\n /** Why the server refused, in its own words. */\n reason?: string;\n /** Messages for individual fields, keyed by field name (`\"name\"`, `\"address.city\"`). */\n fields?: Record<string, string>;\n /** The structured part of the body (`ErrorBody.payload` of the shared contract): what the app can act on, such as what is already running on a 409. Typed by the caller with `errorPayload`. */\n payload?: unknown;\n};\n\n/** Thrown by `fetchJson` on a non-2xx response; carries the status, the response body and the server's reason for `describeHttpError` and `describeActionError`. */\nexport class HttpError extends Error {\n /** The server's sentence for why it refused, from the body (`detail`, `message`, `error`), if it gave one. */\n readonly reason?: string;\n /** Messages for individual fields from the body (FastAPI's 422 `detail: [{loc, msg}]`), keyed by field name. Empty when there are none. */\n readonly fieldErrors: Readonly<Record<string, string>>;\n /** The body's `payload`, when it has one (`{ detail, payload }`): data for the app, not words for the person. Read it typed with `errorPayload`. */\n readonly payload?: unknown;\n\n constructor(\n readonly status: number,\n readonly statusText: string,\n readonly url: string,\n /** The response body: parsed JSON when it was JSON, else its text; undefined when empty. */\n readonly body?: unknown,\n found: ErrorBody = readErrorBody(body),\n ) {\n super(`${status} ${statusText} from ${url}`);\n this.name = \"HttpError\";\n this.reason = found.reason;\n this.fieldErrors = found.fields ?? {};\n this.payload = found.payload;\n }\n}\n\nconst text = (value: unknown) => (typeof value === \"string\" && value.trim() ? value.trim() : undefined);\n\n/** A field name from a FastAPI/pydantic `loc`: the path after where it came from (`[\"body\", \"address\", \"city\"]` is `\"address.city\"`). */\nfunction fieldName(loc: unknown) {\n if (!Array.isArray(loc)) return undefined;\n const path = loc.map(String);\n if ([\"body\", \"query\", \"path\", \"header\", \"cookie\", \"form\"].includes(path[0]) && path.length > 1) path.shift();\n return path.join(\".\") || undefined;\n}\n\n/**\n * The default reading of an error body, for the shapes most JSON APIs use: `{ detail: \"…\" }`\n * (FastAPI), `{ message: \"…\" }`, `{ error: \"…\" }` or `{ error: { message: \"…\" } }` for the reason,\n * and FastAPI's validation list `{ detail: [{ loc, msg }] }` for per-field messages. A short\n * plain-text body (not HTML) is taken as the reason too. Pass your own to `fetchJson` for other APIs.\n */\nexport function readErrorBody(body: unknown): ErrorBody {\n if (typeof body === \"string\") {\n const t = text(body);\n return t && t.length <= 300 && !t.startsWith(\"<\") ? { reason: t } : {};\n }\n if (!body || typeof body !== \"object\") return {};\n const b = body as Record<string, unknown>;\n const payload = b.payload !== undefined && b.payload !== null ? { payload: b.payload } : {};\n if (Array.isArray(b.detail)) {\n const fields: Record<string, string> = {};\n for (const item of b.detail as unknown[]) {\n const entry = item as { loc?: unknown; msg?: unknown } | null;\n const name = fieldName(entry?.loc);\n const msg = text(entry?.msg);\n if (name && msg && !fields[name]) fields[name] = msg;\n }\n return { fields, ...payload };\n }\n const nested = b.error && typeof b.error === \"object\" ? text((b.error as Record<string, unknown>).message) : undefined;\n return { reason: text(b.detail) ?? text(b.message) ?? text(b.error) ?? nested, ...payload };\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\n/** A sentence ends once: \"…absolute path\" and \"…absolute path.\" both end in one full stop. */\nconst sentence = (s: string) => (/[.!?…]$/.test(s) ? s : `${s}.`);\n\nfunction refused(error: HttpError) {\n if (error.reason) return `The request was refused: ${sentence(error.reason)}`;\n if (Object.keys(error.fieldErrors).length) return \"The request was refused: check the fields marked.\";\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 (with the server's reason for a 4xx), 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 (with the server's reason for a 4xx), 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\n/** Messages for individual fields carried by what was thrown: an `HttpError`'s `fieldErrors`, else none. */\nexport function fieldErrorsOf(error: unknown): Readonly<Record<string, string>> {\n return error instanceof HttpError ? error.fieldErrors : {};\n}\n\n/** The payload of an error from the server as the type the app expects (`errorPayload<{ running: string }>(error)`), or `undefined` when it is not an `HttpError` or carries none. The type is the caller's claim: check it against the API's schema. */\nexport function errorPayload<T>(error: unknown): T | undefined {\n return error instanceof HttpError ? (error.payload as T | undefined) : undefined;\n}\n"],"mappings":";;;;;;;AAOA,SAAgB,QAAiB;CAC/B,IAAI;EACF,OAAA,QAAA,IAAA,aAAgC;CAClC,QAAQ;EACN,OAAO;CACT;AACF;;ACaA,IAAa,iBAAiB,IAC5B,oRACA;CACE,UAAU;EACR,SAAS;GACP,SAAS;GACT,SAAS;GACT,WAAW;GACX,OAAO;GACP,aAAa;GACb,MAAM;EACR;EACA,MAAM;GACJ,SAAS;GACT,IAAI;GACJ,MAAM;GACN,WAAW;EACb;CACF;CACA,iBAAiB;EAAE,SAAS;EAAW,MAAM;CAAU;AACzD,CACF;;;;;;;AAoBA,SAAgBA,SAAO,EAAE,WAAW,SAAS,MAAM,OAAO,UAAU,UAAU,UAAU,aAAa,UAAU,GAAG,SAAsB;CAGtI,MAAM,MAAM,MAAM,OAA0B,IAAI;CAChD,MAAM,gBAAgB;EACpB,MAAM,KAAK,IAAI;EACf,IAAI,CAAC,IAAI;EACT,IAAI,UAAU,GAAG,aAAa,aAAa,OAAO,QAAQ,CAAC;OACtD,GAAG,gBAAgB,WAAW;CACrC,GAAG,CAAC,QAAQ,CAAC;CACb,IAAI,MAAM,GAAG,WAAW,OAAkC,QAAQ;CAGlE,OACE,oBAACC,QAAD;EACO;EACC;EACN,YAAY;EACZ,gBAAc,WAAW;EACzB,WAAW,GAAG,eAAe;GAAE;GAAS;EAAK,CAAC,GAAG,SAAS;EAC1D,GAAK;EAGJ,UAAA,OAAO,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AG;GAC3B,IAAI,QAAQ,OAAO,CAAC,OAAO,OAAO,OAAO,QAAQ;EACnD;EACA,OAAO;GAAE;GAAQ,GAAG;EAAQ;CAC9B;CACA,MAAM,SAAS,EAAE,SAAS,OAAO,EAAE,UAAU,WAAW,KAAM,EAAE,MAAkC,OAAO,IAAI,KAAA;CAC7G,OAAO;EAAE,QAAQ,KAAK,EAAE,MAAM,KAAK,KAAK,EAAE,OAAO,KAAK,KAAK,EAAE,KAAK,KAAK;EAAQ,GAAG;CAAQ;AAC5F;;AAMA,IAAM,YAAY,MAAe,UAAU,KAAK,CAAC,IAAI,IAAI,GAAG,EAAE;AAE9D,SAAS,QAAQ,OAAkB;CACjC,IAAI,MAAM,QAAQ,OAAO,4BAA4B,SAAS,MAAM,MAAM;CAC1E,IAAI,OAAO,KAAK,MAAM,WAAW,CAAC,CAAC,QAAQ,OAAO;CAClD,OAAO,4BAA4B,MAAM,OAAO,KAAK,MAAM,cAAc,kBAAkB;AAC7F;;AAGA,IAAa,qBAAoC,UAC/C,iBAAiB,YACb,MAAM,UAAU,MACd,gCAAgC,MAAM,OAAO,2BAC7C,QAAQ,KAAK,IACf,iBAAiB,SAAS,MAAM,UAC9B,MAAM,UACN;;AAGR,IAAa,uBAAuB,UAClC,iBAAiB,YACb,MAAM,UAAU,MACd,gCAAgC,MAAM,OAAO,MAC7C,QAAQ,KAAK,IACf,iBAAiB,SAAS,MAAM,UAC9B,MAAM,UACN,KAAA;;AAGR,SAAgB,cAAc,OAAkD;CAC9E,OAAO,iBAAiB,YAAY,MAAM,cAAc,CAAC;AAC3D;;AAGA,SAAgB,aAAgB,OAA+B;CAC7D,OAAO,iBAAiB,YAAa,MAAM,UAA4B,KAAA;AACzE"}
|
|
1
|
+
{"version":3,"file":"errors-D99YX4XL.js","names":["Button","AriaButton","Tooltip"],"sources":["../src/lib/dev.ts","../src/components/button.tsx","../src/lib/errors.ts"],"sourcesContent":["// Development-only checks (a warning for a mistake a type cannot catch). `import.meta.env.DEV` is\n// replaced by the library build itself, so in the published package it is always false and the check\n// never runs in an app's development. `process.env.NODE_ENV` is left for the app's bundler to replace\n// (Vite, webpack and the rest do, in dependencies too), so the app decides. Where nothing replaces it\n// `process` does not exist, and the check is off.\n\n/** Whether the app is running in development, decided by the app's bundler. */\nexport function isDev(): boolean {\n try {\n return process.env.NODE_ENV !== \"production\";\n } catch {\n return false;\n }\n}\n","import * as React from \"react\";\nimport { Button as AriaButton, type PressEvent } from \"react-aria-components\";\nimport { cva, type VariantProps } from \"class-variance-authority\";\nimport type { IconComponent } from \"../lib/icon\";\nimport { cn } from \"../lib/utils\";\nimport type { ControlSize } from \"../lib/control\";\nimport { Tooltip } from \"./tooltip\";\nimport { isDev } from \"../lib/dev\";\n\n// Variant names are shadcn's, so copied code and agents' prior knowledge still work. Two things\n// differ on purpose:\n// 1. The default variant is `outline`, not the filled accent. A bare <Button> is the restrained\n// one; the accent (`variant=\"default\"`) has to be asked for, once per view. Generated app screens\n// put the accent on every button; 12 of 23 real product screens had no filled primary at all.\n// 2. Heights come from --control-h, shared with Input and NativeSelect, so density changes move\n// every control together.\n// 3. React Aria is the primitives layer (CLAUDE.md, \"The stack\"): behaviour and accessibility come\n// from it, the look from our tokens. `asChild`/`Slot` is gone; a button that navigates is a link.\n// 4. `press`: the button gives 2% under a click or a finger, over 100ms. Buttons are used tens of\n// times a day, so that is all the motion they get (character.md, the frequency budget).\n// 5. `title` is refused, not passed through (issue #231). React Aria's `Button` does not forward it,\n// so a tip moved over from a native button vanished with nothing said. Passing it through would\n// give a tip that has no keyboard focus, no touch and a long, unstyled delay; the answer is a\n// `Tooltip` (and `IconButton`'s `label` and `hint`). The type says so (`title?: never`) and, for\n// an untyped caller, so does a development warning. A button whose only child is one symbol\n// (`✕`, `−`, `+`) has no accessible name from its text and gets a development warning too.\nexport const buttonVariants = cva(\n \"inline-flex max-w-full shrink-0 cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-control type-label transition-state press disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-(--control-icon) [&_svg]:shrink-0\",\n {\n variants: {\n variant: {\n default: \"bg-primary text-primary-foreground hover:bg-primary-10\",\n outline: \"border border-input bg-background text-foreground hover:bg-muted\",\n secondary: \"bg-muted text-foreground hover:bg-neutral-4\",\n ghost: \"text-foreground hover:bg-muted\",\n destructive: \"bg-destructive text-destructive-foreground hover:bg-danger\",\n link: \"h-auto px-0 text-primary-11 underline underline-offset-4 hover:text-primary-12\",\n },\n size: {\n default: \"h-(--control-h) px-(--control-px)\",\n sm: \"h-(--control-h-sm) px-(--control-px-sm)\",\n icon: \"size-(--control-h)\",\n \"icon-sm\": \"size-(--control-h-sm)\",\n },\n },\n defaultVariants: { variant: \"outline\", size: \"default\" },\n },\n);\n\nexport type ButtonProps = Omit<React.ComponentProps<\"button\">, \"className\" | \"style\" | \"title\"> &\n VariantProps<typeof buttonVariants> & {\n className?: string;\n /** Not accepted: a `title` is a poor tooltip (no keyboard focus, no touch) and React Aria's button drops it. Wrap the button in a `Tooltip`, or use `IconButton`'s `label` and `hint`. */\n title?: never;\n /** React Aria's press event (mouse, touch, pen and keyboard alike). `onClick` also works. */\n onPress?: (event: PressEvent) => void;\n /** When a press begins and ends: for a control that acts while held (a nudge that repeats). */\n onPressStart?: (event: PressEvent) => void;\n onPressEnd?: (event: PressEvent) => void;\n };\n\n/**\n * A button with shadcn's variant names, built on React Aria's `Button` (press handling that behaves\n * the same for mouse, touch, pen and keyboard, focus-visible and hover state). The default variant is\n * `outline`; ask for the filled accent (`variant=\"default\"`) once per view. `type` defaults to `button`.\n * `onClick` and `disabled` are the DOM names and keep working; `onPress` is also accepted.\n */\nexport function Button({ className, variant, size, type = \"button\", disabled, children, \"aria-busy\": ariaBusy, ...props }: ButtonProps) {\n // React Aria's button drops `aria-busy` (it forwards only the aria props it knows), so it is set\n // on the element here; a pending row action says it is busy to a screen reader (issue #248).\n const ref = React.useRef<HTMLButtonElement>(null);\n React.useEffect(() => {\n const el = ref.current;\n if (!el) return;\n if (ariaBusy) el.setAttribute(\"aria-busy\", String(ariaBusy));\n else el.removeAttribute(\"aria-busy\");\n }, [ariaBusy]);\n if (isDev()) warnOnLoss(props as Record<string, unknown>, children);\n // data-variant says which variant was drawn, so a test can check \"one filled button per view\"\n // without reading class names (strata-react issue #48, `filledButtons` in strata-react/testing).\n return (\n <AriaButton\n ref={ref}\n type={type}\n isDisabled={disabled}\n data-variant={variant ?? \"outline\"}\n className={cn(buttonVariants({ variant, size }), className)}\n {...(props as object)}\n >\n {/* A text label that cannot fit its column is cut with an ellipsis, not drawn past the button (issue #116). */}\n {typeof children === \"string\" ? <span className=\"min-w-0 truncate\">{children}</span> : children}\n </AriaButton>\n );\n}\n\n/** Development only: what a native button had that this one loses or cannot name (issue #231). */\nfunction warnOnLoss(props: Record<string, unknown>, children: React.ReactNode) {\n if (props.title !== undefined && !warned.has(\"title\")) {\n warned.add(\"title\");\n console.warn(\"strata-react: Button does not pass `title` through (React Aria's button drops it, and a title has no keyboard or touch). Wrap the button in a `Tooltip`, or use IconButton's `label` and `hint`.\");\n }\n const glyph = typeof children === \"string\" ? children.trim() : \"\";\n if (glyph && Array.from(glyph).length === 1 && !/[\\p{L}\\p{N}]/u.test(glyph) && !props[\"aria-label\"] && !props[\"aria-labelledby\"] && !warned.has(\"glyph\")) {\n warned.add(\"glyph\");\n console.warn(`strata-react: a Button whose only content is \"${glyph}\" has no accessible name. Give it an aria-label, or use an IconButton with a label.`);\n }\n}\nconst warned = new Set<string>();\n\n// An icon-only button cannot be written without a name: `label` is required by the type, becomes\n// the accessible name and is shown as a `Tooltip` on hover and keyboard focus, so the name and the\n// visible hint come from one string and cannot drift. This makes the most common generated\n// accessibility defect (an unlabelled icon button) a compile error instead of an audit finding.\nexport type IconButtonProps = Omit<ButtonProps, \"size\" | \"children\" | \"aria-label\"> & {\n /** `sm` is --control-h-sm, the height of a small `Toggle` or `Button`, for a toolbar or property row. Default --control-h. */\n size?: ControlSize;\n icon: IconComponent;\n label: string;\n /** Shown after the label in its tooltip, muted: \"Ctrl+Z\". */\n hint?: React.ReactNode;\n};\n\n/** An icon-only button. `label` is required and becomes the accessible name and the tooltip (hover and keyboard focus); `hint` adds a muted aside to it, such as a shortcut. */\nexport function IconButton({ icon: Icon, label, hint, variant = \"ghost\", size = \"default\", ...props }: IconButtonProps) {\n return (\n <Tooltip label={label} hint={hint}>\n <Button size={size === \"sm\" ? \"icon-sm\" : \"icon\"} variant={variant} aria-label={label} {...props}>\n <Icon aria-hidden />\n </Button>\n </Tooltip>\n );\n}\n\n// A row action says what it does in the row (\"Withdraw\") and whom it does it to in its name\n// (\"Withdraw Tom Ellery\"): a table of eight \"Withdraw\" buttons is eight identical names in a\n// screen reader's list of controls. The name is an aria-label that starts with the visible verb,\n// so it meets WCAG 2.5.3 (label in name) and voice control still finds it by \"Withdraw\". Visually\n// hidden suffix text is not used: a hidden span joined to the verb did not form a name with its\n// space in dom-testing-library (strata-react issue #11). Ghost and small, one per row, shown only\n// on the rows where it applies; an icon-only row action is an `IconButton` whose `label` names the\n// row the same way. It keeps the row's pitch: rows with and without the action are the same height.\nexport type RowActionProps = Omit<ButtonProps, \"children\" | \"aria-label\"> & {\n /** The visible verb, sentence case: \"Withdraw\", \"Remove\". */\n label: string;\n /** What the row is, as a person would say it: \"Tom Ellery\", \"Moonbeam\". Completes the accessible name. */\n subject: string;\n icon?: IconComponent;\n};\n\n/** A small ghost action for one table row: shows `label`, and is named \"`label` `subject`\" so every row's action has its own name. */\nexport function RowAction({ label, subject, icon: Icon, variant = \"ghost\", size = \"sm\", className, ...props }: RowActionProps) {\n // -my-1.5 lets the 32px button sit in the 20px line of a table row, inside the row's padding, so\n // rows with an action keep the same pitch as rows without one.\n return (\n <Button variant={variant} size={size} aria-label={`${label} ${subject}`} className={cn(\"-my-1.5\", className)} {...props}>\n {Icon && <Icon aria-hidden />}\n {label}\n </Button>\n );\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// A server's own reason beats the status text (strata-react issue #42, from python-app-template).\n// FastAPI and most JSON APIs say why a 4xx happened in the body (`{\"detail\": \"the data folder must\n// be an absolute path\"}`), and a client that drops it has to repeat every server rule to show the\n// person anything better than \"Bad Request\", which drifts and cannot cover rules only the server\n// can check. So `fetchJson` reads an error response's body, `HttpError` keeps it with the reason\n// and any per-field messages found in it, and the sentences below use the reason for a 4xx.\n// Per-field messages (FastAPI's 422 `detail: [{loc, msg}]`) are keyed by field name, so\n// `useAsyncAction`'s `fieldErrors` can put each under its `Field`, never in a toast. A 5xx body is\n// not shown: it is usually a stack trace or a proxy's HTML page, and is kept on `body` for logs.\n\n/** What `readErrorBody` finds in an error response: the server's sentence, and messages per field. */\nexport type ErrorBody = {\n /** Why the server refused, in its own words. */\n reason?: string;\n /** Messages for individual fields, keyed by field name (`\"name\"`, `\"address.city\"`). */\n fields?: Record<string, string>;\n /** The structured part of the body (`ErrorBody.payload` of the shared contract): what the app can act on, such as what is already running on a 409. Typed by the caller with `errorPayload`. */\n payload?: unknown;\n};\n\n/** Thrown by `fetchJson` on a non-2xx response; carries the status, the response body and the server's reason for `describeHttpError` and `describeActionError`. */\nexport class HttpError extends Error {\n /** The server's sentence for why it refused, from the body (`detail`, `message`, `error`), if it gave one. */\n readonly reason?: string;\n /** Messages for individual fields from the body (FastAPI's 422 `detail: [{loc, msg}]`), keyed by field name. Empty when there are none. */\n readonly fieldErrors: Readonly<Record<string, string>>;\n /** The body's `payload`, when it has one (`{ detail, payload }`): data for the app, not words for the person. Read it typed with `errorPayload`. */\n readonly payload?: unknown;\n\n constructor(\n readonly status: number,\n readonly statusText: string,\n readonly url: string,\n /** The response body: parsed JSON when it was JSON, else its text; undefined when empty. */\n readonly body?: unknown,\n found: ErrorBody = readErrorBody(body),\n ) {\n super(`${status} ${statusText} from ${url}`);\n this.name = \"HttpError\";\n this.reason = found.reason;\n this.fieldErrors = found.fields ?? {};\n this.payload = found.payload;\n }\n}\n\nconst text = (value: unknown) => (typeof value === \"string\" && value.trim() ? value.trim() : undefined);\n\n/** A field name from a FastAPI/pydantic `loc`: the path after where it came from (`[\"body\", \"address\", \"city\"]` is `\"address.city\"`). */\nfunction fieldName(loc: unknown) {\n if (!Array.isArray(loc)) return undefined;\n const path = loc.map(String);\n if ([\"body\", \"query\", \"path\", \"header\", \"cookie\", \"form\"].includes(path[0]) && path.length > 1) path.shift();\n return path.join(\".\") || undefined;\n}\n\n/**\n * The default reading of an error body, for the shapes most JSON APIs use: `{ detail: \"…\" }`\n * (FastAPI), `{ message: \"…\" }`, `{ error: \"…\" }` or `{ error: { message: \"…\" } }` for the reason,\n * and FastAPI's validation list `{ detail: [{ loc, msg }] }` for per-field messages. A short\n * plain-text body (not HTML) is taken as the reason too. Pass your own to `fetchJson` for other APIs.\n */\nexport function readErrorBody(body: unknown): ErrorBody {\n if (typeof body === \"string\") {\n const t = text(body);\n return t && t.length <= 300 && !t.startsWith(\"<\") ? { reason: t } : {};\n }\n if (!body || typeof body !== \"object\") return {};\n const b = body as Record<string, unknown>;\n const payload = b.payload !== undefined && b.payload !== null ? { payload: b.payload } : {};\n if (Array.isArray(b.detail)) {\n const fields: Record<string, string> = {};\n for (const item of b.detail as unknown[]) {\n const entry = item as { loc?: unknown; msg?: unknown } | null;\n const name = fieldName(entry?.loc);\n const msg = text(entry?.msg);\n if (name && msg && !fields[name]) fields[name] = msg;\n }\n return { fields, ...payload };\n }\n const nested = b.error && typeof b.error === \"object\" ? text((b.error as Record<string, unknown>).message) : undefined;\n return { reason: text(b.detail) ?? text(b.message) ?? text(b.error) ?? nested, ...payload };\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\n/** A sentence ends once: \"…absolute path\" and \"…absolute path.\" both end in one full stop. */\nconst sentence = (s: string) => (/[.!?…]$/.test(s) ? s : `${s}.`);\n\nfunction refused(error: HttpError) {\n if (error.reason) return `The request was refused: ${sentence(error.reason)}`;\n if (Object.keys(error.fieldErrors).length) return \"The request was refused: check the fields marked.\";\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 (with the server's reason for a 4xx), 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 (with the server's reason for a 4xx), 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\n/** Messages for individual fields carried by what was thrown: an `HttpError`'s `fieldErrors`, else none. */\nexport function fieldErrorsOf(error: unknown): Readonly<Record<string, string>> {\n return error instanceof HttpError ? error.fieldErrors : {};\n}\n\n/** The payload of an error from the server as the type the app expects (`errorPayload<{ running: string }>(error)`), or `undefined` when it is not an `HttpError` or carries none. The type is the caller's claim: check it against the API's schema. */\nexport function errorPayload<T>(error: unknown): T | undefined {\n return error instanceof HttpError ? (error.payload as T | undefined) : undefined;\n}\n"],"mappings":";;;;;;;AAOA,SAAgB,QAAiB;CAC/B,IAAI;EACF,OAAA,QAAA,IAAA,aAAgC;CAClC,QAAQ;EACN,OAAO;CACT;AACF;;ACaA,IAAa,iBAAiB,IAC5B,oRACA;CACE,UAAU;EACR,SAAS;GACP,SAAS;GACT,SAAS;GACT,WAAW;GACX,OAAO;GACP,aAAa;GACb,MAAM;EACR;E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c,kBAAkB;AAC7F;;AAGA,IAAa,qBAAoC,UAC/C,iBAAiB,YACb,MAAM,UAAU,MACd,gCAAgC,MAAM,OAAO,2BAC7C,QAAQ,KAAK,IACf,iBAAiB,SAAS,MAAM,UAC9B,MAAM,UACN;;AAGR,IAAa,uBAAuB,UAClC,iBAAiB,YACb,MAAM,UAAU,MACd,gCAAgC,MAAM,OAAO,MAC7C,QAAQ,KAAK,IACf,iBAAiB,SAAS,MAAM,UAC9B,MAAM,UACN,KAAA;;AAGR,SAAgB,cAAc,OAAkD;CAC9E,OAAO,iBAAiB,YAAY,MAAM,cAAc,CAAC;AAC3D;;AAGA,SAAgB,aAAgB,OAA+B;CAC7D,OAAO,iBAAiB,YAAa,MAAM,UAA4B,KAAA;AACzE"}
|
|
@@ -4,6 +4,7 @@ import * as React from "react";
|
|
|
4
4
|
import { Label, Radio, RadioGroup, Tooltip, TooltipTrigger } from "react-aria-components";
|
|
5
5
|
import { ArrowBigUp, ArrowDown, ArrowLeft, ArrowRight, ArrowUp, ChevronUp, CircleAlert, Command, Option } from "lucide-react";
|
|
6
6
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
7
|
+
import { useSearchParams } from "react-router";
|
|
7
8
|
// src/lib/utils.ts
|
|
8
9
|
var typeSteps = [
|
|
9
10
|
"caption",
|
|
@@ -98,6 +99,33 @@ function Tooltip$1({ label, hint, children, side = "top", delay = 500, open, cla
|
|
|
98
99
|
})]
|
|
99
100
|
});
|
|
100
101
|
}
|
|
102
|
+
// src/lib/search-param.ts
|
|
103
|
+
/**
|
|
104
|
+
* One value held in a URL search parameter (React Router): `const [mode, setMode] = useSearchParam("mode", { default: "all", parse: isMode })`.
|
|
105
|
+
* Reads and validates it, drops the param when set to the default or `null`, keeps the others, and replaces the history entry by default.
|
|
106
|
+
*/
|
|
107
|
+
function useSearchParam(key, { default: fallback, parse, replace = true }) {
|
|
108
|
+
const [params, setParams] = useSearchParams();
|
|
109
|
+
const raw = params.get(key);
|
|
110
|
+
let value = fallback;
|
|
111
|
+
if (raw !== null) {
|
|
112
|
+
const parsed = parse ? parse(raw) : raw;
|
|
113
|
+
if (parsed === true) value = raw;
|
|
114
|
+
else if (typeof parsed === "string") value = parsed;
|
|
115
|
+
}
|
|
116
|
+
const set = React.useCallback((next) => setParams((p) => {
|
|
117
|
+
const out = new URLSearchParams(p);
|
|
118
|
+
if (next === null || next === fallback) out.delete(key);
|
|
119
|
+
else out.set(key, next);
|
|
120
|
+
return out;
|
|
121
|
+
}, { replace }), [
|
|
122
|
+
key,
|
|
123
|
+
fallback,
|
|
124
|
+
replace,
|
|
125
|
+
setParams
|
|
126
|
+
]);
|
|
127
|
+
return [value, set];
|
|
128
|
+
}
|
|
101
129
|
// src/lib/control.ts
|
|
102
130
|
/** The height class of each control size. */
|
|
103
131
|
var controlHeight = {
|
|
@@ -193,15 +221,60 @@ function Textarea({ className, id, ...props }) {
|
|
|
193
221
|
});
|
|
194
222
|
}
|
|
195
223
|
/** The platform select, styled. The default for short lists, especially on touch screens. `size="sm"` is --control-h-sm. */
|
|
196
|
-
function NativeSelect(
|
|
224
|
+
function NativeSelect(props) {
|
|
225
|
+
return props.param === void 0 ? /* @__PURE__ */ jsx(PlainSelect, { ...props }) : /* @__PURE__ */ jsx(ParamSelect, { ...props });
|
|
226
|
+
}
|
|
227
|
+
function PlainSelect({ className, id, size = "default", ...props }) {
|
|
197
228
|
return /* @__PURE__ */ jsx("select", {
|
|
198
229
|
...useField(id),
|
|
199
230
|
className: cn(control, controlHeight[size], "pr-8", className),
|
|
200
231
|
...props
|
|
201
232
|
});
|
|
202
233
|
}
|
|
234
|
+
/** The values of every `<option>`, looking inside `<optgroup>`s and fragments. */
|
|
235
|
+
function optionValues(children) {
|
|
236
|
+
return React.Children.toArray(children).flatMap((c) => {
|
|
237
|
+
if (!React.isValidElement(c)) return [];
|
|
238
|
+
if (c.type === "option") return [c.props.value ?? String(c.props.children)];
|
|
239
|
+
return optionValues(c.props.children);
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
function ParamSelect({ param, paramDefault, onChange, children, ...props }) {
|
|
243
|
+
const options = optionValues(children);
|
|
244
|
+
const [value, setValue] = useSearchParam(param, {
|
|
245
|
+
default: paramDefault,
|
|
246
|
+
parse: (raw) => options.length === 0 || options.includes(raw)
|
|
247
|
+
});
|
|
248
|
+
return /* @__PURE__ */ jsx(PlainSelect, {
|
|
249
|
+
...props,
|
|
250
|
+
value,
|
|
251
|
+
onChange: (e) => {
|
|
252
|
+
setValue(e.target.value);
|
|
253
|
+
onChange?.(e.target.value);
|
|
254
|
+
},
|
|
255
|
+
children
|
|
256
|
+
});
|
|
257
|
+
}
|
|
203
258
|
/** 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. */
|
|
204
|
-
function ChoiceGroup(
|
|
259
|
+
function ChoiceGroup(props) {
|
|
260
|
+
return props.param === void 0 ? /* @__PURE__ */ jsx(ChoiceGroupView, { ...props }) : /* @__PURE__ */ jsx(ParamChoiceGroup, { ...props });
|
|
261
|
+
}
|
|
262
|
+
function ParamChoiceGroup({ param, choices, onChange, ...props }) {
|
|
263
|
+
const [value, setValue] = useSearchParam(param, {
|
|
264
|
+
default: choices[0]?.value ?? "",
|
|
265
|
+
parse: (raw) => choices.some((c) => c.value === raw)
|
|
266
|
+
});
|
|
267
|
+
return /* @__PURE__ */ jsx(ChoiceGroupView, {
|
|
268
|
+
...props,
|
|
269
|
+
choices,
|
|
270
|
+
value,
|
|
271
|
+
onChange: (next) => {
|
|
272
|
+
setValue(next);
|
|
273
|
+
onChange?.(next);
|
|
274
|
+
}
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
function ChoiceGroupView({ legend, name, choices, value, onChange, error }) {
|
|
205
278
|
const errorId = React.useId();
|
|
206
279
|
return /* @__PURE__ */ jsxs(RadioGroup, {
|
|
207
280
|
name,
|
|
@@ -243,6 +316,6 @@ function ChoiceGroup({ legend, name, choices, value, onChange, error }) {
|
|
|
243
316
|
]
|
|
244
317
|
});
|
|
245
318
|
}
|
|
246
|
-
export { Textarea as a,
|
|
319
|
+
export { Textarea as a, useSearchParam as c, cn as d, typeSteps as f, NativeSelect as i, Tooltip$1 as l, Field as n, useFieldControl as o, Input$1 as r, controlHeight as s, ChoiceGroup as t, KeyText as u };
|
|
247
320
|
|
|
248
|
-
//# sourceMappingURL=field-
|
|
321
|
+
//# sourceMappingURL=field-QCCmWTuY.js.map
|