strata-react 1.3.3 → 1.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -165,6 +165,7 @@ thousands of lines. Such an app imports the same stylesheet **without the reset*
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
167
  | Speech | `speak`, `useSpeech`, `SayAgain`, `installFakeSpeech` (`strata-react/testing`) | The browser's `speechSynthesis` with the voice picked by language once voices have loaded, what is being said cancelled by the next prompt, a slightly slow default rate, and nothing where there is no speech or the person muted it. `SayAgain`'s name is the sentence it says. `installFakeSpeech()` records what was said in a test |
168
+ | Recording | `useRecorder`, `InputLevel`, `TakeLevel`, `MicrophoneContext`, `encodeWav`, `fakeMicrophone` (`strata-react/testing`) | One take of speech from the microphone as a lossless 16-bit PCM WAV (an AudioWorklet, not MediaRecorder, which only writes compressed audio), with the browser's echo cancellation, noise suppression and gain off. `start()` resolves with the take when it stops, by `stop()` or at `maxSeconds`. `InputLevel` is the live peak in dBFS with a "Too loud" notch at -3; `TakeLevel` judges the finished take for speech in words. The device comes from `MicrophoneContext`, so tests pass `renderWithStrata(ui, { microphone: fakeMicrophone() })`. The microphone needs a secure page (https or localhost); the refusals read as sentences |
168
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 |
169
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 |
170
171
  | Overlays | `Dialog`, `DialogProps`, `AlertDialog`, `Popover`, `Tooltip` | React Aria underneath. A dialog always has a title and, via `actions`'s close render prop, a way out; `closable={false}` while work cannot stop; `placement="end"` is a sheet. `AlertDialog` is the only confirm: required verb on the confirm button, Cancel focused first, no outside dismiss, stays open with the reason when an async confirm fails. `Popover` needs a `label`. `Tooltip` opens on hover and focus and `IconButton` uses it. All portal onto the `layer-*` stacking utilities |
@@ -182,7 +183,7 @@ thousands of lines. Such an app imports the same stylesheet **without the reset*
182
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 |
183
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 |
184
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 |
185
- | 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`) |
186
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 |
187
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 |
188
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,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
+ - `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
16
  - `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
17
  - `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
