@supersuit/components 0.0.0-stage → 0.3.0

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.
Files changed (84) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/LICENSE +21 -0
  3. package/README.md +338 -2
  4. package/bin/supersuit-theme.mjs +116 -0
  5. package/dist/app-shell/app-shell.d.ts +68 -0
  6. package/dist/app-shell/app-shell.js +62 -0
  7. package/dist/app-shell/index.d.ts +3 -0
  8. package/dist/app-shell/index.js +5 -0
  9. package/dist/app-shell/sheet.d.ts +14 -0
  10. package/dist/app-shell/sheet.js +57 -0
  11. package/dist/app-shell/styles.css +112 -0
  12. package/dist/check/depth/bar.d.ts +27 -0
  13. package/dist/check/depth/bar.js +40 -0
  14. package/dist/check/depth/check.d.ts +40 -0
  15. package/dist/check/depth/check.js +50 -0
  16. package/dist/check/depth/crop.d.ts +24 -0
  17. package/dist/check/depth/crop.js +126 -0
  18. package/dist/check/depth/index.d.ts +3 -0
  19. package/dist/check/depth/index.js +5 -0
  20. package/dist/check/depth/measure.d.ts +42 -0
  21. package/dist/check/depth/measure.js +141 -0
  22. package/dist/check/depth/parts-page.d.ts +6 -0
  23. package/dist/check/depth/parts-page.js +69 -0
  24. package/dist/check/depth/playwright.d.ts +4 -0
  25. package/dist/check/depth/playwright.js +10 -0
  26. package/dist/check/depth/png.d.ts +3 -0
  27. package/dist/check/depth/png.js +12 -0
  28. package/dist/check/depth/shoot.d.ts +37 -0
  29. package/dist/check/depth/shoot.js +30 -0
  30. package/dist/choice-chips/choice-chips.d.ts +40 -0
  31. package/dist/choice-chips/choice-chips.js +106 -0
  32. package/dist/choice-chips/index.d.ts +1 -0
  33. package/dist/choice-chips/index.js +3 -0
  34. package/dist/choice-chips/styles.css +38 -0
  35. package/dist/index.d.ts +4 -0
  36. package/dist/index.js +11 -0
  37. package/dist/page-header/index.d.ts +2 -0
  38. package/dist/page-header/index.js +4 -0
  39. package/dist/page-header/page-header.d.ts +58 -0
  40. package/dist/page-header/page-header.js +124 -0
  41. package/dist/page-header/shell-context.d.ts +12 -0
  42. package/dist/page-header/shell-context.js +21 -0
  43. package/dist/page-header/styles.css +77 -0
  44. package/dist/row/index.d.ts +1 -0
  45. package/dist/row/index.js +3 -0
  46. package/dist/row/row.d.ts +76 -0
  47. package/dist/row/row.js +69 -0
  48. package/dist/row/styles.css +69 -0
  49. package/dist/sound/engine.d.ts +59 -0
  50. package/dist/sound/engine.js +325 -0
  51. package/dist/sound/index.d.ts +18 -0
  52. package/dist/sound/index.js +10 -0
  53. package/dist/sound/synth.d.ts +24 -0
  54. package/dist/sound/synth.js +139 -0
  55. package/dist/theme/color.d.ts +29 -0
  56. package/dist/theme/color.js +116 -0
  57. package/dist/theme/compile.d.ts +23 -0
  58. package/dist/theme/compile.js +138 -0
  59. package/dist/theme/index.d.ts +3 -0
  60. package/dist/theme/index.js +4 -0
  61. package/dist/theme/record.d.ts +90 -0
  62. package/dist/theme/record.js +222 -0
  63. package/dist/voice-field/box-trace.d.ts +18 -0
  64. package/dist/voice-field/box-trace.js +87 -0
  65. package/dist/voice-field/index.d.ts +8 -0
  66. package/dist/voice-field/index.js +10 -0
  67. package/dist/voice-field/recorder.d.ts +71 -0
  68. package/dist/voice-field/recorder.js +211 -0
  69. package/dist/voice-field/rules.d.ts +27 -0
  70. package/dist/voice-field/rules.js +62 -0
  71. package/dist/voice-field/saved-take.d.ts +7 -0
  72. package/dist/voice-field/saved-take.js +66 -0
  73. package/dist/voice-field/store.d.ts +27 -0
  74. package/dist/voice-field/store.js +40 -0
  75. package/dist/voice-field/styles.css +161 -0
  76. package/dist/voice-field/toast.d.ts +13 -0
  77. package/dist/voice-field/toast.js +26 -0
  78. package/dist/voice-field/voice-field.d.ts +80 -0
  79. package/dist/voice-field/voice-field.js +259 -0
  80. package/dist/voice-field/words.d.ts +37 -0
  81. package/dist/voice-field/words.js +33 -0
  82. package/package.json +126 -4
  83. package/specs/brand-theme/v1/SPEC.md +130 -0
  84. package/specs/brand-theme/v1/default-bar.json +1196 -0
