@vocalstack/payload 0.1.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.
@@ -0,0 +1,341 @@
1
+ 'use client';
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { Button, toast, useConfig } from '@payloadcms/ui';
4
+ import { useEffect, useMemo, useRef, useState } from 'react';
5
+ import { useAPI } from './useConnection.js';
6
+ /** 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. */
7
+ export const PICK_MIN_S = 5;
8
+ const PICK_GOOD_S = 20;
9
+ const PICK_TARGET_S = 25;
10
+ const PICK_MAX_S = 60;
11
+ export const sampleStyles = `
12
+ .vs-steps { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; margin-bottom: 4px; }
13
+ .vs-step { border-top: 3px solid var(--theme-elevation-150); padding-top: 6px; font-size: 12px; color: var(--theme-elevation-500); }
14
+ .vs-step--on { border-color: var(--vs-accent); color: var(--theme-text); font-weight: 600; }
15
+ .vs-step--done { border-color: color-mix(in srgb, var(--vs-accent) 45%, transparent); }
16
+ .vs-sample { border: 1px solid var(--theme-elevation-150); border-radius: 8px; overflow: hidden; }
17
+ .vs-sample-body { padding: 10px 12px; display: grid; gap: 8px; }
18
+ .vs-sample-head { display: flex; justify-content: space-between; align-items: center; font-size: 12px; color: var(--theme-elevation-500); }
19
+ .vs-sample-text { font-size: 14px; line-height: 1.45; min-height: 2.9em; }
20
+ .vs-sample-play { display: flex; align-items: center; gap: 10px; }
21
+ .vs-play { width: 34px; height: 34px; flex: none; border-radius: 50%; border: 0; background: var(--vs-accent); color: #fff; cursor: pointer; font-size: 12px; }
22
+ .vs-play:disabled { opacity: .5; cursor: default; }
23
+ .vs-wave { flex: 1; display: flex; align-items: center; gap: 2px; height: 28px; min-width: 0; }
24
+ .vs-wave span { flex: 1; border-radius: 1px; background: var(--theme-elevation-250); }
25
+ .vs-wave span.on { background: var(--vs-accent); }
26
+ .vs-sample-use { display: flex; align-items: center; gap: 8px; padding: 10px 12px; border-top: 1px solid var(--theme-elevation-150);
27
+ background: var(--theme-elevation-50); font-size: 14px; cursor: pointer; }
28
+ .vs-pager { display: flex; gap: 4px; }
29
+ .vs-pager button { border: 0; background: none; color: var(--theme-text); cursor: pointer; font-size: 16px; padding: 0 6px; }
30
+ .vs-pager button:disabled { opacity: .3; cursor: default; }
31
+ .vs-meter { position: relative; height: 6px; border-radius: 3px; background: var(--theme-elevation-100); overflow: hidden; }
32
+ .vs-meter span { position: absolute; inset: 0 auto 0 0; background: var(--vs-accent); transition: width .3s; }
33
+ .vs-meter-marks { position: relative; height: 16px; font-size: 11px; color: var(--theme-elevation-500); }
34
+ .vs-meter-marks span { position: absolute; transform: translateX(-50%); }
35
+ .vs-chips { display: flex; flex-wrap: wrap; gap: 6px; }
36
+ .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; }
37
+ .vs-chip button { border: 0; background: none; cursor: pointer; color: var(--theme-elevation-500); }
38
+ .vs-chips--none { border: 1px dashed var(--theme-elevation-200); border-radius: 12px; padding: 4px 10px; font-size: 12px; color: var(--theme-elevation-500); }
39
+ `;
40
+ const secs = (c) => Math.max(0, c.end - c.start);
41
+ const TERMINAL = /[.!?…。!?।؟;]["'”’»)\]]*$/;
42
+ /** The sentences of the one who speaks most in the recording: the person whose voice this is. */
43
+ function candidates(sentences) {
44
+ const bySpeaker = new Map();
45
+ for (const s of sentences)
46
+ if (s.speaker >= 0)
47
+ bySpeaker.set(s.speaker, (bySpeaker.get(s.speaker) ?? 0) + (s.end - s.start));
48
+ const speaker = [...bySpeaker.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? 0;
49
+ const clips = sentences.filter((s) => s.speaker === speaker && s.end > s.start && s.text.trim()).map((s) => ({ end: s.end, start: s.start, text: s.text.trim() }));
50
+ return { clips, speaker };
51
+ }
52
+ /** The clearest picks first, as the dashboard ranks them: whole sentences of 4–11 s, about 8 s best. */
53
+ function chooseFor(clips) {
54
+ const tier = (c) => (!TERMINAL.test(c.text) ? 2 : secs(c) >= 4 && secs(c) <= 11 ? 0 : 1);
55
+ const near = (c) => -Math.abs(secs(c) - 8);
56
+ const order = clips.map((c, i) => i).sort((a, b) => tier(clips[a]) - tier(clips[b]) || near(clips[b]) - near(clips[a]) || a - b);
57
+ const out = new Set();
58
+ let total = 0;
59
+ for (const i of order) {
60
+ if (total + 0.05 >= PICK_TARGET_S)
61
+ break;
62
+ if (total + secs(clips[i]) > PICK_MAX_S + 0.5)
63
+ continue;
64
+ out.add(i);
65
+ total += secs(clips[i]);
66
+ }
67
+ return out;
68
+ }
69
+ const pickedSeconds = (clips, picked) => [...picked].reduce((t, i) => t + (clips[i] ? secs(clips[i]) : 0), 0);
70
+ const spansOf = (clips, picked) => [...picked]
71
+ .filter((i) => clips[i])
72
+ .sort((a, b) => clips[a].start - clips[b].start)
73
+ .map((i) => ({ end: clips[i].end, start: clips[i].start }));
74
+ function useBase() {
75
+ const { config: { routes: { api }, serverURL, }, } = useConfig();
76
+ return `${serverURL}${api}`;
77
+ }
78
+ /** One sentence of the recording: its waveform, and a play button. */
79
+ const SampleAudio = ({ src }) => {
80
+ const [bars, setBars] = useState();
81
+ const [url, setUrl] = useState();
82
+ const [at, setAt] = useState(0);
83
+ const [playing, setPlaying] = useState(false);
84
+ const [failed, setFailed] = useState(false);
85
+ const audio = useRef(null);
86
+ useEffect(() => {
87
+ let gone = false;
88
+ let made;
89
+ setBars(undefined);
90
+ setUrl(undefined);
91
+ setFailed(false);
92
+ setAt(0);
93
+ setPlaying(false);
94
+ fetch(src, { credentials: 'include' })
95
+ .then((r) => (r.ok ? r.arrayBuffer() : Promise.reject(r)))
96
+ .then((wav) => {
97
+ if (gone)
98
+ return;
99
+ // 16-bit PCM after the 44-byte header: the peak of each stretch, as a bar.
100
+ const pcm = new Int16Array(wav, 44, Math.max(0, (wav.byteLength - 44) >> 1));
101
+ const n = 40;
102
+ const per = Math.max(1, Math.floor(pcm.length / n));
103
+ const peaks = Array.from({ length: n }, (_, i) => {
104
+ let p = 0;
105
+ for (let k = i * per; k < Math.min((i + 1) * per, pcm.length); k++)
106
+ p = Math.max(p, Math.abs(pcm[k]));
107
+ return p;
108
+ });
109
+ const top = Math.max(1, ...peaks);
110
+ setBars(peaks.map((p) => 14 + (p / top) * 86));
111
+ made = URL.createObjectURL(new Blob([wav], { type: 'audio/wav' }));
112
+ setUrl(made);
113
+ })
114
+ .catch(() => !gone && setFailed(true));
115
+ return () => {
116
+ gone = true;
117
+ if (made)
118
+ URL.revokeObjectURL(made);
119
+ };
120
+ }, [src]);
121
+ const toggle = () => {
122
+ const a = audio.current;
123
+ if (!a)
124
+ return;
125
+ if (a.paused)
126
+ void a.play();
127
+ else
128
+ a.pause();
129
+ };
130
+ const duration = audio.current?.duration || 0;
131
+ const share = duration ? at / duration : 0;
132
+ return (_jsxs("div", { className: "vs-sample-play", children: [_jsx("button", { "aria-label": playing ? 'Pause' : 'Play', className: "vs-play", disabled: !url, onClick: toggle, type: "button", children: playing ? '❚❚' : '▶' }), _jsx("div", { className: "vs-wave", children: failed ? (_jsx("span", { style: { background: 'none', color: 'var(--theme-elevation-500)', fontSize: 12 }, children: "Could not load this sample." })) : ((bars ?? Array.from({ length: 40 }, () => 14)).map((h, i, all) => _jsx("span", { className: i / all.length < share ? 'on' : '', style: { height: `${h}%` } }, i))) }), _jsx("span", { style: { fontVariantNumeric: 'tabular-nums', fontSize: 13 }, children: `00:${String(Math.round(duration - at || 0)).padStart(2, '0')}` }), url && (_jsx("audio", { onEnded: () => {
133
+ setPlaying(false);
134
+ setAt(0);
135
+ }, onPause: () => setPlaying(false), onPlay: () => setPlaying(true), onTimeUpdate: (e) => setAt(e.currentTarget.currentTime), ref: audio, src: url }))] }));
136
+ };
137
+ /**
138
+ * Clone a voice from sentences of one of the person's own transcribed recordings, as in the
139
+ * VocalStack dashboard: pick samples (or have them chosen), hear the voice, then name and keep it.
140
+ */
141
+ export const VoiceFromRecording = ({ base, name, onCreated, sources }) => {
142
+ const call = useAPI();
143
+ const apiBase = useBase();
144
+ const [sourceIdx, setSourceIdx] = useState(0);
145
+ const source = sources[sourceIdx];
146
+ const { clips, speaker } = useMemo(() => candidates(source?.sentences ?? []), [source]);
147
+ const [idx, setIdx] = useState(0);
148
+ const [picked, setPicked] = useState(new Set());
149
+ const [step, setStep] = useState(1);
150
+ const [trial, setTrial] = useState();
151
+ const [voiceName, setVoiceName] = useState(name);
152
+ const [consent, setConsent] = useState(false);
153
+ const [busy, setBusy] = useState(false);
154
+ const [error, setError] = useState();
155
+ const kept = useRef(false);
156
+ const trialId = useRef(undefined);
157
+ trialId.current = trial?.id;
158
+ // A trial voice nobody kept is deleted when the panel closes.
159
+ useEffect(() => () => {
160
+ if (trialId.current && !kept.current)
161
+ void call(`${base}/trial?${new URLSearchParams({ voice: trialId.current })}`, { method: 'DELETE' }).catch(() => undefined);
162
+ }, [base, call]);
163
+ // Follow the trial voice while it trains.
164
+ useEffect(() => {
165
+ if (!trial || (trial.state !== 'training' && trial.state !== 'queued'))
166
+ return;
167
+ const t = setTimeout(() => {
168
+ call(`${base}/trial?${new URLSearchParams({ voice: trial.id })}`).then((r) => setTrial((cur) => (cur?.id === r.voice.id ? { ...cur, ...r.voice } : cur)), () => undefined);
169
+ }, 2000);
170
+ return () => clearTimeout(t);
171
+ }, [base, call, trial]);
172
+ const total = pickedSeconds(clips, picked);
173
+ const pickKey = JSON.stringify(spansOf(clips, picked));
174
+ const clip = clips[Math.min(idx, clips.length - 1)];
175
+ const here = picked.has(idx);
176
+ const room = here || (clip && total + secs(clip) <= PICK_MAX_S + 0.5);
177
+ const enough = total + 0.05 >= PICK_MIN_S && total <= PICK_MAX_S + 0.5;
178
+ const best = useMemo(() => chooseFor(clips), [clips]);
179
+ const chosen = best.size > 0 && best.size === picked.size && [...best].every((i) => picked.has(i));
180
+ const toggle = (i) => setPicked((p) => {
181
+ const next = new Set(p);
182
+ if (next.has(i))
183
+ next.delete(i);
184
+ else if (clips[i] && pickedSeconds(clips, p) + secs(clips[i]) <= PICK_MAX_S + 0.5)
185
+ next.add(i);
186
+ return next;
187
+ });
188
+ /** Step 2: make a trial voice from the picked samples (a new one when the picks changed). */
189
+ const tryVoice = async () => {
190
+ setStep(2);
191
+ if (trial && trial.key === pickKey && trial.state !== 'failed')
192
+ return;
193
+ setBusy(true);
194
+ setError(undefined);
195
+ try {
196
+ const r = await call(`${base}/trial`, {
197
+ body: JSON.stringify({ recordingId: source.recordingId, replace: trial?.id, spans: spansOf(clips, picked), speaker }),
198
+ method: 'POST',
199
+ });
200
+ setTrial({ ...r.voice, key: pickKey });
201
+ }
202
+ catch (err) {
203
+ setError(err.message);
204
+ }
205
+ finally {
206
+ setBusy(false);
207
+ }
208
+ };
209
+ const keep = async () => {
210
+ if (!trial)
211
+ return;
212
+ setBusy(true);
213
+ setError(undefined);
214
+ try {
215
+ const res = await call(`${base}/trial/keep`, {
216
+ body: JSON.stringify({ consent, name: voiceName, voice: trial.id }),
217
+ method: 'POST',
218
+ });
219
+ kept.current = true;
220
+ toast.success('Voice saved.');
221
+ onCreated(res);
222
+ }
223
+ catch (err) {
224
+ setError(err.message);
225
+ }
226
+ finally {
227
+ setBusy(false);
228
+ }
229
+ };
230
+ const muted = { color: 'var(--theme-elevation-500)', fontSize: 13, margin: 0 };
231
+ const scale = PICK_TARGET_S * 1.2;
232
+ const meterAt = (s) => `${Math.min(100, (s / scale) * 100)}%`;
233
+ const steps = ['Pick samples', 'Hear the voice', 'Name and save'];
234
+ return (_jsxs("div", { style: { display: 'grid', gap: 10 }, children: [_jsx("style", { children: sampleStyles }), _jsx("div", { className: "vs-steps", children: steps.map((label, i) => (_jsxs("div", { className: `vs-step${step === i + 1 ? ' vs-step--on' : step > i + 1 ? ' vs-step--done' : ''}`, children: [i + 1, ". ", label] }, label))) }), step === 1 && (_jsxs(_Fragment, { children: [sources.length > 1 && (_jsx("select", { "aria-label": "Recording", onChange: (e) => {
235
+ setSourceIdx(Number(e.target.value));
236
+ setIdx(0);
237
+ setPicked(new Set());
238
+ }, value: sourceIdx, children: sources.map((s, i) => (_jsx("option", { value: i, children: s.label }, s.recordingId))) })), _jsxs("div", { style: { alignItems: 'baseline', display: 'flex', gap: 8, justifyContent: 'space-between' }, children: [_jsxs("p", { style: muted, children: ["Pick about ", PICK_TARGET_S, "s of clear speech, with no music or other voices."] }), _jsxs("strong", { style: { fontSize: 13, whiteSpace: 'nowrap' }, children: [Math.round(total), "s ", _jsxs("span", { style: { color: 'var(--theme-elevation-500)', fontWeight: 400 }, children: ["/ ", PICK_TARGET_S, "s"] })] })] }), _jsx("div", { children: _jsx(Button, { buttonStyle: "secondary", disabled: chosen || !clips.length, margin: false, onClick: () => setPicked(new Set(best)), size: "small", children: "\u2728 Choose for me" }) }), clip ? (_jsxs("div", { className: "vs-sample", children: [_jsxs("div", { className: "vs-sample-body", children: [_jsxs("div", { className: "vs-sample-head", children: [_jsxs("span", { children: ["Sample ", idx + 1, " of ", clips.length] }), _jsxs("span", { className: "vs-pager", children: [_jsx("button", { "aria-label": "Previous sample", disabled: idx === 0, onClick: () => setIdx((i) => Math.max(0, i - 1)), type: "button", children: "\u2039" }), _jsx("button", { "aria-label": "Next sample", disabled: idx >= clips.length - 1, onClick: () => setIdx((i) => Math.min(clips.length - 1, i + 1)), type: "button", children: "\u203A" })] })] }), _jsx("div", { className: "vs-sample-text", children: clip.text }), _jsx(SampleAudio, { src: `${apiBase}${base}/clip?${new URLSearchParams({ endS: clip.end.toFixed(2), recording: source.recordingId, startS: clip.start.toFixed(2) })}` })] }), _jsxs("label", { className: "vs-sample-use", style: { opacity: room ? 1 : 0.5 }, children: [_jsx("input", { checked: here, disabled: !room, onChange: () => toggle(idx), type: "checkbox" }), room ? 'Use this sample' : `Full: ${PICK_MAX_S}s at most`] })] })) : (_jsx("p", { style: muted, children: "No sentences of theirs in this recording." })), _jsxs("div", { children: [_jsx("div", { className: "vs-meter", children: _jsx("span", { style: { width: meterAt(total) } }) }), _jsx("div", { className: "vs-meter-marks", children: [PICK_MIN_S, PICK_GOOD_S, PICK_TARGET_S].map((s) => (_jsxs("span", { style: { fontWeight: total + 0.05 >= s ? 600 : 400, left: meterAt(s) }, children: [s, "s"] }, s))) })] }), _jsx("p", { style: muted, children: !picked.size
239
+ ? `At least ${PICK_MIN_S}s makes a voice.`
240
+ : total + 0.05 < PICK_MIN_S
241
+ ? `${Math.ceil(PICK_MIN_S - total)}s more to make a voice.`
242
+ : total >= PICK_TARGET_S
243
+ ? 'Plenty.'
244
+ : total + 0.05 < PICK_GOOD_S
245
+ ? `Enough for a voice. ${PICK_GOOD_S}s or more sounds steadier.`
246
+ : `Good. About ${PICK_TARGET_S}s gives it more to choose from.` }), picked.size ? (_jsx("div", { className: "vs-chips", children: [...picked]
247
+ .sort((a, b) => a - b)
248
+ .map((i) => (_jsxs("span", { className: "vs-chip", children: [_jsxs("button", { onClick: () => setIdx(i), style: { color: 'inherit', padding: 0 }, type: "button", children: [i + 1, " \u00B7 ", Math.round(secs(clips[i])), "s"] }), _jsx("button", { "aria-label": `Leave sample ${i + 1} out`, onClick: () => toggle(i), type: "button", children: "\u2715" })] }, i))) })) : (_jsx("span", { className: "vs-chips--none", children: "No samples picked yet" })), _jsx("div", { children: _jsx(Button, { disabled: !enough || busy, margin: false, onClick: tryVoice, size: "small", children: "Next" }) })] })), step === 2 && (_jsxs(_Fragment, { children: [!trial || trial.state === 'training' || trial.state === 'queued' ? (_jsxs("p", { style: muted, children: ["Making the voice", trial?.progress ? ` · ${trial.progress}%` : '…', " It takes a minute or two."] })) : trial.state === 'failed' ? (_jsxs("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: ["The voice could not be made: ", trial.error ?? 'no reason given', ". Pick other samples."] })) : (_jsx(TrialPreview, { base: base, voice: trial.id })), _jsxs("div", { style: { display: 'flex', gap: 6 }, children: [_jsx(Button, { buttonStyle: "secondary", margin: false, onClick: () => setStep(1), size: "small", children: "Back" }), _jsx(Button, { disabled: trial?.state !== 'ready', margin: false, onClick: () => setStep(3), size: "small", children: "Next" })] })] })), step === 3 && (_jsxs(_Fragment, { children: [_jsxs("label", { style: { display: 'grid', fontSize: 13, gap: 4 }, children: ["Name", _jsx("input", { maxLength: 60, onChange: (e) => setVoiceName(e.target.value), style: { font: 'inherit', padding: '6px 8px' }, value: voiceName })] }), _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."] })] }), _jsxs("div", { style: { display: 'flex', gap: 6 }, children: [_jsx(Button, { buttonStyle: "secondary", disabled: busy, margin: false, onClick: () => setStep(2), size: "small", children: "Back" }), _jsx(Button, { disabled: busy || !consent || !voiceName.trim(), margin: false, onClick: keep, size: "small", children: busy ? 'Saving…' : 'Save voice' })] })] })), error && _jsx("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: error })] }));
249
+ };
250
+ /** Ogg/Opus where the browser plays it, else CAF (Safari). */
251
+ const previewFormat = () => (typeof Audio !== 'undefined' && new Audio().canPlayType('audio/ogg; codecs=opus') ? 'ogg' : 'caf');
252
+ /** The trial voice speaking a few seconds, in a language picked. */
253
+ const TrialPreview = ({ base, voice }) => {
254
+ const call = useAPI();
255
+ const apiBase = useBase();
256
+ const [langs, setLangs] = useState();
257
+ const [lang, setLang] = useState('en');
258
+ const [src, setSrc] = useState();
259
+ const [waiting, setWaiting] = useState(false);
260
+ const [error, setError] = useState();
261
+ const audio = useRef(null);
262
+ useEffect(() => {
263
+ call('/vocalstack/languages').then(setLangs, () => undefined);
264
+ }, [call]);
265
+ const play = async () => {
266
+ setError(undefined);
267
+ setWaiting(true);
268
+ const url = `${apiBase}${base}/trial/preview?${new URLSearchParams({ format: previewFormat(), lang, voice })}`;
269
+ try {
270
+ for (let i = 0; i < 30; i++) {
271
+ const res = await fetch(url, { credentials: 'include' });
272
+ if (res.status === 202) {
273
+ await new Promise((r) => setTimeout(r, 2000));
274
+ continue;
275
+ }
276
+ if (!res.ok)
277
+ throw new Error((await res.json().catch(() => ({}))).error ?? `Preview failed (${res.status})`);
278
+ setSrc(URL.createObjectURL(await res.blob()));
279
+ requestAnimationFrame(() => void audio.current?.play().catch(() => undefined));
280
+ return;
281
+ }
282
+ throw new Error('The preview is taking a while; try again in a minute.');
283
+ }
284
+ catch (err) {
285
+ setError(err.message);
286
+ }
287
+ finally {
288
+ setWaiting(false);
289
+ }
290
+ };
291
+ const names = new Map(langs?.languages.map((l) => [l.code, l.name]));
292
+ return (_jsxs("div", { style: { display: 'grid', gap: 8 }, children: [_jsx("p", { style: { color: 'var(--theme-elevation-500)', fontSize: 13, margin: 0 }, children: "Hear it before you keep it. Not right? Go back and pick other samples." }), _jsxs("div", { style: { display: 'flex', gap: 6 }, children: [_jsx("select", { "aria-label": "Preview language", onChange: (e) => setLang(e.target.value), value: lang, children: (langs?.voice ?? ['en']).map((code) => (_jsx("option", { value: code, children: names.get(code) ?? code }, code))) }), _jsx(Button, { buttonStyle: "secondary", disabled: waiting, margin: false, onClick: play, size: "small", children: waiting ? 'Making…' : '▶ Hear the voice' })] }), src && _jsx("audio", { controls: true, ref: audio, src: src, style: { width: '100%' } }), error && _jsx("p", { style: { color: 'var(--theme-error-500)', fontSize: 13, margin: 0 }, children: error })] }));
293
+ };
294
+ /** Record them speaking, in the browser, as the sample to clone from. */
295
+ export const RecordSample = ({ onRecorded }) => {
296
+ const [recording, setRecording] = useState(false);
297
+ const [elapsed, setElapsed] = useState(0);
298
+ const [url, setUrl] = useState();
299
+ const [error, setError] = useState();
300
+ const rec = useRef(undefined);
301
+ const started = useRef(0);
302
+ useEffect(() => {
303
+ if (!recording)
304
+ return;
305
+ const t = setInterval(() => setElapsed((Date.now() - started.current) / 1000), 250);
306
+ return () => clearInterval(t);
307
+ }, [recording]);
308
+ const start = async () => {
309
+ setError(undefined);
310
+ try {
311
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true } });
312
+ const chunks = [];
313
+ const r = new MediaRecorder(stream);
314
+ r.ondataavailable = (e) => e.data.size && chunks.push(e.data);
315
+ r.onstop = () => {
316
+ stream.getTracks().forEach((t) => t.stop());
317
+ const type = r.mimeType || 'audio/webm';
318
+ const blob = new Blob(chunks, { type });
319
+ const seconds = (Date.now() - started.current) / 1000;
320
+ setUrl(URL.createObjectURL(blob));
321
+ onRecorded(new File([blob], `recording.${type.includes('mp4') ? 'm4a' : type.includes('ogg') ? 'ogg' : 'webm'}`, { type }), seconds);
322
+ };
323
+ rec.current = r;
324
+ started.current = Date.now();
325
+ setElapsed(0);
326
+ setUrl(undefined);
327
+ onRecorded(undefined, undefined);
328
+ r.start(1000);
329
+ setRecording(true);
330
+ }
331
+ catch {
332
+ setError('The microphone could not be used. Allow it for this site, or upload a sample instead.');
333
+ }
334
+ };
335
+ const stop = () => {
336
+ rec.current?.stop();
337
+ setRecording(false);
338
+ };
339
+ const muted = { color: 'var(--theme-elevation-500)', fontSize: 13, margin: 0 };
340
+ return (_jsxs("div", { style: { display: 'grid', gap: 8 }, children: [_jsx("p", { style: muted, children: "Record them reading or speaking naturally for 30 seconds to a minute, alone, in a quiet room." }), _jsxs("div", { style: { alignItems: 'center', display: 'flex', gap: 10 }, children: [_jsx(Button, { buttonStyle: recording ? 'error' : 'primary', margin: false, onClick: recording ? stop : start, size: "small", children: recording ? '■ Stop' : url ? '● Record again' : '● Record' }), (recording || url) && _jsx("span", { style: { fontVariantNumeric: 'tabular-nums', fontSize: 13 }, children: `${Math.floor(elapsed / 60)}:${String(Math.floor(elapsed % 60)).padStart(2, '0')}` })] }), url && !recording && _jsx("audio", { controls: true, src: url, style: { width: '100%' } }), error && _jsx("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: error })] }));
341
+ };
@@ -0,0 +1,27 @@
1
+ import type { CollectionSlug, Endpoint, Payload } from 'payload';
2
+ import type { AudioFieldConfig, Translation, VocalStackFieldData, VocalStackPluginOptions } from '../types.js';
3
+ /** Whether a language is fully translated (older translations, made before `pending`, are). */
4
+ export declare const isTranslated: (t: null | Translation | undefined) => boolean;
5
+ /**
6
+ * A document was read with work still left on its languages: carry it forward after the
7
+ * response, so a translation or reading is ready for listeners without an editor watching.
8
+ */
9
+ export declare function refreshAfterRead(payload: Payload, collection: CollectionSlug, options: VocalStackPluginOptions, rowFields: AudioFieldConfig[], id: number | string, data: null | undefined | VocalStackFieldData, where?: {
10
+ field: string;
11
+ row: string;
12
+ }): void;
13
+ /**
14
+ * Translations of a transcript, and spoken readings of them, on the same document or
15
+ * row as the transcript (`?field=&row=` as for transcribing):
16
+ * POST /:id/vocalstack/translate { langs } translate (call again while `more`)
17
+ * DELETE /:id/vocalstack/translate?lang= drop a language, spoken reading too
18
+ * POST /:id/vocalstack/voices { voices } 'cloned' or 'synthetic', for readings from now on
19
+ * POST /:id/vocalstack/request { langs, speak? } translate and read aloud, carried on by the server
20
+ * POST /:id/vocalstack/speak { langs } read translations aloud (VocalStack picks the voice)
21
+ * GET /:id/vocalstack/speak where the readings stand
22
+ * GET /:id/vocalstack/audio?lang= public: the audio, or its reading in `lang`
23
+ * With `listeners` on, for anyone who may read the document:
24
+ * GET /:id/vocalstack/listen?lang= where a language stands
25
+ * POST /:id/vocalstack/listen { lang } ask for a language
26
+ */
27
+ export declare function speechEndpoints(collection: CollectionSlug, options: VocalStackPluginOptions, rowFields: AudioFieldConfig[]): Endpoint[];