18
  - `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: Record<Exclude<ChoiceState, "open">, string>;
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 or shown as the answer, with its word; answered tiles cannot be pressed again, and the grid closes once the answer shows. */
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 }: {
@@ -0,0 +1,73 @@
1
+ import { Microphone } from '../lib/microphone';
2
+ import { MeterThreshold } from './meter';
3
+ import * as React from "react";
4
+ /** A finished take: the samples, the same as a WAV, and what was measured. */
5
+ export type Recording = {
6
+ samples: Float32Array;
7
+ sampleRate: number;
8
+ /** 16-bit PCM mono WAV of `samples`, ready to upload. */
9
+ wav: Blob;
10
+ seconds: number;
11
+ /** The highest sample in dBFS, never below `LEVEL_FLOOR_DB`. */
12
+ peak: number;
13
+ /** What the browser calls the microphone, or null. */
14
+ device: string | null;
15
+ };
16
+ /** Where a recorder is: idle, waiting for the browser to open the device, recording, or refused. */
17
+ export type RecorderState = {
18
+ phase: "idle";
19
+ } | {
20
+ phase: "opening";
21
+ } | {
22
+ phase: "recording";
23
+ seconds: number;
24
+ level: number;
25
+ } | {
26
+ phase: "failed";
27
+ reason: string;
28
+ };
29
+ /** `useRecorder`'s options. */
30
+ export type UseRecorderOptions = {
31
+ /** The longest take, in seconds: the recorder stops itself there. */
32
+ maxSeconds: number;
33
+ /** The microphone to record from; `useMicrophone()` (the nearest `MicrophoneContext`) when left out. */
34
+ microphone?: Microphone;
35
+ };
36
+ /** What `useRecorder` returns. */
37
+ export type Recorder = {
38
+ state: RecorderState;
39
+ /** Starts a take; resolves with it once it stops (`stop`, or `maxSeconds`), or null when the microphone would not open or a take is already running. */
40
+ start: () => Promise<Recording | null>;
41
+ /** Stops the take, which resolves `start`. Does nothing when nothing is recording. */
42
+ stop: () => void;
43
+ /** True while opening or recording: the moment Record becomes Stop. */
44
+ recording: boolean;
45
+ };
46
+ /** Records one take at a time from the microphone, with its live level, as a lossless WAV. */
47
+ export declare function useRecorder({ maxSeconds, microphone }: UseRecorderOptions): Recorder;
48
+ /** `InputLevel`'s "Too loud" notch: -3 dBFS on the meter's `LEVEL_FLOOR_DB`..0 scale. */
49
+ export declare const inputLevelThresholds: MeterThreshold[];
50
+ /** `InputLevel`'s props. */
51
+ export type InputLevelProps = {
52
+ /** The live peak in dBFS (`state.level` while recording). */
53
+ level: number;
54
+ /** How long the take has run. */
55
+ seconds: number;
56
+ /** The longest take, said beside the running time. */
57
+ maxSeconds: number;
58
+ /** The meter's name. Default "Input level". */
59
+ label?: string;
60
+ className?: string;
61
+ };
62
+ /** The microphone's live level while a take records: a peak meter in dBFS with a "Too loud" notch, and the take's running time. */
63
+ export declare function InputLevel({ level, seconds, maxSeconds, label, className }: InputLevelProps): React.JSX.Element;
64
+ /** `TakeLevel`'s props. */
65
+ export type TakeLevelProps = {
66
+ /** The take's peak in dBFS (`Recording.peak`). */
67
+ peak: number;
68
+ /** What comes before the peak in the sentence, such as "Kept 0:04". */
69
+ lead?: string;
70
+ className?: string;
71
+ };
72
+ /** How a finished take's level reads for speech: a status word, the peak, and what to do about it. */
73
+ export declare function TakeLevel({ peak, lead, className }: TakeLevelProps): React.JSX.Element;
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';
@@ -81,6 +81,9 @@ export { appBase, withBase } from './lib/base';
81
81
  export { useSearchParam, type SearchParam, type SearchParamOptions } from './lib/search-param';
82
82
  export { speak, stopSpeaking, canSpeak, pickVoice, useSpeech, type SpeakOptions, type Speech, type UseSpeechOptions } from './lib/speech';
83
83
  export { SayAgain, type SayAgainProps } from './components/say-again';
84
+ export { browserMicrophone, explainMicrophoneError, MicrophoneContext, MicrophoneError, useMicrophone, type Microphone, type MicrophoneStream, } from './lib/microphone';
85
+ export { LEVEL_FLOOR_DB, joinSamples, encodeWav, peakDb, speechLevel, type SpeechLevel } from './lib/recording';
86
+ export { useRecorder, InputLevel, TakeLevel, inputLevelThresholds, type Recorder, type RecorderState, type Recording, type UseRecorderOptions, type InputLevelProps, type TakeLevelProps, } from './components/recorder';
84
87
  export { ButtonLink, TextLink, type ButtonLinkProps, type TextLinkProps } from './components/link';
85
88
  export { Compare, type CompareProps, type CompareMode, type Candidate, type ImageMedia, type AudioMedia, type TextMedia, type VideoMedia } from './components/compare';
86
89
  export { ViewportFrame, useViewport, type ViewportFrameProps, type ViewportState } from './components/viewport';
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@ import { a as Textarea, c as useSearchParam, d as cn, f as typeSteps, i as Nativ
2
2
  import { a as toDate, i as format, n as NBSP, r as createFormat, t as MISSING } from "./format-B32-PVi2.js";
3
3
  import { a as useAsyncAction, c as KeysLegend, d as useInView, i as AsyncButton, l as isTypingTarget, n as NumberField, o as Toolbar, r as Slider, s as ToolbarSeparator, t as ColorField, u as useHotkeys } from "./value-controls-B7iNh4WO.js";
4
4
  import { a as fieldErrorsOf, c as IconButton, d as isDev, i as errorPayload, l as RowAction, n as describeActionError, o as readErrorBody, r as describeHttpError, s as Button, t as HttpError, u as buttonVariants } from "./errors-D99YX4XL.js";
5
- import { a as toLoad, c as toast, i as staleOf, l as toastTimeout, n as createQueryClient, o as useLoad, r as fetchJson, s as StrataToastRegion, t as StrataQueryProvider, u as overlaySurface } from "./query-CfonqUzU.js";
5
+ import { a as useMicrophone, c as fetchJson, d as useLoad, f as StrataToastRegion, h as overlaySurface, i as explainMicrophoneError, l as staleOf, m as toastTimeout, n as MicrophoneError, o as StrataQueryProvider, p as toast, r as browserMicrophone, s as createQueryClient, t as MicrophoneContext, u as toLoad } from "./microphone-BZXMKTCM.js";
6
6
  import { n as useSharedCursor, r as geo, t as CursorScope } from "./cursor-DDGBPiTJ.js";
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";
@@ -1177,7 +1177,7 @@ function LoadError({ message, retry, className }) {
1177
1177
  }
1178
1178
  var defaultError = (failure) => /* @__PURE__ */ jsx(LoadError, { ...failure });
1179
1179
  /** Every view of remote data: renders `skeleton` while loading, an alert with Try again on error, `empty` when `isEmpty`, else `children(data)`, under a `StaleNotice` when a refresh failed. The skeleton and empty state are required. */
1180
- function DataView({ state, isEmpty, skeleton, empty, children, staleNotice = (stale) => /* @__PURE__ */ jsx(StaleNotice, { stale }), error = defaultError, className }) {
1180
+ function DataView$1({ state, isEmpty, skeleton, empty, children, staleNotice = (stale) => /* @__PURE__ */ jsx(StaleNotice, { stale }), error = defaultError, className }) {
1181
1181
  return /* @__PURE__ */ jsxs("div", {
1182
1182
  className: cn("min-w-0", className),
1183
1183
  "aria-busy": state.status === "loading" || void 0,
@@ -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 or shown as the answer, with its word; answered tiles cannot be pressed again, and the grid closes once the answer shows. */
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", closed(s) && "border-4 border-success bg-success-subtle disabled:hover:border-success"),
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
  })]
@@ -9603,7 +9603,7 @@ function InfiniteList({ state, label, children, skeleton, empty, moreLabel, more
9603
9603
  ruled
9604
9604
  })
9605
9605
  });
9606
- return /* @__PURE__ */ jsx(DataView, {
9606
+ return /* @__PURE__ */ jsx(DataView$1, {
9607
9607
  state,
9608
9608
  isEmpty: (items) => items.length === 0 && !more.hasMore,
9609
9609
  skeleton,
@@ -11345,6 +11345,199 @@ function SayAgain({ text, verb = "Say", className, ...options }) {
11345
11345
  className
11346
11346
  });
11347
11347
  }
11348
+ // src/lib/recording.ts
11349
+ /** The quietest level a speech meter draws, in dBFS: below it is silence for speech. */
11350
+ var LEVEL_FLOOR_DB = -60;
11351
+ /** Joins chunks of samples into one buffer, in order. */
11352
+ function joinSamples(chunks) {
11353
+ const out = new Float32Array(chunks.reduce((n, c) => n + c.length, 0));
11354
+ let at = 0;
11355
+ for (const c of chunks) {
11356
+ out.set(c, at);
11357
+ at += c.length;
11358
+ }
11359
+ return out;
11360
+ }
11361
+ /** A mono 16-bit PCM WAV of `samples` (-1 to 1; beyond full scale is clipped). */
11362
+ function encodeWav(samples, sampleRate) {
11363
+ const bytes = samples.length * 2;
11364
+ const view = new DataView(new ArrayBuffer(44 + bytes));
11365
+ const text = (at, s) => {
11366
+ for (let i = 0; i < s.length; i++) view.setUint8(at + i, s.charCodeAt(i));
11367
+ };
11368
+ text(0, "RIFF");
11369
+ view.setUint32(4, 36 + bytes, true);
11370
+ text(8, "WAVE");
11371
+ text(12, "fmt ");
11372
+ view.setUint32(16, 16, true);
11373
+ view.setUint16(20, 1, true);
11374
+ view.setUint16(22, 1, true);
11375
+ view.setUint32(24, sampleRate, true);
11376
+ view.setUint32(28, sampleRate * 2, true);
11377
+ view.setUint16(32, 2, true);
11378
+ view.setUint16(34, 16, true);
11379
+ text(36, "data");
11380
+ view.setUint32(40, bytes, true);
11381
+ for (let i = 0; i < samples.length; i++) {
11382
+ const s = Math.max(-1, Math.min(1, samples[i]));
11383
+ view.setInt16(44 + i * 2, s < 0 ? s * 32768 : s * 32767, true);
11384
+ }
11385
+ return new Blob([view.buffer], { type: "audio/wav" });
11386
+ }
11387
+ /** The highest sample in dBFS, never below `LEVEL_FLOOR_DB` (silence reads as the floor, not minus infinity). */
11388
+ function peakDb(samples) {
11389
+ let peak = 0;
11390
+ for (let i = 0; i < samples.length; i++) peak = Math.max(peak, Math.abs(samples[i]));
11391
+ return peak > 0 ? Math.max(-60, 20 * Math.log10(peak)) : -60;
11392
+ }
11393
+ /** Judges a take by its peak (dBFS). */
11394
+ function speechLevel(peak) {
11395
+ if (peak >= -1) return {
11396
+ tone: "danger",
11397
+ word: "Too loud",
11398
+ advice: "It may have clipped. Move back from the microphone or turn its gain down."
11399
+ };
11400
+ if (peak < -30) return {
11401
+ tone: "warning",
11402
+ word: "Too quiet",
11403
+ advice: "Move closer to the microphone or turn its gain up."
11404
+ };
11405
+ return {
11406
+ tone: "success",
11407
+ word: "Good level",
11408
+ advice: "The level suits speech."
11409
+ };
11410
+ }
11411
+ // src/components/recorder.tsx
11412
+ /** Records one take at a time from the microphone, with its live level, as a lossless WAV. */
11413
+ function useRecorder({ maxSeconds, microphone }) {
11414
+ const fromContext = useMicrophone();
11415
+ const device = microphone ?? fromContext;
11416
+ const [state, setState] = React.useState({ phase: "idle" });
11417
+ const stream = React.useRef(null);
11418
+ const chunks = React.useRef([]);
11419
+ const resolveStop = React.useRef(null);
11420
+ const limit = React.useRef(maxSeconds);
11421
+ limit.current = maxSeconds;
11422
+ const mounted = React.useRef(true);
11423
+ const stop = React.useCallback(() => {
11424
+ const s = stream.current;
11425
+ if (!s) return;
11426
+ stream.current = null;
11427
+ s.close();
11428
+ const samples = joinSamples(chunks.current);
11429
+ chunks.current = [];
11430
+ setState({ phase: "idle" });
11431
+ resolveStop.current?.({
11432
+ samples,
11433
+ sampleRate: s.sampleRate,
11434
+ wav: encodeWav(samples, s.sampleRate),
11435
+ seconds: samples.length / s.sampleRate,
11436
+ peak: peakDb(samples),
11437
+ device: s.device
11438
+ });
11439
+ resolveStop.current = null;
11440
+ }, []);
11441
+ const start = React.useCallback(async () => {
11442
+ if (stream.current || resolveStop.current) return null;
11443
+ setState({ phase: "opening" });
11444
+ chunks.current = [];
11445
+ let recent = [];
11446
+ let frames = 0;
11447
+ const done = new Promise((resolve) => {
11448
+ resolveStop.current = resolve;
11449
+ });
11450
+ let opened;
11451
+ try {
11452
+ opened = await device.open((chunk) => {
11453
+ const s = stream.current;
11454
+ if (!s) return;
11455
+ const room = Math.round(limit.current * s.sampleRate) - frames;
11456
+ const kept = chunk.length > room ? chunk.subarray(0, Math.max(0, room)) : chunk;
11457
+ chunks.current.push(kept);
11458
+ frames += kept.length;
11459
+ recent = [...recent.slice(-4), peakDb(kept)];
11460
+ setState({
11461
+ phase: "recording",
11462
+ seconds: frames / s.sampleRate,
11463
+ level: Math.max(...recent)
11464
+ });
11465
+ if (kept.length < chunk.length || frames >= limit.current * s.sampleRate) stop();
11466
+ });
11467
+ } catch (e) {
11468
+ resolveStop.current = null;
11469
+ setState({
11470
+ phase: "failed",
11471
+ reason: e instanceof MicrophoneError ? e.message : `The microphone could not be opened (${String(e)}).`
11472
+ });
11473
+ return null;
11474
+ }
11475
+ if (!mounted.current) {
11476
+ opened.close();
11477
+ resolveStop.current = null;
11478
+ return null;
11479
+ }
11480
+ stream.current = opened;
11481
+ setState((now) => now.phase === "opening" ? {
11482
+ phase: "recording",
11483
+ seconds: 0,
11484
+ level: -60
11485
+ } : now);
11486
+ return done;
11487
+ }, [device, stop]);
11488
+ React.useEffect(() => {
11489
+ mounted.current = true;
11490
+ return () => {
11491
+ mounted.current = false;
11492
+ stream.current?.close();
11493
+ stream.current = null;
11494
+ };
11495
+ }, []);
11496
+ return {
11497
+ state,
11498
+ start,
11499
+ stop,
11500
+ recording: state.phase === "recording" || state.phase === "opening"
11501
+ };
11502
+ }
11503
+ /** `InputLevel`'s "Too loud" notch: -3 dBFS on the meter's `LEVEL_FLOOR_DB`..0 scale. */
11504
+ var inputLevelThresholds = [{
11505
+ at: -57 / -60,
11506
+ tone: "danger",
11507
+ label: "Too loud"
11508
+ }];
11509
+ /** The microphone's live level while a take records: a peak meter in dBFS with a "Too loud" notch, and the take's running time. */
11510
+ function InputLevel({ level, seconds, maxSeconds, label = "Input level", className }) {
11511
+ const db = Math.min(0, Math.max(-60, level));
11512
+ return /* @__PURE__ */ jsx(Meter, {
11513
+ label,
11514
+ value: db - -60,
11515
+ max: 60,
11516
+ thresholds: inputLevelThresholds,
11517
+ valueText: `${format.integer(Math.round(db) || 0)}\u00a0dBFS`,
11518
+ detail: `Recording ${format.runningTime(seconds)} of at most ${format.runningTime(maxSeconds)}`,
11519
+ className
11520
+ });
11521
+ }
11522
+ /** How a finished take's level reads for speech: a status word, the peak, and what to do about it. */
11523
+ function TakeLevel({ peak, lead, className }) {
11524
+ const verdict = speechLevel(peak);
11525
+ const figure = `peak ${format.integer(Math.round(peak) || 0)}\u00a0dBFS`;
11526
+ return /* @__PURE__ */ jsxs("p", {
11527
+ className: cn("flex items-baseline gap-2 type-body-sm", className),
11528
+ children: [/* @__PURE__ */ jsx(Status, {
11529
+ tone: verdict.tone,
11530
+ children: verdict.word
11531
+ }), /* @__PURE__ */ jsxs("span", {
11532
+ className: "min-w-0 flex-1",
11533
+ children: [
11534
+ lead ? `${lead}, ${figure}` : figure.charAt(0).toUpperCase() + figure.slice(1),
11535
+ ". ",
11536
+ verdict.advice
11537
+ ]
11538
+ })]
11539
+ });
11540
+ }
11348
11541
  // src/components/link.tsx
11349
11542
  function useTarget(target, newTab) {
11350
11543
  const navigate = useNavigate();
@@ -12062,7 +12255,7 @@ function PairJudge({ pair, skeleton, empty, onAnswer, pending, progress, flagRea
12062
12255
  className: "type-body-sm text-muted-foreground",
12063
12256
  children: progress
12064
12257
  }),
12065
- /* @__PURE__ */ jsx(DataView, {
12258
+ /* @__PURE__ */ jsx(DataView$1, {
12066
12259
  state: pair,
12067
12260
  isEmpty: (p) => p === null,
12068
12261
  skeleton,
@@ -17022,6 +17215,6 @@ function FolderPicker({ label, useFolders: useListing, value, onChange, onChoose
17022
17215
  ]
17023
17216
  });
17024
17217
  }
17025
- 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, Density, Dialog, Disclosure, Done, DragSource, EmptyState, FIT, Field, FileButton, FileDropZone, FileOutcomes, FolderPicker, FullscreenFrame, HttpError, IconButton, InfiniteList, Input, Inspector, InspectorSection, JobStatus, KeysLegend, Lightbox, LineChart, LineChartGroup, LinkCard, LinkCardList, LoadError, LoadMore, MAX_SCALE, MAX_SIDE, MIN_SCALE, MISSING, Mark, MarkSummary, MarkableText, MediaGroup, MediaPlayer, MediaStage, Menu, Meter, Metric, MetricStrip, 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, 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, buttonVariants, canFullscreen, canSpeak, clampToRoom, clampViewport, cn, colorSchemeScript, commandShortcut, countMarks, createApi, createFormat, createQueryClient, createTypedApi, crossedThreshold, describeActionError, describeHttpError, describeRegion, detectPlatform, diffWords, differences, drawRect, ease, errorPayload, fetchJson, fieldErrorsOf, findPage, fitRect, format, formatChord, gainToVolume, geo, gridPoints, gutterOf, isDoubtful, isReservedChord, isTaskRunning, isTypingTarget, jobProgressText, joinMediaGroup, joinRects, labelOf, lerpRect, logScale, loudnessOf, matchEntities, matchGains, matchesAccept, matchesChord, measureLoudness, moveGutter, moveRect, noOverlap, normaliseAngle, pageName, parentOf, parseChord, parseInline, parseRichText, parseSort, peaksFromAudio, phraseAt, phraseDoubtful, phraseOfWordId, pickVoice, plainText, rangeBetween, readErrorBody, readPixels, readingOrder, regionShares, resample, resamplePeaks, resizeRect, safeHref, sayPosition, serialiseSort, settleCut, snapToGrid, sortRows, speak, 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, usePlayerWarnings, useSearchParam, useSelection, useSharedCursor, useSpeech, useSystemColorScheme, useTimelineZoom, useUndoable, useViewOptions, useViewport, useWorkspaceState, valueAt, viewOf, viewsOf, withBase, wordAt, wordId, zoomAt, zoomToBox };
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 };
17026
17219
 
17027
17220
  //# sourceMappingURL=index.js.map