@supersuit/components 0.0.0-stage → 0.2.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 (60) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/LICENSE +21 -0
  3. package/README.md +250 -2
  4. package/bin/supersuit-theme.mjs +116 -0
  5. package/dist/check/depth/bar.d.ts +27 -0
  6. package/dist/check/depth/bar.js +40 -0
  7. package/dist/check/depth/check.d.ts +40 -0
  8. package/dist/check/depth/check.js +50 -0
  9. package/dist/check/depth/crop.d.ts +24 -0
  10. package/dist/check/depth/crop.js +126 -0
  11. package/dist/check/depth/index.d.ts +3 -0
  12. package/dist/check/depth/index.js +5 -0
  13. package/dist/check/depth/measure.d.ts +42 -0
  14. package/dist/check/depth/measure.js +141 -0
  15. package/dist/check/depth/parts-page.d.ts +6 -0
  16. package/dist/check/depth/parts-page.js +69 -0
  17. package/dist/check/depth/playwright.d.ts +4 -0
  18. package/dist/check/depth/playwright.js +10 -0
  19. package/dist/check/depth/png.d.ts +3 -0
  20. package/dist/check/depth/png.js +12 -0
  21. package/dist/check/depth/shoot.d.ts +37 -0
  22. package/dist/check/depth/shoot.js +30 -0
  23. package/dist/index.d.ts +4 -0
  24. package/dist/index.js +11 -0
  25. package/dist/sound/engine.d.ts +59 -0
  26. package/dist/sound/engine.js +325 -0
  27. package/dist/sound/index.d.ts +18 -0
  28. package/dist/sound/index.js +10 -0
  29. package/dist/sound/synth.d.ts +24 -0
  30. package/dist/sound/synth.js +139 -0
  31. package/dist/theme/color.d.ts +29 -0
  32. package/dist/theme/color.js +116 -0
  33. package/dist/theme/compile.d.ts +23 -0
  34. package/dist/theme/compile.js +138 -0
  35. package/dist/theme/index.d.ts +3 -0
  36. package/dist/theme/index.js +4 -0
  37. package/dist/theme/record.d.ts +90 -0
  38. package/dist/theme/record.js +222 -0
  39. package/dist/voice-field/box-trace.d.ts +18 -0
  40. package/dist/voice-field/box-trace.js +87 -0
  41. package/dist/voice-field/index.d.ts +8 -0
  42. package/dist/voice-field/index.js +10 -0
  43. package/dist/voice-field/recorder.d.ts +71 -0
  44. package/dist/voice-field/recorder.js +211 -0
  45. package/dist/voice-field/rules.d.ts +27 -0
  46. package/dist/voice-field/rules.js +62 -0
  47. package/dist/voice-field/saved-take.d.ts +7 -0
  48. package/dist/voice-field/saved-take.js +66 -0
  49. package/dist/voice-field/store.d.ts +27 -0
  50. package/dist/voice-field/store.js +40 -0
  51. package/dist/voice-field/styles.css +161 -0
  52. package/dist/voice-field/toast.d.ts +13 -0
  53. package/dist/voice-field/toast.js +26 -0
  54. package/dist/voice-field/voice-field.d.ts +80 -0
  55. package/dist/voice-field/voice-field.js +259 -0
  56. package/dist/voice-field/words.d.ts +37 -0
  57. package/dist/voice-field/words.js +33 -0
  58. package/package.json +106 -4
  59. package/specs/brand-theme/v1/SPEC.md +130 -0
  60. package/specs/brand-theme/v1/default-bar.json +1196 -0
