strata-react 1.3.8 → 1.3.10
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 +3 -2
- package/UPGRADING.md +4 -0
- package/dist/components/film-strip.d.ts +35 -0
- package/dist/components/waveform.d.ts +6 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.js +300 -14
- package/dist/index.js.map +1 -1
- package/dist/lib/waveform.d.ts +10 -0
- package/dist/query/api.d.ts +1 -1
- package/dist/query/clips.d.ts +48 -0
- package/dist/query/reserve.d.ts +33 -0
- package/dist/query/typed-api.d.ts +8 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -163,9 +163,10 @@ thousands of lines. Such an app imports the same stylesheet **without the reset*
|
|
|
163
163
|
| Density | `Density`, `DensityName`, `ThemeProvider`'s `density`, `ControlSize` (`size="sm"` on `Input`, `NativeSelect`, `NumberField`, `IconButton`) | Control height is two variables, `--control-h` and `--control-h-sm`. `<ThemeProvider density="compact">` or `<Density page value="compact">` sets them app-wide, including dialogs and menus, which portal out of the app's root; `<Density value="compact">` is one region (a toolbar, a dense panel) and does not reach its overlays. A coarse pointer (touch) always gets 44px targets, whatever the density A second look for a region is roles alone: set `--control-h`, `--control-h-sm`, `--control-px`, `--control-px-sm`, `--control-icon` and each type step's `--type-<step>-size`, `-leading` and `-weight` (`caption`, `label`, `body-sm`, `body`, `heading`, `title`, `figure`) on a class; the defaults are today's values. |
|
|
164
164
|
| Workspace | `Workspace`, `Split`, `Pane`, `useWorkspaceState`, `WorkspaceState` | One screen of panes for a tool: splits of panes with a growing stage, a header on every pane (name, actions, fold button), separators that resize by pointer and by keyboard (arrows, Shift, Home, End, Enter to restore) within each pane's `min` and `max`, panes that fold to a rail or header bar with a visible way back (and `state.toggle(id)` from a menu), sizes and folds remembered with `useWorkspaceState("name")`, and stacking below 720px. Each pane is a labelled region |
|
|
165
165
|
| 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 |
|
|
166
|
+
| Items kept for offline | `createReserve`, `useReserve` | The read side of the outbox: items the server made ahead (rounds of play), kept per key in localStorage (`strata:reserve:<name>:<key>`), `size` each. `take(key)` removes and returns the oldest (an item is used once); `refresh(key, fresh)` after a fresh item arrives drops kept items `sameMake(kept, fresh)` calls out of date and tops up in one request when fewer than half remain (one in flight per key; a failure is tried again at the next refresh); `useReserve(reserve, key)` is the count for "6 rounds kept for offline"; `seed` and `clear` for tests and stories. Without storage nothing is kept and `persisted` says so |
|
|
166
167
|
| 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` |
|
|
167
168
|
| 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 |
|
|
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()`) |
|
|
169
|
+
| Speech | `speak`, `useSpeech`, `SayAgain`, `ClipsProvider`, `useClips`, `useSayOnShow`, `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()`) . `ClipsProvider load=` reads the app's clip list once (a record of line text to URL, read again only when `clipsQueryKey` is invalidated); `useClips()` gives `ready`, `parts(text)`, `say(text)` and `words(text)` (`split` cuts a prompt into lines, `describe` words a line that has no clip), `useSayOnShow(text)` says a prompt once the list has arrived or failed, and `SayAgain` inside the provider needs no `parts` or `lang`; outside it, the browser's voice alone |
|
|
169
170
|
| 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 |
|
|
170
171
|
| 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 |
|
|
171
172
|
| 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 |
|
|
@@ -174,7 +175,7 @@ thousands of lines. Such an app imports the same stylesheet **without the reset*
|
|
|
174
175
|
| Notices and progress | `Alert`, `toast`, `StrataToastRegion`, `useClientWork`, `JobStatus` | Three weights. A `toast` confirms finished work and goes by itself (5 s plus 40 ms a character, 8 s minimum with an action, paused under the pointer or focus, always dismissable); it has no danger tone, because an error a person must act on is an inline `Alert` with its recovery as `action` (`announce` makes it `role="alert"` only when it answers something the person just did). `StrataToastRegion` goes once at the app root. `useClientWork` runs browser work with progress, cancel (aborts its `signal`, ends `cancelled`, never `failed`) and a double-start guard; `JobStatus` shows it exactly as it shows a server job, with `onCancel`, `cancelled` and `onDismiss` |
|
|
175
176
|
| Media player | `MediaPlayer`, `useMediaElement`, `SPEECH_RATES`, `useMediaSpans`, `SpanActions`, `PlayerNotice`, `SpanStrip` | Play a file or a sequence of chapters without the event glue: the element, its state, Strata's controls (or the browser's own on a touch device, `controls="auto"`), a load error with Try again, `navigator.mediaSession` metadata, the seek bar spanning the whole sequence. `useMediaElement(ref)` alone follows an element drawn with the browser's controls `spans` and `spanKinds` mark stretches (an intro, a recap, a sponsor read) on the seek bar as named ranges in a status role's tone and act on them as playback reaches them: `auto` skips (or mutes, for `action: "mute"`) with "Skipped intro" and Undo, `ask` offers a Skip button over the picture and on the `s` key, `off` only draws; each is acted on once, `onSpan` reports `skipped`, `muted`, `undone` or `played`, and `SeekBar` takes `spans` too. `mediaRef` hands out the player's state and requests (an object ref holds the latest, no render of its own), `overlay` draws the app's own thing over the picture only, and a video keeps a 16:9 (or `aspect`) box before its metadata loads. A video has a Full screen button and the `f` key by default (`fullscreen={false}` removes them); on the picture a click plays or pauses, a double click toggles full screen and the wheel sets the volume while the player has focus. A kind's `colour` names a custom property of the app's theme (`"--seg-sponsor"`) instead of a tone, each range carries `data-kind`, and under the browser's own controls a `SpanStrip` under the picture draws the ranges. `start` begins a first load at a time (an attacher's `startAt`, or a seek once the metadata is in) and says "Picked up at 2:05" with Start over (`resumeWords`); `onProgress` reports the position and the seconds actually played through, each once, a skipped span counted (`useMediaElement` takes it too, with `markWatched`). The HLS attacher starts a `growing` source at its beginning, honours `config.startPosition` and takes `words` for its failures. |
|
|
176
177
|
| Media playback | `Transport`, `SeekBar`, `TimeReadout`, `VolumeControl`, `RateChoice`, `MediaStage`, `StageGuides`, `transportShortcuts`, `format.timecode` | The controls around anything that plays, wired to a player the app owns (HTML media, Web Audio, a canvas, a data replay). Every control is a named icon button in one toolbar; the play button's name is "Play" or "Pause". `SeekBar` has the formatted time as its accessible value, arrows step 5 s and Page keys 30 s by default, and optional marks. `VolumeControl` shows its percent, and muting remembers the level. `transportShortcuts` is the one list for `useHotkeys` and `KeysLegend` (Space and K, J and L, the arrows by a frame, Home and End). `format.timecode` prints m:ss, m:ss.mmm or m:ss:ff. `MediaStage` fits a picture of any aspect ratio into the pane with a letterbox on the sunken surface role, and takes overlays such as `StageGuides` |
|
|
177
|
-
| Listening and reading | `Waveform`, `TranscriptView`, `PlayWindowButton`, `MediaGroup`; `resamplePeaks`, `peaksFromAudio`, `phraseAt`, `wordAt` | Timed media: a waveform from peaks or a decoded file (one slider, marks by line style, named spans, zoom, a keyboard-made range, a spectrogram underlay); timed text that marks the heard word and plays from any word (modes, speakers, follow and Jump to now, virtualised), with doubtful words (dotted, named, counted, "Only doubtful"), a mark per phrase set from a row menu (`states`, `onPhraseState`), correction in place (Enter or F2, `onEdit`) and a hover and focus card (`renderCard`); `MediaPlayer window` plays one stretch of a file, `MediaGroup` lets one player play at a time, `PlayWindowButton` is a row's play control on a shared element; a review transcript needs no player (`time` and `onSeek` are optional), takes `marking` (words become `MarkableText` marks with ids `wordId(phraseId, index)`, selected across rows that are not mounted) and shows a corrected word (`word.correction`) dotted with the original on hover and `onCorrectionPress` to open it |
|
|
178
|
+
| Listening and reading | `Waveform`, `TranscriptView`, `PlayWindowButton`, `MediaGroup`, `FilmStrip`; `resamplePeaks`, `peaksFromAudio`, `peakGain`, `phraseAt`, `wordAt`, `pickEvenly`, `frameAt` | Timed media: a waveform from peaks or a decoded file (one slider, marks by line style, named spans, zoom, a keyboard-made range, a spectrogram underlay, `normalise` to draw quiet sound to fill the height and say by how much); `FilmStrip` is a row of frames from a stretch of video that fits its width (picked evenly), each with its time, pressing one seeks (`onSeek`, one tab stop with arrow keys), and the frame at `time` inside `span` is ringed; timed text that marks the heard word and plays from any word (modes, speakers, follow and Jump to now, virtualised), with doubtful words (dotted, named, counted, "Only doubtful"), a mark per phrase set from a row menu (`states`, `onPhraseState`), correction in place (Enter or F2, `onEdit`) and a hover and focus card (`renderCard`); `MediaPlayer window` plays one stretch of a file, `MediaGroup` lets one player play at a time, `PlayWindowButton` is a row's play control on a shared element; a review transcript needs no player (`time` and `onSeek` are optional), takes `marking` (words become `MarkableText` marks with ids `wordId(phraseId, index)`, selected across rows that are not mounted) and shows a corrected word (`word.correction`) dotted with the original on hover and `onCorrectionPress` to open it |
|
|
178
179
|
| Streams | `MediaPlayer attach`/`growing`, `useAttachedSource`, `attachHls` (`strata-react/hls`) | A source the element cannot play is attached by an engine; a source still being made says so, shows what exists as ready, and waits at its end without ending |
|
|
179
180
|
| 360 | `PanoramaViewer` (`strata-react/panorama`), `project`, `unproject`, `describeView` | A 360 picture or video as a controlled window (yaw, pitch, field of view), drag, wheel, pinch and keys, an overlay in the picture's coordinates, said in words, a flat fallback with no WebGL2 |
|
|
180
181
|
| Conversation | `Conversation`, `Composer`, `RichText`; `matchEntities`, `parseRichText` | A question-and-answer thread: answers stream, finish or fail in place (Try again), one polite announcement per finished answer, following only while at the bottom (Jump to latest); answers can carry pictures (`images`, labelled, lazy, linked to full size) that stay visible beside the collapsed "looked up"; a composer that sends on Enter and is disabled with its reason while answering (Stop); a safe text subset (bold, code, lists, http links, never HTML) whose known ids, longest first and whole words only, become buttons |
|
package/UPGRADING.md
CHANGED
|
@@ -11,6 +11,10 @@ time. While the version is 0.x, any release may break.
|
|
|
11
11
|
|
|
12
12
|
Every PR that changes what an app sees adds a line here (see `CLAUDE.md`, "Changelog").
|
|
13
13
|
|
|
14
|
+
## 2026-11-24
|
|
15
|
+
- `createApi`'s `post`/`put`/`patch` send a `Blob`, bytes, `FormData`, `URLSearchParams` or a stream as it is (a Blob with its own type as Content-Type); before, any body was `JSON.stringify`ed, so such a body arrived as `{}`. `createTypedApi` takes `body` (not `json`) on an operation whose request body has only a non-JSON media type, so a workaround that went round the typed client through `fetchJson` can be deleted.
|
|
16
|
+
- `SayAgain` inside a `ClipsProvider` takes the recordings of `text` and the provider's `lang` itself; one given `parts` or `lang` is unchanged, and outside a provider nothing changes.
|
|
17
|
+
|
|
14
18
|
## 2026-11-23
|
|
15
19
|
- 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
20
|
- `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: … }`.
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { AspectRatio } from './thumbnail';
|
|
2
|
+
import * as React from "react";
|
|
3
|
+
/** One frame: its time in seconds and its picture (`null` when there is none). */
|
|
4
|
+
export type FilmFrame = {
|
|
5
|
+
time: number;
|
|
6
|
+
src: string | null;
|
|
7
|
+
};
|
|
8
|
+
/** The film strip's props. */
|
|
9
|
+
export type FilmStripProps = {
|
|
10
|
+
/** Names the strip: "Frames of scene 3". */
|
|
11
|
+
label: string;
|
|
12
|
+
/** The frames, in time order. More than fit are thinned evenly. */
|
|
13
|
+
frames: readonly FilmFrame[];
|
|
14
|
+
/** The stretch the strip stands for, seconds: `time` inside it marks the frame being watched. Default the first frame's time to the last's. */
|
|
15
|
+
span?: readonly [number, number];
|
|
16
|
+
/** The playhead, seconds. */
|
|
17
|
+
time?: number;
|
|
18
|
+
/** A frame was pressed: play from its time. Makes the frames buttons. */
|
|
19
|
+
onSeek?: (time: number) => void;
|
|
20
|
+
/** Width over height of each frame. Default 4/3. */
|
|
21
|
+
aspect?: AspectRatio;
|
|
22
|
+
/** The narrowest a frame is drawn, px: sets how many fit. Default 96. */
|
|
23
|
+
frameWidth?: number;
|
|
24
|
+
/** The words for a frame with no picture. Default "No picture". */
|
|
25
|
+
missing?: string;
|
|
26
|
+
/** The verb of a frame's button. Default "Play from", as "Play from 1:20". */
|
|
27
|
+
seekVerb?: string;
|
|
28
|
+
className?: string;
|
|
29
|
+
};
|
|
30
|
+
/** `n` of `items` spread evenly from the first to the last (all of them when there are no more than `n`). */
|
|
31
|
+
export declare function pickEvenly<T>(items: readonly T[], n: number): T[];
|
|
32
|
+
/** The index of the frame showing `time`: the last at or before it, or -1 outside `span`. */
|
|
33
|
+
export declare function frameAt(frames: readonly FilmFrame[], time: number | undefined, span: readonly [number, number]): number;
|
|
34
|
+
/** A row of frames from a stretch of video that fits its width, each with its time; pressing one seeks when `onSeek` is given, and the frame at `time` is marked. */
|
|
35
|
+
export declare function FilmStrip({ label, frames, span, time, onSeek, aspect, frameWidth, missing, seekVerb, className }: FilmStripProps): React.JSX.Element;
|
|
@@ -42,6 +42,11 @@ type Common = {
|
|
|
42
42
|
defaultView?: readonly [number, number];
|
|
43
43
|
/** How many peaks a decoded file is reduced to. Default 2000. */
|
|
44
44
|
buckets?: number;
|
|
45
|
+
/** Scale the drawing so the loud parts fill the height (a quiet recording, such as a camcorder tape), and say by how much. `true` uses the defaults of `peakGain`; an object sets them. Only the drawing changes. */
|
|
46
|
+
normalise?: boolean | {
|
|
47
|
+
percentile?: number;
|
|
48
|
+
maxGain?: number;
|
|
49
|
+
};
|
|
45
50
|
/** Turns a decoded file into samples. Default: the browser's `AudioContext.decodeAudioData`. */
|
|
46
51
|
decode?: (data: ArrayBuffer) => Promise<DecodedAudio>;
|
|
47
52
|
/** The words of the reading state; defaults say "Reading the waveform". */
|
|
@@ -62,5 +67,5 @@ export type WaveformProps = Common & ({
|
|
|
62
67
|
peaks?: never;
|
|
63
68
|
});
|
|
64
69
|
/** An audio waveform with marks, spans and a playhead: one slider you click, drag or key to seek, zoom, and a range to select. */
|
|
65
|
-
export declare function Waveform({ label, peaks, source, duration: given, time, onSeek, marks, spans, underlay, range: controlledRange, onRangeChange, step, bigStep, defaultView, buckets, decode, words, disabled, className }: WaveformProps): React.JSX.Element;
|
|
70
|
+
export declare function Waveform({ label, peaks, source, duration: given, time, onSeek, marks, spans, underlay, range: controlledRange, onRangeChange, step, bigStep, defaultView, buckets, normalise, decode, words, disabled, className }: WaveformProps): React.JSX.Element;
|
|
66
71
|
export {};
|
package/dist/index.d.ts
CHANGED
|
@@ -39,13 +39,14 @@ export { useJobAction, type JobAction, type JobActionOptions } from './component
|
|
|
39
39
|
export { WorkflowSteps, type WorkflowStepsProps, type WorkflowStage, type StageState, type StageWords } from './components/workflow-steps';
|
|
40
40
|
export { JobsTable, type JobsTableProps, type JobRow } from './components/jobs-table';
|
|
41
41
|
export { Thumbnail, ThumbnailSkeleton, type ThumbnailProps, type AspectRatio } from './components/thumbnail';
|
|
42
|
+
export { FilmStrip, pickEvenly, frameAt, type FilmStripProps, type FilmFrame } from './components/film-strip';
|
|
42
43
|
export { DataTable, TableSkeleton, parseSort, serialiseSort, type CellValue, type Column, type Sort, type DataTableProps, type RowSelection, type RowExpansion, } from './components/data-table';
|
|
43
44
|
export { MediaPlayer, useMediaElement, useAttachedSource, SPEECH_RATES, type MediaPlayerProps, type MediaElementState, type MediaElementOptions, type MediaWindow, type StreamContext, type StreamAttachment, type SourceAttacher, type MediaProblem, type MediaSource, type MediaSession, type MediaProgress, type ResumeWords } from './components/media-player';
|
|
44
45
|
export { useMediaSpans, SpanActions, PlayerNotice, type SpanActionsNotice, type MediaSpanData, type SpanKind, type SpanBehaviour, type SpanOutcome, type SpanWords, type MediaSpansState } from './components/media-spans';
|
|
45
46
|
export { TranscriptView, type TranscriptViewProps, type TranscriptSeek } from './components/transcript-view';
|
|
46
47
|
export { phraseAt, wordAt, wordId, phraseOfWordId, isDoubtful, phraseDoubtful, type TranscriptGroup, type TranscriptPhrase, type TranscriptPhraseState, type TranscriptWord } from './lib/transcript';
|
|
47
48
|
export { Waveform, type WaveformProps, type WaveformMark, type WaveformMarkKind, type WaveformSpan, type WaveformTone } from './components/waveform';
|
|
48
|
-
export { resamplePeaks, toPeakPair, peaksFromAudio, type WaveformPeaks, type PeakPair, type DecodedAudio } from './lib/waveform';
|
|
49
|
+
export { resamplePeaks, toPeakPair, peaksFromAudio, peakGain, type WaveformPeaks, type PeakPair, type DecodedAudio } from './lib/waveform';
|
|
49
50
|
export { MediaGroup, PlayWindowButton, joinMediaGroup, type PlayWindowButtonProps } from './components/media-group';
|
|
50
51
|
export { Transport, TimeReadout, SeekBar, SpanStrip, VolumeControl, RateChoice, MediaStage, StageGuides, transportShortcuts, type TransportProps, type SeekBarProps, type SeekBarSpan, type VolumeControlProps, type Precision } from './components/media';
|
|
51
52
|
export { Timeline, TimelineZoomControls, useTimelineZoom, noOverlap, type TimelineProps, type TimelineItem, type TimelineLane, type TimelineMarker, type TimelineChange, type TimelineDrop } from './components/timeline';
|
|
@@ -80,6 +81,8 @@ export { ThemeProvider, useColorScheme, useSystemColorScheme, ColorSchemeChoice,
|
|
|
80
81
|
export { StrataQueryProvider, createQueryClient, toLoad, staleOf, useLoad, useInfiniteLoad, useJob, isTaskRunning, useWorkflowRun, isWorkflowRunning, type WorkflowRunLike, type WorkflowRunOptions, 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';
|
|
81
82
|
export { createOutbox, useOutbox, useOutboxStarted, isRefusal, type Outbox, type OutboxOptions, type OutboxRequest, type OutboxItem, type OutboxRefusal, type OutboxSnapshot, type Delivery, } from './query/outbox';
|
|
82
83
|
export { OutboxStatus, type OutboxStatusProps } from './components/outbox-status';
|
|
84
|
+
export { createReserve, useReserve, type Reserve, type ReserveOptions } from './query/reserve';
|
|
85
|
+
export { ClipsProvider, useClips, useSayOnShow, clipsQueryKey, type Clips, type ClipsContext, type ClipsProviderProps, type SayOnShowOptions } from './query/clips';
|
|
83
86
|
export { describeActionError, fieldErrorsOf } from './lib/errors';
|
|
84
87
|
export { appBase, withBase } from './lib/base';
|
|
85
88
|
export { useSearchParam, type SearchParam, type SearchParamOptions } from './lib/search-param';
|
package/dist/index.js
CHANGED
|
@@ -2819,6 +2819,81 @@ function ThumbnailSkeleton({ aspect = 1, className }) {
|
|
|
2819
2819
|
children: /* @__PURE__ */ jsx(Skeleton, { className: "absolute inset-0" })
|
|
2820
2820
|
});
|
|
2821
2821
|
}
|
|
2822
|
+
// src/components/film-strip.tsx
|
|
2823
|
+
var GAP$1 = 4;
|
|
2824
|
+
/** `n` of `items` spread evenly from the first to the last (all of them when there are no more than `n`). */
|
|
2825
|
+
function pickEvenly(items, n) {
|
|
2826
|
+
if (n <= 0) return [];
|
|
2827
|
+
if (items.length <= n) return [...items];
|
|
2828
|
+
if (n === 1) return [items[Math.floor((items.length - 1) / 2)]];
|
|
2829
|
+
return Array.from({ length: n }, (_, i) => items[Math.round(i * (items.length - 1) / (n - 1))]);
|
|
2830
|
+
}
|
|
2831
|
+
/** The index of the frame showing `time`: the last at or before it, or -1 outside `span`. */
|
|
2832
|
+
function frameAt(frames, time, span) {
|
|
2833
|
+
if (time === void 0 || frames.length === 0 || time < span[0] || time >= span[1]) return -1;
|
|
2834
|
+
let found = 0;
|
|
2835
|
+
for (let i = 0; i < frames.length; i++) if (frames[i].time <= time) found = i;
|
|
2836
|
+
return found;
|
|
2837
|
+
}
|
|
2838
|
+
/** A row of frames from a stretch of video that fits its width, each with its time; pressing one seeks when `onSeek` is given, and the frame at `time` is marked. */
|
|
2839
|
+
function FilmStrip({ label, frames, span, time, onSeek, aspect = "4/3", frameWidth = 96, missing = "No picture", seekVerb = "Play from", className }) {
|
|
2840
|
+
const box = React.useRef(null);
|
|
2841
|
+
const [width, setWidth] = React.useState(0);
|
|
2842
|
+
React.useLayoutEffect(() => {
|
|
2843
|
+
const el = box.current;
|
|
2844
|
+
if (!el) return;
|
|
2845
|
+
const read = () => setWidth(Math.round(el.getBoundingClientRect().width));
|
|
2846
|
+
read();
|
|
2847
|
+
if (typeof ResizeObserver === "undefined") return;
|
|
2848
|
+
const ro = new ResizeObserver(read);
|
|
2849
|
+
ro.observe(el);
|
|
2850
|
+
return () => ro.disconnect();
|
|
2851
|
+
}, []);
|
|
2852
|
+
const shown = pickEvenly(frames, Math.max(1, Math.floor((width + GAP$1) / (frameWidth + GAP$1))));
|
|
2853
|
+
const current = frameAt(shown, time, span ?? [frames[0]?.time ?? 0, frames.length ? frames[frames.length - 1].time + 1e-6 : 0]);
|
|
2854
|
+
const picture = (f, i) => /* @__PURE__ */ jsx(Thumbnail, {
|
|
2855
|
+
src: f.src,
|
|
2856
|
+
alt: onSeek ? "" : `Frame at ${format.runningTime(f.time)}`,
|
|
2857
|
+
missing,
|
|
2858
|
+
aspect,
|
|
2859
|
+
className: cn("w-full", i === current && "ring-2 ring-primary ring-offset-1 ring-offset-background"),
|
|
2860
|
+
children: /* @__PURE__ */ jsx("span", {
|
|
2861
|
+
"aria-hidden": true,
|
|
2862
|
+
className: "absolute bottom-0.5 right-0.5 rounded-control bg-background/80 px-1 type-caption tabular-nums text-foreground",
|
|
2863
|
+
children: format.runningTime(f.time)
|
|
2864
|
+
})
|
|
2865
|
+
});
|
|
2866
|
+
return /* @__PURE__ */ jsx("div", {
|
|
2867
|
+
ref: box,
|
|
2868
|
+
className: cn("min-w-0", className),
|
|
2869
|
+
children: frames.length === 0 ? /* @__PURE__ */ jsx(Thumbnail, {
|
|
2870
|
+
src: null,
|
|
2871
|
+
alt: label,
|
|
2872
|
+
missing,
|
|
2873
|
+
aspect,
|
|
2874
|
+
className: "w-full max-w-24"
|
|
2875
|
+
}) : onSeek ? /* @__PURE__ */ jsx(Toolbar, {
|
|
2876
|
+
label,
|
|
2877
|
+
className: "flex-nowrap gap-1",
|
|
2878
|
+
children: shown.map((f, i) => /* @__PURE__ */ jsx(Button$1, {
|
|
2879
|
+
"aria-label": `${seekVerb} ${format.runningTime(f.time)}`,
|
|
2880
|
+
"aria-current": i === current ? "time" : void 0,
|
|
2881
|
+
onPress: () => onSeek(f.time),
|
|
2882
|
+
className: "min-w-0 flex-1 rounded-control outline-offset-2 transition-state press",
|
|
2883
|
+
children: picture(f, i)
|
|
2884
|
+
}, `${f.time}-${i}`))
|
|
2885
|
+
}) : /* @__PURE__ */ jsx("div", {
|
|
2886
|
+
role: "group",
|
|
2887
|
+
"aria-label": label,
|
|
2888
|
+
className: "flex gap-1",
|
|
2889
|
+
children: shown.map((f, i) => /* @__PURE__ */ jsx("div", {
|
|
2890
|
+
"aria-current": i === current ? "time" : void 0,
|
|
2891
|
+
className: "min-w-0 flex-1",
|
|
2892
|
+
children: picture(f, i)
|
|
2893
|
+
}, `${f.time}-${i}`))
|
|
2894
|
+
})
|
|
2895
|
+
});
|
|
2896
|
+
}
|
|
2822
2897
|
// src/components/fullscreen-frame.tsx
|
|
2823
2898
|
/** Whether this browser can show an element full screen. False in jsdom and on iPhone, where the modal fallback is used. */
|
|
2824
2899
|
function canFullscreen() {
|
|
@@ -5660,6 +5735,23 @@ function resamplePeaks(peaks, buckets) {
|
|
|
5660
5735
|
};
|
|
5661
5736
|
}
|
|
5662
5737
|
/**
|
|
5738
|
+
* How much to scale peaks so the loud parts fill the height: one over the `percentile` of the slices'
|
|
5739
|
+
* largest magnitudes, at most `maxGain` and never below 1. A percentile rather than the loudest slice,
|
|
5740
|
+
* so one thump or click on a quiet recording (a dropped camcorder, a tape splice) does not keep the rest
|
|
5741
|
+
* flat; a ceiling, so a recording that is only hiss is not drawn as if it were speech.
|
|
5742
|
+
*/
|
|
5743
|
+
function peakGain(pair, { percentile = .995, maxGain = 16 } = {}) {
|
|
5744
|
+
const n = Math.min(pair.min.length, pair.max.length);
|
|
5745
|
+
if (n === 0) return 1;
|
|
5746
|
+
const stride = Math.max(1, Math.floor(n / 5e4));
|
|
5747
|
+
const loud = [];
|
|
5748
|
+
for (let i = 0; i < n; i += stride) loud.push(Math.max(Math.abs(pair.min[i]), Math.abs(pair.max[i])));
|
|
5749
|
+
loud.sort((a, b) => a - b);
|
|
5750
|
+
const top = loud[Math.min(loud.length - 1, Math.floor(percentile * (loud.length - 1)))];
|
|
5751
|
+
if (!(top > 0)) return 1;
|
|
5752
|
+
return Math.min(Math.max(1 / top, 1), maxGain);
|
|
5753
|
+
}
|
|
5754
|
+
/**
|
|
5663
5755
|
* Reduces decoded audio to `buckets` peaks over all channels, in chunks, calling `progress` with
|
|
5664
5756
|
* the buckets done and awaiting between chunks so the page stays responsive and `signal` can stop it.
|
|
5665
5757
|
*/
|
|
@@ -5760,7 +5852,7 @@ async function defaultDecode(data) {
|
|
|
5760
5852
|
var clamp$2 = (v, lo, hi) => Math.min(Math.max(v, lo), hi);
|
|
5761
5853
|
var clock = (t) => format.runningTime(t);
|
|
5762
5854
|
/** An audio waveform with marks, spans and a playhead: one slider you click, drag or key to seek, zoom, and a range to select. */
|
|
5763
|
-
function Waveform({ label, peaks, source, duration: given, time, onSeek, marks = [], spans = [], underlay, range: controlledRange, onRangeChange, step = 5, bigStep = 30, defaultView, buckets = 2e3, decode = defaultDecode, words = WORDS, disabled, className }) {
|
|
5855
|
+
function Waveform({ label, peaks, source, duration: given, time, onSeek, marks = [], spans = [], underlay, range: controlledRange, onRangeChange, step = 5, bigStep = 30, defaultView, buckets = 2e3, normalise = false, decode = defaultDecode, words = WORDS, disabled, className }) {
|
|
5764
5856
|
const work = useClientWork(async ({ signal, progress }) => {
|
|
5765
5857
|
const data = typeof source === "string" ? await (await fetch(source, { signal })).arrayBuffer() : await source.arrayBuffer();
|
|
5766
5858
|
progress(0, buckets + 2);
|
|
@@ -5789,6 +5881,17 @@ function Waveform({ label, peaks, source, duration: given, time, onSeek, marks =
|
|
|
5789
5881
|
const pair = React.useMemo(() => peaks === void 0 ? null : toPeakPair(peaks), [peaks]) ?? (work.phase === "finished" ? work.result.pair : null);
|
|
5790
5882
|
const duration = given ?? (work.phase === "finished" ? work.result.duration : 0);
|
|
5791
5883
|
const ready = pair !== null && duration > 0;
|
|
5884
|
+
const percentile = typeof normalise === "object" ? normalise.percentile : void 0;
|
|
5885
|
+
const maxGain = typeof normalise === "object" ? normalise.maxGain : void 0;
|
|
5886
|
+
const gain = React.useMemo(() => normalise && pair ? peakGain(pair, {
|
|
5887
|
+
percentile,
|
|
5888
|
+
maxGain
|
|
5889
|
+
}) : 1, [
|
|
5890
|
+
normalise,
|
|
5891
|
+
pair,
|
|
5892
|
+
percentile,
|
|
5893
|
+
maxGain
|
|
5894
|
+
]);
|
|
5792
5895
|
const [view, setView] = React.useState(defaultView ? [defaultView[0], defaultView[1]] : null);
|
|
5793
5896
|
const [v0, v1] = view ? clampView(view[0], view[1] - view[0], duration || 1) : [0, duration];
|
|
5794
5897
|
const zoomed = ready && v1 - v0 < duration - 1e-6;
|
|
@@ -5960,8 +6063,8 @@ function Waveform({ label, peaks, source, duration: given, time, onSeek, marks =
|
|
|
5960
6063
|
for (let x = 0; x < width; x += column) {
|
|
5961
6064
|
const [lo, hi] = peaksBetween(pair, (v0 + x / width * (v1 - v0)) / duration, (v0 + (x + column) / width * (v1 - v0)) / duration);
|
|
5962
6065
|
if (!Number.isFinite(lo)) continue;
|
|
5963
|
-
const top = 50 - clamp$2(hi, -1, 1) * 48;
|
|
5964
|
-
const bottom = 50 - clamp$2(lo, -1, 1) * 48;
|
|
6066
|
+
const top = 50 - clamp$2(hi * gain, -1, 1) * 48;
|
|
6067
|
+
const bottom = 50 - clamp$2(lo * gain, -1, 1) * 48;
|
|
5965
6068
|
d += `M${x + .5} ${top.toFixed(1)}V${Math.max(bottom, top + 1).toFixed(1)}`;
|
|
5966
6069
|
}
|
|
5967
6070
|
return d;
|
|
@@ -5970,7 +6073,8 @@ function Waveform({ label, peaks, source, duration: given, time, onSeek, marks =
|
|
|
5970
6073
|
width,
|
|
5971
6074
|
v0,
|
|
5972
6075
|
v1,
|
|
5973
|
-
duration
|
|
6076
|
+
duration,
|
|
6077
|
+
gain
|
|
5974
6078
|
]);
|
|
5975
6079
|
const clipId = React.useId();
|
|
5976
6080
|
const px = (t) => (t - v0) / span * width;
|
|
@@ -5978,7 +6082,8 @@ function Waveform({ label, peaks, source, duration: given, time, onSeek, marks =
|
|
|
5978
6082
|
const thin = visibleMarks.length > width / 8;
|
|
5979
6083
|
const listedMarks = marks.filter((m) => m.label && (m.listed ?? m.kind !== "beat"));
|
|
5980
6084
|
const counts = marks.reduce((c, m) => (c[m.kind ?? "mark"] = (c[m.kind ?? "mark"] ?? 0) + 1, c), {});
|
|
5981
|
-
const
|
|
6085
|
+
const louder = gain >= 1.1 ? `Shown ${gain < 10 ? gain.toFixed(1).replace(/\.0$/, "") : Math.round(gain)}× louder` : null;
|
|
6086
|
+
const summary = ready ? `${clock(duration)} long${Object.keys(counts).length ? `, ${Object.entries(counts).map(([k, n]) => `${n} ${k}${n === 1 ? "" : "s"}`).join(", ")}` : ""}${spans.length ? `, ${spans.length} span${spans.length === 1 ? "" : "s"}` : ""}${zoomed ? `, showing ${clock(v0)} to ${clock(v1)}` : ""}${range ? `, range ${clock(range[0])} to ${clock(range[1])}` : ""}${louder ? `, ${louder.toLowerCase()}` : ""}` : "";
|
|
5982
6087
|
const summaryId = React.useId();
|
|
5983
6088
|
return /* @__PURE__ */ jsxs("div", {
|
|
5984
6089
|
role: "group",
|
|
@@ -6140,6 +6245,11 @@ function Waveform({ label, peaks, source, duration: given, time, onSeek, marks =
|
|
|
6140
6245
|
})
|
|
6141
6246
|
]
|
|
6142
6247
|
}),
|
|
6248
|
+
ready && louder && /* @__PURE__ */ jsx("p", {
|
|
6249
|
+
"aria-hidden": true,
|
|
6250
|
+
className: "justify-self-end type-caption text-muted-foreground",
|
|
6251
|
+
children: louder
|
|
6252
|
+
}),
|
|
6143
6253
|
/* @__PURE__ */ jsxs(VisuallyHidden, { children: [
|
|
6144
6254
|
/* @__PURE__ */ jsx("p", {
|
|
6145
6255
|
id: summaryId,
|
|
@@ -11277,16 +11387,17 @@ function withBase(path, base = appBase()) {
|
|
|
11277
11387
|
return path.startsWith("/") && !path.startsWith("//") ? base + path : path;
|
|
11278
11388
|
}
|
|
11279
11389
|
// src/query/api.ts
|
|
11390
|
+
var isRaw = (body) => typeof Blob !== "undefined" && body instanceof Blob || body instanceof ArrayBuffer || ArrayBuffer.isView(body) || typeof FormData !== "undefined" && body instanceof FormData || body instanceof URLSearchParams || typeof ReadableStream !== "undefined" && body instanceof ReadableStream;
|
|
11280
11391
|
/**
|
|
11281
11392
|
* A small client over `fetchJson` for the app's own server: root-relative paths get the app's base (so it works behind a reverse proxy),
|
|
11282
|
-
* and `post`, `put` and `patch` send their body as JSON. `api.post<Learner>("/api/learners", { nickname })`.
|
|
11393
|
+
* and `post`, `put` and `patch` send their body as JSON (a `Blob`, bytes, `FormData` or a stream is sent as it is, with the Blob's own type). `api.post<Learner>("/api/learners", { nickname })`.
|
|
11283
11394
|
*/
|
|
11284
11395
|
function createApi({ base, ...options } = {}) {
|
|
11285
11396
|
const url = (path) => withBase(path, base ?? appBase());
|
|
11286
11397
|
const send = (method, path, body, init) => fetchJson(url(path), {
|
|
11287
11398
|
...init,
|
|
11288
11399
|
method,
|
|
11289
|
-
...body === void 0 ? {} : { json: body }
|
|
11400
|
+
...body === void 0 ? {} : isRaw(body) ? { body } : { json: body }
|
|
11290
11401
|
}, options);
|
|
11291
11402
|
return {
|
|
11292
11403
|
url,
|
|
@@ -11316,10 +11427,10 @@ function fill(path, values, query) {
|
|
|
11316
11427
|
function createTypedApi(options = {}) {
|
|
11317
11428
|
const api = createApi(options);
|
|
11318
11429
|
const call = (method) => (path, request) => {
|
|
11319
|
-
const { path: values, query, json, ...init } = request ?? {};
|
|
11430
|
+
const { path: values, query, json, body, ...init } = request ?? {};
|
|
11320
11431
|
const target = fill(path, values, query);
|
|
11321
11432
|
const rest = init;
|
|
11322
|
-
return method === "get" ? api.get(target, rest) : method === "delete" ? api.delete(target, rest) : api[method](target, json, rest);
|
|
11433
|
+
return method === "get" ? api.get(target, rest) : method === "delete" ? api.delete(target, rest) : api[method](target, body ?? json, rest);
|
|
11323
11434
|
};
|
|
11324
11435
|
return {
|
|
11325
11436
|
url: api.url,
|
|
@@ -11528,7 +11639,7 @@ function problemOf(error) {
|
|
|
11528
11639
|
}
|
|
11529
11640
|
return "The server could not be reached.";
|
|
11530
11641
|
}
|
|
11531
|
-
function defaultStorage() {
|
|
11642
|
+
function defaultStorage$1() {
|
|
11532
11643
|
try {
|
|
11533
11644
|
const s = window.localStorage;
|
|
11534
11645
|
const probe = "strata:outbox:probe";
|
|
@@ -11545,7 +11656,7 @@ function randomId() {
|
|
|
11545
11656
|
/** A queue of writes kept on the device (localStorage) and sent in order when the server can take them; see `useOutbox` and `OutboxStatus`. */
|
|
11546
11657
|
function createOutbox({ name, send, storage, retryMs = 2e3, maxRetryMs = 6e4 }) {
|
|
11547
11658
|
const key = `strata:outbox:${name}`;
|
|
11548
|
-
const store = storage === void 0 ? defaultStorage() : storage;
|
|
11659
|
+
const store = storage === void 0 ? defaultStorage$1() : storage;
|
|
11549
11660
|
const post = send ?? ((item) => fetchJson(withBase(item.path, appBase()), {
|
|
11550
11661
|
method: item.method,
|
|
11551
11662
|
json: item.json
|
|
@@ -11812,6 +11923,104 @@ function OutboxStatus({ outbox, noun, className }) {
|
|
|
11812
11923
|
})]
|
|
11813
11924
|
});
|
|
11814
11925
|
}
|
|
11926
|
+
// src/query/reserve.ts
|
|
11927
|
+
function defaultStorage() {
|
|
11928
|
+
try {
|
|
11929
|
+
const s = window.localStorage;
|
|
11930
|
+
const probe = "strata:reserve:probe";
|
|
11931
|
+
s.setItem(probe, "1");
|
|
11932
|
+
s.removeItem(probe);
|
|
11933
|
+
return s;
|
|
11934
|
+
} catch {
|
|
11935
|
+
return null;
|
|
11936
|
+
}
|
|
11937
|
+
}
|
|
11938
|
+
/** Items the server made ahead, kept on the device (localStorage) and used once each; see `useReserve`. */
|
|
11939
|
+
function createReserve({ name, size, fetch, sameMake = () => true, storage }) {
|
|
11940
|
+
const prefix = `strata:reserve:${name}:`;
|
|
11941
|
+
const store = storage === void 0 ? defaultStorage() : storage;
|
|
11942
|
+
let persisted = store !== null;
|
|
11943
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
11944
|
+
const inFlight = /* @__PURE__ */ new Set();
|
|
11945
|
+
const latest = /* @__PURE__ */ new Map();
|
|
11946
|
+
const changed = () => {
|
|
11947
|
+
for (const l of listeners) l();
|
|
11948
|
+
};
|
|
11949
|
+
const read = (key) => {
|
|
11950
|
+
if (!persisted || !store) return [];
|
|
11951
|
+
try {
|
|
11952
|
+
const raw = JSON.parse(store.getItem(prefix + key) ?? "null");
|
|
11953
|
+
return Array.isArray(raw) ? raw : [];
|
|
11954
|
+
} catch {
|
|
11955
|
+
return [];
|
|
11956
|
+
}
|
|
11957
|
+
};
|
|
11958
|
+
const write = (key, items) => {
|
|
11959
|
+
if (persisted && store) try {
|
|
11960
|
+
if (items.length) store.setItem(prefix + key, JSON.stringify(items.slice(0, size)));
|
|
11961
|
+
else store.removeItem(prefix + key);
|
|
11962
|
+
} catch {
|
|
11963
|
+
persisted = false;
|
|
11964
|
+
}
|
|
11965
|
+
changed();
|
|
11966
|
+
};
|
|
11967
|
+
return {
|
|
11968
|
+
take(key) {
|
|
11969
|
+
const items = read(key);
|
|
11970
|
+
const [next, ...rest] = items;
|
|
11971
|
+
if (items.length === 0) return void 0;
|
|
11972
|
+
write(key, rest);
|
|
11973
|
+
return next;
|
|
11974
|
+
},
|
|
11975
|
+
async refresh(key, fresh) {
|
|
11976
|
+
latest.set(key, fresh);
|
|
11977
|
+
const current = read(key);
|
|
11978
|
+
const kept = current.filter((item) => sameMake(item, fresh));
|
|
11979
|
+
if (kept.length !== current.length) write(key, kept);
|
|
11980
|
+
if (kept.length * 2 >= size || inFlight.has(key)) return;
|
|
11981
|
+
inFlight.add(key);
|
|
11982
|
+
try {
|
|
11983
|
+
const more = await fetch(key, size - kept.length);
|
|
11984
|
+
const now = read(key);
|
|
11985
|
+
write(key, [...now, ...more.filter((item) => sameMake(item, latest.get(key)))].slice(0, size));
|
|
11986
|
+
} catch {} finally {
|
|
11987
|
+
inFlight.delete(key);
|
|
11988
|
+
}
|
|
11989
|
+
},
|
|
11990
|
+
kept: (key) => read(key).length,
|
|
11991
|
+
get persisted() {
|
|
11992
|
+
return persisted;
|
|
11993
|
+
},
|
|
11994
|
+
seed(key, items) {
|
|
11995
|
+
write(key, items);
|
|
11996
|
+
},
|
|
11997
|
+
clear(key) {
|
|
11998
|
+
if (key !== void 0) return write(key, []);
|
|
11999
|
+
if (persisted && store) try {
|
|
12000
|
+
for (const k of Object.keys(store).filter((k) => k.startsWith(prefix))) store.removeItem(k);
|
|
12001
|
+
} catch {
|
|
12002
|
+
persisted = false;
|
|
12003
|
+
}
|
|
12004
|
+
changed();
|
|
12005
|
+
},
|
|
12006
|
+
subscribe(listener) {
|
|
12007
|
+
listeners.add(listener);
|
|
12008
|
+
return () => listeners.delete(listener);
|
|
12009
|
+
}
|
|
12010
|
+
};
|
|
12011
|
+
}
|
|
12012
|
+
/** How many items `reserve` keeps for `key`, re-rendering as they are taken, topped up or changed by another tab: "6 rounds kept for offline". */
|
|
12013
|
+
function useReserve(reserve, key) {
|
|
12014
|
+
const subscribe = React.useCallback((listener) => {
|
|
12015
|
+
const stop = reserve.subscribe(listener);
|
|
12016
|
+
window.addEventListener("storage", listener);
|
|
12017
|
+
return () => {
|
|
12018
|
+
stop();
|
|
12019
|
+
window.removeEventListener("storage", listener);
|
|
12020
|
+
};
|
|
12021
|
+
}, [reserve]);
|
|
12022
|
+
return React.useSyncExternalStore(subscribe, () => reserve.kept(key), () => 0);
|
|
12023
|
+
}
|
|
11815
12024
|
// src/lib/speech.ts
|
|
11816
12025
|
var partsOf = (saying) => (typeof saying === "string" ? [{ text: saying }] : [...saying]).filter((p) => p.text.trim() || p.clip);
|
|
11817
12026
|
/** 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. */
|
|
@@ -11954,11 +12163,88 @@ function useSpeech({ lang, rate, muted = false } = {}) {
|
|
|
11954
12163
|
}, [])
|
|
11955
12164
|
};
|
|
11956
12165
|
}
|
|
12166
|
+
// src/query/clips.tsx
|
|
12167
|
+
/** The query key of the clip list: invalidate it after a recording is kept, `queryClient.invalidateQueries({ queryKey: clipsQueryKey })`. */
|
|
12168
|
+
var clipsQueryKey = ["strata", "clips"];
|
|
12169
|
+
var Context$1 = React.createContext({
|
|
12170
|
+
ready: true,
|
|
12171
|
+
parts: (text) => [{
|
|
12172
|
+
text,
|
|
12173
|
+
clip: null
|
|
12174
|
+
}],
|
|
12175
|
+
say: (text) => speak(text),
|
|
12176
|
+
words: (text) => text
|
|
12177
|
+
});
|
|
12178
|
+
/** Reads the app's clip list once and gives `useClips`, `SayAgain` and `useSayOnShow` each line's recording. Put it in the shell, inside the query provider. */
|
|
12179
|
+
function ClipsProvider({ load, lang, split, describe, queryKey = clipsQueryKey, children }) {
|
|
12180
|
+
const list = useLoad({
|
|
12181
|
+
queryKey,
|
|
12182
|
+
queryFn: load,
|
|
12183
|
+
staleTime: Infinity,
|
|
12184
|
+
networkMode: "always"
|
|
12185
|
+
});
|
|
12186
|
+
const clips = list.status === "ready" ? list.data : void 0;
|
|
12187
|
+
const value = React.useMemo(() => {
|
|
12188
|
+
const parts = (text) => (split ? split(text) : [text]).map((line) => line.trim()).filter(Boolean).map((line) => {
|
|
12189
|
+
const url = clips?.[line];
|
|
12190
|
+
return url ? {
|
|
12191
|
+
text: line,
|
|
12192
|
+
clip: withBase(url, appBase())
|
|
12193
|
+
} : {
|
|
12194
|
+
text: describe?.(line) ?? line,
|
|
12195
|
+
clip: null
|
|
12196
|
+
};
|
|
12197
|
+
});
|
|
12198
|
+
return {
|
|
12199
|
+
ready: list.status !== "loading",
|
|
12200
|
+
lang,
|
|
12201
|
+
parts,
|
|
12202
|
+
say: (text) => speak(parts(text), { lang }),
|
|
12203
|
+
words: (text) => textOf(parts(text))
|
|
12204
|
+
};
|
|
12205
|
+
}, [
|
|
12206
|
+
clips,
|
|
12207
|
+
list.status,
|
|
12208
|
+
lang,
|
|
12209
|
+
split,
|
|
12210
|
+
describe
|
|
12211
|
+
]);
|
|
12212
|
+
return /* @__PURE__ */ jsx(Context$1.Provider, {
|
|
12213
|
+
value,
|
|
12214
|
+
children
|
|
12215
|
+
});
|
|
12216
|
+
}
|
|
12217
|
+
/** The app's clips: `const { say, parts, words, ready } = useClips()`. The browser's voice alone outside a `ClipsProvider`. */
|
|
12218
|
+
function useClips() {
|
|
12219
|
+
return React.useContext(Context$1);
|
|
12220
|
+
}
|
|
12221
|
+
/**
|
|
12222
|
+
* Says `text` once when it appears and the clips are `ready`, and again when `text` changes; stops it on unmount so a prompt does not talk
|
|
12223
|
+
* after its screen is gone. `useSayOnShow(question.text)`.
|
|
12224
|
+
*/
|
|
12225
|
+
function useSayOnShow(text, { muted = false } = {}) {
|
|
12226
|
+
const { ready, say } = useClips();
|
|
12227
|
+
const latest = React.useRef(say);
|
|
12228
|
+
latest.current = say;
|
|
12229
|
+
React.useEffect(() => {
|
|
12230
|
+
if (muted || !ready || !text) return;
|
|
12231
|
+
latest.current(text);
|
|
12232
|
+
return () => stopSpeaking();
|
|
12233
|
+
}, [
|
|
12234
|
+
muted,
|
|
12235
|
+
ready,
|
|
12236
|
+
text
|
|
12237
|
+
]);
|
|
12238
|
+
}
|
|
11957
12239
|
// src/components/say-again.tsx
|
|
11958
12240
|
/** 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. */
|
|
11959
12241
|
function SayAgain({ text, parts, verb = "Say", className, ...options }) {
|
|
11960
|
-
const
|
|
11961
|
-
const
|
|
12242
|
+
const clips = useClips();
|
|
12243
|
+
const { say, speaking } = useSpeech({
|
|
12244
|
+
...options,
|
|
12245
|
+
lang: options.lang ?? clips.lang
|
|
12246
|
+
});
|
|
12247
|
+
const saying = parts?.length ? parts : clips.parts(text);
|
|
11962
12248
|
if (options.muted || !canSay(saying)) return null;
|
|
11963
12249
|
return /* @__PURE__ */ jsx(IconButton, {
|
|
11964
12250
|
icon: Volume2,
|
|
@@ -17838,6 +18124,6 @@ function FolderPicker({ label, useFolders: useListing, value, onChange, onChoose
|
|
|
17838
18124
|
]
|
|
17839
18125
|
});
|
|
17840
18126
|
}
|
|
17841
|
-
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, JobsTable, 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, WorkflowSteps, 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, isWorkflowRunning, 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, useWorkflowRun, useWorkspaceState, valueAt, viewOf, viewsOf, withBase, wordAt, wordId, zoomAt, zoomToBox };
|
|
18127
|
+
export { ActiveList, Alert, AlertDialog, AppShell, AsyncButton, BookViewer, BoxList, BoxOverlay, Breadcrumb, BulkBar, Button, ButtonLink, COLOR_SCHEME_STORAGE_KEY, Checkbox, ChoiceGrid, ChoiceGridSkeleton, ChoiceGroup, ClipsProvider, 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, FilmStrip, FolderPicker, FullscreenFrame, HttpError, IconButton, InfiniteList, Input, InputLevel, Inspector, InspectorSection, JobStatus, JobsTable, 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, WorkflowSteps, Workspace, actualPixelsScale, ancestorsOf, apiPage, appBase, boxViewport, browserMicrophone, buttonVariants, canFullscreen, canPlayClips, canSay, canSpeak, clampToRoom, clampViewport, clipsQueryKey, cn, colorSchemeScript, commandShortcut, countMarks, createApi, createFormat, createOutbox, createQueryClient, createReserve, createTypedApi, crossedThreshold, describeActionError, describeHttpError, describeRegion, detectPlatform, diffWords, differences, drawRect, ease, encodeWav, errorPayload, explainMicrophoneError, fetchJson, fieldErrorsOf, findPage, fitRect, format, formatChord, frameAt, gainToVolume, geo, gridPoints, gutterOf, inputLevelThresholds, isDoubtful, isRefusal, isReservedChord, isTaskRunning, isTypingTarget, isWorkflowRunning, jobProgressText, joinMediaGroup, joinRects, joinSamples, labelOf, lerpRect, logScale, loudnessOf, matchEntities, matchGains, matchesAccept, matchesChord, measureLoudness, moveGutter, moveRect, noOverlap, normaliseAngle, pageName, parentOf, parseChord, parseInline, parseRichText, parseSort, peakDb, peakGain, peaksFromAudio, phraseAt, phraseDoubtful, phraseOfWordId, pickEvenly, 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, useClips, useColorScheme, useCommands, useDifference, useExpanded, useFileIntake, useHistory, useHistoryState, useHotkeys, useInView, useInfiniteLoad, useJob, useJobAction, useLeaveGuard, useLightboxUrl, useLoad, useMediaElement, useMediaSpans, useMicrophone, useOutbox, useOutboxStarted, usePlayerWarnings, useRecorder, useReserve, useSayOnShow, useSearchParam, useSelection, useSharedCursor, useSpeech, useSystemColorScheme, useTimelineZoom, useUndoable, useViewOptions, useViewport, useWorkflowRun, useWorkspaceState, valueAt, viewOf, viewsOf, withBase, wordAt, wordId, zoomAt, zoomToBox };
|
|
17842
18128
|
|
|
17843
18129
|
//# sourceMappingURL=index.js.map
|