strata-react 1.3.5 → 1.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -162,9 +162,10 @@ thousands of lines. Such an app imports the same stylesheet **without the reset*
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
+ | 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 |
165
166
  | 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
167
  | 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
+ | Speech | `speak`, `useSpeech`, `SayAgain`, `canSay`, `textOf`, `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. Recorded prompts (`speak(parts)`, `SayAgain parts=`): each part's clip plays in order, and the browser's voice says the words when a part has no clip or one fails (one voice per prompt). `SayAgain`'s name is the sentence it says. `installFakeSpeech()` records what was said and which clips played in a test (`clips()`, `finish()`, `failClip()`) |
168
169
  | 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 |
169
170
  | 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 |
170
171
  | 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 |
package/UPGRADING.md CHANGED
@@ -12,6 +12,7 @@ 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
+ - Speech (#310): `installFakeSpeech()` now also replaces `window.Audio` until `uninstall()`, and each `Spoken` entry has `clip` (null for the browser's voice), so a test that compares a whole entry with `toEqual` adds `clip: null`. `useSpeech().say` takes a sentence or recorded parts; `stopSpeaking()` and unmounting `useSpeech` stop a playing clip too.
15
16
  - `ChoiceGrid`'s `marks` type is `ChoiceMarks` (a quiz's three words, or `{ picked }` alone); `createTypedApi`'s POST/PUT/PATCH on an operation with `requestBody?: never` no longer ask for `json`, so a `json: undefined` workaround can be deleted. The request argument is now required when the operation has a required path or query value (a call that left it out compiled and threw at run time); pass `{ path: … }`.
16
17
  - `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.
