strata-react 1.3.19 → 1.3.21
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 +32 -7
- package/UPGRADING.md +10 -1
- package/dist/{errors-jep2voNI.js → button-KGJI6jQr.js} +3 -95
- package/dist/button-KGJI6jQr.js.map +1 -0
- package/dist/components/byte-view.d.ts +32 -0
- package/dist/components/composition.d.ts +10 -1
- package/dist/components/console.d.ts +34 -0
- package/dist/components/disclosure.d.ts +2 -0
- package/dist/components/file-intake.d.ts +9 -0
- package/dist/components/hotkeys.d.ts +4 -0
- package/dist/components/pixel-image.d.ts +29 -0
- package/dist/components/shortcut-editor.d.ts +44 -0
- package/dist/components/tree.d.ts +4 -2
- package/dist/components/workspace.d.ts +22 -2
- package/dist/errors-BUvY1Z4d.js +95 -0
- package/dist/errors-BUvY1Z4d.js.map +1 -0
- package/dist/{field-t4Hoer0d.js → field-BjeE_FeB.js} +6 -101
- package/dist/field-BjeE_FeB.js.map +1 -0
- package/dist/index.d.ts +8 -3
- package/dist/index.js +963 -14
- package/dist/index.js.map +1 -1
- package/dist/lib/object-url.d.ts +2 -0
- package/dist/map.js +3 -2
- package/dist/map.js.map +1 -1
- package/dist/{microphone-B5ITwm4G.js → microphone-Bo3WaXgD.js} +5 -3
- package/dist/{microphone-B5ITwm4G.js.map → microphone-Bo3WaXgD.js.map} +1 -1
- package/dist/panorama.js +3 -3
- package/dist/scene/camera.d.ts +71 -0
- package/dist/scene/index.d.ts +2 -0
- package/dist/scene/scene-viewport.d.ts +46 -0
- package/dist/scene.js +526 -0
- package/dist/scene.js.map +1 -0
- package/dist/strata.bare.css +1 -0
- package/dist/strata.css +1 -0
- package/dist/strata.migrate.css +1 -0
- package/dist/testing/index.d.ts +1 -0
- package/dist/testing/layout.d.ts +1 -1
- package/dist/testing/setup.d.ts +14 -0
- package/dist/testing.js +21 -5
- package/dist/testing.js.map +1 -1
- package/dist/{theme-DXacprlw.js → theme-CxYZkUNk.js} +3 -2
- package/dist/{theme-DXacprlw.js.map → theme-CxYZkUNk.js.map} +1 -1
- package/dist/tooltip-DhqrDtyu.js +103 -0
- package/dist/tooltip-DhqrDtyu.js.map +1 -0
- package/dist/{value-controls-DB5l5Qe2.js → value-controls-Dq2-QpvA.js} +8 -4
- package/dist/value-controls-Dq2-QpvA.js.map +1 -0
- package/package.json +6 -1
- package/dist/errors-jep2voNI.js.map +0 -1
- package/dist/field-t4Hoer0d.js.map +0 -1
- package/dist/value-controls-DB5l5Qe2.js.map +0 -1
package/README.md
CHANGED
|
@@ -40,10 +40,20 @@ it against the built files:
|
|
|
40
40
|
| `strata-react/map` | `leaflet` (optional peer, `^1.9.4`) | `RouteMap`: themed routes and a moving position on the tiles an app supplies |
|
|
41
41
|
| `strata-react/hls` | `hls.js` (optional peer, `^1.6.0`) | `attachHls` for `MediaPlayer attach` and `useAttachedSource`: HLS through hls.js wherever the browser has Media Source Extensions (the element's own where not), recovered quietly where it can be, and a stream still being made |
|
|
42
42
|
| `strata-react/panorama` | none | `PanoramaViewer`: a 360 (equirectangular) picture or video as a window you pan and zoom, WebGL2 with a flat fallback; its own entry so an app with no 360 ships no GL code |
|
|
43
|
+
| `strata-react/scene` | none | `SceneViewport`: the frame, input and camera for a 3D scene the app draws (WebGL2); its own entry so an app with no 3D ships none of it |
|
|
43
44
|
| `strata-react/visual`, `strata-visual` | `playwright` (exact version), `msw`, `vite` | The screenshot runner; see [Visual regression for apps](#visual-regression-for-apps) |
|
|
44
45
|
|
|
45
46
|
The map, HLS, testing and visual entries need optional peers: an app that never imports those entries never needs them.
|
|
46
47
|
|
|
48
|
+
**pnpm 12** will not install a version younger than its `minimumReleaseAge`, and strata-react releases on every merge, so a fresh release is skipped until it is old enough (pnpm then adds that one version to `minimumReleaseAgeExclude`, which exempts only it). To take each release as it comes, exempt the package once in `pnpm-workspace.yaml`:
|
|
49
|
+
|
|
50
|
+
```yaml
|
|
51
|
+
minimumReleaseAgeExclude:
|
|
52
|
+
- strata-react
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
The alternative is to accept the wait on every release.
|
|
56
|
+
|
|
47
57
|
**An unreleased commit** can be installed from GitHub with
|
|
48
58
|
`npm install github:jburnhams/strata-react#<sha>`. npm then runs `prepare`, which installs every
|
|
49
59
|
dev dependency and builds the package, so it is slow and also needs Node 26.
|
|
@@ -158,7 +168,18 @@ function KilnRoom() {
|
|
|
158
168
|
|
|
159
169
|
### Testing with Vitest, or with Jest
|
|
160
170
|
|
|
161
|
-
strata-react is ESM-only (`exports` has only `import`), as is its peer `react-router`. **Vitest is the supported runner**: it needs no configuration beyond the `strata-react/testing` helpers.
|
|
171
|
+
strata-react is ESM-only (`exports` has only `import`), as is its peer `react-router`. **Vitest is the supported runner**: it needs no configuration beyond the `strata-react/testing` helpers. Its setup file is these lines (MSW's server lifecycle is the app's own, beside them):
|
|
172
|
+
|
|
173
|
+
```ts
|
|
174
|
+
// tests/setup.ts
|
|
175
|
+
import "@testing-library/jest-dom/vitest";
|
|
176
|
+
import { afterEach } from "vitest";
|
|
177
|
+
import { setupStrataTests } from "strata-react/testing";
|
|
178
|
+
|
|
179
|
+
setupStrataTests({ afterEach }); // layout shims, then after each test: unmount, clear toasts, forget loaded thumbnails
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
With Vitest's `globals` off (its default) Testing Library does not clean up by itself, so without this each `renderRoutes` stacks on the last and a role query finds the same tree twice. The shims do nothing where there is no DOM, so the same file can serve `// @vitest-environment node` tests. An app on Jest has to do the work itself (strata-vid's `jest.base.config.js` is a working example): transform `.mjs` along with `.js`; leave `strata-react`, `react-router`, `@remix-run`, `cookie-es`, `@tanstack` and `pixelmatch` out of `transformIgnorePatterns` so Babel compiles them; and replace `import.meta` for CommonJS with a small Babel plugin (react-router reads it). Strata's own suite runs on Vitest only, so a Jest setup is the app's to keep working.
|
|
162
183
|
|
|
163
184
|
### An app that already has its own Tailwind colours and sizes
|
|
164
185
|
|
|
@@ -190,17 +211,17 @@ thousands of lines. Such an app imports the same stylesheet **without the reset*
|
|
|
190
211
|
|---|---|---|
|
|
191
212
|
| Actions | `Button`, `IconButton`, `RowAction`, `AsyncButton`, `useAsyncAction` | Default is `outline`; one filled button per view; `IconButton` requires `label`; `RowAction` is named for its row ("Withdraw Tom Ellery"); `AsyncButton` keeps one width through idle, pending, done and error, and announces `error` with its retry label; buttons carry `data-variant` and `AsyncButton` `data-phase` for tests; a `title` is refused (type `never`, and a development warning): a tip is a `Tooltip`, or `IconButton`'s `label` and `hint`; `useAsyncAction` returns `{ phase, run, error, thrown, fieldErrors, clearFieldError }` with a stable `run`, describes an `HttpError` in a sentence with the server's own reason for a 4xx (`describeActionError`, or the product's own `describeError`), and `validate` plus a server's 422 put messages on `fieldErrors` for each `Field` |
|
|
192
213
|
| Form | `Field`, `Input`, `Textarea`, `NativeSelect`, `ChoiceGroup`, `Checkbox` | `Field` wires label, hint, error, `aria-describedby`, `aria-invalid`, and `action` puts a one-field form's button on the control's row with the hint and error under both; `Checkbox` requires `label` and is one target with it, and has a mixed state |
|
|
193
|
-
| Status and figures | `Status`, `Metric`, `MetricStrip`, `Meter`, `crossedThreshold`, `CompositionBar`, `WorkflowSteps`, `WorkflowSummary`, `JobsTable`, `ScheduleTable`, `SystemPanel`, `useSystemInfo`, `PauseButton` | A status is always a word; figures have no icons or sparklines; `Meter` is a `meter` named for what it measures, with its reading in words ("72% used"), threshold notches, and a `Status` word once a threshold is crossed (each threshold must name its state); `CompositionBar` is a stacked bar over a table naming every part, its amount and share, and names the remainder (`total` needs `restLabel`); a part that is there reads "<1%" and keeps a sliver, never "0%"; `JobStatus` is a long-running server job (its `progress` `{ done, total, current }` reads "12 of 40 done, 28 remaining · IMG_0412"; `useJobAction` starts one: busy until the server answers, a "queued" toast with a link to the jobs page, a "finished" toast when it ends): a required word per state beside the app's sentence, a progress bar when the total is known, each failure named with its reason, announced only when the item changes or the job ends; `WorkflowSteps` draws strata-python's shared `WorkflowRun` (`/api/workflows/<pipeline>/subjects/<id>`): each stage's state as a word, when it ran and how long it took, a failed stage's error with Try again, and Approve on a waiting gate (the first is the view's filled button), saying who approved or that its policy did; `JobsTable` is the shared jobs page (`GET /api/jobs`): each job's state as a word with its progress or error, and Cancel or Run again only where they apply. Both take the app's generated `Schema<"WorkflowRun">` and `Schema<"Task">` as they come; `ScheduleTable` is a machine's scheduled jobs (systemd timers, cron), not the queue: each job's last result as a word (OK, Failed, Running, Never run), when it last ran and when it runs next, the last two dropping on a phone; `SystemPanel` is strata-python's `GET /api/system` (`useSystemInfo()` reads it): version and commit, uptime, each folder as a `Meter` on shared disk limits ("Filling up", "Nearly full") or the word Missing, each service Up or Down with the server's reason, and the app's own `facts`; `PauseButton` takes the `Poll` from `usePoll` (passed to `useLoad({ poll })`): a fixed-name "Pause updates" toggle and "Updated 12:00" |
|
|
214
|
+
| Status and figures | `Status`, `Metric`, `MetricStrip`, `Meter`, `crossedThreshold`, `CompositionBar`, `WorkflowSteps`, `WorkflowSummary`, `JobsTable`, `ScheduleTable`, `SystemPanel`, `useSystemInfo`, `PauseButton` | A status is always a word; figures have no icons or sparklines; `Meter` is a `meter` named for what it measures, with its reading in words ("72% used"), threshold notches, and a `Status` word once a threshold is crossed (each threshold must name its state); `CompositionBar` is a stacked bar over a table naming every part, its amount and share, and names the remainder (`total` needs `restLabel`); `other={{ label }}` folds data-driven parts past five into one "Other" part (the four largest stay in order), and a production build folds instead of throwing; a part that is there reads "<1%" and keeps a sliver, never "0%"; `JobStatus` is a long-running server job (its `progress` `{ done, total, current }` reads "12 of 40 done, 28 remaining · IMG_0412"; `useJobAction` starts one: busy until the server answers, a "queued" toast with a link to the jobs page, a "finished" toast when it ends): a required word per state beside the app's sentence, a progress bar when the total is known, each failure named with its reason, announced only when the item changes or the job ends; `WorkflowSteps` draws strata-python's shared `WorkflowRun` (`/api/workflows/<pipeline>/subjects/<id>`): each stage's state as a word, when it ran and how long it took, a failed stage's error with Try again, and Approve on a waiting gate (the first is the view's filled button), saying who approved or that its policy did; `JobsTable` is the shared jobs page (`GET /api/jobs`): each job's state as a word with its progress or error, and Cancel or Run again only where they apply. Both take the app's generated `Schema<"WorkflowRun">` and `Schema<"Task">` as they come; `ScheduleTable` is a machine's scheduled jobs (systemd timers, cron), not the queue: each job's last result as a word (OK, Failed, Running, Never run), when it last ran and when it runs next, the last two dropping on a phone; `SystemPanel` is strata-python's `GET /api/system` (`useSystemInfo()` reads it): version and commit, uptime, each folder as a `Meter` on shared disk limits ("Filling up", "Nearly full") or the word Missing, each service Up or Down with the server's reason, and the app's own `facts`; `PauseButton` takes the `Poll` from `usePoll` (passed to `useLoad({ poll })`): a fixed-name "Pause updates" toggle and "Updated 12:00" |
|
|
194
215
|
| Data | `DataView`, `Load<T>`, `Stale`, `StaleNotice`, `LoadError`, `EmptyState`, `Skeleton`, `Thumbnail`, `ThumbnailSkeleton`, `DataTable`, `TableSkeleton`, `VirtualList`, `InfiniteList`, `LoadMore`, `useInView`, `LineChart` | `DataView` requires skeleton and empty, keeps data on screen under a `StaleNotice` (why, how old, Try again) when a refresh fails, and takes an `error` renderer for an app's own look of a failed read (default `LoadError`, always inside an alert); `Thumbnail` is a remote image in a box of fixed `aspect`, with a skeleton while it loads, the required `missing` words (or a `fallback` drawing, such as an avatar's initial) when it fails or `src` is null, required `alt`, `children` overlaid in its corners, and a request only once it nears the screen (`eager` for the first few); tables, lists and tile grids virtualise from 100 rows, on React Aria's Virtualizer; a `DataTable` is a React Aria table (a `grid`) over TanStack Table's data model; a `DataTable` column with `value` sorts by type with missing values last both ways and draws a placeholder (`missing`, default an en dash); `InfiniteList` loads the next page on approach, with a skeleton for it, a Try again row when it fails and a Show more button for the keyboard, and `scroll="page"` draws a grid that scrolls with the page; `LoadMore` is that next-page row for any list or grid; charts label values directly; `LineChart` can also follow an app's position (`current`), read a value at the pointer or by arrow keys (`readout`, one slider whose value text is the reading), report a picked x (`onPick`) and fill one flat area (`area`); `xLabel` names the x column of its table `Thumbnail`'s `src` may be a list tried in order, `onLoad` can reject a picture that loaded (a host's grey placeholder) and `onMissing` is told once when none worked; with `alt=""` and a `fallback` its missing state is presentational. `LoadMore` and `InfiniteList` can draw the Show more and loading rows the app's way (`more`, `loading`, and `ruled={false}` for no hairlines).; a `DataTable` column's `hideBelow="sm"` hides its header and cells together on a narrow screen (CSS only; a virtualised table drops the column by a media query), never a hand-written `matchMedia` filter |
|
|
195
216
|
| 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 |
|
|
196
217
|
| 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") |
|
|
197
218
|
| 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 |
|
|
198
219
|
| Data loading | `StrataQueryProvider`, `createQueryClient`, `useLoad`, `usePoll`, `useInfiniteLoad`, `useJob`, `useWorkflowRun`, `isWorkflowRunning`, `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; `useLoad({ poll })` with `usePoll({ every })` reads again on an interval until the person pauses it (`PauseButton`), and once at once on resume; `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)`; `useWorkflowRun({ finished })` is `useJob` for a `WorkflowRun`, polling while the run's job (`WorkflowRun.job`) is in a state not in `finished` |
|
|
199
220
|
| 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 only when it is on another origin or `external`) |
|
|
200
|
-
| 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 |
|
|
221
|
+
| Keyboard | `useHotkeys`, `KeysLegend`, `Shortcut`, `useActiveItem`, `ActiveList`, `isTypingTarget`, `useRebindableShortcuts`, `ShortcutEditor`, `keyName` | 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. To let a person rebind the keys, give the same `Shortcut[]` to `useRebindableShortcuts` (remembered under `storageKey`, or handed to `onChange`) and pass its `shortcuts` to `useHotkeys` and `KeysLegend` and its result to `ShortcutEditor`: each action with its keys and a Change that records the next key, a chord refused with the reason (Ctrl, Cmd and Alt belong to the browser), a conflict named with a swap, Reset and Reset all, all said in a polite status |
|
|
201
222
|
| Theme | `ThemeProvider` (`defaultPalette`), `PaletteChoice`, `usePalette`, `paletteScript`, `palettes`, `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 |
|
|
202
223
|
| 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. |
|
|
203
|
-
| 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 |
|
|
224
|
+
| Workspace | `Workspace`, `WorkspaceBar`, `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. `WorkspaceBar` is the one bar across the top (the tool's name as the `h1`, a polite status, the filled action, an end slot for the scheme and palette choice, wrapping on a phone), where `PageHeader` is an app screen's heading and `Toolbar` a row of controls inside a pane. A pane's body is inset by default so an `Inspector` lines up with the pane's name; `flush` draws a tree, table or stage edge to edge. `onFiles` and `acceptLabel` on `Workspace` take files dropped anywhere on the window (`FileDropOverlay`). Each pane is a labelled region |
|
|
204
225
|
| Writes kept while offline | `createOutbox`, `useOutbox`, `useOutboxStarted`, `OutboxStatus`, `isRefusal` | Writes that must not be lost when the connection is (answers in a game played on a tablet whose wifi drops): kept in localStorage (`strata:outbox:<name>`), sent one at a time oldest first, a dependent write (`after`) refused with what it follows; a 4xx is refused and listed with the server's reason until dismissed, anything else (no answer, 5xx, 401/403 from a login, 408, 429) waits and is tried again after 2 s doubling to a minute, at once on `online` or when the page is shown. `add` answers how the first try went (`sent`, `waiting`, `refused`) so a screen goes on without the server. Every write must be idempotent on the server (a client-made id). `OutboxStatus noun="answer"` is the sign: nothing while all is sent, "3 answers kept on this device. The server could not be reached. Trying again at 10:42." with Send now, and the refused list |
|
|
205
226
|
| Items kept for offline | `createReserve`, `useReserve` | The read side of the outbox: items the server made ahead (rounds of play), kept per key in localStorage (`strata:reserve:<name>:<key>`), `size` each. `take(key)` removes and returns the oldest (an item is used once); `refresh(key, fresh)` after a fresh item arrives drops kept items `sameMake(kept, fresh)` calls out of date and tops up in one request when fewer than half remain (one in flight per key; a failure is tried again at the next refresh); `useReserve(reserve, key)` is the count for "6 rounds kept for offline"; `seed` and `clear` for tests and stories. Without storage nothing is kept and `persisted` says so |
|
|
206
227
|
| 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` |
|
|
@@ -220,7 +241,7 @@ thousands of lines. Such an app imports the same stylesheet **without the reset*
|
|
|
220
241
|
| Conversation | `Conversation`, `Composer`, `RichText`; `matchEntities`, `parseRichText` | A question-and-answer thread: answers stream, finish or fail in place (Try again), one polite announcement per finished answer, following only while at the bottom (Jump to latest); answers can carry pictures (`images`, labelled, lazy, linked to full size) that stay visible beside the collapsed "looked up"; a composer that sends on Enter and is disabled with its reason while answering (Stop); a safe text subset (bold, code, lists, http links, never HTML) whose known ids, longest first and whole words only, become buttons |
|
|
221
242
|
| Pictures from a set | `Lightbox` (`useLightboxUrl`), `BookViewer` (`useBookUrl`), `TileGrid`, `BoxOverlay`/`BoxList`/`useBoxes`, `BoxedPicture`, `RegionEditor`; `regionStyle`, `moveRect`, `resizeRect`, `lerpRect`, `turnedSize`, `turnRect`, `readingOrder`, `zoomToBox`, `findPage` | A picture opened from a grid in a full-size `Dialog` (previous/next, arrow keys, "3 of 40" or a position like "Page 22 (12) of 44", zoom and 1:1, details beside it, an overlay and actions for the item, a thumbnail strip, `?view=` in the URL, neighbours preloaded, a `missing` sentence, Compare ticked hand-off); a scanned book read inline as spreads or single pages with printed and scan names, go-to, `?page=` and a strip with badges; a grid of picture tiles that link (`TileGrid`, with `TileGridSkeleton`); read-only boxes on a picture linked to a list beside it, and the picture opened zoomed to one of them (a face in its photo, `BoxedPicture`); one box of a picture shown on its own in a `Thumbnail` (`region`); `RegionEditor` also turns the picture by an angle (the windows turn with it) and edits a spread's gutter; named windows drawn and moved on a picture by pointer, keys and numbers, with aspect and bounds held, and a from/to move with a Watch preview |
|
|
222
243
|
| Sequences | `SequenceTimeline`; `snapToGrid`, `stepOnGrid`, `settleCut` | A gapless strip of windows whose cuts are sliders: dragged or stepped along a beat grid inside the room the app gives, the refusal said in words, both windows' new lengths announced; Shift+click chooses a run |
|
|
223
|
-
| Browsing | `Tree`, `FolderPicker` | A hierarchy that loads as it opens (`current` + `onCurrentChange` is the row in view beside the ticked ones, `count` and `badge` per row, `sortChildren`, `reveal` of a deep link, `resolveBranch` so ticking a year says "2019 and its 91 folders" without opening them; a hook per open node; skeleton, Try again and empty rows; always virtualised); `choices` (from `useChoices`) chooses several: a checkbox per row, Shift ranges, a parent drawn mixed from what has loaded under it (ticking a branch never opened reads and opens it and chooses everything under it), "Select all shown", and rows the choice implies marked "Included because of …" in words and a server folder chooser on it: breadcrumb that is also editable text, Up, recents, New folder with the server's refusal on the field, Choose this folder; a `Folder` may carry a `badge` and `tone` ("project", as words), `canChoose` gives the reason the button is disabled beside it, `chooseLabel` names it, `onOpen` can answer `"choose"` to take a folder at once instead of entering it, and the listing may return a `footer` under the tree |
|
|
244
|
+
| Browsing | `Tree`, `FolderPicker` | A hierarchy that loads as it opens (`current` + `onCurrentChange` is the row in view beside the ticked ones, `count` and `badge` per row, `sortChildren`, `reveal` of a deep link (its ancestors are written into `useExpanded({ param })`'s URL), `branchPress="toggle"` so pressing a folder's name opens it and only files are chosen, `resolveBranch` so ticking a year says "2019 and its 91 folders" without opening them; a hook per open node; skeleton, Try again and empty rows; always virtualised); `choices` (from `useChoices`) chooses several: a checkbox per row, Shift ranges, a parent drawn mixed from what has loaded under it (ticking a branch never opened reads and opens it and chooses everything under it), "Select all shown", and rows the choice implies marked "Included because of …" in words and a server folder chooser on it: breadcrumb that is also editable text, Up, recents, New folder with the server's refusal on the field, Choose this folder; a `Folder` may carry a `badge` and `tone` ("project", as words), `canChoose` gives the reason the button is disabled beside it, `chooseLabel` names it, `onOpen` can answer `"choose"` to take a folder at once instead of entering it, and the listing may return a `footer` under the tree |
|
|
224
245
|
| Marking text | `MarkableText`, `Mark`, `MarkSummary`; `rangeBetween` | Select words by drag, Shift+click and Shift+arrows (ids in document order, so it holds across virtualised rows), apply the app's marks from a bar or single-key chords, marks drawn by role, pattern and text, summarised and announced |
|
|
225
246
|
| Maps | `strata-react/map`: `RouteMap`; `geo`, `LatLng` (main entry) | Routes and a position that moves along them, on Leaflet (no react-leaflet), behind its own entry. Tiles are the app's (`tiles.light`, `tiles.dark`, each with its attribution); the dark scheme uses the dark set or a filter over the light one. Route colours are roles resolved at draw time; `values` with `colourScale` colour a route by value in runs of one step, with a key that names the steps; a single route gets direction chevrons and start/finish marks (a loop is one mark). The position is one marker moved with `setLatLng`: no route is redrawn for it (keep `routes` stable). As picture content (a route inset over footage): `zoom` sets any zoom (animate it per frame), `follow="centre"` holds the view exactly on a position with no animation (a frame is deterministic), and `positions` draws several, each tied to a route, in its colour and named in the text alternative; routes are not redrawn for any of it. Leaflet's keyboard pan and zoom stay; the map is named by `label` and described by a generated text alternative (routes, lengths, position along). Overlay slots `topEnd` and `bottomStart` avoid Leaflet's own controls and attribution. Leaflet's stylesheet is injected once, so an app imports nothing. `geo` (distance, bearing, bounds, `pointAlong`, `arrows`, `ends`) and `format.distance` need no map library |
|
|
226
247
|
| Timeline | `Timeline`, `useTimelineZoom`, `TimelineZoomControls`, `noOverlap` | Items with a start and a length in lanes on a zoomable time axis, for media edits, bookings, rotas and plans. The timeline draws and the app decides: every move, trim, lane change, selection and current-time change is reported (`onItemChange`, `onSelect`, `onPositionChange`) and the app applies it; `validate` refuses a change with a reason shown in words while it is made. One tab stop for the items; arrows move between them, Ctrl+arrows nudge and change lane, Alt+arrows trim, the current time is its own slider, `+` `-` `0` zoom, and each change is announced ("run-02.mp4 moved to 0:13"). The ruler picks steps people write on a scale so labels never collide. Lanes take drops from outside (`dropTypes`, `onDrop` with the lane and snapped time, `validateDrop`, and React Aria's keyboard drag landing at the current time), `laneRows` makes them taller, `kindColours` fixes each kind's stripe, and the header column fits its content. Only items near the view are rendered |
|
|
@@ -228,11 +249,15 @@ thousands of lines. Such an app imports the same stylesheet **without the reset*
|
|
|
228
249
|
| Answering by placing | `PlaceBoard`, `PlaceState` | An answer that is an arrangement (give a number, put in order, match pairs, sort), for someone who may not read yet. Two taps: pick a piece up (`aria-pressed`, "Picked up"), put it in a place ("Put apple in the basket"); tap it again to put it down, "Put … back" returns a placed one. Same presses by touch, mouse, keyboard and screen reader; places are disabled until a piece is held, so Tab walks the pieces, then the places; focus follows a moved piece. The app owns `placement`, applies `onMove` and checks; `placeState` marks a place `right` or `wrong` (neutral, never red) with its word, `locked` ends the round. Pieces 96px or more in the pile, 72px once placed |
|
|
229
250
|
| Sortable list | `SortableList` | Reorder a list and move items between lists, by pointer and by keyboard. React Aria's `GridList` with `useDragAndDrop` (no `@dnd-kit`): a grip per row is the drag handle, so clicking a row selects it and its own actions still work; Enter on the grip picks up, arrows and Tab choose a position or list, Enter drops, Escape cancels, with React Aria's screen-reader announcements. Items carry a kind (`getKind`); a list takes the kinds in `accepts` and says why it refuses another (`refuses`, shown with an icon while that kind is dragged over it). The list never changes the data: `onReorder` and `onInsert` report the move and the app applies it, undoably |
|
|
230
251
|
| Drag source | `DragSource` | A row that is dragged onto a drop target elsewhere (a `Timeline` lane), by pointer or from the keyboard. React Aria's `useDrag` with a drag button: a grip named "Drag <label>" picks it up with Enter, Tab moves between targets that take its types, Enter drops, Escape cancels, with React Aria's announcements; the pointer can pick up the whole row and the row's own buttons still work. `items` returns the drag's data (`DragData`, a type to a value), read by the target |
|
|
231
|
-
| File intake | `FileButton`, `FileDropZone`, `FileOutcomes`, `MissingFile`, `useFileIntake` | Pick or drop local files, then one outcome per file. `FileButton` is React Aria's `FileTrigger` behind a real named button (the keyboard and phone route); `FileDropZone` is its `DropZone` and says what it takes while a drag is over it; it ignores the app's own drags (every `DragSource`'s, and any type named in `refuseTypes`), so a keyboard drag to a timeline lane does not stop on it. `useFileIntake({ accept, acceptLabel, process })` judges each file after the drop, so a wrong one is named with its reason (type, `maxBytes`, your `check`), runs your own `process` per file (a throw becomes `Failed` with its message and a retry), and never blocks the rest. `FileOutcomes` draws the rows and announces one summary per batch. `MissingFile` is a status word and a "Relink" that opens the picker for that item; the name wraps in a narrow pane and a `thumbnail` can lead it. Nothing assumes a server |
|
|
252
|
+
| File intake | `FileButton`, `FileDropZone`, `FileDropOverlay`, `FileOutcomes`, `MissingFile`, `useFileIntake` | Pick or drop local files, then one outcome per file. `FileButton` is React Aria's `FileTrigger` behind a real named button (the keyboard and phone route); `FileDropZone` is its `DropZone` and says what it takes while a drag is over it; `FileDropOverlay` (also `Workspace onFiles`) is the whole window as the target, with an overlay that names what it takes; it ignores the app's own drags (every `DragSource`'s, and any type named in `refuseTypes`), so a keyboard drag to a timeline lane does not stop on it. `useFileIntake({ accept, acceptLabel, process })` judges each file after the drop, so a wrong one is named with its reason (type, `maxBytes`, your `check`), runs your own `process` per file (a throw becomes `Failed` with its message and a retry), and never blocks the rest. `FileOutcomes` draws the rows and announces one summary per batch. `MissingFile` is a status word and a "Relink" that opens the picker for that item; the name wraps in a narrow pane and a `thumbnail` can lead it. Nothing assumes a server |
|
|
232
253
|
| Inspector | `Inspector`, `InspectorSection`, `PropertyRow`, `PropertyList` | Properties of the selected thing. `Inspector` is a labelled region with the selection's name as its heading and the empty state (`empty`, required) when `title` is `null`; `selectionKey` gives a new selection fresh controls and keeps focus in the panel. `InspectorSection` is React Aria's `Disclosure` with the body mounted only while open; open and closed are remembered under `storageKey` (storage that throws just means defaults). `PropertyRow` is a `Field` with a "Reset <label>" that shows only while `modified`. `PropertyList` is a `dl`: missing values print an en dash heard as "Not known", units follow a non-breaking space, long values truncate with the whole value in a tooltip |
|
|
233
254
|
| Feedback | `UndoBar`, `useUndoable`, `Done` | Undo before confirm; the hook owns which rows are out of view (`isRemoved`), a failed commit brings the row back with Try again in the same bar, and `flush()` commits before a dependent action; `Done` is the one celebration, and it must say what happens next |
|
|
234
255
|
| 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; `format.bytes(n, unit?)` writes sizes in decimal units, `{ binary: true }` (or a unit such as "GiB") in KiB, MiB, GiB (`byteUnit` shares one unit across figures); `format.duration(seconds)` ("16 min", "3.5 h", "2 days", or `{ style: "parts" }` for an uptime, "1d 1h 0m"), `format.measure(12.3, "GB")` and `format.agoTick(seconds)` ("−2 min", for a history chart's axis); `format.date(at)` ("8 Nov 2026") and `format.dateTime(at)` ("8 Nov 2026, 06:05"), like `clock`, `day` and `shortDay`, take a Date, ISO string or epoch ms; `format.ago(at, now?)` ("3 weeks ago"), `format.compact(n)` ("1.2k", and `count(n, one, many, { compact: true })`), `format.runningTime(seconds)` ("1:02:09") and `format.share(n)` ("<1%" for a part that rounds to 0); every number and date formatter prints the placeholder (`format.missing`, an en dash) for `null` or `undefined`; `createFormat(locale, { timeZone, missing })` fixes the zone and the placeholder; units and counts join with a non-breaking space |
|
|
235
|
-
|
|
|
256
|
+
| Bytes | `ByteView`, `ByteHighlight`, `ByteRange` | A hex dump for the file no other viewer understands: offsets, sixteen bytes a row and the printable characters, windowed so a 50 MB file scrolls, one tab stop with Left/Right by byte, Up/Down by row, PageUp/PageDown by screen, Home/End, Shift to extend; the range reported as `{ start, end }` (end exclusive) for a decoder beside it; `highlight` tints ranges by tone and names them in the status |
|
|
257
|
+
| Pictures from bytes | `PixelImage`, `pixelZoom`, `rgbaToBlob`, `useObjectUrl` | A decoded RGBA buffer (or `ImageData`) on a canvas at a whole-number zoom with square pixels and a checkerboard behind clear ones, named with its size; `useObjectUrl(bytes \| Blob, type)` is a URL for `MediaPlayer`, `Thumbnail` or a download, revoked when the value changes or the component unmounts |
|
|
258
|
+
| Console | `Console`, `ConsoleLine`, `ConsoleLevel` | A command line over a polite `log` that is virtualised from 100 lines and pinned to the end unless scrolled up: levels as words (`Warning`, `Error`), an echo of the command, history with Up and Down kept under `historyKey`, Tab completion from the app's `complete` |
|
|
259
|
+
| 3D scene | `strata-react/scene`: `SceneViewport`, `useOrbitCamera`, `frameFor`, `describeCamera`, camera maths | A frame for a scene the app draws in WebGL2: `render(gl, frame)` runs on change (frame has the view, projection and eye), orbit by drag, pan by right drag or Shift, zoom by Ctrl/Cmd+wheel or pinch (a plain wheel scrolls the page), arrows, `+` `-` `0`, a Reset button (animated unless motion is reduced), `mode="fly"` for a walkthrough, a lost context restored (`frame.context` counts them), the camera in words; its own entry, no dependency |
|
|
260
|
+
| Testing | `strata-react/testing`: `renderWithStrata`, `renderRoutes`, `createTestQueryClient`, `installLayoutShims`, `setupStrataTests`, `installFakeIntersectionObserver`, `filledButtons`, `expectOneFilledButton`, `asyncButtonPhase` | Router + query client around Testing Library's `render`; `renderRoutes(routes, { route, basename })` renders the app's own `RouteObject[]` in a memory data router, so layout routes, redirects, loaders and error elements run, and returns the `router` (where a redirect landed is `router.state.location`) and an act-wrapped `navigate`; a fixed box and ResizeObserver so measuring components render in jsdom (a no-op without a DOM, so a setup file shared with node-environment tests is safe); `setupStrataTests({ afterEach })` is the one setup call (the layout shims, and after each test unmounting, the toast queue and loaded thumbnails: Testing Library only cleans up by itself when Vitest's `globals` are on); an IntersectionObserver the test fires with `scrollToEnd()` or `intersect(el)`; `filledButtons()` and `expectOneFilledButton()` check "one filled button per view" from `data-variant`, and `asyncButtonPhase(el)` reads an `AsyncButton`'s phase. Role names keep the non-breaking space from `format.count`, so match them with the same call or a `\s` regex |
|
|
236
261
|
| API types | `strata-react/api-types` and the `strata-api-types` command | See "API types from the server" below |
|
|
237
262
|
| Visual regression | `strata-react/visual` and the `strata-visual` command | Screenshots an app's Storybook and its routes in each MSW state, light and dark, against baselines in the app's repo |
|
|
238
263
|
|
package/UPGRADING.md
CHANGED
|
@@ -11,7 +11,16 @@ time. While the version is 0.x, any release may break.
|
|
|
11
11
|
|
|
12
12
|
Every PR that changes what an app sees adds a line here (see `CLAUDE.md`, "Changelog").
|
|
13
13
|
|
|
14
|
-
## 2026-11-25 (
|
|
14
|
+
## 2026-11-25 (CompositionBar, #377)
|
|
15
|
+
- `CompositionBar` no longer crashes a production build when a sixth part has no `colour`: it folds the smallest into "Other" and logs `console.error`. Development and tests still throw. Parts that come from data should pass `other={{ label }}` to fold on purpose; a test that expected the throw under `NODE_ENV=production` now sees the folded bar.
|
|
16
|
+
|
|
17
|
+
## 2026-11-25 (twelve issues, #359–#370)
|
|
18
|
+
- **`Pane`'s body is inset** (`p-3`, the header's own padding) so an `Inspector` or text lines up with the pane's name (#366). A pane that holds a tree, table, list or stage drawn to the edge adds `flush`; a pane whose content you inset yourself (`className="p-3"` on the child) can delete that. Visual baselines with a `Pane` move.
|
|
19
|
+
- `Expanded` (from `useExpanded`) has a new member, `toggle(key)` (#364): an `Expanded` you build by hand in a test or story must supply it. `Tree`'s new `branchPress="toggle"` makes pressing a folder's row open it instead of choosing it; the default (`"select"`) is unchanged.
|
|
20
|
+
- `installLayoutShims()` returns a no-op where there is no DOM (#363), so a setup file shared with `// @vitest-environment node` tests no longer throws. New `setupStrataTests({ afterEach })` in `strata-react/testing` is the one setup call (shims, then after each test: unmount, clear toasts, forget loaded thumbnails); an app whose Vitest `globals` are off and that had its own `afterEach(cleanup)` can replace it. `strata.bare.css` gains the `image-pixelated` utility.
|
|
21
|
+
- pnpm 12: add `minimumReleaseAgeExclude: [strata-react]` to `pnpm-workspace.yaml` to take each release the day it is cut (#362); README, Install.
|
|
22
|
+
|
|
23
|
+
## 2026-11-25 (thumbnails and polling)
|
|
15
24
|
- A `Thumbnail` for a picture the page has already loaded now asks for it at once when it mounts again, wherever it is, and shows it as soon as the image is there (a `FilmStrip` after a resize, a re-sorted list), instead of waiting near the screen as a skeleton (#352). `renderWithStrata` and `renderRoutes` reset this per test; a test using plain `render` that expects no request for a repeated `src` before it scrolls near sees one (call `forgetLoadedThumbnails`).
|
|
16
25
|
|
|
17
26
|
- `Poll` has a new member, `with({ every })` (#349): a read with its own pace takes `useLoad({ poll: poll.with({ every: 60_000 }) })` and keeps the page's pause, resume and "updated" time. A `Poll` you build by hand (in a test or story) must now supply `with`; one from `usePoll` already has it.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { r as cn, t as Tooltip$1 } from "./tooltip-DhqrDtyu.js";
|
|
2
2
|
import * as React from "react";
|
|
3
3
|
import { Button } from "react-aria-components";
|
|
4
4
|
import { cva } from "class-variance-authority";
|
|
@@ -143,98 +143,6 @@ function RowAction({ label, subject, icon: Icon, variant = "ghost", size = "sm",
|
|
|
143
143
|
children: [Icon && /* @__PURE__ */ jsx(Icon, { "aria-hidden": true }), label]
|
|
144
144
|
});
|
|
145
145
|
}
|
|
146
|
-
|
|
147
|
-
/** Thrown by `fetchJson` on a non-2xx response; carries the status, the response body and the server's reason for `describeHttpError` and `describeActionError`. */
|
|
148
|
-
var HttpError = class extends Error {
|
|
149
|
-
status;
|
|
150
|
-
statusText;
|
|
151
|
-
url;
|
|
152
|
-
body;
|
|
153
|
-
/** The server's sentence for why it refused, from the body (`detail`, `message`, `error`), if it gave one. */
|
|
154
|
-
reason;
|
|
155
|
-
/** Messages for individual fields from the body (FastAPI's 422 `detail: [{loc, msg}]`), keyed by field name. Empty when there are none. */
|
|
156
|
-
fieldErrors;
|
|
157
|
-
/** The body's `payload`, when it has one (`{ detail, payload }`): data for the app, not words for the person. Read it typed with `errorPayload`. */
|
|
158
|
-
payload;
|
|
159
|
-
constructor(status, statusText, url, body, found = readErrorBody(body)) {
|
|
160
|
-
super(`${status} ${statusText} from ${url}`);
|
|
161
|
-
this.status = status;
|
|
162
|
-
this.statusText = statusText;
|
|
163
|
-
this.url = url;
|
|
164
|
-
this.body = body;
|
|
165
|
-
this.name = "HttpError";
|
|
166
|
-
this.reason = found.reason;
|
|
167
|
-
this.fieldErrors = found.fields ?? {};
|
|
168
|
-
this.payload = found.payload;
|
|
169
|
-
}
|
|
170
|
-
};
|
|
171
|
-
var text = (value) => typeof value === "string" && value.trim() ? value.trim() : void 0;
|
|
172
|
-
/** A field name from a FastAPI/pydantic `loc`: the path after where it came from (`["body", "address", "city"]` is `"address.city"`). */
|
|
173
|
-
function fieldName(loc) {
|
|
174
|
-
if (!Array.isArray(loc)) return void 0;
|
|
175
|
-
const path = loc.map(String);
|
|
176
|
-
if ([
|
|
177
|
-
"body",
|
|
178
|
-
"query",
|
|
179
|
-
"path",
|
|
180
|
-
"header",
|
|
181
|
-
"cookie",
|
|
182
|
-
"form"
|
|
183
|
-
].includes(path[0]) && path.length > 1) path.shift();
|
|
184
|
-
return path.join(".") || void 0;
|
|
185
|
-
}
|
|
186
|
-
/**
|
|
187
|
-
* The default reading of an error body, for the shapes most JSON APIs use: `{ detail: "…" }`
|
|
188
|
-
* (FastAPI), `{ message: "…" }`, `{ error: "…" }` or `{ error: { message: "…" } }` for the reason,
|
|
189
|
-
* and FastAPI's validation list `{ detail: [{ loc, msg }] }` for per-field messages. A short
|
|
190
|
-
* plain-text body (not HTML) is taken as the reason too. Pass your own to `fetchJson` for other APIs.
|
|
191
|
-
*/
|
|
192
|
-
function readErrorBody(body) {
|
|
193
|
-
if (typeof body === "string") {
|
|
194
|
-
const t = text(body);
|
|
195
|
-
return t && t.length <= 300 && !t.startsWith("<") ? { reason: t } : {};
|
|
196
|
-
}
|
|
197
|
-
if (!body || typeof body !== "object") return {};
|
|
198
|
-
const b = body;
|
|
199
|
-
const payload = b.payload !== void 0 && b.payload !== null ? { payload: b.payload } : {};
|
|
200
|
-
if (Array.isArray(b.detail)) {
|
|
201
|
-
const fields = {};
|
|
202
|
-
for (const item of b.detail) {
|
|
203
|
-
const entry = item;
|
|
204
|
-
const name = fieldName(entry?.loc);
|
|
205
|
-
const msg = text(entry?.msg);
|
|
206
|
-
if (name && msg && !fields[name]) fields[name] = msg;
|
|
207
|
-
}
|
|
208
|
-
return {
|
|
209
|
-
fields,
|
|
210
|
-
...payload
|
|
211
|
-
};
|
|
212
|
-
}
|
|
213
|
-
const nested = b.error && typeof b.error === "object" ? text(b.error.message) : void 0;
|
|
214
|
-
return {
|
|
215
|
-
reason: text(b.detail) ?? text(b.message) ?? text(b.error) ?? nested,
|
|
216
|
-
...payload
|
|
217
|
-
};
|
|
218
|
-
}
|
|
219
|
-
/** A sentence ends once: "…absolute path" and "…absolute path." both end in one full stop. */
|
|
220
|
-
var sentence = (s) => /[.!?…]$/.test(s) ? s : `${s}.`;
|
|
221
|
-
function refused(error) {
|
|
222
|
-
if (error.reason) return `The request was refused: ${sentence(error.reason)}`;
|
|
223
|
-
if (Object.keys(error.fieldErrors).length) return "The request was refused: check the fields marked.";
|
|
224
|
-
return `The request was refused (${error.status}): ${error.statusText || "no reason given"}.`;
|
|
225
|
-
}
|
|
226
|
-
/** 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. */
|
|
227
|
-
var describeHttpError = (error) => error instanceof HttpError ? error.status >= 500 ? `The server could not answer (${error.status}). Nothing was changed.` : refused(error) : error instanceof Error && error.message ? error.message : "The data could not be loaded. Nothing was changed.";
|
|
228
|
-
/** 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). */
|
|
229
|
-
var describeActionError = (error) => error instanceof HttpError ? error.status >= 500 ? `The server could not answer (${error.status}).` : refused(error) : error instanceof Error && error.message ? error.message : void 0;
|
|
230
|
-
/** Messages for individual fields carried by what was thrown: an `HttpError`'s `fieldErrors`, else none. */
|
|
231
|
-
function fieldErrorsOf(error) {
|
|
232
|
-
return error instanceof HttpError ? error.fieldErrors : {};
|
|
233
|
-
}
|
|
234
|
-
/** 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. */
|
|
235
|
-
function errorPayload(error) {
|
|
236
|
-
return error instanceof HttpError ? error.payload : void 0;
|
|
237
|
-
}
|
|
238
|
-
export { fieldErrorsOf as a, IconButton as c, isDev as d, useInView as f, 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 };
|
|
146
|
+
export { isDev as a, buttonVariants as i, IconButton as n, useInView as o, RowAction as r, Button$1 as t };
|
|
239
147
|
|
|
240
|
-
//# sourceMappingURL=
|
|
148
|
+
//# sourceMappingURL=button-KGJI6jQr.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"button-KGJI6jQr.js","names":["Button","AriaButton","Tooltip"],"sources":["../src/lib/in-view.ts","../src/lib/dev.ts","../src/components/button.tsx"],"sourcesContent":["import * as React from \"react\";\n\n// One IntersectionObserver hook for everything that waits until it is near the screen: the\n// sentinel at the end of an InfiniteList and an image in a Thumbnail. Both watch from the nearest\n// `[data-strata-scroll]` region (a VirtualList's) or else the viewport, with a root\n// margin so the work starts before the element is reached. They differ in two ways, which are\n// options rather than two hooks:\n//\n// - `once`: an image, once asked for, stays asked for; scrolling it away again must not unload it.\n// A sentinel reports in and out of view every time.\n// - `unsupported`: where there is no IntersectionObserver (an old browser, a test without the\n// fake), an image loads at once, because a photo that never loads is worse than one loaded\n// early. A sentinel reports out of view, because InfiniteList's Show more button is the path\n// that always works.\n\n/** Options for {@link useInView}. */\nexport type InViewOptions = {\n /** Watch only while this is true. Default true. */\n active?: boolean;\n /** How far outside the scroll region still counts as in view (IntersectionObserver `rootMargin`). */\n rootMargin?: string;\n /** Stay in view after the first time, and stop watching. */\n once?: boolean;\n /** What to report where `IntersectionObserver` does not exist. Default false. */\n unsupported?: boolean;\n};\n\n/**\n * Whether an element is within `rootMargin` of its scroll region (the nearest\n * `[data-strata-scroll]` ancestor, else the viewport). Returns a callback ref, so it follows the\n * element as it mounts and unmounts.\n */\nexport function useInView({ active = true, rootMargin = \"0px\", once = false, unsupported = false }: InViewOptions = {}) {\n const [inView, setInView] = React.useState(false);\n const [el, setEl] = React.useState<Element | null>(null);\n const seen = once && inView;\n React.useEffect(() => {\n if (seen) return;\n if (!active || !el) {\n setInView(false);\n return;\n }\n if (typeof IntersectionObserver === \"undefined\") {\n setInView(unsupported);\n return;\n }\n const root = el.parentElement?.closest<HTMLElement>(\"[data-strata-scroll]\") ?? null;\n const observer = new IntersectionObserver((entries) => setInView(entries[entries.length - 1].isIntersecting), { root, rootMargin });\n observer.observe(el);\n return () => observer.disconnect();\n }, [active, el, rootMargin, seen, unsupported]);\n return { ref: setEl, inView };\n}\n","// 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"],"mappings":";;;;;;;;;;;AAgCA,SAAgB,UAAU,EAAE,SAAS,MAAM,aAAa,OAAO,OAAO,OAAO,cAAc,UAAyB,CAAC,GAAG;CACtH,MAAM,CAAC,QAAQ,aAAa,MAAM,SAAS,KAAK;CAChD,MAAM,CAAC,IAAI,SAAS,MAAM,SAAyB,IAAI;CACvD,MAAM,OAAO,QAAQ;CACrB,MAAM,gBAAgB;EACpB,IAAI,MAAM;EACV,IAAI,CAAC,UAAU,CAAC,IAAI;GAClB,UAAU,KAAK;GACf;EACF;EACA,IAAI,OAAO,yBAAyB,aAAa;GAC/C,UAAU,WAAW;GACrB;EACF;EACA,MAAM,OAAO,GAAG,eAAe,QAAqB,sBAAsB,KAAK;EAC/E,MAAM,WAAW,IAAI,sBAAsB,YAAY,UAAU,QAAQ,QAAQ,SAAS,EAAE,CAAC,cAAc,GAAG;GAAE;GAAM;EAAW,CAAC;EAClI,SAAS,QAAQ,EAAE;EACnB,aAAa,SAAS,WAAW;CACnC,GAAG;EAAC;EAAQ;EAAI;EAAY;EAAM;CAAW,CAAC;CAC9C,OAAO;EAAE,KAAK;EAAO;CAAO;AAC9B;;;AC7CA,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,aAAa,WAAW,oBAAC,QAAD;GAAM,WAAU;GAAoB;EAAe,CAAA,IAAI;CAC7E,CAAA;AAEhB;;AAGA,SAAS,WAAW,OAAgC,UAA2B;CAC7E,IAAI,MAAM,UAAU,KAAA,KAAa,CAAC,OAAO,IAAI,OAAO,GAAG;EACrD,OAAO,IAAI,OAAO;EAClB,QAAQ,KAAK,kMAAkM;CACjN;CACA,MAAM,QAAQ,OAAO,aAAa,WAAW,SAAS,KAAK,IAAI;CAC/D,IAAI,SAAS,MAAM,KAAK,KAAK,CAAC,CAAC,WAAW,KAAK,CAAC,gBAAgB,KAAK,KAAK,KAAK,CAAC,MAAM,iBAAiB,CAAC,MAAM,sBAAsB,CAAC,OAAO,IAAI,OAAO,GAAG;EACxJ,OAAO,IAAI,OAAO;EAClB,QAAQ,KAAK,iDAAiD,MAAM,oFAAoF;CAC1J;AACF;AACA,IAAM,yBAAS,IAAI,IAAY;;AAgB/B,SAAgB,WAAW,EAAE,MAAM,MAAM,OAAO,MAAM,UAAU,SAAS,OAAO,WAAW,GAAG,SAA0B;CACtH,OACE,oBAACC,WAAD;EAAgB;EAAa;EAC3B,UAAA,oBAACF,UAAD;GAAQ,MAAM,SAAS,OAAO,YAAY;GAAiB;GAAS,cAAY;GAAO,GAAI;GACzF,UAAA,oBAAC,MAAD,EAAM,eAAA,KAAa,CAAA;EACb,CAAA;CACD,CAAA;AAEb;;AAmBA,SAAgB,UAAU,EAAE,OAAO,SAAS,MAAM,MAAM,UAAU,SAAS,OAAO,MAAM,WAAW,GAAG,SAAyB;CAG7H,OACE,qBAACA,UAAD;EAAiB;EAAe;EAAM,cAAY,GAAG,MAAM,GAAG;EAAW,WAAW,GAAG,WAAW,SAAS;EAAG,GAAI;EAAlH,UAAA,CACG,QAAQ,oBAAC,MAAD,EAAM,eAAA,KAAa,CAAA,GAC3B,KACK;;AAEZ"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { Tone } from './status';
|
|
2
|
+
import * as React from "react";
|
|
3
|
+
/** A range of bytes the app has understood, drawn tinted; `end` is exclusive, `label` is what the status says of it. */
|
|
4
|
+
export type ByteHighlight = {
|
|
5
|
+
start: number;
|
|
6
|
+
end: number;
|
|
7
|
+
tone?: Tone;
|
|
8
|
+
label?: string;
|
|
9
|
+
};
|
|
10
|
+
/** The selected bytes: `start` to `end`, `end` exclusive. */
|
|
11
|
+
export type ByteRange = {
|
|
12
|
+
start: number;
|
|
13
|
+
end: number;
|
|
14
|
+
};
|
|
15
|
+
export type ByteViewProps = {
|
|
16
|
+
bytes: Uint8Array;
|
|
17
|
+
/** Names the dump: "pak0.pak, raw bytes". The byte count is added to it. */
|
|
18
|
+
label: string;
|
|
19
|
+
/** The address of `bytes[0]`, shown in the offsets column. Default 0. */
|
|
20
|
+
offset?: number;
|
|
21
|
+
/** Ranges to tint and name. */
|
|
22
|
+
highlight?: readonly ByteHighlight[];
|
|
23
|
+
/** The range chosen first. Default none until the person moves or presses. */
|
|
24
|
+
defaultSelection?: ByteRange;
|
|
25
|
+
/** The selected range changed (a press, a drag, a key). */
|
|
26
|
+
onSelectionChange?: (range: ByteRange) => void;
|
|
27
|
+
/** The height of the dump in px. Default 320. */
|
|
28
|
+
height?: number;
|
|
29
|
+
className?: string;
|
|
30
|
+
};
|
|
31
|
+
/** A virtualised hex dump: offsets, sixteen bytes a row and the printable characters, byte and range keyboard, and the selected range reported as `{ start, end }`. */
|
|
32
|
+
export declare function ByteView({ bytes, label, offset, highlight, defaultSelection, onSelectionChange, height, className }: ByteViewProps): React.JSX.Element;
|
|
@@ -15,6 +15,15 @@ export type CompositionBarProps = {
|
|
|
15
15
|
formatValue: (value: number) => string;
|
|
16
16
|
/** Formats a part's share of the whole (0 to 1). Defaults to `format.share` ("<1%" for a part that rounds to 0). */
|
|
17
17
|
formatShare?: (share: number) => string;
|
|
18
|
+
/**
|
|
19
|
+
* Fold the smallest parts into one last part when there are more than five. The four largest keep
|
|
20
|
+
* their given order; the rest are summed under this label (a function gets how many were folded:
|
|
21
|
+
* `(n) => `${n} other apps``). Opt in for parts that come from data and have no order of their own;
|
|
22
|
+
* leave it off for ordered parts (used, cached, free).
|
|
23
|
+
*/
|
|
24
|
+
other?: {
|
|
25
|
+
label: string | ((count: number) => string);
|
|
26
|
+
};
|
|
18
27
|
/** Header of the parts column, for screen readers and over the table. Defaults to "Part". */
|
|
19
28
|
partHeader?: string;
|
|
20
29
|
/** Header of the amounts column. Defaults to "Amount". */
|
|
@@ -32,4 +41,4 @@ export type CompositionBarProps = {
|
|
|
32
41
|
restLabel?: undefined;
|
|
33
42
|
});
|
|
34
43
|
/** What a whole is made of: a stacked bar for proportion and a table that names every part, its amount and its share, so colour is never the only cue. */
|
|
35
|
-
export declare function CompositionBar({ label, parts, formatValue, formatShare, partHeader, valueHeader, shareHeader, className, ...whole }: CompositionBarProps): React.JSX.Element;
|
|
44
|
+
export declare function CompositionBar({ label, parts, formatValue, formatShare, partHeader, valueHeader, shareHeader, other, className, ...whole }: CompositionBarProps): React.JSX.Element;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import * as React from "react";
|
|
2
|
+
/** The kind of a console line: output (`info`), a `warning` or `error`, or the `echo` of a command that ran. */
|
|
3
|
+
export type ConsoleLevel = "info" | "warning" | "error" | "echo";
|
|
4
|
+
/** One line of the log. */
|
|
5
|
+
export type ConsoleLine = {
|
|
6
|
+
/** Unique and stable: the row's key. A counter will do. */
|
|
7
|
+
id: string | number;
|
|
8
|
+
text: string;
|
|
9
|
+
/** Default `info`. */
|
|
10
|
+
level?: ConsoleLevel;
|
|
11
|
+
};
|
|
12
|
+
export type ConsoleProps = {
|
|
13
|
+
/** Names the console: "Game console". The log and the command line are named from it. */
|
|
14
|
+
label: string;
|
|
15
|
+
/** The log, oldest first. */
|
|
16
|
+
lines: readonly ConsoleLine[];
|
|
17
|
+
/** A command was entered (Enter or Run), trimmed and not empty. The line clears. Append its echo and output to `lines`. */
|
|
18
|
+
onCommand: (text: string) => void;
|
|
19
|
+
/** The whole inputs that could follow what is typed, for Tab. Not given: Tab moves on as it does anywhere. */
|
|
20
|
+
complete?: (text: string) => readonly string[];
|
|
21
|
+
/** Where the history of commands is kept (localStorage). Not given: kept for this visit only. */
|
|
22
|
+
historyKey?: string;
|
|
23
|
+
/** The tallest the log may be, in px, before it scrolls. Default 320. */
|
|
24
|
+
height?: number;
|
|
25
|
+
/** Every line is exactly this tall (px) and does not wrap (a long line is cut with an ellipsis, whole in its title): nothing is measured, which is faster for a long log and what a test DOM, which does no layout, needs. Default: lines wrap and are measured. */
|
|
26
|
+
lineHeight?: number;
|
|
27
|
+
/** The command line's label. Default "Command". */
|
|
28
|
+
commandLabel?: string;
|
|
29
|
+
/** The input, for moving focus to it when the console opens. */
|
|
30
|
+
inputRef?: React.Ref<HTMLInputElement>;
|
|
31
|
+
className?: string;
|
|
32
|
+
};
|
|
33
|
+
/** A command console: a polite, virtualised log pinned to its end, above a command line with history (Up, Down) and Tab completion from the app's list. */
|
|
34
|
+
export declare function Console({ label, lines, onCommand, complete, historyKey, height, lineHeight, commandLabel, inputRef, className }: ConsoleProps): React.JSX.Element;
|
|
@@ -33,6 +33,8 @@ export type Expanded = {
|
|
|
33
33
|
onChange: (next: Set<string>) => void;
|
|
34
34
|
isOpen: (key: string) => boolean;
|
|
35
35
|
setOpen: (key: string, open: boolean) => void;
|
|
36
|
+
/** Opens a closed key, closes an open one (the same word as `WorkspaceState.toggle`). */
|
|
37
|
+
toggle: (key: string) => void;
|
|
36
38
|
collapseAll: () => void;
|
|
37
39
|
};
|
|
38
40
|
export type ExpandedOptions = {
|
|
@@ -30,6 +30,15 @@ export declare function FileDropZone({ onFiles, acceptLabel, title, disabled, re
|
|
|
30
30
|
children?: React.ReactNode;
|
|
31
31
|
className?: string;
|
|
32
32
|
}): React.JSX.Element;
|
|
33
|
+
/** While files are dragged anywhere over the window, a dim overlay names what is taken ("Drop to add PAK files"); a drop calls `onFiles`. The app's own drags never trigger it. Keep a `FileButton` beside it for the keyboard and phones. */
|
|
34
|
+
export declare function FileDropOverlay({ onFiles, acceptLabel, disabled, refuseTypes, }: {
|
|
35
|
+
onFiles: (files: File[]) => void;
|
|
36
|
+
/** What it takes, in words ("PAK files"), shown in "Drop to add …". */
|
|
37
|
+
acceptLabel: string;
|
|
38
|
+
disabled?: boolean;
|
|
39
|
+
/** Drag types of the app's own drags to ignore, besides every `DragSource`'s. */
|
|
40
|
+
refuseTypes?: readonly string[];
|
|
41
|
+
}): React.JSX.Element | null;
|
|
33
42
|
/** One row per file offered: its name, a status word, and for a rejected or failed file the reason and (for failed) a retry. Announces a summary politely when a batch finishes. */
|
|
34
43
|
export declare function FileOutcomes({ intake, className }: {
|
|
35
44
|
intake: FileIntake;
|
|
@@ -5,6 +5,8 @@ export type Shortcut = {
|
|
|
5
5
|
keys: string[];
|
|
6
6
|
/** What it does, in the product's words: "Accept booking", not "Action 1". */
|
|
7
7
|
label: string;
|
|
8
|
+
/** What names it when keys are rebound (`ShortcutEditor`): stable across releases, so a person's saved keys still mean the same action. Default: the label. */
|
|
9
|
+
id?: string;
|
|
8
10
|
run: () => void;
|
|
9
11
|
/** Fire again while the key is held. On for moving through a list, off (the default) for answers. */
|
|
10
12
|
repeat?: boolean;
|
|
@@ -20,6 +22,8 @@ export declare function isTypingTarget(target: EventTarget | null): boolean;
|
|
|
20
22
|
export declare function useHotkeys(shortcuts: Shortcut[] | Record<string, () => void>, { enabled }?: {
|
|
21
23
|
enabled?: boolean;
|
|
22
24
|
}): void;
|
|
25
|
+
/** How a `KeyboardEvent.key` is drawn in a legend and an editor: arrows as arrows, the rest by name. */
|
|
26
|
+
export declare const keyName: (key: string) => string;
|
|
23
27
|
/** A quiet legend of the screen's shortcuts, from the same list `useHotkeys` binds. Hidden on touch screens. */
|
|
24
28
|
export declare function KeysLegend({ shortcuts, label, className, }: {
|
|
25
29
|
shortcuts: Pick<Shortcut, "keys" | "label" | "disabled">[];
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import * as React from "react";
|
|
2
|
+
type PixelSource = {
|
|
3
|
+
width: number;
|
|
4
|
+
height: number;
|
|
5
|
+
rgba: Uint8Array | Uint8ClampedArray;
|
|
6
|
+
image?: never;
|
|
7
|
+
} | {
|
|
8
|
+
image: ImageData;
|
|
9
|
+
width?: never;
|
|
10
|
+
height?: never;
|
|
11
|
+
rgba?: never;
|
|
12
|
+
};
|
|
13
|
+
/** What `PixelImage` takes: a width, height and RGBA bytes, or an `ImageData`, and how to show it. */
|
|
14
|
+
export type PixelImageProps = PixelSource & {
|
|
15
|
+
/** What the picture is, in words: "e1u1/clip.wal". The size and zoom are added to the name. */
|
|
16
|
+
label: string;
|
|
17
|
+
/** A whole number of screen pixels per picture pixel, or `"fit"` for the largest that fits `maxSize`. Default `"fit"`. */
|
|
18
|
+
zoom?: number | "fit";
|
|
19
|
+
/** The most `zoom="fit"` may take, in CSS pixels, each way. Default 512. */
|
|
20
|
+
maxSize?: number;
|
|
21
|
+
className?: string;
|
|
22
|
+
};
|
|
23
|
+
/** The zoom a picture is drawn at: a whole number, at least 1. */
|
|
24
|
+
export declare function pixelZoom(width: number, height: number, zoom?: number | "fit", maxSize?: number): number;
|
|
25
|
+
/** A decoded RGBA picture on a canvas at a whole-number zoom with square pixels, a checkerboard behind clear pixels, named with its size. */
|
|
26
|
+
export declare function PixelImage({ label, zoom, maxSize, className, ...source }: PixelImageProps): React.JSX.Element;
|
|
27
|
+
/** The same pixels as a PNG `Blob`, for a download (`useObjectUrl` makes the link). Rejects where there is no canvas. */
|
|
28
|
+
export declare function rgbaToBlob(width: number, height: number, rgba: Uint8Array | Uint8ClampedArray): Promise<Blob>;
|
|
29
|
+
export {};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { Shortcut } from './hotkeys';
|
|
2
|
+
import * as React from "react";
|
|
3
|
+
/** The keys a person has chosen, by shortcut id; an action absent here keeps its default keys. */
|
|
4
|
+
export type ShortcutOverrides = Record<string, string[]>;
|
|
5
|
+
/** What `useRebindableShortcuts` returns: the list to hand to `useHotkeys` and `KeysLegend`, and what `ShortcutEditor` edits. */
|
|
6
|
+
export type Rebinding = {
|
|
7
|
+
/** The defaults with the person's keys: give this to `useHotkeys` and `KeysLegend`. */
|
|
8
|
+
shortcuts: Shortcut[];
|
|
9
|
+
/** The defaults the editor resets to. */
|
|
10
|
+
defaults: readonly Shortcut[];
|
|
11
|
+
overrides: ShortcutOverrides;
|
|
12
|
+
/** Whether an action has other keys than its default. */
|
|
13
|
+
isChanged: (id: string) => boolean;
|
|
14
|
+
/** Sets an action's keys (or `null` to go back to its default). */
|
|
15
|
+
setKeys: (id: string, keys: string[] | null) => void;
|
|
16
|
+
/** Back to the defaults, every action. */
|
|
17
|
+
resetAll: () => void;
|
|
18
|
+
};
|
|
19
|
+
/** Holds a person's rebound keys over a default `Shortcut[]`, remembered under `storageKey` and handed to `onChange`. The result's `shortcuts` is what `useHotkeys` and `KeysLegend` take. */
|
|
20
|
+
export declare function useRebindableShortcuts(defaults: readonly Shortcut[], { storageKey, initial, onChange }?: {
|
|
21
|
+
storageKey?: string;
|
|
22
|
+
initial?: ShortcutOverrides;
|
|
23
|
+
onChange?: (overrides: ShortcutOverrides) => void;
|
|
24
|
+
}): Rebinding;
|
|
25
|
+
/** What a pressed key means for one action: take it, refuse it with a reason, or ask about the action that already has it. */
|
|
26
|
+
export type KeyCheck = {
|
|
27
|
+
ok: true;
|
|
28
|
+
key: string;
|
|
29
|
+
} | {
|
|
30
|
+
ok: false;
|
|
31
|
+
reason: string;
|
|
32
|
+
} | {
|
|
33
|
+
ok: "conflict";
|
|
34
|
+
key: string;
|
|
35
|
+
other: Shortcut;
|
|
36
|
+
};
|
|
37
|
+
/** Judges a key pressed while recording for the shortcut `id`, against the current list. */
|
|
38
|
+
export declare function checkKey(e: Pick<KeyboardEvent, "key" | "ctrlKey" | "metaKey" | "altKey" | "shiftKey">, id: string, shortcuts: readonly Shortcut[]): KeyCheck;
|
|
39
|
+
/** Each shortcut with its keys and a "Change" that records the next key pressed; refuses keys that cannot be bound, names a conflict and offers a swap, and resets one or all. Edits the list a `useRebindableShortcuts` holds. */
|
|
40
|
+
export declare function ShortcutEditor({ rebinding, label, className }: {
|
|
41
|
+
rebinding: Rebinding;
|
|
42
|
+
label?: string;
|
|
43
|
+
className?: string;
|
|
44
|
+
}): React.JSX.Element;
|
|
@@ -39,6 +39,8 @@ type TreeCommon<N> = {
|
|
|
39
39
|
renderNode?: (node: N, state: TreeNodeState) => React.ReactNode;
|
|
40
40
|
/** Which nodes are open; from `useExpanded`, optionally in the URL. */
|
|
41
41
|
expanded: Expanded;
|
|
42
|
+
/** What pressing a branch's row (not its chevron) does. `"select"` (default) chooses it like a leaf; `"toggle"` opens or closes it and leaves the chosen row where it was, as a file tree does (Finder, VS Code), so only files are chosen. Not used with `choices`, where a press ticks. `beforeOpen` is still asked. */
|
|
43
|
+
branchPress?: "select" | "toggle";
|
|
42
44
|
/** Asked when the person opens a branch (chevron or Right arrow): return `false` to keep it closed, having done something else with it (a folder that is a project is chosen, not entered). Not asked for opens the app makes itself. */
|
|
43
45
|
beforeOpen?: (node: N) => boolean;
|
|
44
46
|
/** The skeleton row while a node's children load. Default: a muted bar. */
|
|
@@ -57,7 +59,7 @@ type TreeCommon<N> = {
|
|
|
57
59
|
} | null | undefined;
|
|
58
60
|
/** Orders the children of every node, and the top level. */
|
|
59
61
|
sortChildren?: (a: N, b: N) => number;
|
|
60
|
-
/** The keys from the top down to a node to bring into view: its ancestors open and the tree scrolls to it. Give the same array to reveal again. */
|
|
62
|
+
/** The keys from the top down to a node to bring into view: its ancestors open and the tree scrolls to it. Give the same array to reveal again. The ancestors are opened through `expanded`, so with `useExpanded({ param })` they are written into the URL (`?open=textures&open=textures/e1u1`): a link to a file carries its folders, and a test checks `open` by key, not by the exact search string. */
|
|
61
63
|
reveal?: readonly string[];
|
|
62
64
|
/** What is under a branch, as keys (not the branch itself), for a branch ticked before it was read. When given, ticking it does not open it: the keys are chosen and the live region says "2019 and its 91 folders". */
|
|
63
65
|
resolveBranch?: (node: N) => Promise<readonly string[]>;
|
|
@@ -68,5 +70,5 @@ type TreeCommon<N> = {
|
|
|
68
70
|
className?: string;
|
|
69
71
|
};
|
|
70
72
|
/** A hierarchy whose children load as each node opens (a `useChildren` hook per open node): a skeleton row, a Try again row and an "empty" row per node, type-ahead and arrow keys, single selection, open state optionally in the URL, always virtualised. */
|
|
71
|
-
export declare function Tree<N>({ label, roots, useChildren, nodeKey, nodeLabel, isBranch, renderNode, selected, onSelect, choices, current, onCurrentChange, count, badge, sortChildren, reveal, resolveBranch, coverNoun, expanded, beforeOpen, loadingRow, emptyRow, height, className }: TreeProps<N>): React.JSX.Element;
|
|
73
|
+
export declare function Tree<N>({ label, roots, useChildren, nodeKey, nodeLabel, isBranch, renderNode, selected, onSelect, choices, current, onCurrentChange, count, badge, sortChildren, reveal, resolveBranch, coverNoun, branchPress, expanded, beforeOpen, loadingRow, emptyRow, height, className }: TreeProps<N>): React.JSX.Element;
|
|
72
74
|
export {};
|