strata-react 1.3.13 → 1.3.15
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 +6 -4
- package/UPGRADING.md +3 -0
- package/dist/components/auto-recorder.d.ts +67 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +284 -1
- package/dist/index.js.map +1 -1
- package/dist/lib/segmenter.d.ts +40 -0
- package/dist/strata.css +11 -3
- package/dist/strata.migrate.css +11 -3
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/microphone.d.ts +16 -1
- package/dist/testing.js +22 -3
- package/dist/testing.js.map +1 -1
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -70,7 +70,7 @@ automatic detection.
|
|
|
70
70
|
|
|
71
71
|
`theme.css` supplies what Strata names but does not choose: `--success`, `--success-subtle`,
|
|
72
72
|
`--warning…`, `--danger…`, `--info…` (pale tint + dark ink of one hue, ink at least 6:1),
|
|
73
|
-
`--font-sans` / `--font-display` in an `@theme` block, and optionally `--title-weight`,
|
|
73
|
+
`--font-sans` / `--font-display` in an `@theme` block (Strata's default `--font-sans` is Geist Variable, bundled; name your own to replace it), and optionally `--title-weight`,
|
|
74
74
|
`--title-stretch`, `--title-tracking`. See `.storybook/theme.css` for a complete example (the
|
|
75
75
|
kiln-room fixture).
|
|
76
76
|
|
|
@@ -167,7 +167,7 @@ thousands of lines. Such an app imports the same stylesheet **without the reset*
|
|
|
167
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` |
|
|
168
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 |
|
|
169
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 |
|
|
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
|
+
| Recording | `useRecorder`, `useAutoRecorder`, `InputLevel`, `ListeningLevel`, `TakeLevel`, `MicrophoneContext`, `encodeWav`, `createSegmenter`, `fakeMicrophone`, `speechScript` (`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. Hands-free: `useAutoRecorder({ maxSeconds, onTake, paused })` keeps the microphone open and hands over each stretch of speech as its own take (`AutoTake`, `cut` when it ran past `maxSeconds`), cut by `createSegmenter` (20 ms frames against the room's measured quiet: 12 dB to start, 1 s of quiet to end, 0.3 s kept either side, under 0.3 s of speech dropped); `ListeningLevel` says whether it is waiting, hearing a take or paused, with the room's level. `fakeMicrophone({ script: speechScript(n), loop })` reads with gaps |
|
|
171
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 |
|
|
172
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 |
|
|
173
173
|
| 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 |
|
|
@@ -301,8 +301,10 @@ many shots were pixel-identical and how many matched within tolerance (the five
|
|
|
301
301
|
failing are listed as `within`).
|
|
302
302
|
|
|
303
303
|
**Fonts.** Every face must be one the page loads: bundle it with `@fontsource` (or your own
|
|
304
|
-
`@font-face`) and name it first in the theme's `--font-*`. Strata's
|
|
305
|
-
`
|
|
304
|
+
`@font-face`) and name it first in the theme's `--font-*`. Strata's own default sans is Geist Variable, bundled with the package
|
|
305
|
+
(`strata.css` imports it; the app's build must resolve a CSS `url()` to a `.woff2`, which Vite does and the bare Tailwind CLI does not),
|
|
306
|
+
so an app that names none still loads a face. Anything that falls through to
|
|
307
|
+
`ui-sans-serif` (the mono default, a face you name that fails to load) is Cantarell on one Linux, DejaVu Sans on another and San Francisco on a
|
|
306
308
|
Mac, and a glyph missing from a web font (an arrow, `⌘`) falls back the same way; no threshold
|
|
307
309
|
absorbs that. The runner asks Chromium which face drew each element's text and fails the shot
|
|
308
310
|
naming the face and an example (`"DejaVu Sans" in <kbd> "⌘"`). `systemFonts: "warn"` reports
|
package/UPGRADING.md
CHANGED
|
@@ -11,6 +11,9 @@ time. While the version is 0.x, any release may break.
|
|
|
11
11
|
|
|
12
12
|
Every PR that changes what an app sees adds a line here (see `CLAUDE.md`, "Changelog").
|
|
13
13
|
|
|
14
|
+
## 2026-11-25
|
|
15
|
+
- The default `--font-sans` is **Geist Variable**, bundled (Fontsource, a dependency of strata-react), where it was the system sans. An app that names its own face in `--font-sans` is unchanged; an app that never did gets a new look and moved baselines (re-record them: the face is now the same on every machine, so the screenshots no longer depend on its fonts). Mono is still a system face. `strata.css` now `@import`s `@fontsource-variable/geist`, so **the app's build must resolve a CSS `url()` to a `.woff2`**: Vite does this with nothing added (the files are emitted with hashed names under the app's base); a build that runs the Tailwind CLI and esbuild on its own must copy `node_modules/@fontsource-variable/geist/files/*.woff2` next to the compiled CSS (the rules say `./files/…`) or name its own face.
|
|
16
|
+
|
|
14
17
|
## 2026-11-24
|
|
15
18
|
- `RateChoice` (the speed in `MediaPlayer`, `VideoClock`, `CompareVideo`, `CompareVideoGrid`) is React Aria's `Select`, not a native select (#324): a test that did `user.selectOptions(getByRole("combobox", { name: "Playback speed" }), "1.5×")` now clicks `getByRole("button", { name: /Playback speed/ })` and then `findByRole("option", { name: "1.5×" })`. Visual baselines with a player move: the control is narrower, so a phone-width player's controls can fit on one row.
|
|
16
19
|
- `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.
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { Microphone } from '../lib/microphone';
|
|
2
|
+
import { SegmenterOptions } from '../lib/segmenter';
|
|
3
|
+
import { Recording } from './recorder';
|
|
4
|
+
import * as React from "react";
|
|
5
|
+
/** Where an auto recorder is: idle, opening the device, listening (and hearing a take or not), or refused. */
|
|
6
|
+
export type AutoRecorderState = {
|
|
7
|
+
phase: "idle";
|
|
8
|
+
} | {
|
|
9
|
+
phase: "opening";
|
|
10
|
+
} | {
|
|
11
|
+
phase: "listening";
|
|
12
|
+
/** The live peak in dBFS. */
|
|
13
|
+
level: number;
|
|
14
|
+
/** The room's quiet in dBFS (RMS), or null before the first chunk. */
|
|
15
|
+
noise: number | null;
|
|
16
|
+
/** True while a take is being heard. */
|
|
17
|
+
speaking: boolean;
|
|
18
|
+
/** How long the take being heard has run, 0 when none. */
|
|
19
|
+
seconds: number;
|
|
20
|
+
/** True while `paused`: the microphone is open but nothing is taken. */
|
|
21
|
+
paused: boolean;
|
|
22
|
+
} | {
|
|
23
|
+
phase: "failed";
|
|
24
|
+
reason: string;
|
|
25
|
+
};
|
|
26
|
+
/** A take cut from a microphone that is always open. */
|
|
27
|
+
export type AutoTake = Recording & {
|
|
28
|
+
/** True when the speaker was still talking at `maxSeconds` and the take was cut there. */
|
|
29
|
+
cut: boolean;
|
|
30
|
+
};
|
|
31
|
+
/** `useAutoRecorder`'s options: the segmenter's (`SegmenterOptions`) plus these. */
|
|
32
|
+
export type UseAutoRecorderOptions = Omit<SegmenterOptions, "maxSeconds"> & {
|
|
33
|
+
/** The longest take, in seconds: a longer stretch of speech is cut there (`AutoTake.cut`). */
|
|
34
|
+
maxSeconds: number;
|
|
35
|
+
/** Called with each take as it ends. */
|
|
36
|
+
onTake: (take: AutoTake) => void;
|
|
37
|
+
/** Keep the microphone open but take nothing. */
|
|
38
|
+
paused?: boolean;
|
|
39
|
+
/** The microphone to listen to; `useMicrophone()` (the nearest `MicrophoneContext`) when left out. */
|
|
40
|
+
microphone?: Microphone;
|
|
41
|
+
};
|
|
42
|
+
/** What `useAutoRecorder` returns. */
|
|
43
|
+
export type AutoRecorder = {
|
|
44
|
+
state: AutoRecorderState;
|
|
45
|
+
/** Opens the microphone and listens until `stop`; resolves false when it would not open or is already open. */
|
|
46
|
+
start: () => Promise<boolean>;
|
|
47
|
+
/** Closes the microphone, handing over a take being heard if it has enough speech. */
|
|
48
|
+
stop: () => void;
|
|
49
|
+
/** True while opening or listening. */
|
|
50
|
+
listening: boolean;
|
|
51
|
+
};
|
|
52
|
+
/** Listens all the time and hands over each stretch of speech as its own lossless take. */
|
|
53
|
+
export declare function useAutoRecorder({ maxSeconds, onTake, paused, microphone, ...tuning }: UseAutoRecorderOptions): AutoRecorder;
|
|
54
|
+
/** `ListeningLevel`'s props. */
|
|
55
|
+
export type ListeningLevelProps = {
|
|
56
|
+
/** The recorder's state while listening. */
|
|
57
|
+
state: Extract<AutoRecorderState, {
|
|
58
|
+
phase: "listening";
|
|
59
|
+
}>;
|
|
60
|
+
/** The longest take, said beside a take's running time. */
|
|
61
|
+
maxSeconds: number;
|
|
62
|
+
/** The meter's name. Default "Input level". */
|
|
63
|
+
label?: string;
|
|
64
|
+
className?: string;
|
|
65
|
+
};
|
|
66
|
+
/** The live level of a microphone that is always open, with what it is doing in words: waiting, hearing a take, or paused. */
|
|
67
|
+
export declare function ListeningLevel({ state, maxSeconds, label, className }: ListeningLevelProps): React.JSX.Element;
|
package/dist/index.d.ts
CHANGED
|
@@ -91,6 +91,8 @@ export { SayAgain, type SayAgainProps } from './components/say-again';
|
|
|
91
91
|
export { browserMicrophone, explainMicrophoneError, MicrophoneContext, MicrophoneError, useMicrophone, type Microphone, type MicrophoneStream, } from './lib/microphone';
|
|
92
92
|
export { LEVEL_FLOOR_DB, joinSamples, encodeWav, peakDb, speechLevel, type SpeechLevel } from './lib/recording';
|
|
93
93
|
export { useRecorder, InputLevel, TakeLevel, inputLevelThresholds, type Recorder, type RecorderState, type Recording, type UseRecorderOptions, type InputLevelProps, type TakeLevelProps, } from './components/recorder';
|
|
94
|
+
export { createSegmenter, rmsDb, type Segment, type Segmenter, type SegmenterOptions } from './lib/segmenter';
|
|
95
|
+
export { useAutoRecorder, ListeningLevel, type AutoRecorder, type AutoRecorderState, type AutoTake, type UseAutoRecorderOptions, type ListeningLevelProps, } from './components/auto-recorder';
|
|
94
96
|
export { ButtonLink, TextLink, type ButtonLinkProps, type TextLinkProps } from './components/link';
|
|
95
97
|
export { Compare, type CompareProps, type CompareMode, type Candidate, type ImageMedia, type AudioMedia, type TextMedia, type VideoMedia } from './components/compare';
|
|
96
98
|
export { ViewportFrame, useViewport, type ViewportFrameProps, type ViewportState } from './components/viewport';
|
package/dist/index.js
CHANGED
|
@@ -12597,6 +12597,289 @@ function TakeLevel({ peak, lead, className }) {
|
|
|
12597
12597
|
})]
|
|
12598
12598
|
});
|
|
12599
12599
|
}
|
|
12600
|
+
// src/lib/segmenter.ts
|
|
12601
|
+
var FRAME_SECONDS = .02;
|
|
12602
|
+
var ONSET_FRAMES = 3;
|
|
12603
|
+
var HYSTERESIS_DB = 6;
|
|
12604
|
+
var RISE_DB_PER_SECOND = 2.5;
|
|
12605
|
+
var FALL = .2;
|
|
12606
|
+
var SILENT_DB = -100;
|
|
12607
|
+
/** The RMS of `frame` in dBFS, `SILENT_DB` for zeros. */
|
|
12608
|
+
function rmsDb(frame) {
|
|
12609
|
+
let sum = 0;
|
|
12610
|
+
for (let i = 0; i < frame.length; i++) sum += frame[i] * frame[i];
|
|
12611
|
+
const rms = Math.sqrt(sum / Math.max(1, frame.length));
|
|
12612
|
+
return rms > 0 ? Math.max(SILENT_DB, 20 * Math.log10(rms)) : SILENT_DB;
|
|
12613
|
+
}
|
|
12614
|
+
/** A segmenter for a stream at `sampleRate`. */
|
|
12615
|
+
function createSegmenter(sampleRate, { onsetDb = 12, floorDb = -55, silenceSeconds = 1, padSeconds = .3, minSpeechSeconds = .3, maxSeconds } = {}) {
|
|
12616
|
+
const frameLength = Math.max(1, Math.round(sampleRate * FRAME_SECONDS));
|
|
12617
|
+
const frames = (seconds) => Math.max(0, Math.round(seconds / FRAME_SECONDS));
|
|
12618
|
+
const padFrames = frames(padSeconds);
|
|
12619
|
+
const silenceFrames = Math.max(1, frames(silenceSeconds));
|
|
12620
|
+
const minSpeechFrames = frames(minSpeechSeconds);
|
|
12621
|
+
const maxSamples = maxSeconds === void 0 ? Infinity : Math.floor(maxSeconds * sampleRate);
|
|
12622
|
+
const rise = RISE_DB_PER_SECOND * FRAME_SECONDS;
|
|
12623
|
+
let carry = new Float32Array(frameLength);
|
|
12624
|
+
let carried = 0;
|
|
12625
|
+
const recent = [];
|
|
12626
|
+
const recentSize = padFrames + ONSET_FRAMES;
|
|
12627
|
+
let noise = null;
|
|
12628
|
+
let loudRun = 0;
|
|
12629
|
+
let take = null;
|
|
12630
|
+
let lastSpeech = 0;
|
|
12631
|
+
let speechFrames = 0;
|
|
12632
|
+
let hush = 0;
|
|
12633
|
+
const join = (parts, length) => {
|
|
12634
|
+
const out = new Float32Array(length);
|
|
12635
|
+
let at = 0;
|
|
12636
|
+
for (const p of parts) {
|
|
12637
|
+
if (at >= length) break;
|
|
12638
|
+
const n = Math.min(p.length, length - at);
|
|
12639
|
+
out.set(n < p.length ? p.subarray(0, n) : p, at);
|
|
12640
|
+
at += n;
|
|
12641
|
+
}
|
|
12642
|
+
return out;
|
|
12643
|
+
};
|
|
12644
|
+
const length = (parts) => parts.length * frameLength;
|
|
12645
|
+
const end = () => {
|
|
12646
|
+
const t = take;
|
|
12647
|
+
const spoke = speechFrames;
|
|
12648
|
+
take = null;
|
|
12649
|
+
speechFrames = 0;
|
|
12650
|
+
if (!t || spoke < minSpeechFrames) return null;
|
|
12651
|
+
const keep = Math.min(t.length, lastSpeech + padFrames);
|
|
12652
|
+
return {
|
|
12653
|
+
samples: join(t, Math.min(keep * frameLength, maxSamples)),
|
|
12654
|
+
cut: false
|
|
12655
|
+
};
|
|
12656
|
+
};
|
|
12657
|
+
const frame = (f) => {
|
|
12658
|
+
const db = rmsDb(f);
|
|
12659
|
+
const quiet = noise ?? db;
|
|
12660
|
+
const on = Math.max(quiet + onsetDb, floorDb);
|
|
12661
|
+
const still = Math.max(quiet + onsetDb - HYSTERESIS_DB, floorDb - HYSTERESIS_DB);
|
|
12662
|
+
recent.push(f);
|
|
12663
|
+
if (recent.length > recentSize) recent.shift();
|
|
12664
|
+
if (take) {
|
|
12665
|
+
take.push(f);
|
|
12666
|
+
if (db >= still) {
|
|
12667
|
+
lastSpeech = take.length;
|
|
12668
|
+
speechFrames++;
|
|
12669
|
+
}
|
|
12670
|
+
if (lastSpeech * frameLength >= maxSamples) {
|
|
12671
|
+
const t = take;
|
|
12672
|
+
take = null;
|
|
12673
|
+
speechFrames = 0;
|
|
12674
|
+
hush = silenceFrames;
|
|
12675
|
+
loudRun = 0;
|
|
12676
|
+
return {
|
|
12677
|
+
samples: join(t, maxSamples),
|
|
12678
|
+
cut: true
|
|
12679
|
+
};
|
|
12680
|
+
}
|
|
12681
|
+
return take.length - lastSpeech >= silenceFrames ? end() : null;
|
|
12682
|
+
}
|
|
12683
|
+
if (db < on) {
|
|
12684
|
+
noise = db < quiet ? quiet + (db - quiet) * FALL : Math.min(db, quiet + rise);
|
|
12685
|
+
loudRun = 0;
|
|
12686
|
+
if (hush > 0) hush--;
|
|
12687
|
+
return null;
|
|
12688
|
+
}
|
|
12689
|
+
if (hush > 0) {
|
|
12690
|
+
hush = silenceFrames;
|
|
12691
|
+
return null;
|
|
12692
|
+
}
|
|
12693
|
+
loudRun++;
|
|
12694
|
+
if (loudRun < ONSET_FRAMES) return null;
|
|
12695
|
+
take = [...recent];
|
|
12696
|
+
lastSpeech = take.length;
|
|
12697
|
+
speechFrames = ONSET_FRAMES;
|
|
12698
|
+
loudRun = 0;
|
|
12699
|
+
return null;
|
|
12700
|
+
};
|
|
12701
|
+
return {
|
|
12702
|
+
push(chunk) {
|
|
12703
|
+
const out = [];
|
|
12704
|
+
let at = 0;
|
|
12705
|
+
while (at < chunk.length) {
|
|
12706
|
+
const n = Math.min(frameLength - carried, chunk.length - at);
|
|
12707
|
+
carry.set(chunk.subarray(at, at + n), carried);
|
|
12708
|
+
carried += n;
|
|
12709
|
+
at += n;
|
|
12710
|
+
if (carried === frameLength) {
|
|
12711
|
+
const f = carry;
|
|
12712
|
+
carry = new Float32Array(frameLength);
|
|
12713
|
+
carried = 0;
|
|
12714
|
+
const s = frame(f);
|
|
12715
|
+
if (s) out.push(s);
|
|
12716
|
+
}
|
|
12717
|
+
}
|
|
12718
|
+
return out;
|
|
12719
|
+
},
|
|
12720
|
+
flush() {
|
|
12721
|
+
hush = 0;
|
|
12722
|
+
return end();
|
|
12723
|
+
},
|
|
12724
|
+
reset() {
|
|
12725
|
+
take = null;
|
|
12726
|
+
speechFrames = 0;
|
|
12727
|
+
loudRun = 0;
|
|
12728
|
+
hush = 0;
|
|
12729
|
+
recent.length = 0;
|
|
12730
|
+
},
|
|
12731
|
+
get noise() {
|
|
12732
|
+
return noise === null ? null : Math.max(-60, noise);
|
|
12733
|
+
},
|
|
12734
|
+
get speaking() {
|
|
12735
|
+
return take !== null;
|
|
12736
|
+
},
|
|
12737
|
+
get seconds() {
|
|
12738
|
+
return take ? length(take) / sampleRate : 0;
|
|
12739
|
+
}
|
|
12740
|
+
};
|
|
12741
|
+
}
|
|
12742
|
+
// src/components/auto-recorder.tsx
|
|
12743
|
+
/** Listens all the time and hands over each stretch of speech as its own lossless take. */
|
|
12744
|
+
function useAutoRecorder({ maxSeconds, onTake, paused = false, microphone, ...tuning }) {
|
|
12745
|
+
const fromContext = useMicrophone();
|
|
12746
|
+
const device = microphone ?? fromContext;
|
|
12747
|
+
const [state, setState] = React.useState({ phase: "idle" });
|
|
12748
|
+
const stream = React.useRef(null);
|
|
12749
|
+
const segmenter = React.useRef(null);
|
|
12750
|
+
const latest = React.useRef({
|
|
12751
|
+
onTake,
|
|
12752
|
+
paused,
|
|
12753
|
+
maxSeconds,
|
|
12754
|
+
tuning
|
|
12755
|
+
});
|
|
12756
|
+
latest.current = {
|
|
12757
|
+
onTake,
|
|
12758
|
+
paused,
|
|
12759
|
+
maxSeconds,
|
|
12760
|
+
tuning
|
|
12761
|
+
};
|
|
12762
|
+
const mounted = React.useRef(true);
|
|
12763
|
+
const opening = React.useRef(false);
|
|
12764
|
+
const hand = React.useCallback((samples, cut, s) => {
|
|
12765
|
+
latest.current.onTake({
|
|
12766
|
+
samples,
|
|
12767
|
+
sampleRate: s.sampleRate,
|
|
12768
|
+
wav: encodeWav(samples, s.sampleRate),
|
|
12769
|
+
seconds: samples.length / s.sampleRate,
|
|
12770
|
+
peak: peakDb(samples),
|
|
12771
|
+
device: s.device,
|
|
12772
|
+
cut
|
|
12773
|
+
});
|
|
12774
|
+
}, []);
|
|
12775
|
+
const flush = React.useCallback(() => {
|
|
12776
|
+
const s = stream.current;
|
|
12777
|
+
const taken = segmenter.current?.flush();
|
|
12778
|
+
if (s && taken) hand(taken.samples, taken.cut, s);
|
|
12779
|
+
}, [hand]);
|
|
12780
|
+
const stop = React.useCallback(() => {
|
|
12781
|
+
const s = stream.current;
|
|
12782
|
+
if (!s) return;
|
|
12783
|
+
flush();
|
|
12784
|
+
stream.current = null;
|
|
12785
|
+
segmenter.current = null;
|
|
12786
|
+
s.close();
|
|
12787
|
+
setState({ phase: "idle" });
|
|
12788
|
+
}, [flush]);
|
|
12789
|
+
const start = React.useCallback(async () => {
|
|
12790
|
+
if (stream.current || opening.current) return false;
|
|
12791
|
+
opening.current = true;
|
|
12792
|
+
setState({ phase: "opening" });
|
|
12793
|
+
let recent = [];
|
|
12794
|
+
let opened;
|
|
12795
|
+
try {
|
|
12796
|
+
opened = await device.open((chunk) => {
|
|
12797
|
+
const s = stream.current;
|
|
12798
|
+
const seg = segmenter.current;
|
|
12799
|
+
if (!s || !seg) return;
|
|
12800
|
+
recent = [...recent.slice(-4), peakDb(chunk)];
|
|
12801
|
+
const quiet = latest.current.paused;
|
|
12802
|
+
if (!quiet) for (const taken of seg.push(chunk)) hand(taken.samples, taken.cut, s);
|
|
12803
|
+
setState({
|
|
12804
|
+
phase: "listening",
|
|
12805
|
+
level: Math.max(...recent),
|
|
12806
|
+
noise: seg.noise,
|
|
12807
|
+
speaking: !quiet && seg.speaking,
|
|
12808
|
+
seconds: quiet ? 0 : seg.seconds,
|
|
12809
|
+
paused: quiet
|
|
12810
|
+
});
|
|
12811
|
+
});
|
|
12812
|
+
} catch (e) {
|
|
12813
|
+
opening.current = false;
|
|
12814
|
+
setState({
|
|
12815
|
+
phase: "failed",
|
|
12816
|
+
reason: e instanceof MicrophoneError ? e.message : `The microphone could not be opened (${String(e)}).`
|
|
12817
|
+
});
|
|
12818
|
+
return false;
|
|
12819
|
+
}
|
|
12820
|
+
opening.current = false;
|
|
12821
|
+
if (!mounted.current) {
|
|
12822
|
+
opened.close();
|
|
12823
|
+
return false;
|
|
12824
|
+
}
|
|
12825
|
+
const { maxSeconds: max, tuning: t } = latest.current;
|
|
12826
|
+
segmenter.current = createSegmenter(opened.sampleRate, {
|
|
12827
|
+
...t,
|
|
12828
|
+
maxSeconds: max
|
|
12829
|
+
});
|
|
12830
|
+
stream.current = opened;
|
|
12831
|
+
const quiet = latest.current.paused;
|
|
12832
|
+
setState({
|
|
12833
|
+
phase: "listening",
|
|
12834
|
+
level: -60,
|
|
12835
|
+
noise: null,
|
|
12836
|
+
speaking: false,
|
|
12837
|
+
seconds: 0,
|
|
12838
|
+
paused: quiet
|
|
12839
|
+
});
|
|
12840
|
+
return true;
|
|
12841
|
+
}, [device, hand]);
|
|
12842
|
+
React.useEffect(() => {
|
|
12843
|
+
if (paused) flush();
|
|
12844
|
+
else segmenter.current?.reset();
|
|
12845
|
+
setState((now) => now.phase === "listening" ? {
|
|
12846
|
+
...now,
|
|
12847
|
+
paused,
|
|
12848
|
+
speaking: false,
|
|
12849
|
+
seconds: 0
|
|
12850
|
+
} : now);
|
|
12851
|
+
}, [paused, flush]);
|
|
12852
|
+
React.useEffect(() => {
|
|
12853
|
+
mounted.current = true;
|
|
12854
|
+
return () => {
|
|
12855
|
+
mounted.current = false;
|
|
12856
|
+
stream.current?.close();
|
|
12857
|
+
stream.current = null;
|
|
12858
|
+
segmenter.current = null;
|
|
12859
|
+
};
|
|
12860
|
+
}, []);
|
|
12861
|
+
return {
|
|
12862
|
+
state,
|
|
12863
|
+
start,
|
|
12864
|
+
stop,
|
|
12865
|
+
listening: state.phase === "listening" || state.phase === "opening"
|
|
12866
|
+
};
|
|
12867
|
+
}
|
|
12868
|
+
/** The live level of a microphone that is always open, with what it is doing in words: waiting, hearing a take, or paused. */
|
|
12869
|
+
function ListeningLevel({ state, maxSeconds, label = "Input level", className }) {
|
|
12870
|
+
const db = Math.min(0, Math.max(-60, state.level));
|
|
12871
|
+
const room = state.noise === null ? "" : `; the room is at ${format.integer(Math.round(state.noise) || 0)} dBFS`;
|
|
12872
|
+
const detail = state.paused ? `Paused: nothing is kept until you resume${room}` : state.speaking ? `Hearing you: ${format.runningTime(state.seconds)} of at most ${format.runningTime(maxSeconds)}` : `Listening: start speaking to record${room}`;
|
|
12873
|
+
return /* @__PURE__ */ jsx(Meter, {
|
|
12874
|
+
label,
|
|
12875
|
+
value: db - -60,
|
|
12876
|
+
max: 60,
|
|
12877
|
+
thresholds: inputLevelThresholds,
|
|
12878
|
+
valueText: `${format.integer(Math.round(db) || 0)} dBFS`,
|
|
12879
|
+
detail,
|
|
12880
|
+
className
|
|
12881
|
+
});
|
|
12882
|
+
}
|
|
12600
12883
|
// src/lib/image-diff.ts
|
|
12601
12884
|
/** The longest side, in pixels, a picture is compared at. */
|
|
12602
12885
|
var MAX_SIDE = 2048;
|
|
@@ -18216,6 +18499,6 @@ function FolderPicker({ label, useFolders: useListing, value, onChange, onChoose
|
|
|
18216
18499
|
]
|
|
18217
18500
|
});
|
|
18218
18501
|
}
|
|
18219
|
-
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 };
|
|
18502
|
+
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, ListeningLevel, 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, createSegmenter, 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, rmsDb, 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, useAutoRecorder, 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 };
|
|
18220
18503
|
|
|
18221
18504
|
//# sourceMappingURL=index.js.map
|