@vocalstack/payload 0.2.0 → 0.4.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.
@@ -12,6 +12,8 @@ const styles = `
12
12
  border-top: 1px solid var(--theme-elevation-100); font-size: 13px; }
13
13
  .vs-speech-row:first-of-type { border-top: 0; }
14
14
  .vs-speech-muted { color: var(--theme-elevation-500); font-size: 13px; margin: 0; }
15
+ .vs-speech-voices { display: flex; flex-wrap: wrap; gap: 14px; align-items: center; margin: 4px 0; font-size: 13px; }
16
+ .vs-speech-voices label { display: inline-flex; gap: 6px; align-items: center; cursor: pointer; }
15
17
  .vs-speech-error { color: var(--theme-error-500); font-size: 13px; margin: 0; }
16
18
  .vs-speech select, .vs-speech input[type=search] { font: inherit; font-size: 13px; padding: 4px 6px; border: 1px solid var(--theme-elevation-150);
17
19
  border-radius: var(--style-radius-s, 4px); background: var(--theme-input-bg, var(--theme-elevation-0)); color: var(--theme-text); max-width: 100%; }
@@ -21,7 +23,16 @@ const styles = `
21
23
  .vs-spin { display: inline-block; width: 10px; height: 10px; border: 2px solid var(--theme-elevation-200); border-top-color: var(--vs-accent);
22
24
  border-radius: 50%; animation: vs-spin .8s linear infinite; margin-right: 6px; vertical-align: -1px; }
23
25
  @keyframes vs-spin { to { transform: rotate(360deg); } }