17
18
  - `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).
@@ -0,0 +1,10 @@
1
+ import { Outbox } from '../query/outbox';
2
+ /** Props for `OutboxStatus`. */
3
+ export type OutboxStatusProps = {
4
+ outbox: Outbox;
5
+ /** What a write is, singular, for `format.count`: "answer" gives "3 answers kept on this device". */
6
+ noun: string;
7
+ className?: string;
8
+ };
9
+ /** Says how many writes wait on this device and why, with Send now, and lists any the server refused; renders nothing while all is sent. */
10
+ export declare function OutboxStatus({ outbox, noun, className }: OutboxStatusProps): import('react').JSX.Element | null;
@@ -1,11 +1,13 @@
1
- import { UseSpeechOptions } from '../lib/speech';
1
+ import { SpeechPart, UseSpeechOptions } from '../lib/speech';
2
2
  /** Props of `SayAgain`. */
3
3
  export type SayAgainProps = UseSpeechOptions & {
4
4
  /** The one sentence it speaks. Also names the button: "Say: Which one is the cat?". */
5
5
  text: string;
6
+ /** The recordings to play instead of the browser's voice, in order; their words together should be `text`. */
7
+ parts?: readonly SpeechPart[];
6
8
  /** Replaces "Say" in the name, for an app that words it differently ("Hear"). */
7
9
  verb?: string;
8
10
  className?: string;
9
11
  };
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;
12
+ /** An icon button that says one sentence aloud, from its recordings when given, else with the browser's voice; hidden where neither can be heard or it is muted. */
13
+ export declare function SayAgain({ text, parts, verb, className, ...options }: SayAgainProps): import('react').JSX.Element | null;
package/dist/index.d.ts CHANGED
@@ -76,10 +76,12 @@ export { useHotkeys, KeysLegend, isTypingTarget, type Shortcut } from './compone
76
76
  export { useActiveItem, ActiveList, type ActiveItem } from './components/active-list';
77
77
  export { ThemeProvider, useColorScheme, useSystemColorScheme, ColorSchemeChoice, colorSchemeScript, COLOR_SCHEME_STORAGE_KEY, type ColorScheme, type ColorSchemePreference, type ColorSchemeLabels, type ColorSchemeState, } from './components/theme';
78
78
  export { StrataQueryProvider, createQueryClient, toLoad, staleOf, useLoad, useInfiniteLoad, useJob, isTaskRunning, apiPage, fetchJson, HttpError, describeHttpError, errorPayload, readErrorBody, type DescribeError, type ErrorBody, type FetchJsonOptions, type FetchJsonInit, createApi, createTypedApi, type TypedApi, type Api, type ApiOptions, type ApiPage, type InfiniteLoad, type InfiniteLoadOptions, type Job, type JobOptions, type More, } from './query';
79
+ export { createOutbox, useOutbox, useOutboxStarted, isRefusal, type Outbox, type OutboxOptions, type OutboxRequest, type OutboxItem, type OutboxRefusal, type OutboxSnapshot, type Delivery, } from './query/outbox';
80
+ export { OutboxStatus, type OutboxStatusProps } from './components/outbox-status';
79
81
  export { describeActionError, fieldErrorsOf } from './lib/errors';
80
82
  export { appBase, withBase } from './lib/base';
81
83
  export { useSearchParam, type SearchParam, type SearchParamOptions } from './lib/search-param';
82
- export { speak, stopSpeaking, canSpeak, pickVoice, useSpeech, type SpeakOptions, type Speech, type UseSpeechOptions } from './lib/speech';
84
+ export { speak, stopSpeaking, canSpeak, canPlayClips, canSay, textOf, pickVoice, useSpeech, type SpeakOptions, type Speech, type SpeechPart, type Saying, type UseSpeechOptions } from './lib/speech';
83
85
  export { SayAgain, type SayAgainProps } from './components/say-again';
84
86
  export { browserMicrophone, explainMicrophoneError, MicrophoneContext, MicrophoneError, useMicrophone, type Microphone, type MicrophoneStream, } from './lib/microphone';
85
87
  export { LEVEL_FLOOR_DB, joinSamples, encodeWav, peakDb, speechLevel, type SpeechLevel } from './lib/recording';
package/dist/index.js CHANGED
@@ -7,7 +7,7 @@ import { n as useSharedCursor, r as geo, t as CursorScope } from "./cursor-DDGBP
7
7
  import { a as useColorScheme, i as colorSchemeScript, n as ColorSchemeChoice, o as useSystemColorScheme, r as ThemeProvider, s as Density, t as COLOR_SCHEME_STORAGE_KEY } from "./theme-By3DSUTs.js";
8
8
  import * as React from "react";
9
9
  import { Autocomplete, Button as Button$1, Cell, Checkbox as Checkbox$1, Collection, Column, Dialog as Dialog$1, DialogTrigger, Disclosure as Disclosure$1, DisclosurePanel, DropIndicator, DropZone, FileTrigger, GridLayout, GridList, GridListItem, Header, Heading, Input as Input$1, Keyboard, Link, ListBox, ListBoxItem, ListLayout, ListStateContext, Menu as Menu$1, MenuItem, MenuSection, MenuTrigger, Modal, ModalOverlay, Popover as Popover$1, RouterProvider, Row, SearchField, Separator, Slider as Slider$1, SliderThumb, SliderTrack, SubmenuTrigger, Switch as Switch$1, Tab, TabList, TabPanel, Table, TableBody, TableHeader, TableLayout, Tabs as Tabs$1, Text, ToggleButton, ToggleButtonGroup, Tree as Tree$1, TreeItem, TreeItemContent, Virtualizer, useDragAndDrop, useFilter } from "react-aria-components";
10
- import { ArrowDown, ArrowUp, ArrowUpDown, ArrowUpRight, Ban, Check, ChevronDown, ChevronLeft, ChevronRight, CircleAlert, CircleCheck, Columns2, Ellipsis, Eye, EyeOff, FileQuestion, Flag, Folder, FolderOpen, GripVertical, History, ImageOff, Info, KeyRound, LayoutGrid, List, Loader, LoaderCircle, Lock, Maximize, Maximize2, Minimize, Minus, PanelBottomClose, PanelBottomOpen, PanelLeftClose, PanelLeftOpen, PanelRightClose, PanelRightOpen, PanelTopClose, PanelTopOpen, Pause, Pencil, Play, Redo2, RotateCcw, RotateCw, Scan, Search, Send, SkipBack, SkipForward, SlidersHorizontal, Square, StepBack, StepForward, Trash2, TriangleAlert, Undo2, Upload, Volume2, VolumeX, X, ZoomIn, ZoomOut } from "lucide-react";
10
+ import { ArrowDown, ArrowUp, ArrowUpDown, ArrowUpRight, Ban, Check, ChevronDown, ChevronLeft, ChevronRight, CircleAlert, CircleCheck, CloudOff, Columns2, Ellipsis, Eye, EyeOff, FileQuestion, Flag, Folder, FolderOpen, GripVertical, History, ImageOff, Info, KeyRound, LayoutGrid, List, Loader, LoaderCircle, Lock, Maximize, Maximize2, Minimize, Minus, PanelBottomClose, PanelBottomOpen, PanelLeftClose, PanelLeftOpen, PanelRightClose, PanelRightOpen, PanelTopClose, PanelTopOpen, Pause, Pencil, Play, Redo2, RotateCcw, RotateCw, Scan, Search, Send, SkipBack, SkipForward, SlidersHorizontal, Square, StepBack, StepForward, Trash2, TriangleAlert, Undo2, Upload, Volume2, VolumeX, X, ZoomIn, ZoomOut } from "lucide-react";
11
11
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
12
12
  import { Link as Link$1, NavLink, useHref, useNavigate, useSearchParams } from "react-router";
13
13
  import { createSortedRowModel, flexRender, rowSortingFeature, tableFeatures, useTable } from "@tanstack/react-table";
@@ -11252,7 +11252,325 @@ function useJob({ isRunning, every = 2e3, invalidates = [], describeError, ...op
11252
11252
  function isTaskRunning(task, finished) {
11253
11253
  return !(Array.isArray(finished) ? finished.includes(task.state) : finished.has(task.state));
11254
11254
  }
11255
+ // src/query/outbox.ts
11256
+ /** Whether a failure is the server's answer for good (refused) rather than for now (waiting). */
11257
+ function isRefusal(error) {
11258
+ return error instanceof HttpError && error.status >= 400 && error.status < 500 && ![
11259
+ 401,
11260
+ 403,
11261
+ 408,
11262
+ 425,
11263
+ 429
11264
+ ].includes(error.status);
11265
+ }
11266
+ function problemOf(error) {
11267
+ if (error instanceof HttpError) {
11268
+ if (error.status === 401 || error.status === 403) return "Sign in again to send them.";
11269
+ if (error.status === 429) return "The server asked to wait.";
11270
+ return error.reason ?? "The server had a problem.";
11271
+ }
11272
+ return "The server could not be reached.";
11273
+ }
11274
+ function defaultStorage() {
11275
+ try {
11276
+ const s = window.localStorage;
11277
+ const probe = "strata:outbox:probe";
11278
+ s.setItem(probe, "1");
11279
+ s.removeItem(probe);
11280
+ return s;
11281
+ } catch {
11282
+ return null;
11283
+ }
11284
+ }
11285
+ function randomId() {
11286
+ return Array.from(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)), (b) => b.toString(16).padStart(2, "0")).join("");
11287
+ }
11288
+ /** A queue of writes kept on the device (localStorage) and sent in order when the server can take them; see `useOutbox` and `OutboxStatus`. */
11289
+ function createOutbox({ name, send, storage, retryMs = 2e3, maxRetryMs = 6e4 }) {
11290
+ const key = `strata:outbox:${name}`;
11291
+ const store = storage === void 0 ? defaultStorage() : storage;
11292
+ const post = send ?? ((item) => fetchJson(withBase(item.path, appBase()), {
11293
+ method: item.method,
11294
+ json: item.json
11295
+ }));
11296
+ let memory = {
11297
+ items: [],
11298
+ refused: []
11299
+ };
11300
+ let persisted = store !== null;
11301
+ let sending = false;
11302
+ let problem = null;
11303
+ let retryAt = null;
11304
+ let wait = retryMs;
11305
+ let timer;
11306
+ let running = null;
11307
+ const firstTry = /* @__PURE__ */ new Map();
11308
+ const adding = /* @__PURE__ */ new Set();
11309
+ const listeners = /* @__PURE__ */ new Set();
11310
+ const sentListeners = /* @__PURE__ */ new Set();
11311
+ let snap = null;
11312
+ const read = () => {
11313
+ if (!persisted || !store) return memory;
11314
+ try {
11315
+ const raw = JSON.parse(store.getItem(key) ?? "null");
11316
+ return {
11317
+ items: Array.isArray(raw?.items) ? raw.items : [],
11318
+ refused: Array.isArray(raw?.refused) ? raw.refused : []
11319
+ };
11320
+ } catch {
11321
+ return memory;
11322
+ }
11323
+ };
11324
+ const write = (kept) => {
11325
+ memory = kept;
11326
+ if (persisted && store) try {
11327
+ store.setItem(key, JSON.stringify(kept));
11328
+ } catch {
11329
+ persisted = false;
11330
+ }
11331
+ changed();
11332
+ };
11333
+ const changed = () => {
11334
+ snap = null;
11335
+ for (const l of listeners) l();
11336
+ };
11337
+ const settle = (id, d) => {
11338
+ for (const resolve of firstTry.get(id) ?? []) resolve(d);
11339
+ firstTry.delete(id);
11340
+ };
11341
+ const lockManager = () => navigator.locks;
11342
+ const mutate = (change) => {
11343
+ const apply = () => write(change(read()));
11344
+ const locks = persisted ? lockManager() : void 0;
11345
+ if (!locks) {
11346
+ apply();
11347
+ return Promise.resolve();
11348
+ }
11349
+ return locks.request(`${key}:write`, apply);
11350
+ };
11351
+ const refuse = (kept, item, reason) => ({
11352
+ items: kept.items.filter((x) => x.id !== item.id),
11353
+ refused: [...kept.refused, {
11354
+ id: item.id,
11355
+ label: item.label,
11356
+ reason,
11357
+ at: (/* @__PURE__ */ new Date()).toISOString()
11358
+ }].slice(-50)
11359
+ });
11360
+ const pass = async () => {
11361
+ sending = true;
11362
+ changed();
11363
+ try {
11364
+ for (;;) {
11365
+ const kept = read();
11366
+ const item = kept.items[0];
11367
+ if (!item) {
11368
+ for (const id of [...firstTry.keys()]) if (!adding.has(id)) settle(id, kept.refused.some((r) => r.id === id) ? "refused" : "sent");
11369
+ problem = null;
11370
+ retryAt = null;
11371
+ wait = retryMs;
11372
+ return;
11373
+ }
11374
+ const parent = item.after ? kept.refused.find((r) => r.id === item.after) : void 0;
11375
+ if (parent) {
11376
+ await mutate((k) => refuse(k, item, `Not sent, as what it follows was refused: ${parent.reason}`));
11377
+ settle(item.id, "refused");
11378
+ continue;
11379
+ }
11380
+ try {
11381
+ await post(item);
11382
+ await mutate((k) => ({
11383
+ ...k,
11384
+ items: k.items.filter((x) => x.id !== item.id)
11385
+ }));
11386
+ settle(item.id, "sent");
11387
+ for (const l of sentListeners) l(item);
11388
+ } catch (error) {
11389
+ if (!isRefusal(error)) {
11390
+ problem = problemOf(error);
11391
+ retryAt = new Date(Date.now() + wait);
11392
+ clearTimeout(timer);
11393
+ timer = setTimeout(() => void flush(), wait);
11394
+ wait = Math.min(wait * 2, maxRetryMs);
11395
+ for (const x of read().items) settle(x.id, "waiting");
11396
+ return;
11397
+ }
11398
+ const reason = error.reason ?? `${error.status} ${error.statusText}`;
11399
+ await mutate((k) => refuse(k, item, reason));
11400
+ settle(item.id, "refused");
11401
+ }
11402
+ }
11403
+ } finally {
11404
+ sending = false;
11405
+ changed();
11406
+ }
11407
+ };
11408
+ const flush = () => {
11409
+ if (running) return running.then(flush);
11410
+ clearTimeout(timer);
11411
+ const locks = lockManager();
11412
+ running = (locks ? locks.request(key, pass) : pass()).finally(() => {
11413
+ running = null;
11414
+ });
11415
+ return running;
11416
+ };
11417
+ return {
11418
+ add({ id = randomId(), ...request }) {
11419
+ const delivered = new Promise((resolve) => firstTry.set(id, [...firstTry.get(id) ?? [], resolve]));
11420
+ const item = {
11421
+ ...request,
11422
+ id,
11423
+ queuedAt: (/* @__PURE__ */ new Date()).toISOString()
11424
+ };
11425
+ adding.add(id);
11426
+ mutate((k) => k.items.some((x) => x.id === id) ? k : {
11427
+ ...k,
11428
+ items: [...k.items, item]
11429
+ }).then(() => {
11430
+ adding.delete(id);
11431
+ if (running) running.then(() => firstTry.has(id) ? flush() : void 0);
11432
+ else flush();
11433
+ });
11434
+ return {
11435
+ id,
11436
+ delivered
11437
+ };
11438
+ },
11439
+ flush,
11440
+ snapshot() {
11441
+ if (!snap) {
11442
+ const kept = read();
11443
+ snap = {
11444
+ waiting: kept.items.length,
11445
+ sending,
11446
+ problem: kept.items.length ? problem : null,
11447
+ retryAt: kept.items.length ? retryAt : null,
11448
+ refused: kept.refused,
11449
+ persisted
11450
+ };
11451
+ }
11452
+ return snap;
11453
+ },
11454
+ subscribe(listener) {
11455
+ listeners.add(listener);
11456
+ return () => listeners.delete(listener);
11457
+ },
11458
+ onSent(listener) {
11459
+ sentListeners.add(listener);
11460
+ return () => sentListeners.delete(listener);
11461
+ },
11462
+ dismiss(id) {
11463
+ mutate((k) => ({
11464
+ ...k,
11465
+ refused: id === void 0 ? [] : k.refused.filter((r) => r.id !== id)
11466
+ }));
11467
+ },
11468
+ start() {
11469
+ const now = () => {
11470
+ wait = retryMs;
11471
+ flush();
11472
+ };
11473
+ const shown = () => {
11474
+ if (document.visibilityState === "visible") now();
11475
+ };
11476
+ const other = (e) => {
11477
+ if (e.key !== key) return;
11478
+ changed();
11479
+ if (e.newValue) flush();
11480
+ };
11481
+ window.addEventListener("online", now);
11482
+ document.addEventListener("visibilitychange", shown);
11483
+ window.addEventListener("storage", other);
11484
+ flush();
11485
+ return () => {
11486
+ clearTimeout(timer);
11487
+ window.removeEventListener("online", now);
11488
+ document.removeEventListener("visibilitychange", shown);
11489
+ window.removeEventListener("storage", other);
11490
+ };
11491
+ }
11492
+ };
11493
+ }
11494
+ /** Where `outbox` stands, re-rendering when it changes. Call `outbox.start()` once for the app (`useOutboxStarted`). */
11495
+ function useOutbox(outbox) {
11496
+ return React.useSyncExternalStore(outbox.subscribe, outbox.snapshot, outbox.snapshot);
11497
+ }
11498
+ /** Starts `outbox` (sends what waits, and again on reconnect) for as long as the calling component is mounted: put it in the app's shell. */
11499
+ function useOutboxStarted(outbox) {
11500
+ React.useEffect(() => outbox.start(), [outbox]);
11501
+ }
11502
+ // src/components/outbox-status.tsx
11503
+ /** Says how many writes wait on this device and why, with Send now, and lists any the server refused; renders nothing while all is sent. */
11504
+ function OutboxStatus({ outbox, noun, className }) {
11505
+ const s = useOutbox(outbox);
11506
+ if (s.waiting === 0 && s.refused.length === 0) return null;
11507
+ const count = format.count(s.waiting, noun);
11508
+ return /* @__PURE__ */ jsxs("div", {
11509
+ className: cn("grid gap-2 type-body-sm", className),
11510
+ children: [s.waiting > 0 && /* @__PURE__ */ jsxs("p", {
11511
+ role: "status",
11512
+ className: "flex flex-wrap items-center gap-x-3 gap-y-1 text-muted-foreground",
11513
+ children: [
11514
+ s.sending ? /* @__PURE__ */ jsx(LoaderCircle, {
11515
+ "aria-hidden": true,
11516
+ className: "size-4 shrink-0 motion-safe:animate-spin"
11517
+ }) : /* @__PURE__ */ jsx(CloudOff, {
11518
+ "aria-hidden": true,
11519
+ className: "size-4 shrink-0"
11520
+ }),
11521
+ /* @__PURE__ */ jsxs("span", { children: [
11522
+ s.sending ? `Sending ${count}…` : `${count} kept on this device.`,
11523
+ !s.sending && s.problem && ` ${s.problem}`,
11524
+ !s.sending && s.retryAt && ` Trying again at ${format.clock(s.retryAt)}.`,
11525
+ !s.persisted && " They are kept only while this page is open."
11526
+ ] }),
11527
+ !s.sending && /* @__PURE__ */ jsx(Button, {
11528
+ size: "sm",
11529
+ onClick: () => void outbox.flush(),
11530
+ children: "Send now"
11531
+ })
11532
+ ]
11533
+ }), s.refused.length > 0 && /* @__PURE__ */ jsxs("div", {
11534
+ role: "status",
11535
+ className: "grid gap-1 text-danger",
11536
+ children: [/* @__PURE__ */ jsxs("p", {
11537
+ className: "flex flex-wrap items-center gap-x-3 gap-y-1",
11538
+ children: [
11539
+ /* @__PURE__ */ jsx(CircleAlert, {
11540
+ "aria-hidden": true,
11541
+ className: "size-4 shrink-0"
11542
+ }),
11543
+ /* @__PURE__ */ jsx("span", { children: s.refused.length === 1 ? `The server refused 1 ${noun}; it will not be sent.` : `The server refused ${format.count(s.refused.length, noun)}; they will not be sent.` }),
11544
+ /* @__PURE__ */ jsx(Button, {
11545
+ size: "sm",
11546
+ variant: "ghost",
11547
+ onClick: () => outbox.dismiss(),
11548
+ children: "Dismiss"
11549
+ })
11550
+ ]
11551
+ }), /* @__PURE__ */ jsx("ul", {
11552
+ className: "grid gap-1 pl-6",
11553
+ children: s.refused.map((r) => /* @__PURE__ */ jsxs("li", { children: [r.label ? `${r.label}: ` : "", r.reason] }, r.id))
11554
+ })]
11555
+ })]
11556
+ });
11557
+ }
11255
11558
  // src/lib/speech.ts
11559
+ var partsOf = (saying) => (typeof saying === "string" ? [{ text: saying }] : [...saying]).filter((p) => p.text.trim() || p.clip);
11560
+ /** The words of what is said, as one sentence: what the browser's voice says when a recording is missing, and the button's name. */
11561
+ function textOf(saying) {
11562
+ return partsOf(saying).map((p) => p.text.trim()).filter(Boolean).join(" ");
11563
+ }
11564
+ /** Whether this browser can play a recording. */
11565
+ function canPlayClips() {
11566
+ return typeof window !== "undefined" && typeof window.Audio === "function";
11567
+ }
11568
+ var allRecorded = (parts) => parts.length > 0 && parts.every((p) => p.clip);
11569
+ /** Whether `saying` can be said here: every part recorded and audio plays, or the browser has speech and there are words. */
11570
+ function canSay(saying) {
11571
+ const parts = partsOf(saying);
11572
+ return allRecorded(parts) && canPlayClips() || canSpeak() && textOf(parts) !== "";
11573
+ }
11256
11574
  /** Whether this browser can say text aloud. */
11257
11575
  function canSpeak() {
11258
11576
  return typeof window !== "undefined" && "speechSynthesis" in window && typeof SpeechSynthesisUtterance !== "undefined";
@@ -11264,11 +11582,11 @@ function pickVoice(voices, lang) {
11264
11582
  const base = wanted.split("-")[0];
11265
11583
  return voices.find((v) => v.lang.toLowerCase().replace("_", "-") === wanted) ?? voices.find((v) => v.lang.toLowerCase().replace("_", "-").split("-")[0] === base);
11266
11584
  }
11267
- /** Says `text` aloud now, cancelling what is still being said. Does nothing where there is no speech. Returns whether it was handed to the browser. */
11268
- function speak(text, { lang, rate = .9, onEnd } = {}) {
11585
+ /** The recording playing now, so the next prompt or `stopSpeaking` can cut it off. */
11586
+ var playing;
11587
+ function speakText(text, { lang, rate = .9, onEnd }) {
11269
11588
  if (!canSpeak() || !text.trim()) return false;
11270
11589
  const synth = window.speechSynthesis;
11271
- synth.cancel();
11272
11590
  const utterance = new SpeechSynthesisUtterance(text);
11273
11591
  if (lang) utterance.lang = lang;
11274
11592
  utterance.rate = rate;
@@ -11281,8 +11599,56 @@ function speak(text, { lang, rate = .9, onEnd } = {}) {
11281
11599
  synth.speak(utterance);
11282
11600
  return true;
11283
11601
  }
11284
- /** Stops whatever is being said. */
11602
+ function playFrom(parts, i, options) {
11603
+ const part = parts[i];
11604
+ if (!part) {
11605
+ options.onEnd?.();
11606
+ return;
11607
+ }
11608
+ const audio = new Audio();
11609
+ audio.title = part.text;
11610
+ let settled = false;
11611
+ const settle = () => {
11612
+ if (settled) return false;
11613
+ settled = true;
11614
+ if (playing === entry) playing = void 0;
11615
+ return true;
11616
+ };
11617
+ const fallBack = () => {
11618
+ if (settle() && !speakText(textOf(parts.slice(i)), options)) options.onEnd?.();
11619
+ };
11620
+ const entry = { stop: () => {
11621
+ if (!settle()) return;
11622
+ audio.pause();
11623
+ options.onEnd?.();
11624
+ } };
11625
+ playing = entry;
11626
+ audio.onended = () => {
11627
+ if (settle()) playFrom(parts, i + 1, options);
11628
+ };
11629
+ audio.onerror = fallBack;
11630
+ audio.src = part.clip ?? "";
11631
+ audio.play()?.catch(fallBack);
11632
+ }
11633
+ /**
11634
+ * Says it aloud now, cancelling what is still being said. A sentence goes to the browser's voice; parts play their recordings in order when
11635
+ * every part has one, else their words go to the browser's voice. Does nothing where neither can. Returns whether it started.
11636
+ */
11637
+ function speak(saying, options = {}) {
11638
+ const parts = partsOf(saying);
11639
+ if (!parts.length) return false;
11640
+ if (allRecorded(parts) && canPlayClips()) {
11641
+ stopSpeaking();
11642
+ playFrom(parts, 0, options);
11643
+ return true;
11644
+ }
11645
+ if (!canSpeak() || !textOf(parts)) return false;
11646
+ stopSpeaking();
11647
+ return speakText(textOf(parts), options);
11648
+ }
11649
+ /** Stops whatever is being said or played. */
11285
11650
  function stopSpeaking() {
11651
+ playing?.stop();
11286
11652
  if (canSpeak()) window.speechSynthesis.cancel();
11287
11653
  }
11288
11654
  /**
@@ -11294,13 +11660,12 @@ function useSpeech({ lang, rate, muted = false } = {}) {
11294
11660
  const [speaking, setSpeaking] = React.useState(false);
11295
11661
  const [, setVoicesVersion] = React.useState(0);
11296
11662
  React.useEffect(() => {
11297
- if (!canSpeak()) return;
11298
- const synth = window.speechSynthesis;
11663
+ const synth = canSpeak() ? window.speechSynthesis : void 0;
11299
11664
  const onVoices = () => setVoicesVersion((n) => n + 1);
11300
- synth.addEventListener?.("voiceschanged", onVoices);
11665
+ synth?.addEventListener?.("voiceschanged", onVoices);
11301
11666
  return () => {
11302
- synth.removeEventListener?.("voiceschanged", onVoices);
11303
- synth.cancel();
11667
+ synth?.removeEventListener?.("voiceschanged", onVoices);
11668
+ stopSpeaking();
11304
11669
  };
11305
11670
  }, []);
11306
11671
  React.useEffect(() => {
@@ -11312,9 +11677,9 @@ function useSpeech({ lang, rate, muted = false } = {}) {
11312
11677
  return {
11313
11678
  supported,
11314
11679
  speaking,
11315
- say: React.useCallback((text) => {
11316
- if (!supported) return false;
11317
- const spoken = speak(text, {
11680
+ say: React.useCallback((saying) => {
11681
+ if (muted) return false;
11682
+ const spoken = speak(saying, {
11318
11683
  lang,
11319
11684
  rate,
11320
11685
  onEnd: () => setSpeaking(false)
@@ -11322,7 +11687,7 @@ function useSpeech({ lang, rate, muted = false } = {}) {
11322
11687
  setSpeaking(spoken);
11323
11688
  return spoken;
11324
11689
  }, [
11325
- supported,
11690
+ muted,
11326
11691
  lang,
11327
11692
  rate
11328
11693
  ]),
@@ -11333,15 +11698,16 @@ function useSpeech({ lang, rate, muted = false } = {}) {
11333
11698
  };
11334
11699
  }
11335
11700
  // src/components/say-again.tsx
11336
- /** An icon button that says one sentence aloud with the browser's voice; hidden where there is no speech or it is muted. */
11337
- function SayAgain({ text, verb = "Say", className, ...options }) {
11338
- const { say, supported, speaking } = useSpeech(options);
11339
- if (!supported) return null;
11701
+ /** An icon button that says one sentence aloud, from its recordings when given, else with the browser's voice; hidden where neither can be heard or it is muted. */
11702
+ function SayAgain({ text, parts, verb = "Say", className, ...options }) {
11703
+ const { say, speaking } = useSpeech(options);
11704
+ const saying = parts?.length ? parts : text;
11705
+ if (options.muted || !canSay(saying)) return null;
11340
11706
  return /* @__PURE__ */ jsx(IconButton, {
11341
11707
  icon: Volume2,
11342
11708
  label: `${verb}: ${text}`,
11343
11709
  "aria-pressed": speaking || void 0,
11344
- onPress: () => say(text),
11710
+ onPress: () => say(saying),
11345
11711
  className
11346
11712
  });
11347
11713
  }
@@ -17215,6 +17581,6 @@ function FolderPicker({ label, useFolders: useListing, value, onChange, onChoose
17215
17581
  ]
17216
17582
  });
17217
17583
  }
17218
- export { ActiveList, Alert, AlertDialog, AppShell, AsyncButton, BookViewer, BoxList, BoxOverlay, Breadcrumb, BulkBar, Button, ButtonLink, COLOR_SCHEME_STORAGE_KEY, Checkbox, ChoiceGrid, ChoiceGridSkeleton, ChoiceGroup, ColorField, ColorSchemeChoice, CommandLegend, CommandMenu, Compare, CompareAudio, CompareGrid, CompareText, CompareVideo, CompareVideoGrid, Composer, CompositionBar, ContextMenu, Conversation, CursorScope, DEFAULT_TOLERANCE, DataTable, DataView$1 as DataView, Density, Dialog, Disclosure, Done, DragSource, EmptyState, FIT, Field, FileButton, FileDropZone, FileOutcomes, FolderPicker, FullscreenFrame, HttpError, IconButton, InfiniteList, Input, InputLevel, Inspector, InspectorSection, JobStatus, KeysLegend, LEVEL_FLOOR_DB, Lightbox, LineChart, LineChartGroup, LinkCard, LinkCardList, LoadError, LoadMore, MAX_SCALE, MAX_SIDE, MIN_SCALE, MISSING, Mark, MarkSummary, MarkableText, MediaGroup, MediaPlayer, MediaStage, Menu, Meter, Metric, MetricStrip, MicrophoneContext, MicrophoneError, MissingFile, NBSP, NativeSelect, NumberField, PageHeader, PairJudge, PairVote, Pane, PlaceBoard, PlayWindowButton, PlayerNotice, Popover, PropertyList, PropertyRow, RateChoice, RegionEditor, RichText, RowAction, SPEECH_RATES, STRATA_DRAG_TYPE, SaveStatus, SayAgain, SecretField, SeekBar, SelectableGrid, SelectableGridSkeleton, SequenceTimeline, SideNav, Skeleton, Slider, SortableList, SpanActions, SpanStrip, Split, StageGuides, StaleNotice, Status, StrataQueryProvider, StrataToastRegion, Switch, TableSkeleton, Tabs, TakeLevel, TextLink, Textarea, ThemeProvider, Thumbnail, ThumbnailSkeleton, TileGrid, TileGridSkeleton, TimeReadout, Timeline, TimelineZoomControls, Toggle, ToggleGroup, Toolbar, ToolbarSeparator, Tooltip, TranscriptView, Transport, Tree, UndoBar, ViewOptions, ViewportFrame, VirtualList, VolumeControl, Waveform, Workspace, actualPixelsScale, ancestorsOf, apiPage, appBase, boxViewport, browserMicrophone, buttonVariants, canFullscreen, canSpeak, clampToRoom, clampViewport, cn, colorSchemeScript, commandShortcut, countMarks, createApi, createFormat, createQueryClient, createTypedApi, crossedThreshold, describeActionError, describeHttpError, describeRegion, detectPlatform, diffWords, differences, drawRect, ease, encodeWav, errorPayload, explainMicrophoneError, fetchJson, fieldErrorsOf, findPage, fitRect, format, formatChord, gainToVolume, geo, gridPoints, gutterOf, inputLevelThresholds, isDoubtful, isReservedChord, isTaskRunning, isTypingTarget, jobProgressText, joinMediaGroup, joinRects, joinSamples, labelOf, lerpRect, logScale, loudnessOf, matchEntities, matchGains, matchesAccept, matchesChord, measureLoudness, moveGutter, moveRect, noOverlap, normaliseAngle, pageName, parentOf, parseChord, parseInline, parseRichText, parseSort, peakDb, peaksFromAudio, phraseAt, phraseDoubtful, phraseOfWordId, pickVoice, plainText, rangeBetween, readErrorBody, readPixels, readingOrder, regionShares, resample, resamplePeaks, resizeRect, safeHref, sayPosition, serialiseSort, settleCut, snapToGrid, sortRows, speak, speechLevel, splitRect, staleOf, stepId, stepOnGrid, stopSpeaking, tickLabel, tickStep, ticksBetween, toDate, toLoad, toPeakPair, toast, toastTimeout, transportShortcuts, turnRect, turnedSize, typeSteps, useActiveItem, useAsyncAction, useAttachedSource, useAutoSave, useBookUrl, useBoxes, useChoices, useClientWork, useColorScheme, useCommands, useDifference, useExpanded, useFileIntake, useHistory, useHistoryState, useHotkeys, useInView, useInfiniteLoad, useJob, useJobAction, useLeaveGuard, useLightboxUrl, useLoad, useMediaElement, useMediaSpans, useMicrophone, usePlayerWarnings, useRecorder, useSearchParam, useSelection, useSharedCursor, useSpeech, useSystemColorScheme, useTimelineZoom, useUndoable, useViewOptions, useViewport, useWorkspaceState, valueAt, viewOf, viewsOf, withBase, wordAt, wordId, zoomAt, zoomToBox };
17584
+ export { ActiveList, Alert, AlertDialog, AppShell, AsyncButton, BookViewer, BoxList, BoxOverlay, Breadcrumb, BulkBar, Button, ButtonLink, COLOR_SCHEME_STORAGE_KEY, Checkbox, ChoiceGrid, ChoiceGridSkeleton, ChoiceGroup, ColorField, ColorSchemeChoice, CommandLegend, CommandMenu, Compare, CompareAudio, CompareGrid, CompareText, CompareVideo, CompareVideoGrid, Composer, CompositionBar, ContextMenu, Conversation, CursorScope, DEFAULT_TOLERANCE, DataTable, DataView$1 as DataView, Density, Dialog, Disclosure, Done, DragSource, EmptyState, FIT, Field, FileButton, FileDropZone, FileOutcomes, FolderPicker, FullscreenFrame, HttpError, IconButton, InfiniteList, Input, InputLevel, Inspector, InspectorSection, JobStatus, KeysLegend, LEVEL_FLOOR_DB, Lightbox, LineChart, LineChartGroup, LinkCard, LinkCardList, LoadError, LoadMore, MAX_SCALE, MAX_SIDE, MIN_SCALE, MISSING, Mark, MarkSummary, MarkableText, MediaGroup, MediaPlayer, MediaStage, Menu, Meter, Metric, MetricStrip, MicrophoneContext, MicrophoneError, MissingFile, NBSP, NativeSelect, NumberField, OutboxStatus, PageHeader, PairJudge, PairVote, Pane, PlaceBoard, PlayWindowButton, PlayerNotice, Popover, PropertyList, PropertyRow, RateChoice, RegionEditor, RichText, RowAction, SPEECH_RATES, STRATA_DRAG_TYPE, SaveStatus, SayAgain, SecretField, SeekBar, SelectableGrid, SelectableGridSkeleton, SequenceTimeline, SideNav, Skeleton, Slider, SortableList, SpanActions, SpanStrip, Split, StageGuides, StaleNotice, Status, StrataQueryProvider, StrataToastRegion, Switch, TableSkeleton, Tabs, TakeLevel, TextLink, Textarea, ThemeProvider, Thumbnail, ThumbnailSkeleton, TileGrid, TileGridSkeleton, TimeReadout, Timeline, TimelineZoomControls, Toggle, ToggleGroup, Toolbar, ToolbarSeparator, Tooltip, TranscriptView, Transport, Tree, UndoBar, ViewOptions, ViewportFrame, VirtualList, VolumeControl, Waveform, Workspace, actualPixelsScale, ancestorsOf, apiPage, appBase, boxViewport, browserMicrophone, buttonVariants, canFullscreen, canPlayClips, canSay, canSpeak, clampToRoom, clampViewport, cn, colorSchemeScript, commandShortcut, countMarks, createApi, createFormat, createOutbox, createQueryClient, createTypedApi, crossedThreshold, describeActionError, describeHttpError, describeRegion, detectPlatform, diffWords, differences, drawRect, ease, encodeWav, errorPayload, explainMicrophoneError, fetchJson, fieldErrorsOf, findPage, fitRect, format, formatChord, gainToVolume, geo, gridPoints, gutterOf, inputLevelThresholds, isDoubtful, isRefusal, isReservedChord, isTaskRunning, isTypingTarget, jobProgressText, joinMediaGroup, joinRects, joinSamples, labelOf, lerpRect, logScale, loudnessOf, matchEntities, matchGains, matchesAccept, matchesChord, measureLoudness, moveGutter, moveRect, noOverlap, normaliseAngle, pageName, parentOf, parseChord, parseInline, parseRichText, parseSort, peakDb, peaksFromAudio, phraseAt, phraseDoubtful, phraseOfWordId, pickVoice, plainText, rangeBetween, readErrorBody, readPixels, readingOrder, regionShares, resample, resamplePeaks, resizeRect, safeHref, sayPosition, serialiseSort, settleCut, snapToGrid, sortRows, speak, speechLevel, splitRect, staleOf, stepId, stepOnGrid, stopSpeaking, textOf, tickLabel, tickStep, ticksBetween, toDate, toLoad, toPeakPair, toast, toastTimeout, transportShortcuts, turnRect, turnedSize, typeSteps, useActiveItem, useAsyncAction, useAttachedSource, useAutoSave, useBookUrl, useBoxes, useChoices, useClientWork, useColorScheme, useCommands, useDifference, useExpanded, useFileIntake, useHistory, useHistoryState, useHotkeys, useInView, useInfiniteLoad, useJob, useJobAction, useLeaveGuard, useLightboxUrl, useLoad, useMediaElement, useMediaSpans, useMicrophone, useOutbox, useOutboxStarted, usePlayerWarnings, useRecorder, useSearchParam, useSelection, useSharedCursor, useSpeech, useSystemColorScheme, useTimelineZoom, useUndoable, useViewOptions, useViewport, useWorkspaceState, valueAt, viewOf, viewsOf, withBase, wordAt, wordId, zoomAt, zoomToBox };
17219
17585
 
17220
17586
  //# sourceMappingURL=index.js.map