@@ -0,0 +1,71 @@
1
+ import type { VoiceStore } from './store.js';
2
+ import { type ToastFn } from './toast.js';
3
+ import { type VoiceFieldWords } from './words.js';
4
+ export interface Recorded {
5
+ key: string;
6
+ blob: Blob;
7
+ ms: number;
8
+ }
9
+ export interface LiveTake {
10
+ started: number;
11
+ /** The input's loudness now, 0 to 1, or null where the browser cannot measure it. */
12
+ level?: () => number | null;
13
+ stop(): Promise<Recorded>;
14
+ cancel(): Promise<void>;
15
+ }
16
+ export type StartTake = (store: VoiceStore, key: string, questionId: string) => Promise<LiveTake>;
17
+ export declare const defaultStartTake: StartTake;
18
+ export type MicState = 'idle' | 'opening' | 'recording' | 'busy' | 'done';
19
+ export type MicSize = 'small' | 'large' | 'inline';
20
+ /** What a class function is told, so an app can draw each state its own way. */
21
+ export interface MicLook {
22
+ shown: MicState;
23
+ size: MicSize;
24
+ recording: boolean;
25
+ keyHint?: string;
26
+ }
27
+ type ClassFor = string | ((l: MicLook) => string);
28
+ export interface MicClassNames {
29
+ button?: ClassFor;
30
+ level?: ClassFor;
31
+ spin?: ClassFor;
32
+ stop?: ClassFor;
33
+ clock?: ClassFor;
34
+ }
35
+ export interface MicReport {
36
+ state: MicState;
37
+ sec: number;
38
+ tapped: boolean;
39
+ }
40
+ /** The default event a screen sends the mic's own button to work it from a key: `toggle` is a tap, `cancel`
41
+ * stops a take and keeps nothing. */
42
+ export declare const VOICE_KEY_EVENT = "voice-field:key";
43
+ export declare const pressVoice: (mic: Element, what: "toggle" | "cancel", event?: string) => boolean;
44
+ export interface RecorderProps {
45
+ store: VoiceStore;
46
+ questionId: string;
47
+ takeKey: () => string;
48
+ onTake(r: Recorded): void;
49
+ disabled?: boolean;
50
+ busy?: boolean;
51
+ done?: boolean;
52
+ size?: MicSize;
53
+ label?: string;
54
+ startTake?: StartTake;
55
+ /** The key that works this mic, set as data-key-hint while idle so the app's CSS can draw it; absent, nothing is drawn. */
56
+ keyHint?: string;
57
+ toast?: ToastFn;
58
+ words?: Partial<VoiceFieldWords>;
59
+ /** The event name a screen sends to work this mic from a key (pressVoice). */
60
+ keyEvent?: string;
61
+ /** Draw the elapsed time as a badge on the button. A box that shows the time itself turns this off. */
62
+ badge?: boolean;
63
+ /** Told of every change of state and each new second, so the box around the mic can show them. */
64
+ onState?(s: MicReport): void;
65
+ /** How the inline mic draws a wait: a ring (the default) or a trace round its own rounded square. */
66
+ inlineWait?: 'ring' | 'trace';
67
+ /** Extra classes for an app that draws the mic with its own CSS instead of the package's styles.css. */
68
+ classNames?: MicClassNames;
69
+ }
70
+ export declare function Recorder({ store, questionId, takeKey, onTake, disabled, busy, done, size, label, startTake, keyHint, toast, words: wordsIn, keyEvent, badge, onState, inlineWait, classNames }: RecorderProps): import("react").JSX.Element;
71
+ export {};
@@ -0,0 +1,211 @@
1
+ 'use client';
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ // THE MIC: one round button that says everything about a take by itself, and takes no space beside it.
4
+ //
5
+ // idle the microphone
6
+ // opening a wait drawn while the browser opens the microphone
7
+ // recording red with a stop square, a ring that swells with the live input level, aria-pressed, and the
8
+ // elapsed time (as a badge on the button, or in the box around it when the box shows it)
9
+ // busy a wait drawn while the words are written down (the field says so: `busy`)
10
+ // done a check, for a moment, when the words are in (the field says so: `done`)
11
+ // Everything else is a toast: a blocked microphone, a take too short to keep, and "No speech heard yet" when
12
+ // the input stays near silence for NO_SPEECH_MS while recording.
13
+ //
14
+ // Tap to start and tap again to stop, or hold to talk and let go to stop. Tap or hold is decided by how long
15
+ // the TAKE has run when the finger lifts, never by the time since the press (rules.ts, releaseIsTap). A
16
+ // cancelled touch never stops a take. The microphone is asked for inside the press itself, before anything
17
+ // is awaited, or iPhone Safari does not count the press as the gesture that may open it.
18
+ //
19
+ // The recording layer is `startTake`: by default @supersuit/suggest-a-change's, which writes every second of
20
+ // the take to the store as it is recorded, so a take the page is closed in the middle of can be made whole.
21
+ import { useEffect, useRef, useState } from 'react';
22
+ import { startTake as moduleStartTake } from '@supersuit/suggest-a-change/client';
23
+ import { BoxTrace } from './box-trace.js';
24
+ import { clock, MAX_SEC, micError, MIN_MS, releaseIsTap, silenceWatch } from './rules.js';
25
+ import { voiceToast } from './toast.js';
26
+ import { wordsWith } from './words.js';
27
+ export const defaultStartTake = (store, key, questionId) => moduleStartTake(store, key, questionId);
28
+ /** The default event a screen sends the mic's own button to work it from a key: `toggle` is a tap, `cancel`
29
+ * stops a take and keeps nothing. */
30
+ export const VOICE_KEY_EVENT = 'voice-field:key';
31
+ export const pressVoice = (mic, what, event = VOICE_KEY_EVENT) => mic.dispatchEvent(new CustomEvent(event, { detail: what }));
32
+ const cls = (base, extra, look) => {
33
+ const more = typeof extra === 'function' ? extra(look) : extra;
34
+ return more ? `${base} ${more}` : base;
35
+ };
36
+ export function Recorder({ store, questionId, takeKey, onTake, disabled, busy = false, done = false, size = 'small', label, startTake = defaultStartTake, keyHint, toast = voiceToast, words: wordsIn, keyEvent = VOICE_KEY_EVENT, badge = true, onState, inlineWait = 'ring', classNames = {} }) {
37
+ const words = wordsWith(wordsIn);
38
+ const [state, setState] = useState('idle');
39
+ const [sec, setSec] = useState(0);
40
+ const live = useRef(null);
41
+ const ring = useRef(null);
42
+ const pressing = useRef(false);
43
+ const tapMode = useRef(false);
44
+ const wantStop = useRef(false);
45
+ const wantCancel = useRef(false);
46
+ const btn = useRef(null);
47
+ const said = useRef({ toast, words });
48
+ said.current = { toast, words };
49
+ useEffect(() => () => { void live.current?.cancel(); }, []);
50
+ useEffect(() => {
51
+ if (state !== 'recording')
52
+ return;
53
+ const cur = live.current;
54
+ const heard = silenceWatch(cur?.started ?? Date.now());
55
+ const iv = setInterval(() => {
56
+ const now = Date.now();
57
+ const s = (now - (cur?.started ?? now)) / 1000;
58
+ setSec(s);
59
+ if (s >= MAX_SEC) {
60
+ void stop();
61
+ return;
62
+ }
63
+ const lvl = cur?.level?.();
64
+ if (lvl == null)
65
+ return;
66
+ ring.current?.style.setProperty('--lvl', String(Math.min(1, lvl * 6)));
67
+ if (heard(lvl, now))
68
+ said.current.toast({ id: 'no-speech', text: said.current.words.noSpeech(), tone: 'warn' });
69
+ }, 80);
70
+ return () => clearInterval(iv);
71
+ }, [state]);
72
+ async function start() {
73
+ setSec(0);
74
+ setState('opening');
75
+ wantStop.current = false;
76
+ wantCancel.current = false;
77
+ try {
78
+ live.current = await startTake(store, takeKey(), questionId);
79
+ // Esc while the microphone was opening: the take is dropped the moment it exists.
80
+ if (wantCancel.current) {
81
+ wantCancel.current = false;
82
+ const cur = live.current;
83
+ live.current = null;
84
+ setState('idle');
85
+ void cur?.cancel();
86
+ return;
87
+ }
88
+ setState('recording');
89
+ if (wantStop.current && !tapMode.current)
90
+ void stop();
91
+ }
92
+ catch (e) {
93
+ setState('idle');
94
+ said.current.toast({ id: 'mic', text: micError(e, said.current.words), tone: 'warn', ms: 6000 });
95
+ }
96
+ }
97
+ async function stop() {
98
+ const cur = live.current;
99
+ if (!cur) {
100
+ wantStop.current = true;
101
+ return;
102
+ }
103
+ live.current = null;
104
+ setState('idle');
105
+ const r = await cur.stop();
106
+ if (r.ms < MIN_MS || !r.blob.size) {
107
+ void store.del('blobs', r.key);
108
+ said.current.toast({ id: 'short', text: said.current.words.tooShort() });
109
+ return;
110
+ }
111
+ onTake(r);
112
+ }
113
+ const down = (e) => {
114
+ e.preventDefault();
115
+ if (disabled || busy)
116
+ return;
117
+ if (state === 'recording' && tapMode.current) {
118
+ tapMode.current = false;
119
+ void stop();
120
+ return;
121
+ }
122
+ if (state !== 'idle')
123
+ return;
124
+ pressing.current = true;
125
+ tapMode.current = false;
126
+ void start();
127
+ };
128
+ const up = () => {
129
+ if (!pressing.current)
130
+ return;
131
+ pressing.current = false;
132
+ if (tapMode.current)
133
+ return;
134
+ // Still opening, or only just recording: that was a tap, and the take keeps going until the next one.
135
+ if (releaseIsTap(live.current?.started, Date.now())) {
136
+ tapMode.current = true;
137
+ return;
138
+ }
139
+ void stop();
140
+ };
141
+ // The phone took the touch away (a scroll, a system prompt). The take keeps going; a tap stops it.
142
+ const cancel = () => {
143
+ if (!pressing.current)
144
+ return;
145
+ pressing.current = false;
146
+ tapMode.current = true;
147
+ };
148
+ const keyed = useRef(() => { });
149
+ keyed.current = (what) => {
150
+ if (what === 'toggle') {
151
+ if (disabled || busy)
152
+ return;
153
+ if (state === 'recording') {
154
+ tapMode.current = false;
155
+ void stop();
156
+ }
157
+ else if (state === 'idle') {
158
+ tapMode.current = true;
159
+ void start();
160
+ }
161
+ return;
162
+ }
163
+ if (what !== 'cancel')
164
+ return;
165
+ if (state === 'opening') {
166
+ wantCancel.current = true;
167
+ return;
168
+ }
169
+ const cur = live.current;
170
+ if (!cur)
171
+ return;
172
+ live.current = null;
173
+ tapMode.current = false;
174
+ setState('idle');
175
+ void cur.cancel();
176
+ said.current.toast({ id: 'rec-cancelled', text: said.current.words.cancelled() });
177
+ };
178
+ useEffect(() => {
179
+ const el = btn.current;
180
+ if (!el)
181
+ return;
182
+ const f = (e) => keyed.current(String(e.detail));
183
+ el.addEventListener(keyEvent, f);
184
+ return () => el.removeEventListener(keyEvent, f);
185
+ }, [keyEvent]);
186
+ const recording = state === 'recording';
187
+ const shown = recording ? 'recording' : state === 'opening' ? 'opening' : busy ? 'busy' : done ? 'done' : 'idle';
188
+ const whole = Math.floor(sec);
189
+ const report = useRef(onState);
190
+ report.current = onState;
191
+ useEffect(() => { report.current?.({ state: shown, sec: whole, tapped: tapMode.current }); }, [shown, whole]);
192
+ const big = size === 'large';
193
+ const inline = size === 'inline';
194
+ const look = { shown, size, recording, keyHint };
195
+ const aria = recording ? words.recordingAria(clock(sec), tapMode.current)
196
+ : shown === 'opening' ? words.opening() : shown === 'busy' ? words.writingDown() : (label ?? words.micLabel());
197
+ const icon = big ? 30 : inline ? 20 : 22;
198
+ const waiting = shown === 'opening' || shown === 'busy';
199
+ return (_jsxs("button", { ref: btn, type: "button", "data-voice-control": "", "data-rec-state": shown, "data-size": size, "data-key-hint": keyHint && !recording ? keyHint : undefined, "aria-label": aria, "aria-pressed": recording, disabled: disabled || busy, onPointerDown: down, onPointerUp: up, onPointerCancel: cancel, onContextMenu: (e) => e.preventDefault(), onKeyDown: (e) => { if (e.key === 'Enter' || e.key === ' ') {
200
+ e.preventDefault();
201
+ if (recording)
202
+ void stop();
203
+ else if (state === 'idle') {
204
+ tapMode.current = true;
205
+ void start();
206
+ }
207
+ } }, className: cls('vf-mic', classNames.button, look), style: { WebkitUserSelect: 'none', WebkitTouchCallout: 'none', touchAction: 'none' }, children: [recording ? _jsx("span", { ref: ring, "aria-hidden": "true", className: cls('vf-level', classNames.level, look) }) : null, inline && inlineWait === 'trace' && waiting ? _jsx(BoxTrace, { tone: shown === 'busy' ? 'on' : 'rec' }) : null, waiting && !(inline && inlineWait === 'trace') ? _jsx("span", { "aria-hidden": "true", className: cls('vf-spin', classNames.spin, look) }) : null, recording ? _jsx("span", { "aria-hidden": "true", className: cls('vf-stop', classNames.stop, look) })
208
+ : shown === 'done'
209
+ ? _jsx("svg", { width: icon, height: icon, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "M5 12.5l4.5 4.5L19 7.5" }) })
210
+ : _jsxs("svg", { width: icon, height: icon, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", "aria-hidden": "true", children: [_jsx("rect", { x: "9", y: "3", width: "6", height: "11", rx: "3" }), _jsx("path", { d: "M5 11a7 7 0 0 0 14 0M12 18v3" })] }), recording && badge ? _jsx("span", { "data-rec-clock": "", "aria-hidden": "true", className: cls('vf-clock-badge', classNames.clock, look), children: clock(sec) }) : null] }));
211
+ }
@@ -0,0 +1,27 @@
1
+ import { type VoiceFieldWords } from './words.js';
2
+ /** A release before the take has run this long was a tap: the take keeps going until the next tap. */
3
+ export declare const TAP_MS = 350;
4
+ /** A take shorter than this is thrown away ("Too short to keep"). */
5
+ export declare const MIN_MS = 600;
6
+ /** A take stops itself at ten minutes. */
7
+ export declare const MAX_SEC = 600;
8
+ /** Below this RMS level the input counts as silence (a quiet room with noise suppression sits near 0.001; speech is 0.02 and up). */
9
+ export declare const SILENCE = 0.01;
10
+ export declare const NO_SPEECH_MS = 3000;
11
+ export declare const clock: (s: number) => string;
12
+ /**
13
+ * TAP OR HOLD, judged by how long the take has RUN, never by the time since the press.
14
+ * A phone takes a moment to open its microphone and may cancel the touch while it does, so timing
15
+ * from the press read an ordinary tap on an iPhone as a short hold and threw the take away (seen
16
+ * 2026-10-15: a tap did not start the recording, only a hold of about a second did). So: a release
17
+ * while the microphone is still opening, or before the take is TAP_MS old, was a tap, and the take
18
+ * keeps going until the next tap. `startedAt` is null while the microphone is still opening.
19
+ */
20
+ export declare const releaseIsTap: (startedAt: number | null | undefined, now: number) => boolean;
21
+ /** Fires once per take, when the level has stayed under SILENCE for NO_SPEECH_MS. */
22
+ export declare function silenceWatch(startedAt: number, ms?: number, threshold?: number): (level: number, now: number) => boolean;
23
+ /** What to tell a person whose microphone did not open, from the browser's error name. */
24
+ export declare function micError(e: unknown, words?: VoiceFieldWords): string;
25
+ /** Bars for a kept recording's waveform: `n` heights between 0.12 and 1, read from the audio when the
26
+ * browser can decode it, else from the bytes, so the same recording always draws the same shape. */
27
+ export declare function barsFromSamples(samples: ArrayLike<number>, n?: number): number[];
@@ -0,0 +1,62 @@
1
+ // The mic's rules that are not the DOM, as pure functions so each can be tested on its own.
2
+ import { defaultWords } from './words.js';
3
+ /** A release before the take has run this long was a tap: the take keeps going until the next tap. */
4
+ export const TAP_MS = 350;
5
+ /** A take shorter than this is thrown away ("Too short to keep"). */
6
+ export const MIN_MS = 600;
7
+ /** A take stops itself at ten minutes. */
8
+ export const MAX_SEC = 600;
9
+ /** Below this RMS level the input counts as silence (a quiet room with noise suppression sits near 0.001; speech is 0.02 and up). */
10
+ export const SILENCE = 0.01;
11
+ export const NO_SPEECH_MS = 3000;
12
+ export const clock = (s) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
13
+ /**
14
+ * TAP OR HOLD, judged by how long the take has RUN, never by the time since the press.
15
+ * A phone takes a moment to open its microphone and may cancel the touch while it does, so timing
16
+ * from the press read an ordinary tap on an iPhone as a short hold and threw the take away (seen
17
+ * 2026-10-15: a tap did not start the recording, only a hold of about a second did). So: a release
18
+ * while the microphone is still opening, or before the take is TAP_MS old, was a tap, and the take
19
+ * keeps going until the next tap. `startedAt` is null while the microphone is still opening.
20
+ */
21
+ export const releaseIsTap = (startedAt, now) => startedAt == null || now - startedAt < TAP_MS;
22
+ /** Fires once per take, when the level has stayed under SILENCE for NO_SPEECH_MS. */
23
+ export function silenceWatch(startedAt, ms = NO_SPEECH_MS, threshold = SILENCE) {
24
+ let lastLoud = startedAt;
25
+ let fired = false;
26
+ return (level, now) => {
27
+ if (level >= threshold) {
28
+ lastLoud = now;
29
+ return false;
30
+ }
31
+ if (fired || now - lastLoud < ms)
32
+ return false;
33
+ fired = true;
34
+ return true;
35
+ };
36
+ }
37
+ /** What to tell a person whose microphone did not open, from the browser's error name. */
38
+ export function micError(e, words = defaultWords) {
39
+ const name = String(e?.name || e);
40
+ if (/NotAllowed|denied|Security/i.test(name))
41
+ return words.micBlocked();
42
+ if (/NotFound|Overconstrained/i.test(name))
43
+ return words.micMissing();
44
+ if (/NotReadable|Abort/i.test(name))
45
+ return words.micBusy();
46
+ return words.micFailed();
47
+ }
48
+ /** Bars for a kept recording's waveform: `n` heights between 0.12 and 1, read from the audio when the
49
+ * browser can decode it, else from the bytes, so the same recording always draws the same shape. */
50
+ export function barsFromSamples(samples, n = 26) {
51
+ if (!samples.length)
52
+ return Array.from({ length: n }, () => 0.12);
53
+ const per = Math.max(1, Math.floor(samples.length / n));
54
+ const raw = Array.from({ length: n }, (_, i) => {
55
+ let peak = 0;
56
+ for (let j = i * per; j < Math.min(samples.length, (i + 1) * per); j++)
57
+ peak = Math.max(peak, Math.abs(samples[j]));
58
+ return peak;
59
+ });
60
+ const top = Math.max(...raw) || 1;
61
+ return raw.map((v) => Math.max(0.12, Math.min(1, v / top)));
62
+ }
@@ -0,0 +1,7 @@
1
+ import type { VoiceFieldWords } from './words.js';
2
+ export declare function SavedTake({ blob, ms, words, onRemove }: {
3
+ blob: Blob | undefined;
4
+ ms: number;
5
+ words: VoiceFieldWords;
6
+ onRemove(): void;
7
+ }): import("react").JSX.Element;
@@ -0,0 +1,66 @@
1
+ 'use client';
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ // A RECORDING KEPT ON THIS DEVICE, drawn inside the box (approved 2026-11-30): play, its waveform, how long it
4
+ // runs, and remove. Every target is 44 px. The waveform is read from the audio when the browser can decode it,
5
+ // else from its bytes, so one recording always draws the same shape.
6
+ import { useEffect, useRef, useState } from 'react';
7
+ import { barsFromSamples, clock } from './rules.js';
8
+ async function bars(blob, n) {
9
+ const AC = globalThis.AudioContext;
10
+ try {
11
+ const buf = await blob.arrayBuffer();
12
+ if (AC) {
13
+ try {
14
+ const ctx = new AC();
15
+ const audio = await ctx.decodeAudioData(buf.slice(0));
16
+ void ctx.close();
17
+ return barsFromSamples(audio.getChannelData(0), n);
18
+ }
19
+ catch { /* not decodable here: fall back to the bytes */ }
20
+ }
21
+ return barsFromSamples(Array.from(new Uint8Array(buf), (b) => (b - 128) / 128), n);
22
+ }
23
+ catch {
24
+ return barsFromSamples([], n);
25
+ }
26
+ }
27
+ export function SavedTake({ blob, ms, words, onRemove }) {
28
+ const [heights, setHeights] = useState(() => barsFromSamples([], 26));
29
+ const [playing, setPlaying] = useState(false);
30
+ const audio = useRef(null);
31
+ useEffect(() => {
32
+ let live = true;
33
+ if (blob)
34
+ void bars(blob, 26).then((h) => { if (live)
35
+ setHeights(h); });
36
+ return () => { live = false; };
37
+ }, [blob]);
38
+ useEffect(() => () => {
39
+ const a = audio.current;
40
+ if (a) {
41
+ a.pause();
42
+ if (a.src.startsWith('blob:'))
43
+ URL.revokeObjectURL(a.src);
44
+ }
45
+ }, []);
46
+ const toggle = () => {
47
+ if (!blob)
48
+ return;
49
+ if (!audio.current) {
50
+ const url = typeof URL.createObjectURL === 'function' ? URL.createObjectURL(blob) : '';
51
+ audio.current = new Audio(url);
52
+ audio.current.onended = () => setPlaying(false);
53
+ }
54
+ if (playing) {
55
+ audio.current.pause();
56
+ setPlaying(false);
57
+ }
58
+ else {
59
+ void audio.current.play()?.catch?.(() => setPlaying(false));
60
+ setPlaying(true);
61
+ }
62
+ };
63
+ return (_jsxs("div", { "data-saved-take": "", className: "vf-take", children: [_jsx("button", { type: "button", className: "vf-play", "aria-label": playing ? words.pause() : words.play(), onClick: toggle, disabled: !blob, children: playing
64
+ ? _jsx("svg", { width: "16", height: "16", viewBox: "0 0 24 24", "aria-hidden": "true", children: _jsx("path", { d: "M7 5h4v14H7zM13 5h4v14h-4z", fill: "currentColor" }) })
65
+ : _jsx("svg", { width: "16", height: "16", viewBox: "0 0 24 24", "aria-hidden": "true", children: _jsx("path", { d: "M8 4.5v15l12-7.5z", fill: "currentColor" }) }) }), _jsx("span", { className: "vf-wave", "aria-hidden": "true", children: heights.map((h, i) => _jsx("span", { style: { height: `${Math.round(h * 100)}%` } }, i)) }), _jsx("span", { className: "vf-dur", children: clock(ms / 1000) }), _jsx("button", { type: "button", className: "vf-remove", "aria-label": words.remove(), onClick: onRemove, children: _jsx("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", "aria-hidden": "true", children: _jsx("path", { d: "M6 6l12 12M18 6L6 18" }) }) })] }));
66
+ }
@@ -0,0 +1,27 @@
1
+ export type Shelf = 'kv' | 'blobs' | (string & {});
2
+ export interface VoiceStore {
3
+ get<T = unknown>(shelf: Shelf, key: string): Promise<T | undefined>;
4
+ put(shelf: Shelf, key: string, value: unknown): Promise<void>;
5
+ del(shelf: Shelf, key: string): Promise<void>;
6
+ }
7
+ /** A store that lives as long as the page. Nothing survives a reload, so use it only where nothing must. */
8
+ export declare function memoryStore(): VoiceStore & {
9
+ dump(): Record<string, Record<string, unknown>>;
10
+ };
11
+ /** A recording kept on this device: its blob is `blobs/<key>`, and `ms` is how long it ran. */
12
+ export interface KeptTake {
13
+ key: string;
14
+ ms: number;
15
+ }
16
+ export declare const fieldDraftKey: (id: string) => string;
17
+ export declare const fieldTakesKey: (id: string) => string;
18
+ /** The words were sent: forget the draft. Runs after the click's render, so a field unmounting in
19
+ * that render cannot write the draft back behind it. */
20
+ export declare function clearFieldDraft(store: VoiceStore, id: string): void;
21
+ /** A recording for this field, kept on the device until it is safely somewhere else. */
22
+ export declare function keepFieldTake(store: VoiceStore, id: string, t: KeptTake): Promise<void>;
23
+ export declare function forgetFieldTake(store: VoiceStore, id: string, key: string): Promise<void>;
24
+ export declare const keptTakes: (store: VoiceStore, id: string) => Promise<KeptTake[]>;
25
+ /** The audio of a kept recording, for an app that sends it somewhere itself. */
26
+ export declare const takeBlob: (store: VoiceStore, key: string) => Promise<Blob | undefined>;
27
+ export declare const newTakeKey: () => string;
@@ -0,0 +1,40 @@
1
+ // THE VAULT: where the field keeps what a person said or typed until it is safe somewhere else.
2
+ //
3
+ // The field never opens a database itself. The app hands it a store with two shelves: `kv` for small
4
+ // records (the typed draft, the list of kept recordings) and `blobs` for audio. Its shape is the one
5
+ // @supersuit/suggest-a-change's IndexedDB store already has, so an app using that store passes it
6
+ // straight in. `memoryStore()` is for tests and for a page that has nowhere to keep anything.
7
+ /** A store that lives as long as the page. Nothing survives a reload, so use it only where nothing must. */
8
+ export function memoryStore() {
9
+ const shelves = new Map();
10
+ const shelf = (s) => { let m = shelves.get(s); if (!m)
11
+ shelves.set(s, (m = new Map())); return m; };
12
+ return {
13
+ async get(s, k) { return shelf(s).get(k); },
14
+ async put(s, k, v) { shelf(s).set(k, v); },
15
+ async del(s, k) { shelf(s).delete(k); },
16
+ dump: () => Object.fromEntries([...shelves].map(([s, m]) => [s, Object.fromEntries(m)])),
17
+ };
18
+ }
19
+ export const fieldDraftKey = (id) => `vfdraft:${id}`;
20
+ export const fieldTakesKey = (id) => `vftakes:${id}`;
21
+ /** The words were sent: forget the draft. Runs after the click's render, so a field unmounting in
22
+ * that render cannot write the draft back behind it. */
23
+ export function clearFieldDraft(store, id) { setTimeout(() => void store.del('kv', fieldDraftKey(id)), 0); }
24
+ /** A recording for this field, kept on the device until it is safely somewhere else. */
25
+ export async function keepFieldTake(store, id, t) {
26
+ const had = (await store.get('kv', fieldTakesKey(id))) ?? [];
27
+ if (!had.some((x) => x.key === t.key))
28
+ await store.put('kv', fieldTakesKey(id), [...had, t]);
29
+ }
30
+ export async function forgetFieldTake(store, id, key) {
31
+ const left = ((await store.get('kv', fieldTakesKey(id))) ?? []).filter((x) => x.key !== key);
32
+ if (left.length)
33
+ await store.put('kv', fieldTakesKey(id), left);
34
+ else
35
+ await store.del('kv', fieldTakesKey(id));
36
+ }
37
+ export const keptTakes = async (store, id) => (await store.get('kv', fieldTakesKey(id))) ?? [];
38
+ /** The audio of a kept recording, for an app that sends it somewhere itself. */
39
+ export const takeBlob = (store, key) => store.get('blobs', key);
40
+ export const newTakeKey = () => `take-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;