@@ -0,0 +1,161 @@
1
+ /* @supersuit/voice-field: the box, the mic, the saved recording and the toasts.
2
+ *
3
+ * Everything is drawn from --vf-* variables, so an app restyles the box by setting variables, never by
4
+ * overriding rules. Two themes ship, both from the Maison tokens of the approved mockup (2026-11-30):
5
+ *
6
+ * .vf-theme-dawn the member interior: Dawn ground, paper card, navy to press, slate focus. The default.
7
+ * .vf-theme-night the Maison night of the artifacts pages: night ground, mist lines, bronze to press.
8
+ *
9
+ * Put the class (or data-vf-theme="dawn|night") on the field or on any element above it.
10
+ */
11
+
12
+ :where(:root),
13
+ .vf-theme-dawn,
14
+ [data-vf-theme="dawn"] {
15
+ --vf-ground: #F3E5D5; /* day.ground: dawn #F1C7A2 22% into paper #F3EDE3 */
16
+ --vf-card: #FAF7F2; /* day.card: paper 45% into white */
17
+ --vf-field: #FFFFFF;
18
+ --vf-text: #2A231B; /* ink */
19
+ --vf-mute: #665B4D; /* day.mute: umber 92% into paper */
20
+ --vf-placeholder: #A39C93; /* day.placeholder: ink 40% into paper */
21
+ --vf-line: #D9CDBB; /* day.line: edge #A88F6C 34% into paper */
22
+ --vf-border: #C5B399; /* day.border: edge 62% into paper */
23
+ --vf-accent: #2B3B50; /* slate: focus */
24
+ --vf-filled: #22324A; /* navy: what you press */
25
+ --vf-on-filled: #F3EDE3; /* paper */
26
+ --vf-rec: #DE6152; /* gem live-rec: the microphone recording */
27
+ --vf-rec-text: #9F4B3F; /* day.bad: rec made legible on the card */
28
+ --vf-on: #58E1D1; /* gem live-on: the computer answering */
29
+ --vf-on-live: #111A22; /* the glyph on a live gem */
30
+ --vf-toast-bg: #2A231B;
31
+ --vf-toast-text: #F3E5D5;
32
+ --vf-radius: 18px;
33
+ --vf-font: "DM Sans", system-ui, -apple-system, sans-serif;
34
+ --vf-trace-tail: var(--vf-filled);
35
+ --vf-trace-head: var(--vf-on);
36
+ --vf-trace-rec-tail: var(--vf-accent);
37
+ --vf-trace-rec-head: var(--vf-rec);
38
+ }
39
+
40
+ .vf-theme-night,
41
+ [data-vf-theme="night"] {
42
+ --vf-ground: #17171A; /* night */
43
+ --vf-card: color-mix(in srgb, #D8D1C4 4%, #17171A); /* artifacts --a-surface */
44
+ --vf-field: color-mix(in srgb, #D8D1C4 6%, #17171A);
45
+ --vf-text: #F4F1EC; /* marble */
46
+ --vf-mute: color-mix(in srgb, #D8D1C4 62%, #17171A); /* mist, quieted */
47
+ --vf-placeholder: color-mix(in srgb, #D8D1C4 46%, #17171A);
48
+ --vf-line: color-mix(in srgb, #D8D1C4 12%, #17171A); /* artifacts --a-line */
49
+ --vf-border: color-mix(in srgb, #D8D1C4 28%, #17171A); /* artifacts --a-line-strong */
50
+ --vf-accent: #A8834F; /* bronze */
51
+ --vf-filled: #A8834F; /* bronze: what you press */
52
+ --vf-on-filled: #17171A; /* artifacts --a-on-accent */
53
+ --vf-rec: #DE6152;
54
+ --vf-rec-text: #E38877; /* night.bad: rec 70% into stone */
55
+ --vf-on: #58E1D1;
56
+ --vf-on-live: #17171A;
57
+ --vf-toast-bg: #F4F1EC;
58
+ --vf-toast-text: #17171A;
59
+ }
60
+
61
+ /* ---------- the box ---------- */
62
+ .vf-box {
63
+ position: relative; box-sizing: border-box; display: flex; flex-wrap: wrap; align-items: center; gap: 4px; min-width: 0;
64
+ padding: 4px 4px 4px 16px; border-radius: var(--vf-radius);
65
+ background: var(--vf-field); color: var(--vf-text); font-family: var(--vf-font);
66
+ box-shadow: inset 0 0 0 1px var(--vf-border);
67
+ }
68
+ .vf-box[data-multiline] { padding: 12px 8px 8px 16px; }
69
+ .vf-box:focus-within { box-shadow: inset 0 0 0 2px var(--vf-accent); }
70
+ .vf-box[data-state="recording"], .vf-box[data-state="opening"] { box-shadow: inset 0 0 0 1.5px color-mix(in srgb, var(--vf-rec) 55%, var(--vf-field)); }
71
+
72
+ .vf-input {
73
+ box-sizing: border-box; flex: 1 1 0; min-width: 0; min-height: 44px; margin: 0; padding: 10px 4px; border: 0; outline: none;
74
+ background: transparent; color: var(--vf-text); font: inherit; font-size: 17px; line-height: 24px; resize: none;
75
+ }
76
+ .vf-input::placeholder { color: var(--vf-placeholder); opacity: 1; }
77
+ textarea.vf-input { overflow-y: auto; max-height: 164px; }
78
+ textarea.vf-input[data-rows] { max-height: 308px; }
79
+ .vf-box[data-multiline] .vf-input { flex-basis: 100%; min-height: 48px; padding: 0 10px 0 0; }
80
+ .vf-box[data-multiline][data-has-takes] .vf-input { min-height: 24px; }
81
+ /* Held while recording or writing down: a token colour, never opacity. */
82
+ .vf-box:is([data-state="recording"], [data-state="busy"]) .vf-input { color: var(--vf-placeholder); }
83
+
84
+ /* The status: the time while recording, the wait while writing down, the note under a kept recording. */
85
+ .vf-status { display: flex; align-items: center; gap: 8px; min-width: 0; font-size: 14px; line-height: 1.3; color: var(--vf-mute); }
86
+ .vf-box:not([data-multiline]) .vf-status { order: 5; flex-basis: 100%; }
87
+ .vf-box:not([data-multiline]) .vf-status:empty { display: none; }
88
+ .vf-box[data-multiline] .vf-status { flex: 1 1 0; min-height: 44px; }
89
+ .vf-dot { flex: none; width: 8px; height: 8px; border-radius: 50%; background: var(--vf-rec); }
90
+ .vf-clock { font-variant-numeric: tabular-nums; font-weight: 600; font-size: 15px; color: var(--vf-rec-text); }
91
+ .vf-cloud { flex: none; }
92
+
93
+ .vf-progress { position: absolute; left: 16px; right: 16px; bottom: 7px; height: 3px; border-radius: 2px; background: var(--vf-line); overflow: hidden; pointer-events: none; }
94
+ .vf-progress i { position: absolute; top: 0; bottom: 0; left: 0; width: 46%; border-radius: 2px;
95
+ background: linear-gradient(90deg, transparent, var(--vf-accent) 30%, var(--vf-accent) 70%, transparent);
96
+ animation: vf-slide 1.4s ease-in-out infinite; }
97
+ @keyframes vf-slide { 0% { transform: translateX(-100%); } 100% { transform: translateX(220%); } }
98
+
99
+ /* ---------- the mic ---------- */
100
+ .vf-mic {
101
+ position: relative; flex: none; display: flex; align-items: center; justify-content: center; box-sizing: border-box;
102
+ width: 48px; height: 48px; padding: 0; border: 0; border-radius: 50%; cursor: pointer; user-select: none;
103
+ background: var(--vf-filled); color: var(--vf-on-filled);
104
+ }
105
+ .vf-mic[data-size="large"] { width: 80px; height: 80px; }
106
+ .vf-mic[data-size="inline"] { width: 44px; height: 44px; background: transparent; color: var(--vf-mute); }
107
+ .vf-mic[data-size="inline"]:active { background: var(--vf-line); }
108
+ .vf-mic[data-rec-state="recording"] { background: var(--vf-rec); color: var(--vf-on-live); }
109
+ .vf-mic[data-size="inline"][data-rec-state="recording"] { margin: 4px 8px 4px 0; }
110
+ .vf-mic[data-rec-state="busy"] { color: var(--vf-placeholder); cursor: default; }
111
+ .vf-mic:disabled:not([data-rec-state="busy"]) { opacity: 0.4; cursor: default; }
112
+ .vf-mic:focus-visible { outline: 2px solid var(--vf-accent); outline-offset: 2px; }
113
+ .vf-mic > svg { position: relative; z-index: 1; }
114
+
115
+ /* The ring that swells with the live input level (--lvl, 0..1, set by the mic as it listens). */
116
+ .vf-level { position: absolute; inset: -4px; border-radius: 50%; pointer-events: none;
117
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--vf-rec) 45%, transparent);
118
+ transform: scale(calc(1 + var(--lvl, 0) * 0.22)); transition: transform 80ms linear; }
119
+ .vf-mic[data-rec-state="recording"]::after { content: ""; position: absolute; inset: -7px; border-radius: 50%; pointer-events: none;
120
+ background: radial-gradient(circle, color-mix(in srgb, var(--vf-rec) 22%, transparent) 55%, transparent 72%); }
121
+ .vf-stop { position: relative; z-index: 1; width: 14px; height: 14px; border-radius: 3px; background: currentColor; }
122
+ .vf-mic[data-size="small"] .vf-stop { width: 16px; height: 16px; }
123
+ .vf-mic[data-size="large"] .vf-stop { width: 28px; height: 28px; }
124
+
125
+ .vf-spin { position: absolute; inset: 3px; border-radius: 50%; pointer-events: none; border: 2px solid transparent;
126
+ border-top-color: var(--vf-accent); border-right-color: var(--vf-accent); animation: vf-spin 0.9s linear infinite; }
127
+ .vf-mic:not([data-size="inline"]) .vf-spin { inset: -4px; border-width: 3px; }
128
+ @keyframes vf-spin { to { transform: rotate(360deg); } }
129
+
130
+ .vf-clock-badge { position: absolute; bottom: -6px; left: 50%; transform: translateX(-50%); z-index: 2; pointer-events: none;
131
+ padding: 1px 6px; border-radius: 999px; background: var(--vf-text); color: var(--vf-field);
132
+ font-size: 10px; font-weight: 600; line-height: 1.2; font-variant-numeric: tabular-nums; }
133
+
134
+ /* ---------- Send ---------- */
135
+ .vf-send { flex: none; display: flex; align-items: center; justify-content: center; width: 44px; height: 44px; margin: 0 0 0 2px;
136
+ padding: 0; border: 0; border-radius: 50%; cursor: pointer; background: var(--vf-filled); color: var(--vf-on-filled); }
137
+ .vf-send:disabled { opacity: 0.4; cursor: default; }
138
+ .vf-send:focus-visible { outline: 2px solid var(--vf-accent); outline-offset: 2px; }
139
+
140
+ /* ---------- a recording kept on this device ---------- */
141
+ .vf-takes { flex-basis: 100%; display: flex; flex-direction: column; gap: 6px; margin: 0 0 2px -8px; }
142
+ .vf-take { display: flex; align-items: center; gap: 10px; padding: 6px 2px 6px 6px; border-radius: 14px;
143
+ background: color-mix(in srgb, var(--vf-line) 45%, var(--vf-field)); }
144
+ .vf-play { flex: none; display: flex; align-items: center; justify-content: center; width: 44px; height: 44px; padding: 0; border: 0;
145
+ border-radius: 50%; cursor: pointer; background: var(--vf-filled); color: var(--vf-on-filled); }
146
+ .vf-wave { flex: 1; min-width: 0; display: flex; align-items: center; gap: 2px; height: 28px; }
147
+ .vf-wave span { flex: 1; min-height: 3px; border-radius: 2px; background: color-mix(in srgb, var(--vf-text) 38%, var(--vf-field)); }
148
+ .vf-dur { font-size: 14px; font-weight: 600; font-variant-numeric: tabular-nums; color: var(--vf-text); }
149
+ .vf-remove { flex: none; display: flex; align-items: center; justify-content: center; width: 44px; height: 44px; padding: 0; border: 0;
150
+ border-radius: 50%; cursor: pointer; background: transparent; color: var(--vf-mute); }
151
+
152
+ /* ---------- toasts ---------- */
153
+ .vf-toasts { position: fixed; left: 0; right: 0; bottom: max(16px, env(safe-area-inset-bottom)); z-index: 50; display: flex; flex-direction: column;
154
+ align-items: center; gap: 8px; pointer-events: none; font-family: var(--vf-font); }
155
+ .vf-toast { max-width: calc(100vw - 32px); padding: 11px 16px; border-radius: 999px; background: var(--vf-toast-bg); color: var(--vf-toast-text);
156
+ font-size: 14px; font-weight: 500; line-height: 1.35; pointer-events: auto; }
157
+
158
+ @media (prefers-reduced-motion: reduce) {
159
+ .vf-spin, .vf-progress i { animation-duration: 0s; }
160
+ .vf-level { transition: none; }
161
+ }
@@ -0,0 +1,13 @@
1
+ export type ToastTone = 'info' | 'warn';
2
+ export interface VoiceToast {
3
+ id?: string;
4
+ text: string;
5
+ tone?: ToastTone;
6
+ ms?: number;
7
+ }
8
+ export type ToastFn = (t: VoiceToast) => void;
9
+ export declare const voiceToast: ToastFn;
10
+ export declare function clearVoiceToasts(): void;
11
+ export declare function VoiceToasts({ className }: {
12
+ className?: string;
13
+ }): import("react").JSX.Element;
@@ -0,0 +1,26 @@
1
+ 'use client';
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ // THE TOAST: everything the box does not say inside itself (a blocked microphone, a take too short,
4
+ // a restored note) is said in a toast, so nothing ever squeezes the box.
5
+ //
6
+ // An app with its own toasts passes `toast={its own}` to the field and never renders this. An app
7
+ // without one renders <VoiceToasts /> once, anywhere on the page, and the field's default reaches it.
8
+ import { useEffect, useState } from 'react';
9
+ let shown = [];
10
+ const listeners = new Set();
11
+ const timers = new Map();
12
+ const tell = () => listeners.forEach((l) => l(shown));
13
+ export const voiceToast = ({ id = `t${Date.now()}${Math.random()}`, text, tone = 'info', ms = 4000 }) => {
14
+ // One toast per id: a second "restored" replaces the first instead of stacking.
15
+ shown = [...shown.filter((t) => t.id !== id), { id, text, tone, ms }].slice(-2);
16
+ clearTimeout(timers.get(id));
17
+ timers.set(id, setTimeout(() => { shown = shown.filter((t) => t.id !== id); timers.delete(id); tell(); }, ms));
18
+ tell();
19
+ };
20
+ export function clearVoiceToasts() { for (const t of timers.values())
21
+ clearTimeout(t); timers.clear(); shown = []; tell(); }
22
+ export function VoiceToasts({ className }) {
23
+ const [list, setList] = useState(shown);
24
+ useEffect(() => { listeners.add(setList); return () => { listeners.delete(setList); }; }, []);
25
+ return (_jsx("div", { "data-vf-toasts": "", className: `vf-toasts${className ? ` ${className}` : ''}`, role: "status", "aria-live": "polite", children: list.map((t) => _jsx("div", { className: "vf-toast", "data-tone": t.tone, children: t.text }, t.id)) }));
26
+ }
@@ -0,0 +1,80 @@
1
+ import { type ComponentType, type ReactNode } from 'react';
2
+ import { type RecorderProps, type StartTake } from './recorder.js';
3
+ import { type KeptTake, type VoiceStore } from './store.js';
4
+ import { type ToastFn } from './toast.js';
5
+ import { type VoiceFieldWords } from './words.js';
6
+ /** Turn one take into words. Answer `{ refused }` for a take the transcriber will never take (it stays kept);
7
+ * THROW when it cannot be reached right now (the take is kept and sent again later). */
8
+ export type Transcribe = (key: string, blob: Blob, ms: number) => Promise<{
9
+ text: string;
10
+ audio?: string;
11
+ } | {
12
+ refused: string;
13
+ }>;
14
+ /** Whether the transcriber can be reached. The default reads navigator.onLine. */
15
+ export interface Reach {
16
+ mark(up: boolean): void;
17
+ check(force?: boolean): Promise<boolean>;
18
+ }
19
+ export declare const DRAFT_MS = 250;
20
+ export declare const RETRY_MS = 15000;
21
+ export interface VoiceFieldProps {
22
+ /** Where drafts and recordings are kept until they are safe (store.ts). */
23
+ store: VoiceStore;
24
+ /** Names this field's draft and kept recordings. One id per field, stable across visits. */
25
+ id: string;
26
+ label: string;
27
+ value: string;
28
+ onChange(v: string): void;
29
+ placeholder?: string;
30
+ multiline?: boolean;
31
+ /** A multiline field that opens this many lines tall, and grows to twelve. */
32
+ rows?: number;
33
+ type?: 'text' | 'search' | 'email';
34
+ /** Turns a take into words. Absent, every take is kept on the device (a hosted page with no transcriber). */
35
+ transcribe?: Transcribe;
36
+ /** A take that became words; `ms` is how long it ran. */
37
+ onHeard?(h: {
38
+ text: string;
39
+ audio?: string;
40
+ ms: number;
41
+ }): void;
42
+ /** The screen keeps takes itself. Without it, the field keeps them and shows them in the box. */
43
+ onKept?(t: KeptTake): void;
44
+ /** Told when a take starts and stops being written down. */
45
+ onHearing?(hearing: boolean): void;
46
+ disabled?: boolean;
47
+ /** Save typed words on the device as they are typed (off for a search, or a screen that saves its own draft). */
48
+ persist?: boolean;
49
+ startTake?: StartTake;
50
+ /** A box that is the main thing on its screen is sent from inside itself: Send in the box, beside the mic. */
51
+ onSend?(): void;
52
+ sendDisabled?: boolean;
53
+ sendLabel?: string;
54
+ /** Drawn inside the box before the words (a search magnifier). */
55
+ leading?: ReactNode;
56
+ autoFocus?: boolean;
57
+ /** The key that works the mic, set on it as data-key-hint. */
58
+ micKey?: string;
59
+ toast?: ToastFn;
60
+ words?: Partial<VoiceFieldWords>;
61
+ reach?: Reach;
62
+ /** Whether an error thrown by transcribe means the transcriber is away (then reach.mark(false)). Default: every error. */
63
+ isUnreachable?(e: unknown): boolean;
64
+ /** Makes the key a take is stored under. */
65
+ newKey?(): string;
66
+ /** Show the time, "Writing down what you said" and the waiting note inside the box. Default true. */
67
+ status?: boolean;
68
+ /** Show recordings this field keeps inside the box, with play and remove. Default true. */
69
+ savedTakes?: boolean;
70
+ /** The mic component, for an app that wraps the package's Recorder with its own defaults. */
71
+ Mic?: ComponentType<RecorderProps>;
72
+ /** Extra classes on the box, the words and Send, for an app that draws them with its own CSS. */
73
+ className?: string;
74
+ inputClassName?: string;
75
+ sendClassName?: string;
76
+ /** Extra classes on the label, which is always drawn visually hidden (an app's own `sr-only`, say). */
77
+ labelClassName?: string;
78
+ retryMs?: number;
79
+ }
80
+ export declare function VoiceField({ store, id, label, value, onChange, placeholder, multiline, rows, type, transcribe, onHeard, onKept, onHearing, disabled, persist, startTake, onSend, sendDisabled, sendLabel, leading, autoFocus, micKey, toast, words: wordsIn, reach, isUnreachable, newKey, status, savedTakes, Mic, className, inputClassName, sendClassName, labelClassName, retryMs }: VoiceFieldProps): import("react").JSX.Element;
@@ -0,0 +1,259 @@
1
+ 'use client';
2
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
3
+ // ONE TEXT BOX THAT CAN ALSO BE SPOKEN, drawn as one box: the words, then a small mic, then Send when the screen
4
+ // gives one, all inside [data-voice-field]. While the mic records, the time shows in the box; while the words
5
+ // are written down, the box says so with a thin progress line; a recording that could not be sent stays in the
6
+ // box with play and remove (approved 2026-11-30). Anything else is a toast, so the box never squeezes.
7
+ //
8
+ // Never lose an idea:
9
+ // - A take is written to the store second by second while it is recorded (the mic's startTake).
10
+ // - A take the transcriber could not take is kept on the device: handed to the screen through onKept when the
11
+ // screen keeps takes itself, else kept by this field (`vftakes:<id>`) and sent again on every open, when the
12
+ // network comes back, and every 15 s while one waits. Its blob is deleted only once the transcriber answered.
13
+ // - With no transcriber at all (a hosted page with no computer behind it), every take is simply kept.
14
+ // - While a take is being written down the box is read-only and Send waits, so the heard words land on exactly
15
+ // what was there when the mic was tapped (asked for 2026-11-29: "disable other input while transcription is
16
+ // happening").
17
+ // - Typed words are saved on every keystroke (debounced, `vfdraft:<id>`) and put back on the next open, with
18
+ // "Restored your unsent note". A screen that sends the words clears the draft (clearFieldDraft).
19
+ //
20
+ // The draft holds the person's unsent words, and nothing else:
21
+ // - The words a screen opens the field with are the screen's. An untouched box writes nothing and erases nothing.
22
+ // - A clear removes the draft at once, not a quarter second behind: the page may run no timer after it closes.
23
+ // - The page going to the background writes what is waiting, for the same reason.
24
+ import { useEffect, useRef, useState } from 'react';
25
+ import { Recorder } from './recorder.js';
26
+ import { clock } from './rules.js';
27
+ import { SavedTake } from './saved-take.js';
28
+ import { fieldDraftKey, fieldTakesKey, forgetFieldTake, keepFieldTake, newTakeKey } from './store.js';
29
+ import { voiceToast } from './toast.js';
30
+ import { wordsWith } from './words.js';
31
+ export const DRAFT_MS = 250;
32
+ export const RETRY_MS = 15_000;
33
+ const defaultReach = { mark() { }, check: async () => typeof navigator === 'undefined' || navigator.onLine !== false };
34
+ const visuallyHidden = { position: 'absolute', width: 1, height: 1, padding: 0, margin: -1, overflow: 'hidden', clip: 'rect(0,0,0,0)', whiteSpace: 'nowrap', border: 0 };
35
+ export function VoiceField({ store, id, label, value, onChange, placeholder, multiline = false, rows, type = 'text', transcribe, onHeard, onKept, onHearing, disabled, persist = true, startTake, onSend, sendDisabled, sendLabel, leading, autoFocus, micKey, toast = voiceToast, words: wordsIn, reach = defaultReach, isUnreachable = () => true, newKey = newTakeKey, status = true, savedTakes = true, Mic = Recorder, className, inputClassName, sendClassName, labelClassName, retryMs = RETRY_MS }) {
36
+ const words = wordsWith(wordsIn);
37
+ const [hearing, setHearingState] = useState(0);
38
+ const [done, setDone] = useState(false);
39
+ const [mic, setMic] = useState({ state: 'idle', sec: 0, tapped: false });
40
+ const [kept, setKept] = useState([]);
41
+ const latest = useRef(value);
42
+ latest.current = value;
43
+ const cb = useRef({ onChange, onHeard, onKept, onHearing, transcribe, toast, words, reach, isUnreachable });
44
+ cb.current = { onChange, onHeard, onKept, onHearing, transcribe, toast, words, reach, isUnreachable };
45
+ const area = useRef(null);
46
+ const draftTimer = useRef(null);
47
+ // Draft saving starts only once the saved draft has been read, or the empty field would erase it.
48
+ const [draftRead, setDraftRead] = useState(!persist);
49
+ // What the screen opened the field with, and whether the words have moved from it since.
50
+ const opened = useRef(value);
51
+ const touched = useRef(false);
52
+ if (value !== opened.current)
53
+ touched.current = true;
54
+ const inFlight = useRef(new Set());
55
+ const doneTimer = useRef(null);
56
+ const later = useRef(() => { });
57
+ const mounted = useRef(true);
58
+ useEffect(() => () => { mounted.current = false; }, []);
59
+ const setHearing = (d) => setHearingState((h) => { const n = Math.max(0, h + d); if ((h > 0) !== (n > 0))
60
+ cb.current.onHearing?.(n > 0); return n; });
61
+ /** What this field keeps, read back for the box. */
62
+ const showKept = useRef(async () => { });
63
+ showKept.current = async () => {
64
+ if (!savedTakes)
65
+ return;
66
+ const list = (await store.get('kv', fieldTakesKey(id))) ?? [];
67
+ const withBlobs = await Promise.all(list.map(async (t) => ({ ...t, blob: await store.get('blobs', t.key) })));
68
+ if (mounted.current)
69
+ setKept(withBlobs);
70
+ };
71
+ /** One take to the transcriber. True once it has it (the blob then leaves the device). */
72
+ async function send(r, fromKept) {
73
+ const run = cb.current.transcribe;
74
+ if (!run) {
75
+ keep(r, fromKept, null);
76
+ return false;
77
+ }
78
+ if (inFlight.current.has(r.key))
79
+ return false;
80
+ inFlight.current.add(r.key);
81
+ setHearing(1);
82
+ try {
83
+ const h = await run(r.key, r.blob, r.ms);
84
+ if ('refused' in h) {
85
+ keep(r, fromKept, cb.current.words.refused(h.refused));
86
+ return false;
87
+ }
88
+ // The transcriber has it: the words go in first, then the device's copy goes.
89
+ void store.del('blobs', r.key);
90
+ if (fromKept)
91
+ void forgetFieldTake(store, id, r.key).then(() => showKept.current());
92
+ cb.current.onHeard?.({ ...h, ms: r.ms });
93
+ if (h.text) {
94
+ cb.current.onChange([latest.current.trim(), h.text].filter(Boolean).join(' '));
95
+ setDone(true);
96
+ if (doneTimer.current)
97
+ clearTimeout(doneTimer.current);
98
+ doneTimer.current = setTimeout(() => setDone(false), 1500);
99
+ }
100
+ else
101
+ cb.current.toast({ id: `nowords-${r.key}`, text: cb.current.words.noWords() });
102
+ return true;
103
+ }
104
+ catch (e) {
105
+ if (cb.current.isUnreachable(e))
106
+ cb.current.reach.mark(false);
107
+ keep(r, fromKept, cb.current.words.kept());
108
+ return false;
109
+ }
110
+ finally {
111
+ inFlight.current.delete(r.key);
112
+ setHearing(-1);
113
+ }
114
+ }
115
+ function keep(r, fromKept, said) {
116
+ if (cb.current.onKept) {
117
+ cb.current.onKept({ key: r.key, ms: r.ms });
118
+ if (fromKept)
119
+ void forgetFieldTake(store, id, r.key).then(() => showKept.current());
120
+ }
121
+ else if (!fromKept)
122
+ void keepFieldTake(store, id, { key: r.key, ms: r.ms }).then(() => { void showKept.current(); if (cb.current.transcribe)
123
+ later.current(); });
124
+ if (said)
125
+ cb.current.toast({ id: 'kept', text: said });
126
+ }
127
+ async function remove(key) {
128
+ await store.del('blobs', key);
129
+ await forgetFieldTake(store, id, key);
130
+ await showKept.current();
131
+ }
132
+ // Takes this field kept (or the page was closed in the middle of): sent again whenever the transcriber may be back.
133
+ const canSend = Boolean(transcribe);
134
+ useEffect(() => {
135
+ let live = true;
136
+ let timer = null;
137
+ let first = true;
138
+ void showKept.current();
139
+ async function retry() {
140
+ if (!live || !canSend)
141
+ return;
142
+ const list = (await store.get('kv', fieldTakesKey(id))) ?? [];
143
+ if (first && list.length)
144
+ cb.current.toast({ id: 'restored', text: cb.current.words.restored() });
145
+ const wasFirst = first;
146
+ first = false;
147
+ let left = 0;
148
+ for (const t of list) {
149
+ const blob = await store.get('blobs', t.key);
150
+ if (!blob) {
151
+ await forgetFieldTake(store, id, t.key);
152
+ continue;
153
+ }
154
+ // A take kept because the transcriber was away is only retried when it answers: no toast storm.
155
+ if (!wasFirst && !(await cb.current.reach.check(true))) {
156
+ left++;
157
+ continue;
158
+ }
159
+ if (!live)
160
+ return;
161
+ if (!(await send({ ...t, blob }, true)) && !cb.current.onKept)
162
+ left++;
163
+ }
164
+ if (live && left && !timer)
165
+ timer = setTimeout(() => { timer = null; void retry(); }, retryMs);
166
+ }
167
+ later.current = () => { if (live && !timer)
168
+ timer = setTimeout(() => { timer = null; void retry(); }, retryMs); };
169
+ void retry();
170
+ const again = () => { if (timer)
171
+ clearTimeout(timer); timer = null; void retry(); };
172
+ addEventListener('online', again);
173
+ const vis = () => { if (document.visibilityState === 'visible')
174
+ again(); };
175
+ document.addEventListener('visibilitychange', vis);
176
+ return () => { live = false; if (timer)
177
+ clearTimeout(timer); removeEventListener('online', again); document.removeEventListener('visibilitychange', vis); };
178
+ }, [store, id, canSend, retryMs]);
179
+ // The typed words, back from the device's copy on open.
180
+ useEffect(() => {
181
+ if (!persist)
182
+ return;
183
+ let live = true;
184
+ void store.get('kv', fieldDraftKey(id)).then((d) => {
185
+ if (!live)
186
+ return;
187
+ if (d && d.trim() && !latest.current.trim()) {
188
+ cb.current.onChange(d);
189
+ cb.current.toast({ id: 'restored', text: cb.current.words.restored() });
190
+ }
191
+ setDraftRead(true);
192
+ });
193
+ return () => { live = false; };
194
+ }, [store, id, persist]);
195
+ // ...and saved on every keystroke, a quarter second behind; written at once if the field goes away.
196
+ const write = () => {
197
+ draftTimer.current = null;
198
+ if (!touched.current)
199
+ return;
200
+ const v = latest.current;
201
+ void (v.trim() && v !== opened.current ? store.put('kv', fieldDraftKey(id), v) : store.del('kv', fieldDraftKey(id)));
202
+ };
203
+ useEffect(() => {
204
+ if (!persist || !draftRead)
205
+ return;
206
+ if (draftTimer.current)
207
+ clearTimeout(draftTimer.current);
208
+ if (touched.current && !value.trim())
209
+ write();
210
+ else
211
+ draftTimer.current = setTimeout(write, DRAFT_MS);
212
+ }, [value, persist, draftRead]);
213
+ useEffect(() => {
214
+ if (!persist)
215
+ return;
216
+ const flush = () => { if (draftTimer.current) {
217
+ clearTimeout(draftTimer.current);
218
+ write();
219
+ } };
220
+ const hidden = () => { if (document.visibilityState === 'hidden')
221
+ flush(); };
222
+ document.addEventListener('visibilitychange', hidden);
223
+ addEventListener('pagehide', flush);
224
+ return () => { document.removeEventListener('visibilitychange', hidden); removeEventListener('pagehide', flush); };
225
+ }, [store, id, persist]);
226
+ useEffect(() => () => { if (draftTimer.current) {
227
+ clearTimeout(draftTimer.current);
228
+ write();
229
+ } if (doneTimer.current)
230
+ clearTimeout(doneTimer.current); }, []);
231
+ // A note grows with what is typed, up to its CSS max-height, then scrolls inside itself.
232
+ useEffect(() => {
233
+ const el = area.current;
234
+ if (!el)
235
+ return;
236
+ el.style.height = 'auto';
237
+ const max = parseFloat(getComputedStyle(el).maxHeight) || Infinity;
238
+ el.style.height = `${Math.min(el.scrollHeight || 0, max) || ''}px`;
239
+ if (!el.scrollHeight)
240
+ el.style.height = '';
241
+ // A kept recording shrinks the empty box's floor, so its height is measured again when one comes or goes.
242
+ }, [value, kept.length]);
243
+ const held = hearing > 0;
244
+ const typed = (v) => { if (!held)
245
+ onChange(v); };
246
+ const boxState = mic.state === 'recording' || mic.state === 'opening' ? mic.state : held ? 'busy' : 'idle';
247
+ const waitingOnline = canSend && kept.length > 0;
248
+ const inputCls = `vf-input${inputClassName ? ` ${inputClassName}` : ''}`;
249
+ const statusLine = !status ? null
250
+ : mic.state === 'recording'
251
+ ? _jsxs(_Fragment, { children: [_jsx("span", { className: "vf-dot", "aria-hidden": "true" }), _jsx("span", { className: "vf-clock", "data-rec-clock": "", children: clock(mic.sec) }), _jsx("span", { children: mic.tapped ? words.tapToStop() : words.letGoToStop() })] })
252
+ : held ? _jsx("span", { children: words.writingDown() })
253
+ : waitingOnline
254
+ ? _jsxs(_Fragment, { children: [_jsxs("svg", { className: "vf-cloud", width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.8", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [_jsx("path", { d: "M7 18h10a4 4 0 0 0 .6-7.95A6 6 0 0 0 6.2 9.1 4.5 4.5 0 0 0 7 18z" }), _jsx("path", { d: "M12 11v3M12 16.5v.01" })] }), _jsx("span", { children: words.waitingOnline() })] })
255
+ : null;
256
+ return (_jsxs("div", { "data-voice-field": "", "data-composer": "", "data-state": boxState, "data-multiline": multiline ? '' : undefined, "data-has-takes": savedTakes && kept.length ? '' : undefined, className: `vf-box${className ? ` ${className}` : ''}`, children: [leading, _jsx("label", { htmlFor: `vf-${id}`, style: visuallyHidden, className: `vf-label${labelClassName ? ` ${labelClassName}` : ''}`, children: label }), savedTakes && kept.length ? (_jsx("div", { className: "vf-takes", children: kept.map((t) => _jsx(SavedTake, { blob: t.blob, ms: t.ms, words: words, onRemove: () => void remove(t.key) }, t.key)) })) : null, multiline
257
+ ? _jsx("textarea", { ref: area, id: `vf-${id}`, rows: rows ?? 1, value: value, placeholder: placeholder, onChange: (e) => typed(e.target.value), readOnly: held, "aria-busy": held || undefined, "data-rows": rows || undefined, style: rows ? { minHeight: `${rows * 1.5 + 1.25}rem` } : undefined, className: inputCls })
258
+ : _jsx("input", { id: `vf-${id}`, type: type, value: value, placeholder: placeholder, onChange: (e) => typed(e.target.value), readOnly: held, "aria-busy": held || undefined, className: inputCls, autoFocus: autoFocus, enterKeyHint: type === 'search' ? 'search' : undefined, autoComplete: type === 'search' ? 'off' : undefined }), status ? _jsx("div", { className: "vf-status", role: "status", "aria-live": "polite", children: statusLine }) : null, status && held ? _jsx("div", { className: "vf-progress", "aria-hidden": "true", children: _jsx("i", {}) }) : null, _jsx(Mic, { store: store, questionId: `field:${id}`, takeKey: newKey, startTake: startTake, size: "inline", onTake: (r) => void send(r, false), disabled: disabled, busy: held, done: done, label: words.say(label), keyHint: micKey, toast: toast, words: wordsIn, badge: !status, onState: setMic }), onSend ? (_jsx("button", { type: "button", "data-composer-send": "", "aria-label": sendLabel ?? words.send(), onClick: onSend, disabled: sendDisabled || held, className: `vf-send${sendClassName ? ` ${sendClassName}` : ''}`, children: _jsx("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "M12 19V5M5.5 11.5L12 5l6.5 6.5" }) }) })) : null] }));
259
+ }
@@ -0,0 +1,37 @@
1
+ export interface VoiceFieldWords {
2
+ /** The mic's name inside a field, for a screen reader. */
3
+ say(label: string): string;
4
+ /** A mic on its own. */
5
+ micLabel(): string;
6
+ /** A note the app was closed on, put back on open (also the toast for a kept recording found again). */
7
+ restored(): string;
8
+ /** A recording that could not be sent, kept on this device. */
9
+ kept(): string;
10
+ /** The transcriber answered, but refused this recording. */
11
+ refused(why: string): string;
12
+ /** The transcriber heard nothing it could write down. */
13
+ noWords(): string;
14
+ tooShort(): string;
15
+ noSpeech(): string;
16
+ micBlocked(): string;
17
+ micMissing(): string;
18
+ micBusy(): string;
19
+ micFailed(): string;
20
+ cancelled(): string;
21
+ /** The mic's name while recording. `tapped` is true when a tap started it (a tap stops it), false when held. */
22
+ recordingAria(clock: string, tapped: boolean): string;
23
+ opening(): string;
24
+ /** Said while a recording is being turned into words: the status in the box and the mic's name. */
25
+ writingDown(): string;
26
+ tapToStop(): string;
27
+ letGoToStop(): string;
28
+ /** Under a kept recording that will be sent again. */
29
+ waitingOnline(): string;
30
+ play(): string;
31
+ pause(): string;
32
+ remove(): string;
33
+ send(): string;
34
+ }
35
+ export declare const defaultWords: VoiceFieldWords;
36
+ /** The app's lines over the defaults. */
37
+ export declare const wordsWith: (over?: Partial<VoiceFieldWords>) => VoiceFieldWords;
@@ -0,0 +1,33 @@
1
+ // Every sentence the field and its mic say to a person, in one replaceable object. An app passes
2
+ // `words={{ ... }}` with only the lines it wants to change; the rest stay as written here.
3
+ //
4
+ // Each entry is a function, read at the moment it is said, never once at import. Supertools names
5
+ // the computer it is served from ("your Mac", "your PC"), and that name is known only after the
6
+ // phone has heard from it, so a sentence built at import would say the wrong one.
7
+ export const defaultWords = {
8
+ say: (label) => `Say it: ${label}`,
9
+ micLabel: () => 'Say it',
10
+ restored: () => 'Restored your unsent note',
11
+ kept: () => "Saved on this phone. It will send when you're back online",
12
+ refused: (why) => `The recording wasn't taken (${why}). It's kept on this phone`,
13
+ noWords: () => "Couldn't transcribe, your recording is kept",
14
+ tooShort: () => 'Too short to keep. Tap the mic once to start, and again to stop.',
15
+ noSpeech: () => 'No speech heard yet. Is the microphone covered or muted?',
16
+ micBlocked: () => 'Microphone blocked: Settings > Safari > Microphone',
17
+ micMissing: () => 'No microphone found on this phone',
18
+ micBusy: () => 'The microphone is busy in another app. Close it and try again',
19
+ micFailed: () => "The microphone didn't start. Try again",
20
+ cancelled: () => 'Recording stopped. Nothing was kept.',
21
+ recordingAria: (clock, tapped) => `Recording, ${clock}. ${tapped ? 'Tap' : 'Let go'} to stop`,
22
+ opening: () => 'Opening the microphone',
23
+ writingDown: () => 'Writing down what you said',
24
+ tapToStop: () => 'Tap to stop',
25
+ letGoToStop: () => 'Let go to stop',
26
+ waitingOnline: () => "Will send when you're back online",
27
+ play: () => 'Play recording',
28
+ pause: () => 'Pause recording',
29
+ remove: () => 'Remove recording',
30
+ send: () => 'Send',
31
+ };
32
+ /** The app's lines over the defaults. */
33
+ export const wordsWith = (over) => (over ? { ...defaultWords, ...over } : defaultWords);