26
+ .vs-bar { position: relative; height: 4px; border-radius: 2px; overflow: hidden; background: var(--theme-elevation-100); }
27
+ .vs-bar span { position: absolute; inset: 0 auto 0 0; min-width: 6%; border-radius: 2px; background: var(--vs-accent); transition: width .6s ease-out; }
28
+ .vs-bar span::after { content: ''; position: absolute; inset: 0; background: linear-gradient(90deg, transparent, rgba(255,255,255,.45), transparent);
29
+ animation: vs-sweep 1.4s ease-in-out infinite; }
30
+ @keyframes vs-sweep { from { transform: translateX(-100%); } to { transform: translateX(100%); } }
31
+ @media (prefers-reduced-motion: reduce) { .vs-spin, .vs-bar span::after { animation: none; } }
24
32
  `;
33
+ const TRANSLATING = 'Translating…';
34
+ /** The most languages one recording may have, besides its spoken one (VocalStack's limit). */
35
+ const LANGUAGE_LIMIT = 10;
25
36
  /** Translations of the transcript, and readings of them aloud: under the transcript once it is done. */
26
37
  export const SpeechField = ({ field, path = '' }) => {
27
38
  const { id, collectionSlug } = useDocumentInfo();
@@ -37,40 +48,49 @@ export const SpeechField = ({ field, path = '' }) => {
37
48
  const translations = (useFormFields(([fields]) => fields[`${group}translations`]?.value) ?? {});
38
49
  const speech = (useFormFields(([fields]) => fields[`${group}speech`]?.value) ?? {});
39
50
  const spoken = useFormFields(([fields]) => fields[`${group}language`]?.value);
40
- const recordingId = useFormFields(([fields]) => fields[`${group}recordingId`]?.value);
51
+ const toggled = (useFormFields(([fields]) => fields[`${group}voices`]?.value) ?? 'synthetic');
52
+ // Decided by the site (e.g. the speaker's own setting), when the server says so.
53
+ const [decided, setDecided] = useState();
54
+ const voices = decided?.fixed ? decided.mode : toggled;
55
+ // As the server counts them: settled, numbered sentences with text.
56
+ const total = useFormFields(([fields]) => (fields[`${group}sentences`]?.value ?? []).filter((s) => !s.draft && s.id !== undefined && s.text.trim()).length);
41
57
  const [langs, setLangs] = useState();
42
- const [defaultVoice, setDefaultVoice] = useState(null);
43
- const [voices, setVoices] = useState({});
44
- const [picked, setPicked] = useState({});
45
58
  const [working, setWorking] = useState({});
46
59
  const [error, setError] = useState();
47
60
  const timer = useRef(undefined);
48
61
  const base = `/${collectionSlug}/${id}/vocalstack`;
49
62
  // The server saved these; make them the form's saved state too, so Save keeps them.
50
63
  const apply = useCallback((data) => {
51
- for (const key of ['translations', 'speech']) {
64
+ for (const key of ['translations', 'speech', 'voices']) {
52
65
  if (data && key in data)
53
66
  dispatchFields({ type: 'UPDATE', initialValue: data[key], path: `${group}${key}`, value: data[key] });
54
67
  }
55
68
  }, [dispatchFields, group]);
56
- const busySpeech = Object.values(speech).some((s) => s.state === 'queued' || s.state === 'running');
69
+ // Work the server carries on with: readings being made, and translations (and the readings waiting for them).
70
+ const busySpeech = Object.values(speech).some((s) => s.state === 'queued' || s.state === 'running' || s.state === 'translating') ||
71
+ Object.values(translations).some((t) => t.pending);
57
72
  const check = useCallback(async () => {
58
73
  clearTimeout(timer.current);
59
74
  try {
60
75
  const res = await call(`${base}/speak${query}`);
61
- setDefaultVoice(res.defaultVoice ?? null);
76
+ if (res.voiceMode)
77
+ setDecided(res.voiceMode);
62
78
  apply(res.vocalstack);
63
79
  const before = speech;
64
80
  for (const [lang, s] of Object.entries(res.vocalstack.speech ?? {})) {
65
81
  if (s.state === 'sealed' && before[lang]?.state !== 'sealed')
66
82
  toast.success(`The ${lang.toUpperCase()} reading is ready.`);
67
83
  }
84
+ for (const [lang, t] of Object.entries(res.vocalstack.translations ?? {})) {
85
+ if (!t.pending && translations[lang]?.pending && !t.error)
86
+ toast.success(`The ${lang.toUpperCase()} translation is ready.`);
87
+ }
68
88
  setError(undefined);
69
89
  }
70
90
  catch (err) {
71
91
  setError(err.message);
72
92
  }
73
- }, [apply, base, call, query, speech]);
93
+ }, [apply, base, call, query, speech, translations]);
74
94
  useEffect(() => {
75
95
  if (!id)
76
96
  return;
@@ -84,31 +104,14 @@ export const SpeechField = ({ field, path = '' }) => {
84
104
  timer.current = setTimeout(check, POLL_MS);
85
105
  return () => clearTimeout(timer.current);
86
106
  }, [busySpeech, check, speech]);
87
- const loadVoices = useCallback((lang) => {
88
- if (voices[lang])
89
- return;
90
- setVoices((v) => ({ ...v, [lang]: [] }));
91
- call(`/vocalstack/voices?${new URLSearchParams({ lang, ...(recordingId ? { recording: recordingId } : {}) })}`).then((r) => setVoices((v) => ({ ...v, [lang]: r.voices })), () => undefined);
92
- }, [call, recordingId, voices]);
93
107
  const names = useMemo(() => new Map(langs?.languages.map((l) => [l.code, l.name])), [langs]);
94
108
  const canSpeak = useMemo(() => new Set(langs?.voice), [langs]);
95
- const shown = [...new Set([...Object.keys(translations), ...Object.keys(speech)])].sort((a, b) => (names.get(a) ?? a).localeCompare(names.get(b) ?? b));
96
- const speakable = shown.filter((l) => canSpeak.has(l)).join();
97
- useEffect(() => {
98
- for (const l of speakable.split(','))
99
- if (l)
100
- loadVoices(l);
101
- }, [loadVoices, speakable]);
102
- /** Translate until done (each call stops after a while and says whether there is more). */
103
- const translate = async (list) => {
104
- if (!list.length)
105
- return;
106
- for (;;) {
107
- const res = await call(`${base}/translate${query}`, { body: JSON.stringify({ langs: list }), method: 'POST' });
108
- apply(res.vocalstack);
109
- if (!res.more)
110
- return;
111
- }
109
+ // Languages being added show up straight away, with their progress.
110
+ const shown = [...new Set([...Object.keys(translations), ...Object.keys(speech), ...Object.keys(working)])].sort((a, b) => (names.get(a) ?? a).localeCompare(names.get(b) ?? b));
111
+ /** Add languages: the server translates them and, with `speak`, reads them aloud, with no one watching. */
112
+ const request = async (list, speak) => {
113
+ const res = await call(`${base}/request${query}`, { body: JSON.stringify({ langs: list, speak }), method: 'POST' });
114
+ apply(res.vocalstack);
112
115
  };
113
116
  const run = async (list, label, job) => {
114
117
  if (!list.length)
@@ -125,53 +128,85 @@ export const SpeechField = ({ field, path = '' }) => {
125
128
  setWorking((w) => Object.fromEntries(Object.entries(w).filter(([l]) => !list.includes(l))));
126
129
  }
127
130
  };
128
- const speak = (list, voice) => run(list, 'Translating…', async () => {
129
- await translate(list.filter((l) => !translations[l]));
130
- const res = await call(`${base}/speak${query}`, { body: JSON.stringify({ langs: list, voice: voice || undefined }), method: 'POST' });
131
+ // VocalStack picks the voice.
132
+ const speak = (list) => run(list, 'Asking VocalStack to read it aloud…', async () => {
133
+ const res = await call(`${base}/speak${query}`, { body: JSON.stringify({ langs: list }), method: 'POST' });
131
134
  apply(res.vocalstack);
132
- setDefaultVoice(res.defaultVoice ?? null);
133
135
  });
136
+ const [switching, setSwitching] = useState(false);
137
+ const setVoices = async (next) => {
138
+ if (next === voices)
139
+ return;
140
+ setSwitching(true);
141
+ setError(undefined);
142
+ try {
143
+ apply((await call(`${base}/voices${query}`, { body: JSON.stringify({ voices: next }), method: 'POST' })).vocalstack);
144
+ }
145
+ catch (err) {
146
+ setError(err.message);
147
+ }
148
+ finally {
149
+ setSwitching(false);
150
+ }
151
+ };
134
152
  const remove = (lang) => window.confirm(`Remove the ${names.get(lang) ?? lang} translation${speech[lang] ? ' and its reading' : ''}?`) &&
135
153
  run([lang], 'Removing…', async () => {
136
154
  apply((await call(`${base}/translate${withQuery({ lang })}`, { method: 'DELETE' })).vocalstack);
137
155
  });
138
- const voiceName = (lang, key) => {
139
- if (!key)
140
- return 'VocalStack’s default voice';
141
- return voices[lang]?.find((v) => v.id === key)?.name ?? (key.startsWith('clone:') ? 'a cloned voice' : key);
142
- };
143
156
  if (!id)
144
157
  return null;
145
- return (_jsxs("div", { className: "vs-brand vs-speech", children: [_jsx(BrandStyles, {}), _jsx("style", { children: styles }), _jsx("h4", { children: "Translations and readings" }), !shown.length && _jsx("p", { className: "vs-speech-muted", children: "Translate the transcript so listeners can read along, or hear it read aloud, in their language." }), shown.map((lang) => {
158
+ return (_jsxs("div", { className: "vs-brand vs-speech", children: [_jsx(BrandStyles, {}), _jsx("style", { children: styles }), _jsx("h4", { children: "Translations and readings" }), decided?.fixed ? (_jsxs("p", { className: "vs-speech-muted", style: { marginBottom: 8 }, children: ["Read aloud in ", _jsx("strong", { children: voices === 'cloned' ? 'cloned voices' : 'synthetic voices' }), ", as set for the person speaking.", voices === 'cloned' ? ' Where they have no cloned voice yet, a synthetic one reads.' : ''] })) : (_jsxs(_Fragment, { children: [_jsxs("div", { className: "vs-speech-voices", role: "radiogroup", "aria-label": "Voices", children: [_jsx("span", { className: "vs-speech-muted", children: "Read aloud in" }), ['synthetic', 'cloned'].map((mode) => (_jsxs("label", { children: [_jsx("input", { checked: voices === mode, disabled: switching, name: `${group}voices-mode`, onChange: () => setVoices(mode), type: "radio" }), mode === 'synthetic' ? 'Synthetic voices' : 'Cloned voices'] }, mode)))] }), _jsxs("p", { className: "vs-speech-muted", style: { marginBottom: 8 }, children: [voices === 'cloned'
159
+ ? 'Each speaker is read in their own cloned voice where they have one (made with their permission), otherwise in a synthetic one.'
160
+ : 'Readings use VocalStack’s synthetic voices.', ' ', "Applies to readings made from now on; read a language again to change one already made."] })] })), !shown.length && _jsx("p", { className: "vs-speech-muted", children: "Translate the transcript so listeners can read along, or hear it read aloud, in their language." }), shown.map((lang) => {
146
161
  const t = translations[lang];
147
162
  const s = speech[lang];
148
163
  const busy = working[lang];
149
- const voicesHere = voices[lang] ?? [];
150
- return (_jsxs("div", { className: "vs-speech-row", children: [_jsxs("div", { children: [_jsx("strong", { children: names.get(lang) ?? lang }), _jsx("p", { className: "vs-speech-muted", children: t ? `${t.sentences.length} sentences translated` : 'Not translated' })] }), _jsxs("div", { style: { display: 'grid', gap: 6 }, children: [busy ? (_jsxs("span", { className: "vs-speech-muted", children: [_jsx("span", { className: "vs-spin" }), busy] })) : s?.state === 'queued' || s?.state === 'running' ? (_jsxs("span", { className: "vs-speech-muted", children: [_jsx("span", { className: "vs-spin" }), s.state === 'queued' ? 'Waiting to be read aloud…' : 'Being read aloud…', " (", voiceName(lang, s.voice), ")"] })) : s?.state === 'sealed' ? (_jsxs(_Fragment, { children: [_jsx("audio", { controls: true, preload: "none", src: `${serverURL}${api}${base}/audio${withQuery({ lang, v: s.renderedAt ?? '' })}` }, s.renderedAt ?? ''), _jsxs("span", { className: "vs-speech-muted", children: ["Read by ", voiceName(lang, s.voice)] })] })) : s?.state === 'failed' ? (_jsxs("p", { className: "vs-speech-error", children: ["Reading failed: ", s.error ?? 'no reason given'] })) : !canSpeak.has(lang) ? (_jsxs("span", { className: "vs-speech-muted", children: ["VocalStack cannot read ", names.get(lang) ?? lang, " aloud yet."] })) : null, canSpeak.has(lang) && !busy && s?.state !== 'queued' && s?.state !== 'running' && (_jsxs("div", { style: { display: 'flex', flexWrap: 'wrap', gap: 6 }, children: [_jsxs("select", { "aria-label": "Voice", onChange: (e) => setPicked((p) => ({ ...p, [lang]: e.target.value })), value: picked[lang] ?? '', children: [_jsxs("option", { value: "", children: ["Default for this recording (", voiceName(lang, defaultVoice), ")"] }), voicesHere.map((v) => (_jsxs("option", { disabled: v.ready === false && v.cloned, value: v.id, children: [v.name, v.cloned ? ' (cloned)' : ''] }, v.id)))] }), _jsx(Button, { buttonStyle: "secondary", margin: false, onClick: () => speak([lang], picked[lang]), size: "small", children: s ? 'Read again' : 'Read aloud' })] }))] }), _jsx(Button, { buttonStyle: "secondary", disabled: Boolean(busy), margin: false, onClick: () => remove(lang), size: "small", children: "Remove" })] }, lang));
151
- }), _jsx(AddLanguages, { busy: Object.keys(working).length > 0, canSpeak: canSpeak, exclude: new Set([...shown, ...(spoken ? [spoken] : [])]), langs: langs, onSpeak: (list) => speak(list), onTranslate: (list) => run(list, 'Translating…', () => translate(list)) }), error && _jsx("p", { className: "vs-speech-error", children: error })] }));
164
+ return (_jsxs("div", { className: "vs-speech-row", children: [_jsxs("div", { children: [_jsx("strong", { children: names.get(lang) ?? lang }), _jsx("p", { className: "vs-speech-muted", children: t?.pending
165
+ ? 'Translating…'
166
+ : t?.error && !t.sentences.length
167
+ ? 'Not translated'
168
+ : t && t.sentences.length < total
169
+ ? `${t.sentences.length} of ${total} sentences translated`
170
+ : t
171
+ ? `${t.sentences.length} sentences translated`
172
+ : 'Not translated' })] }), _jsxs("div", { style: { display: 'grid', gap: 6 }, children: [t?.pending ? (_jsxs(_Fragment, { children: [_jsx(Progress, { done: t.sentences.length, label: TRANSLATING, since: t.requestedAt ?? undefined, total: total }), s?.state === 'translating' && _jsx("span", { className: "vs-speech-muted", children: "Read aloud once translated." }), t.error && _jsxs("span", { className: "vs-speech-muted", children: [t.error, " Trying again shortly."] })] })) : busy ? (_jsxs("span", { className: "vs-speech-muted", children: [_jsx("span", { className: "vs-spin" }), busy] })) : s?.state === 'queued' || s?.state === 'running' ? (_jsx(Progress, { done: s.done ?? 0, label: s.state === 'queued' ? 'Waiting to be read aloud…' : 'Being read aloud…', since: s.requestedAt, total: t?.sentences.length ?? 0 })) : s?.state === 'sealed' ? (_jsx("audio", { controls: true, preload: "none", src: `${serverURL}${api}${base}/audio${withQuery({ lang, v: s.renderedAt ?? '' })}` }, s.renderedAt ?? '')) : t?.error && !t.sentences.length ? (_jsxs("p", { className: "vs-speech-error", children: ["Translating failed: ", t.error] })) : s?.state === 'translating' ? (_jsxs("span", { className: "vs-speech-muted", children: [_jsx("span", { className: "vs-spin" }), "Waiting for VocalStack to read it aloud\u2026"] })) : s?.state === 'failed' ? (_jsxs("p", { className: "vs-speech-error", children: ["Reading failed: ", s.error ?? 'no reason given'] })) : !canSpeak.has(lang) ? (_jsxs("span", { className: "vs-speech-muted", children: ["VocalStack cannot read ", names.get(lang) ?? lang, " aloud yet."] })) : null, canSpeak.has(lang) && !busy && !t?.pending && (!s || s.state === 'failed' || (s.state === 'sealed' && (s.cast ?? 'synthetic') !== voices)) && (_jsx("div", { children: _jsx(Button, { buttonStyle: "secondary", margin: false, onClick: () => speak([lang]), size: "small", children: !s ? 'Read aloud' : s.state === 'failed' ? 'Try again' : `Read again in ${voices} voices` }) }))] }), _jsx(Button, { buttonStyle: "secondary", disabled: Boolean(busy), margin: false, onClick: () => remove(lang), size: "small", children: "Remove" })] }, lang));
173
+ }), _jsx(AddLanguages, { busy: Object.keys(working).length > 0, canSpeak: canSpeak, exclude: new Set([...shown, ...(spoken ? [spoken] : [])]), langs: langs, left: LANGUAGE_LIMIT - shown.filter((l) => l !== spoken).length, onAdd: (list, speakToo) => run(list, 'Starting…', () => request(list, speakToo)) }), error && _jsx("p", { className: "vs-speech-error", children: error })] }));
152
174
  };
153
- const AddLanguages = ({ busy, canSpeak, exclude, langs, onSpeak, onTranslate }) => {
175
+ /** Work under way: the share of sentences done, counted up as each step is saved, and the time it has taken. */
176
+ const Progress = ({ done, label, since, total }) => {
177
+ const [started] = useState(() => (since ? new Date(since).getTime() : Date.now()));
178
+ const [, tick] = useState(0);
179
+ useEffect(() => {
180
+ const t = setInterval(() => tick((n) => n + 1), 1000);
181
+ return () => clearInterval(t);
182
+ }, []);
183
+ const s = Math.max(0, Math.floor((Date.now() - started) / 1000));
184
+ const elapsed = s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${String(s % 60).padStart(2, '0')}s`;
185
+ done = Math.min(done, total);
186
+ const share = total ? done / total : 0;
187
+ return (_jsxs("div", { style: { display: 'grid', gap: 4 }, children: [_jsx("div", { "aria-valuemax": total, "aria-valuemin": 0, "aria-valuenow": done, className: "vs-bar", role: "progressbar", children: _jsx("span", { style: { width: `${share * 100}%` } }) }), _jsxs("span", { className: "vs-speech-muted", children: [_jsx("span", { className: "vs-spin" }), label, " ", total ? `${done} of ${total} sentences` : '', " \u00B7 ", elapsed] })] }));
188
+ };
189
+ const AddLanguages = ({ busy, canSpeak, exclude, langs, left, onAdd }) => {
154
190
  const [open, setOpen] = useState(false);
155
191
  const [filter, setFilter] = useState('');
156
192
  const [chosen, setChosen] = useState([]);
157
193
  if (!langs)
158
194
  return null;
195
+ if (left <= 0) {
196
+ return (_jsxs("p", { className: "vs-speech-muted", style: { marginTop: 10 }, children: ["This recording has ", LANGUAGE_LIMIT, " languages, as many as one recording may have. Remove one to add another."] }));
197
+ }
159
198
  const options = langs.languages
160
199
  .filter((l) => l.translation && !exclude.has(l.code))
161
200
  .filter((l) => !filter || `${l.name} ${l.native} ${l.code}`.toLowerCase().includes(filter.toLowerCase()));
162
- const go = async (fn) => {
201
+ const go = async (speak) => {
163
202
  const list = chosen;
164
203
  setChosen([]);
165
204
  setOpen(false);
166
- await fn(list);
205
+ await onAdd(list, speak);
167
206
  };
168
207
  if (!open) {
169
208
  return (_jsx("div", { style: { marginTop: 10 }, children: _jsx(Button, { buttonStyle: "secondary", disabled: busy, margin: false, onClick: () => setOpen(true), size: "small", children: "Add languages" }) }));
170
209
  }
171
- // A reading is at most a few languages at a time.
172
- const speakable = chosen.filter((l) => canSpeak.has(l));
173
- return (_jsxs("div", { style: { borderTop: '1px solid var(--theme-elevation-100)', marginTop: 10, paddingTop: 10 }, children: [_jsx("input", { onChange: (e) => setFilter(e.target.value), placeholder: "Find a language", type: "search", value: filter }), _jsx("div", { className: "vs-speech-langs", children: options.map((l) => (_jsxs("label", { children: [_jsx("input", { checked: chosen.includes(l.code), onChange: (e) => setChosen((c) => (e.target.checked ? [...c, l.code] : c.filter((x) => x !== l.code))), type: "checkbox" }), l.name, canSpeak.has(l.code) ? ' 🔊' : ''] }, l.code))) }), _jsx("p", { className: "vs-speech-muted", style: { marginBottom: 8 }, children: "\uD83D\uDD0A can also be read aloud. Translating a long recording takes a few minutes." }), _jsxs("div", { style: { display: 'flex', flexWrap: 'wrap', gap: 6 }, children: [_jsx(Button, { disabled: busy || !chosen.length, margin: false, onClick: () => go(onTranslate), size: "small", children: "Translate" }), _jsx(Button, { disabled: busy || !speakable.length || speakable.length > 3, margin: false, onClick: () => go(async (list) => {
174
- await onTranslate(list.filter((l) => !canSpeak.has(l)));
175
- await onSpeak(list.filter((l) => canSpeak.has(l)));
176
- }), size: "small", children: speakable.length > 3 ? 'Read aloud: 3 at a time' : 'Translate and read aloud' }), _jsx(Button, { buttonStyle: "secondary", margin: false, onClick: () => setOpen(false), size: "small", children: "Cancel" })] })] }));
210
+ const tooMany = chosen.length > left;
211
+ return (_jsxs("div", { style: { borderTop: '1px solid var(--theme-elevation-100)', marginTop: 10, paddingTop: 10 }, children: [_jsx("input", { onChange: (e) => setFilter(e.target.value), placeholder: "Find a language", type: "search", value: filter }), _jsx("div", { className: "vs-speech-langs", children: options.map((l) => (_jsxs("label", { children: [_jsx("input", { checked: chosen.includes(l.code), onChange: (e) => setChosen((c) => (e.target.checked ? [...c, l.code] : c.filter((x) => x !== l.code))), type: "checkbox" }), l.name, canSpeak.has(l.code) ? ' 🔊' : ''] }, l.code))) }), _jsxs("p", { className: tooMany ? 'vs-speech-error' : 'vs-speech-muted', style: { marginBottom: 8 }, children: ["\uD83D\uDD0A is read aloud too. ", left, " more language", left === 1 ? '' : 's', " can be added (", LANGUAGE_LIMIT, " at most per recording). VocalStack carries on translating and reading after you leave this page."] }), _jsxs("div", { style: { display: 'flex', flexWrap: 'wrap', gap: 6 }, children: [_jsx(Button, { disabled: busy || !chosen.length || tooMany, margin: false, onClick: () => go(true), size: "small", children: "Translate and read aloud" }), _jsx(Button, { buttonStyle: "secondary", disabled: busy || !chosen.length || tooMany, margin: false, onClick: () => go(false), size: "small", children: "Translate only" }), _jsx(Button, { buttonStyle: "secondary", margin: false, onClick: () => setOpen(false), size: "small", children: "Cancel" })] })] }));
177
212
  };
@@ -1,43 +1,18 @@
1
1
  'use client';
2
2
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
3
  import { Button, toast, useConfig, useDocumentInfo, useForm } from '@payloadcms/ui';
4
- import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
4
+ import { useCallback, useEffect, useRef, useState } from 'react';
5
5
  import { BrandStyles, Logo } from './Brand.js';
6
6
  import { useAPI, useConnection } from './useConnection.js';
7
+ import { RecordSample, VoiceFromRecording } from './VoiceSamples.js';
7
8
  const POLL_MS = 3000;
8
- const TARGET_S = 60;
9
9
  const MIN_S = 30;
10
- const MAX_S = 120;
11
10
  const styles = `
12
- .vs-voice-list { max-height: 260px; overflow-y: auto; border: 1px solid var(--theme-elevation-150); border-radius: var(--style-radius-s, 4px);
13
- background: var(--theme-input-bg, var(--theme-elevation-0)); font-size: 13px; line-height: 1.5; }
14
- .vs-voice-line { display: flex; gap: 8px; width: 100%; padding: 6px 10px; border: 0; background: none; color: inherit; text-align: left; cursor: pointer; font: inherit; }
15
- .vs-voice-line:hover { background: var(--theme-elevation-50); }
16
- .vs-voice-line--in { background: color-mix(in srgb, var(--vs-accent) 14%, transparent); }
17
- .vs-voice-line--start { box-shadow: inset 3px 0 0 var(--vs-accent); }
18
- .vs-voice-time { color: var(--theme-elevation-500); font-variant-numeric: tabular-nums; flex: none; }
19
11
  .vs-voice-tabs { display: flex; gap: 4px; margin-bottom: 8px; }
20
12
  .vs-voice select, .vs-voice input[type=file] { width: 100%; font: inherit; }
21
13
  .vs-voice select { padding: 6px 8px; border: 1px solid var(--theme-elevation-150); border-radius: var(--style-radius-s, 4px);
22
14
  background: var(--theme-input-bg, var(--theme-elevation-0)); color: var(--theme-text); }
23
15
  `;
24
- const clock = (s) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
25
- /** Whole sentences from `start`, about a minute of them: VocalStack clones from 30–120 s. */
26
- function stretchFrom(sentences, start) {
27
- const from = sentences[start];
28
- const ids = new Set();
29
- let endS = from.end;
30
- for (let i = start; i < sentences.length; i++) {
31
- const s = sentences[i];
32
- if (s.end - from.start > MAX_S)
33
- break;
34
- ids.add(s.id);
35
- endS = s.end;
36
- if (endS - from.start >= TARGET_S)
37
- break;
38
- }
39
- return { endS, ids, startS: from.start };
40
- }
41
16
  /** Ogg/Opus where the browser plays it, else CAF (Safari). */
42
17
  const previewFormat = () => (typeof Audio !== 'undefined' && new Audio().canPlayType('audio/ogg; codecs=opus') ? 'ogg' : 'caf');
43
18
  export const VoiceField = () => {
@@ -155,8 +130,6 @@ const CreateVoice = ({ base, name, onCancel, onCreated }) => {
155
130
  const { serverURL, api } = useAPIBase();
156
131
  const [tab, setTab] = useState('recording');
157
132
  const [sources, setSources] = useState();
158
- const [sourceIdx, setSourceIdx] = useState(0);
159
- const [start, setStart] = useState();
160
133
  const [file, setFile] = useState();
161
134
  const [fileS, setFileS] = useState();
162
135
  const [consent, setConsent] = useState(false);
@@ -166,14 +139,10 @@ const CreateVoice = ({ base, name, onCancel, onCreated }) => {
166
139
  call(`${base}/sources`).then((r) => {
167
140
  setSources(r.sources);
168
141
  if (!r.sources.length)
169
- setTab('file');
142
+ setTab('record');
170
143
  }, (err) => setError(err.message));
171
144
  }, [base, call]);
172
- const source = sources?.[sourceIdx];
173
- const sentences = useMemo(() => source?.sentences ?? [], [source]);
174
- const stretch = start !== undefined && sentences[start] ? stretchFrom(sentences, start) : undefined;
175
- const length = stretch ? stretch.endS - stretch.startS : tab === 'file' ? fileS : undefined;
176
- const longEnough = (length ?? 0) >= MIN_S - 1.5;
145
+ const longEnough = (fileS ?? 0) >= MIN_S - 1.5;
177
146
  const pick = (f) => {
178
147
  setFile(f);
179
148
  setFileS(undefined);
@@ -183,28 +152,28 @@ const CreateVoice = ({ base, name, onCancel, onCreated }) => {
183
152
  const a = new Audio(URL.createObjectURL(f));
184
153
  a.onloadedmetadata = () => setFileS(a.duration);
185
154
  };
186
- const create = async () => {
155
+ const switchTo = (next) => {
156
+ setTab(next);
157
+ setFile(undefined);
158
+ setFileS(undefined);
159
+ setError(undefined);
160
+ };
161
+ /** A recorded or uploaded sample: sent through the server to VocalStack. */
162
+ const upload = async () => {
163
+ if (!file)
164
+ return;
187
165
  setBusy(true);
188
166
  setError(undefined);
189
167
  try {
190
- let res;
191
- if (tab === 'recording' && source && stretch) {
192
- res = await call(base, { body: JSON.stringify({ consent, endS: stretch.endS, recordingId: source.recordingId, startS: stretch.startS }), method: 'POST' });
193
- }
194
- else if (file) {
195
- const form = new FormData();
196
- form.append('file', file);
197
- form.append('_payload', JSON.stringify({ consent }));
198
- const r = await fetch(`${serverURL}${api}${base}`, { body: form, credentials: 'include', method: 'POST' });
199
- const body = await r.json().catch(() => ({}));
200
- if (!r.ok)
201
- throw new Error(body.error ?? (r.status === 413 ? 'The sample is too large; use a shorter or compressed file.' : `Request failed (${r.status})`));
202
- res = body;
203
- }
204
- else
205
- return;
168
+ const form = new FormData();
169
+ form.append('file', file);
170
+ form.append('_payload', JSON.stringify({ consent }));
171
+ const r = await fetch(`${serverURL}${api}${base}`, { body: form, credentials: 'include', method: 'POST' });
172
+ const body = await r.json().catch(() => ({}));
173
+ if (!r.ok)
174
+ throw new Error(body.error ?? (r.status === 413 ? 'The sample is too large; use a shorter or compressed file.' : `Request failed (${r.status})`));
206
175
  toast.success('Voice created. It is training now.');
207
- onCreated(res);
176
+ onCreated(body);
208
177
  }
209
178
  catch (err) {
210
179
  setError(err.message);
@@ -214,11 +183,15 @@ const CreateVoice = ({ base, name, onCancel, onCreated }) => {
214
183
  }
215
184
  };
216
185
  const muted = { color: 'var(--theme-elevation-500)', fontSize: 13, margin: 0 };
217
- const clipURL = stretch && source ? `${serverURL}${api}${base}/clip?${new URLSearchParams({ endS: String(stretch.endS), recording: source.recordingId, startS: String(stretch.startS) })}` : undefined;
218
- return (_jsxs("div", { style: { display: 'grid', gap: 10 }, children: [_jsxs("div", { className: "vs-voice-tabs", children: [_jsx(Button, { buttonStyle: tab === 'recording' ? 'primary' : 'secondary', margin: false, onClick: () => setTab('recording'), size: "small", children: "From a recording" }), _jsx(Button, { buttonStyle: tab === 'file' ? 'primary' : 'secondary', margin: false, onClick: () => setTab('file'), size: "small", children: "Upload a sample" })] }), tab === 'recording' ? (!sources ? (_jsx("p", { style: muted, children: error ? '' : 'Looking for transcribed recordings…' })) : !sources.length ? (_jsxs("p", { style: muted, children: ["No transcribed recordings of ", name || 'them', " yet. Transcribe one, or upload a sample."] })) : (_jsxs(_Fragment, { children: [sources.length > 1 && (_jsx("select", { "aria-label": "Recording", onChange: (e) => {
219
- setSourceIdx(Number(e.target.value));
220
- setStart(undefined);
221
- }, value: sourceIdx, children: sources.map((s, i) => (_jsx("option", { value: i, children: s.label }, s.recordingId))) })), _jsxs("p", { style: muted, children: ["Click where ", name || 'they', " start speaking alone, with no music or other voices. About a minute is taken from there."] }), _jsx("div", { className: "vs-voice-list", children: sentences.map((s, i) => (_jsxs("button", { className: `vs-voice-line${stretch?.ids.has(s.id) ? ' vs-voice-line--in' : ''}${i === start ? ' vs-voice-line--start' : ''}`, onClick: () => setStart(i), type: "button", children: [_jsx("span", { className: "vs-voice-time", children: clock(s.start) }), _jsx("span", { children: s.text })] }, s.id ?? i))) }), stretch && (_jsxs(_Fragment, { children: [_jsxs("p", { style: muted, children: [clock(stretch.startS), "\u2013", clock(stretch.endS), " \u00B7 ", Math.round(stretch.endS - stretch.startS), " s", longEnough ? '' : ` (at least ${MIN_S} s needed)`] }), _jsx("audio", { controls: true, preload: "none", src: clipURL, style: { width: '100%' } }, clipURL)] }))] }))) : (_jsxs(_Fragment, { children: [_jsxs("p", { style: muted, children: [MIN_S, " s to 2 min of ", name || 'them', " speaking alone, clearly, with no music. An MP3 or M4A of about a minute is ideal."] }), _jsx("input", { accept: "audio/*", onChange: (e) => pick(e.target.files?.[0]), type: "file" }), file && fileS !== undefined && !longEnough && _jsxs("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: ["That is ", Math.round(fileS), " s; at least ", MIN_S, " s is needed."] })] })), _jsxs("label", { style: { alignItems: 'flex-start', display: 'flex', fontSize: 13, gap: 8 }, children: [_jsx("input", { checked: consent, onChange: (e) => setConsent(e.target.checked), style: { marginTop: 3 }, type: "checkbox" }), _jsxs("span", { children: ["I have ", name || 'their', "\u2019s permission to clone their voice."] })] }), error && _jsx("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: error }), _jsxs("div", { style: { display: 'flex', gap: 6 }, children: [_jsx(Button, { disabled: busy || !consent || !longEnough || (tab === 'file' ? !file : !stretch), margin: false, onClick: create, size: "small", children: busy ? 'Creating…' : 'Create voice' }), _jsx(Button, { buttonStyle: "secondary", disabled: busy, margin: false, onClick: onCancel, size: "small", children: "Cancel" })] })] }));
186
+ const tabs = [
187
+ ['recording', 'From a sermon'],
188
+ ['record', 'Record'],
189
+ ['file', 'Upload'],
190
+ ];
191
+ return (_jsxs("div", { style: { display: 'grid', gap: 10 }, children: [_jsx("div", { className: "vs-voice-tabs", children: tabs.map(([key, label]) => (_jsx(Button, { buttonStyle: tab === key ? 'primary' : 'secondary', margin: false, onClick: () => switchTo(key), size: "small", children: label }, key))) }), tab === 'recording' ? (!sources ? (_jsx("p", { style: muted, children: error ? '' : 'Looking for transcribed recordings…' })) : !sources.length ? (_jsxs("p", { style: muted, children: ["No transcribed recordings of ", name || 'them', " yet. Transcribe one, or record a sample."] })) : (_jsx(VoiceFromRecording, { base: base, name: name, onCreated: onCreated, sources: sources }))) : (_jsxs(_Fragment, { children: [tab === 'record' ? (_jsx(RecordSample, { onRecorded: (f, seconds) => {
192
+ setFile(f);
193
+ setFileS(seconds);
194
+ } })) : (_jsxs(_Fragment, { children: [_jsxs("p", { style: muted, children: [MIN_S, " s to 2 min of ", name || 'them', " speaking alone, clearly, with no music. An MP3 or M4A of about a minute is ideal."] }), _jsx("input", { accept: "audio/*", onChange: (e) => pick(e.target.files?.[0]), type: "file" })] })), file && fileS !== undefined && !longEnough && _jsxs("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: ["That is ", Math.round(fileS), " s; at least ", MIN_S, " s is needed."] }), _jsxs("label", { style: { alignItems: 'flex-start', display: 'flex', fontSize: 13, gap: 8 }, children: [_jsx("input", { checked: consent, onChange: (e) => setConsent(e.target.checked), style: { marginTop: 3 }, type: "checkbox" }), _jsxs("span", { children: ["I have ", name || 'their', "\u2019s permission to clone their voice."] })] }), error && _jsx("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: error }), _jsx("div", { children: _jsx(Button, { disabled: busy || !consent || !longEnough || !file, margin: false, onClick: upload, size: "small", children: busy ? 'Creating…' : 'Create voice' }) })] })), _jsx("div", { children: _jsx(Button, { buttonStyle: "secondary", disabled: busy, margin: false, onClick: onCancel, size: "small", children: "Cancel" }) })] }));
222
195
  };
223
196
  function useAPIBase() {
224
197
  const { config: { routes: { api }, serverURL, }, } = useConfig();
@@ -0,0 +1,21 @@
1
+ import type { VoiceFieldData, VoiceSource } from '../types.js';
2
+ /** As in the VocalStack dashboard: at least 5 s makes a voice, 20 s a steadier one, 25 s is plenty; 60 s at most. */
3
+ export declare const PICK_MIN_S = 5;
4
+ export declare const sampleStyles = "\n .vs-steps { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; margin-bottom: 4px; }\n .vs-step { border-top: 3px solid var(--theme-elevation-150); padding-top: 6px; font-size: 12px; color: var(--theme-elevation-500); }\n .vs-step--on { border-color: var(--vs-accent); color: var(--theme-text); font-weight: 600; }\n .vs-step--done { border-color: color-mix(in srgb, var(--vs-accent) 45%, transparent); }\n .vs-sample { border: 1px solid var(--theme-elevation-150); border-radius: 8px; overflow: hidden; }\n .vs-sample-body { padding: 10px 12px; display: grid; gap: 8px; }\n .vs-sample-head { display: flex; justify-content: space-between; align-items: center; font-size: 12px; color: var(--theme-elevation-500); }\n .vs-sample-text { font-size: 14px; line-height: 1.45; min-height: 2.9em; }\n .vs-sample-play { display: flex; align-items: center; gap: 10px; }\n .vs-play { width: 34px; height: 34px; flex: none; border-radius: 50%; border: 0; background: var(--vs-accent); color: #fff; cursor: pointer; font-size: 12px; }\n .vs-play:disabled { opacity: .5; cursor: default; }\n .vs-wave { flex: 1; display: flex; align-items: center; gap: 2px; height: 28px; min-width: 0; }\n .vs-wave span { flex: 1; border-radius: 1px; background: var(--theme-elevation-250); }\n .vs-wave span.on { background: var(--vs-accent); }\n .vs-sample-use { display: flex; align-items: center; gap: 8px; padding: 10px 12px; border-top: 1px solid var(--theme-elevation-150);\n background: var(--theme-elevation-50); font-size: 14px; cursor: pointer; }\n .vs-pager { display: flex; gap: 4px; }\n .vs-pager button { border: 0; background: none; color: var(--theme-text); cursor: pointer; font-size: 16px; padding: 0 6px; }\n .vs-pager button:disabled { opacity: .3; cursor: default; }\n .vs-meter { position: relative; height: 6px; border-radius: 3px; background: var(--theme-elevation-100); overflow: hidden; }\n .vs-meter span { position: absolute; inset: 0 auto 0 0; background: var(--vs-accent); transition: width .3s; }\n .vs-meter-marks { position: relative; height: 16px; font-size: 11px; color: var(--theme-elevation-500); }\n .vs-meter-marks span { position: absolute; transform: translateX(-50%); }\n .vs-chips { display: flex; flex-wrap: wrap; gap: 6px; }\n .vs-chip { display: inline-flex; gap: 6px; align-items: center; border: 1px solid var(--theme-elevation-150); border-radius: 12px; padding: 2px 4px 2px 10px; font-size: 12px; }\n .vs-chip button { border: 0; background: none; cursor: pointer; color: var(--theme-elevation-500); }\n .vs-chips--none { border: 1px dashed var(--theme-elevation-200); border-radius: 12px; padding: 4px 10px; font-size: 12px; color: var(--theme-elevation-500); }\n";
5
+ /**
6
+ * Clone a voice from sentences of one of the person's own transcribed recordings, as in the
7
+ * VocalStack dashboard: pick samples (or have them chosen), hear the voice, then name and keep it.
8
+ */
9
+ export declare const VoiceFromRecording: React.FC<{
10
+ base: string;
11
+ name: string;
12
+ onCreated: (res: {
13
+ name?: string;
14
+ vocalstackVoice: VoiceFieldData;
15
+ }) => void;
16
+ sources: VoiceSource[];
17
+ }>;
18
+ /** Record them speaking, in the browser, as the sample to clone from. */
19
+ export declare const RecordSample: React.FC<{
20
+ onRecorded: (file: File | undefined, seconds: number | undefined) => void;
21
+ }>;