strata-react 1.3.4 → 1.3.6
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 +2 -2
- package/UPGRADING.md +2 -0
- package/dist/components/choice-grid.d.ts +13 -4
- package/dist/components/say-again.d.ts +5 -3
- package/dist/index.d.ts +2 -2
- package/dist/index.js +87 -24
- package/dist/index.js.map +1 -1
- package/dist/lib/speech.d.ts +24 -8
- package/dist/query/typed-api.d.ts +8 -9
- package/dist/testing/speech.d.ts +7 -1
- package/dist/testing.js +50 -1
- package/dist/testing.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -164,7 +164,7 @@ thousands of lines. Such an app imports the same stylesheet **without the reset*
|
|
|
164
164
|
| Workspace | `Workspace`, `Split`, `Pane`, `useWorkspaceState`, `WorkspaceState` | One screen of panes for a tool: splits of panes with a growing stage, a header on every pane (name, actions, fold button), separators that resize by pointer and by keyboard (arrows, Shift, Home, End, Enter to restore) within each pane's `min` and `max`, panes that fold to a rail or header bar with a visible way back (and `state.toggle(id)` from a menu), sizes and folds remembered with `useWorkspaceState("name")`, and stacking below 720px. Each pane is a labelled region |
|
|
165
165
|
| History and save state | `useHistory`, `useHistoryState`, `History`, `useAutoSave`, `SaveStatus`, `SaveState`, `useLeaveGuard` | Undo and redo for a document edited over a session: a step is a name and an `undo`/`redo` pair, `begin(label)` groups a drag into one step, a `key` merges a slider's pushes, a `limit` drops the oldest. `history.commands` are Undo and Redo as `Command`s ("Undo move clip", Mod+Z, Mod+Shift+Z or Mod+Y) for `useCommands` and `Menu`. `useAutoSave` debounces and never overlaps saves; `SaveStatus` is the fixed-width sign ("Saved 10:42", "Saving…", "Unsaved changes", "Not saved" with the reason and "Try again"), quiet except for a failure and its recovery. For one removal that commits after a few seconds, use `useUndoable` |
|
|
166
166
|
| Links and URL choices | `ButtonLink`, `TextLink`, `useSearchParam`, `NativeSelect param=`, `ChoiceGroup param=`, `ToggleGroup param=` | `ButtonLink` is a link (`to` for a route, `href` for a download) drawn as a `Button` with its variants; it sets `data-variant`, so `variant="default"` is the view's one filled button for `expectOneFilledButton()`. `TextLink` is the house in-app link. Both are React Aria links with React Router navigation. A filter or choice a person would link to is `useSearchParam("mode", { default, parse })` (the default is never written, an invalid value reads as the default, other params are kept, history is replaced), or `param=` on the three controls, as `Tabs` does |
|
|
167
|
-
| Speech | `speak`, `useSpeech`, `SayAgain`, `installFakeSpeech` (`strata-react/testing`) | The browser's `speechSynthesis` with the voice picked by language once voices have loaded, what is being said cancelled by the next prompt, a slightly slow default rate, and nothing where there is no speech or the person muted it. `SayAgain`'s name is the sentence it says. `installFakeSpeech()` records what was said in a test |
|
|
167
|
+
| 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
168
|
| Recording | `useRecorder`, `InputLevel`, `TakeLevel`, `MicrophoneContext`, `encodeWav`, `fakeMicrophone` (`strata-react/testing`) | One take of speech from the microphone as a lossless 16-bit PCM WAV (an AudioWorklet, not MediaRecorder, which only writes compressed audio), with the browser's echo cancellation, noise suppression and gain off. `start()` resolves with the take when it stops, by `stop()` or at `maxSeconds`. `InputLevel` is the live peak in dBFS with a "Too loud" notch at -3; `TakeLevel` judges the finished take for speech in words. The device comes from `MicrophoneContext`, so tests pass `renderWithStrata(ui, { microphone: fakeMicrophone() })`. The microphone needs a secure page (https or localhost); the refusals read as sentences |
|
|
169
169
|
| Toolbar and toggles | `Toolbar`, `ToolbarSeparator`, `Toggle`, `ToggleGroup`, `Switch` | A toolbar is one tab stop with arrows, Home and End inside; needs a `label`. `Toggle` (`aria-pressed`) and `ToggleGroup` (one of 2 to 7, always one chosen) show chosen as an ink border on a tint, never the filled primary, so they do not break the one-filled-button rule; an icon-only toggle still needs its `label` (shown as a tooltip). `Switch` is only for a setting that applies at once, label and control one target |
|
|
170
170
|
| Commands | `Command`, `useCommands`, `Menu`, `ContextMenu`, `CommandMenu`, `CommandLegend`, `formatChord`, `matchesChord` | A command is declared once (label or label function, chords, `disabled` with a reason, `destructive`, `checked`) and drives the key handler, dropdown and menu-bar menus, the context menu, the searchable command menu (Mod+K) and the legend, so they cannot disagree. Chords are written once ("Mod+Shift+Z") and shown per platform (⇧⌘Z, Ctrl+Shift+Z); they never fire while typing or during IME composition, and a chord the browser keeps (Ctrl+S) needs `claim: true`. `useHotkeys` is unchanged for single keys |
|
|
@@ -183,7 +183,7 @@ thousands of lines. Such an app imports the same stylesheet **without the reset*
|
|
|
183
183
|
| 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 |
|
|
184
184
|
| 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 |
|
|
185
185
|
| 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 |
|
|
186
|
-
| Answering by tap | `ChoiceGrid`, `ChoiceGridSkeleton`, `ChoiceState`; the `type-picture` step | One question, large picture tiles, one right answer, for someone who may not read yet (a child's learning game). Each tile is `open`, `wrong` (greyed, never red), `right` or `answer` (shown after the tries ran out), always with its word; the app owns the answer key. Answered tiles cannot be pressed again and the grid closes once the answer shows. React Aria's `GridList`: arrows across and down, Enter answers. Tiles at least 120px (`md`) or 160px (`lg`) |
|
|
186
|
+
| Answering by tap | `ChoiceGrid`, `ChoiceGridSkeleton`, `ChoiceState`; the `type-picture` step | One question, large picture tiles, one right answer, for someone who may not read yet (a child's learning game). Each tile is `open`, `wrong` (greyed, never red), `right` or `answer` (shown after the tries ran out), always with its word; a choice with no answer key ("Which one next?", a rating) uses `picked` (primary border, neutral word, `marks={{ picked }}`), which closes the grid so a slow request cannot be tapped twice; the app owns the answer key. Answered tiles cannot be pressed again and the grid closes once the answer shows. React Aria's `GridList`: arrows across and down, Enter answers. Tiles at least 120px (`md`) or 160px (`lg`) |
|
|
187
187
|
| 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 |
|
|
188
188
|
| 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 |
|
|
189
189
|
| 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 |
|
package/UPGRADING.md
CHANGED
|
@@ -12,6 +12,8 @@ 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.
|
|
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: … }`.
|
|
15
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.
|
|
16
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).
|
|
17
19
|
- `NativeSelect`, `ChoiceGroup` and `ToggleGroup` are now unions that also take `param` (URL-held choice); `ChoiceGroup` and `ToggleGroup` are function components with the same props, so nothing changes for existing callers. `fetchJson`'s init type is `FetchJsonInit` (`RequestInit` plus `json`).
|
|
@@ -1,6 +1,15 @@
|
|
|
1
1
|
import * as React from "react";
|
|
2
2
|
/** Where a tile stands in the round: not yet tried, tried and wrong, tried and right, or shown as the answer after the tries ran out. */
|
|
3
|
-
export type ChoiceState = "open" | "wrong" | "right" | "answer";
|
|
3
|
+
export type ChoiceState = "open" | "wrong" | "right" | "answer" | "picked";
|
|
4
|
+
/** The word under each closed tile. A quiz gives `wrong`, `right` and `answer` (and `picked` if it ever uses it); a choice with no answer key gives only `picked`. A state with no word draws no word, so name every state the grid can reach. */
|
|
5
|
+
export type ChoiceMarks = (Record<"wrong" | "right" | "answer", string> & {
|
|
6
|
+
picked?: string;
|
|
7
|
+
}) | {
|
|
8
|
+
picked: string;
|
|
9
|
+
wrong?: never;
|
|
10
|
+
right?: never;
|
|
11
|
+
answer?: never;
|
|
12
|
+
};
|
|
4
13
|
/** Smallest tile side: `md` 120px, `lg` 160px. Tiles grow to fill the row. */
|
|
5
14
|
export type ChoiceSize = "md" | "lg";
|
|
6
15
|
/** Props of `ChoiceGrid`. */
|
|
@@ -15,15 +24,15 @@ export type ChoiceGridProps<T> = {
|
|
|
15
24
|
renderPicture: (item: T) => React.ReactNode;
|
|
16
25
|
/** Each tile's state in the round. The app owns the answer; the grid only draws it. */
|
|
17
26
|
state: (item: T) => ChoiceState;
|
|
18
|
-
/** The word under a closed tile, for each closed state: `{ wrong: "Not this one", right: "Right", answer: "This one" }
|
|
19
|
-
marks:
|
|
27
|
+
/** The word under a closed tile, for each closed state: `{ wrong: "Not this one", right: "Right", answer: "This one" }`, or `{ picked: "Picked" }` where there is no answer key. */
|
|
28
|
+
marks: ChoiceMarks;
|
|
20
29
|
/** An open tile was pressed (pointer, touch, Enter or Space). */
|
|
21
30
|
onChoose: (item: T) => void;
|
|
22
31
|
/** Default `md`. */
|
|
23
32
|
size?: ChoiceSize;
|
|
24
33
|
className?: string;
|
|
25
34
|
};
|
|
26
|
-
/** A grid of large picture tiles for answering one question with a tap: each tile open, wrong, right
|
|
35
|
+
/** A grid of large picture tiles for answering one question with a tap: each tile open, wrong, right, shown as the answer or (no answer key) picked, with its word; answered tiles cannot be pressed again, and the grid closes once the answer shows. */
|
|
27
36
|
export declare function ChoiceGrid<T>({ label, items, itemKey, itemLabel, renderPicture, state, marks, onChoose, size, className }: ChoiceGridProps<T>): React.JSX.Element;
|
|
28
37
|
/** The loading shape of a `ChoiceGrid`: `count` tiles at the same size, for a `DataView` skeleton. */
|
|
29
38
|
export declare function ChoiceGridSkeleton({ count, size, className }: {
|
|
@@ -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
|
|
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
|
@@ -58,7 +58,7 @@ export { BulkBar, useSelection, useChoices, type InitialSelection, type Choices,
|
|
|
58
58
|
export type { Implies } from './lib/choice';
|
|
59
59
|
export { SelectableGrid, type SelectableGridProps, type TileAspect, type TileSize, } from './components/selectable-grid';
|
|
60
60
|
export { ViewOptions, useViewOptions, sortRows, type ViewOptionsProps, type ViewOptionsConfig, type ViewOptionsState, type ViewSort, type ViewGroup, type ViewGroupRows } from './components/view-options';
|
|
61
|
-
export { ChoiceGrid, ChoiceGridSkeleton, type ChoiceGridProps, type ChoiceState, type ChoiceSize } from './components/choice-grid';
|
|
61
|
+
export { ChoiceGrid, ChoiceGridSkeleton, type ChoiceGridProps, type ChoiceState, type ChoiceMarks, type ChoiceSize } from './components/choice-grid';
|
|
62
62
|
export { PlaceBoard, type PlaceBoardProps, type PlaceState } from './components/place-board';
|
|
63
63
|
export { TileGrid, TileGridSkeleton, SelectableGridSkeleton, type TileGridProps } from './components/tile-grid';
|
|
64
64
|
export { VirtualList } from './components/virtual-list';
|
|
@@ -79,7 +79,7 @@ export { StrataQueryProvider, createQueryClient, toLoad, staleOf, useLoad, useIn
|
|
|
79
79
|
export { describeActionError, fieldErrorsOf } from './lib/errors';
|
|
80
80
|
export { appBase, withBase } from './lib/base';
|
|
81
81
|
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';
|
|
82
|
+
export { speak, stopSpeaking, canSpeak, canPlayClips, canSay, textOf, pickVoice, useSpeech, type SpeakOptions, type Speech, type SpeechPart, type Saying, type UseSpeechOptions } from './lib/speech';
|
|
83
83
|
export { SayAgain, type SayAgainProps } from './components/say-again';
|
|
84
84
|
export { browserMicrophone, explainMicrophoneError, MicrophoneContext, MicrophoneError, useMicrophone, type Microphone, type MicrophoneStream, } from './lib/microphone';
|
|
85
85
|
export { LEVEL_FLOOR_DB, joinSamples, encodeWav, peakDb, speechLevel, type SpeechLevel } from './lib/recording';
|
package/dist/index.js
CHANGED
|
@@ -9280,9 +9280,9 @@ var minSide = {
|
|
|
9280
9280
|
md: 120,
|
|
9281
9281
|
lg: 160
|
|
9282
9282
|
};
|
|
9283
|
-
var closed = (s) => s === "right" || s === "answer";
|
|
9283
|
+
var closed = (s) => s === "right" || s === "answer" || s === "picked";
|
|
9284
9284
|
var columns = (size) => ({ gridTemplateColumns: `repeat(auto-fill, minmax(min(${minSide[size]}px, 100%), 1fr))` });
|
|
9285
|
-
/** A grid of large picture tiles for answering one question with a tap: each tile open, wrong, right
|
|
9285
|
+
/** A grid of large picture tiles for answering one question with a tap: each tile open, wrong, right, shown as the answer or (no answer key) picked, with its word; answered tiles cannot be pressed again, and the grid closes once the answer shows. */
|
|
9286
9286
|
function ChoiceGrid({ label, items, itemKey, itemLabel, renderPicture, state, marks, onChoose, size = "md", className }) {
|
|
9287
9287
|
const byKey = new Map(items.map((item) => [itemKey(item), item]));
|
|
9288
9288
|
const over = items.some((item) => closed(state(item)));
|
|
@@ -9301,19 +9301,19 @@ function ChoiceGrid({ label, items, itemKey, itemLabel, renderPicture, state, ma
|
|
|
9301
9301
|
children: items.map((item) => {
|
|
9302
9302
|
const key = itemKey(item);
|
|
9303
9303
|
const s = state(item);
|
|
9304
|
-
const mark = s === "open" ? null : marks[s];
|
|
9304
|
+
const mark = s === "open" ? null : marks[s] ?? null;
|
|
9305
9305
|
return /* @__PURE__ */ jsxs(GridListItem, {
|
|
9306
9306
|
id: key,
|
|
9307
9307
|
textValue: itemLabel(item),
|
|
9308
9308
|
"aria-label": mark ? `${itemLabel(item)}, ${mark.toLowerCase()}` : itemLabel(item),
|
|
9309
9309
|
"data-choice": s,
|
|
9310
|
-
className: cn("flex aspect-square min-w-0 cursor-pointer flex-col items-center justify-center gap-1 rounded-overlay border-2 border-border bg-card p-2 text-card-foreground select-none outline-offset-2 transition-state press", "hover:border-primary disabled:cursor-default disabled:hover:border-border",
|
|
9310
|
+
className: cn("flex aspect-square min-w-0 cursor-pointer flex-col items-center justify-center gap-1 rounded-overlay border-2 border-border bg-card p-2 text-card-foreground select-none outline-offset-2 transition-state press", "hover:border-primary disabled:cursor-default disabled:hover:border-border", (s === "right" || s === "answer") && "border-4 border-success bg-success-subtle disabled:hover:border-success", s === "picked" && "border-4 border-primary bg-surface-sunken disabled:hover:border-primary"),
|
|
9311
9311
|
children: [/* @__PURE__ */ jsx("span", {
|
|
9312
9312
|
"aria-hidden": true,
|
|
9313
9313
|
className: cn("type-picture transition-state", s === "wrong" && "opacity-40"),
|
|
9314
9314
|
children: renderPicture(item)
|
|
9315
9315
|
}), mark && /* @__PURE__ */ jsx(Status, {
|
|
9316
|
-
tone: s === "wrong" ? "neutral" : "success",
|
|
9316
|
+
tone: s === "wrong" || s === "picked" ? "neutral" : "success",
|
|
9317
9317
|
className: "max-w-full truncate",
|
|
9318
9318
|
children: mark
|
|
9319
9319
|
})]
|
|
@@ -11253,6 +11253,21 @@ function isTaskRunning(task, finished) {
|
|
|
11253
11253
|
return !(Array.isArray(finished) ? finished.includes(task.state) : finished.has(task.state));
|
|
11254
11254
|
}
|
|
11255
11255
|
// src/lib/speech.ts
|
|
11256
|
+
var partsOf = (saying) => (typeof saying === "string" ? [{ text: saying }] : [...saying]).filter((p) => p.text.trim() || p.clip);
|
|
11257
|
+
/** 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. */
|
|
11258
|
+
function textOf(saying) {
|
|
11259
|
+
return partsOf(saying).map((p) => p.text.trim()).filter(Boolean).join(" ");
|
|
11260
|
+
}
|
|
11261
|
+
/** Whether this browser can play a recording. */
|
|
11262
|
+
function canPlayClips() {
|
|
11263
|
+
return typeof window !== "undefined" && typeof window.Audio === "function";
|
|
11264
|
+
}
|
|
11265
|
+
var allRecorded = (parts) => parts.length > 0 && parts.every((p) => p.clip);
|
|
11266
|
+
/** Whether `saying` can be said here: every part recorded and audio plays, or the browser has speech and there are words. */
|
|
11267
|
+
function canSay(saying) {
|
|
11268
|
+
const parts = partsOf(saying);
|
|
11269
|
+
return allRecorded(parts) && canPlayClips() || canSpeak() && textOf(parts) !== "";
|
|
11270
|
+
}
|
|
11256
11271
|
/** Whether this browser can say text aloud. */
|
|
11257
11272
|
function canSpeak() {
|
|
11258
11273
|
return typeof window !== "undefined" && "speechSynthesis" in window && typeof SpeechSynthesisUtterance !== "undefined";
|
|
@@ -11264,11 +11279,11 @@ function pickVoice(voices, lang) {
|
|
|
11264
11279
|
const base = wanted.split("-")[0];
|
|
11265
11280
|
return voices.find((v) => v.lang.toLowerCase().replace("_", "-") === wanted) ?? voices.find((v) => v.lang.toLowerCase().replace("_", "-").split("-")[0] === base);
|
|
11266
11281
|
}
|
|
11267
|
-
/**
|
|
11268
|
-
|
|
11282
|
+
/** The recording playing now, so the next prompt or `stopSpeaking` can cut it off. */
|
|
11283
|
+
var playing;
|
|
11284
|
+
function speakText(text, { lang, rate = .9, onEnd }) {
|
|
11269
11285
|
if (!canSpeak() || !text.trim()) return false;
|
|
11270
11286
|
const synth = window.speechSynthesis;
|
|
11271
|
-
synth.cancel();
|
|
11272
11287
|
const utterance = new SpeechSynthesisUtterance(text);
|
|
11273
11288
|
if (lang) utterance.lang = lang;
|
|
11274
11289
|
utterance.rate = rate;
|
|
@@ -11281,8 +11296,56 @@ function speak(text, { lang, rate = .9, onEnd } = {}) {
|
|
|
11281
11296
|
synth.speak(utterance);
|
|
11282
11297
|
return true;
|
|
11283
11298
|
}
|
|
11284
|
-
|
|
11299
|
+
function playFrom(parts, i, options) {
|
|
11300
|
+
const part = parts[i];
|
|
11301
|
+
if (!part) {
|
|
11302
|
+
options.onEnd?.();
|
|
11303
|
+
return;
|
|
11304
|
+
}
|
|
11305
|
+
const audio = new Audio();
|
|
11306
|
+
audio.title = part.text;
|
|
11307
|
+
let settled = false;
|
|
11308
|
+
const settle = () => {
|
|
11309
|
+
if (settled) return false;
|
|
11310
|
+
settled = true;
|
|
11311
|
+
if (playing === entry) playing = void 0;
|
|
11312
|
+
return true;
|
|
11313
|
+
};
|
|
11314
|
+
const fallBack = () => {
|
|
11315
|
+
if (settle() && !speakText(textOf(parts.slice(i)), options)) options.onEnd?.();
|
|
11316
|
+
};
|
|
11317
|
+
const entry = { stop: () => {
|
|
11318
|
+
if (!settle()) return;
|
|
11319
|
+
audio.pause();
|
|
11320
|
+
options.onEnd?.();
|
|
11321
|
+
} };
|
|
11322
|
+
playing = entry;
|
|
11323
|
+
audio.onended = () => {
|
|
11324
|
+
if (settle()) playFrom(parts, i + 1, options);
|
|
11325
|
+
};
|
|
11326
|
+
audio.onerror = fallBack;
|
|
11327
|
+
audio.src = part.clip ?? "";
|
|
11328
|
+
audio.play()?.catch(fallBack);
|
|
11329
|
+
}
|
|
11330
|
+
/**
|
|
11331
|
+
* 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
|
|
11332
|
+
* every part has one, else their words go to the browser's voice. Does nothing where neither can. Returns whether it started.
|
|
11333
|
+
*/
|
|
11334
|
+
function speak(saying, options = {}) {
|
|
11335
|
+
const parts = partsOf(saying);
|
|
11336
|
+
if (!parts.length) return false;
|
|
11337
|
+
if (allRecorded(parts) && canPlayClips()) {
|
|
11338
|
+
stopSpeaking();
|
|
11339
|
+
playFrom(parts, 0, options);
|
|
11340
|
+
return true;
|
|
11341
|
+
}
|
|
11342
|
+
if (!canSpeak() || !textOf(parts)) return false;
|
|
11343
|
+
stopSpeaking();
|
|
11344
|
+
return speakText(textOf(parts), options);
|
|
11345
|
+
}
|
|
11346
|
+
/** Stops whatever is being said or played. */
|
|
11285
11347
|
function stopSpeaking() {
|
|
11348
|
+
playing?.stop();
|
|
11286
11349
|
if (canSpeak()) window.speechSynthesis.cancel();
|
|
11287
11350
|
}
|
|
11288
11351
|
/**
|
|
@@ -11294,13 +11357,12 @@ function useSpeech({ lang, rate, muted = false } = {}) {
|
|
|
11294
11357
|
const [speaking, setSpeaking] = React.useState(false);
|
|
11295
11358
|
const [, setVoicesVersion] = React.useState(0);
|
|
11296
11359
|
React.useEffect(() => {
|
|
11297
|
-
|
|
11298
|
-
const synth = window.speechSynthesis;
|
|
11360
|
+
const synth = canSpeak() ? window.speechSynthesis : void 0;
|
|
11299
11361
|
const onVoices = () => setVoicesVersion((n) => n + 1);
|
|
11300
|
-
synth
|
|
11362
|
+
synth?.addEventListener?.("voiceschanged", onVoices);
|
|
11301
11363
|
return () => {
|
|
11302
|
-
synth
|
|
11303
|
-
|
|
11364
|
+
synth?.removeEventListener?.("voiceschanged", onVoices);
|
|
11365
|
+
stopSpeaking();
|
|
11304
11366
|
};
|
|
11305
11367
|
}, []);
|
|
11306
11368
|
React.useEffect(() => {
|
|
@@ -11312,9 +11374,9 @@ function useSpeech({ lang, rate, muted = false } = {}) {
|
|
|
11312
11374
|
return {
|
|
11313
11375
|
supported,
|
|
11314
11376
|
speaking,
|
|
11315
|
-
say: React.useCallback((
|
|
11316
|
-
if (
|
|
11317
|
-
const spoken = speak(
|
|
11377
|
+
say: React.useCallback((saying) => {
|
|
11378
|
+
if (muted) return false;
|
|
11379
|
+
const spoken = speak(saying, {
|
|
11318
11380
|
lang,
|
|
11319
11381
|
rate,
|
|
11320
11382
|
onEnd: () => setSpeaking(false)
|
|
@@ -11322,7 +11384,7 @@ function useSpeech({ lang, rate, muted = false } = {}) {
|
|
|
11322
11384
|
setSpeaking(spoken);
|
|
11323
11385
|
return spoken;
|
|
11324
11386
|
}, [
|
|
11325
|
-
|
|
11387
|
+
muted,
|
|
11326
11388
|
lang,
|
|
11327
11389
|
rate
|
|
11328
11390
|
]),
|
|
@@ -11333,15 +11395,16 @@ function useSpeech({ lang, rate, muted = false } = {}) {
|
|
|
11333
11395
|
};
|
|
11334
11396
|
}
|
|
11335
11397
|
// src/components/say-again.tsx
|
|
11336
|
-
/** An icon button that says one sentence aloud with the browser's voice; hidden where
|
|
11337
|
-
function SayAgain({ text, verb = "Say", className, ...options }) {
|
|
11338
|
-
const { say,
|
|
11339
|
-
|
|
11398
|
+
/** 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. */
|
|
11399
|
+
function SayAgain({ text, parts, verb = "Say", className, ...options }) {
|
|
11400
|
+
const { say, speaking } = useSpeech(options);
|
|
11401
|
+
const saying = parts?.length ? parts : text;
|
|
11402
|
+
if (options.muted || !canSay(saying)) return null;
|
|
11340
11403
|
return /* @__PURE__ */ jsx(IconButton, {
|
|
11341
11404
|
icon: Volume2,
|
|
11342
11405
|
label: `${verb}: ${text}`,
|
|
11343
11406
|
"aria-pressed": speaking || void 0,
|
|
11344
|
-
onPress: () => say(
|
|
11407
|
+
onPress: () => say(saying),
|
|
11345
11408
|
className
|
|
11346
11409
|
});
|
|
11347
11410
|
}
|
|
@@ -17215,6 +17278,6 @@ function FolderPicker({ label, useFolders: useListing, value, onChange, onChoose
|
|
|
17215
17278
|
]
|
|
17216
17279
|
});
|
|
17217
17280
|
}
|
|
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 };
|
|
17281
|
+
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, canPlayClips, canSay, 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, 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, usePlayerWarnings, useRecorder, useSearchParam, useSelection, useSharedCursor, useSpeech, useSystemColorScheme, useTimelineZoom, useUndoable, useViewOptions, useViewport, useWorkspaceState, valueAt, viewOf, viewsOf, withBase, wordAt, wordId, zoomAt, zoomToBox };
|
|
17219
17282
|
|
|
17220
17283
|
//# sourceMappingURL=index.js.map
|