1import { useEffect, useMemo, useState } from "react";
2import { RecordPanel } from "./components/RecordPanel.tsx";
3import { TearView } from "./components/TearView.tsx";
4import { CompareView } from "./components/CompareView.tsx";
5import { About } from "./components/About.tsx";
6import { readTheme } from "./components/CanvasPlot.tsx";
7import { DEFAULT_SETTINGS, DETECT_VERSION, detectSegment, energyBand } from "./analysis/analyze.ts";
8import type { CaptureInfo } from "./audio/recorder.ts";
9import { encodeWavFloat32 } from "./audio/wav.ts";
10import { exportDataset, readDataset } from "./storage/dataset.ts";
11import { clearAll, deleteRecording, listRecordings, newId, saveRecording, updateMeta, type RecordingMeta } from "./storage/db.ts";
12import {
13 download,
14 durationColor,
15 fmtDate,
16 fmtSec,
17 forgetAllAudio,
18 forgetAudio,
19 getAudio,
20 loadSettings,
21 putAudio,
22 safeName,
23 sampleTitle,
24 sortSamples,
25 storeSettings,
26 tearDuration,
27} from "./model.ts";
28import type { AnalysisSettings } from "./analysis/analyze.ts";
30type Tab = "record" | "compare" | "about";
31const NEW = "new"; // selection value for the "new sample" page
33export function App() {
34 const [recs, setRecs] = useState<RecordingMeta[]>([]);
35 const [loaded, setLoaded] = useState(false);
36 const [selected, setSelected] = useState<string>(NEW);
37 const [rerecording, setRerecording] = useState<string | null>(null);
38 const [tab, setTab] = useState<Tab>("record");
39 const [settings, setSettingsState] = useState<AnalysisSettings>(loadSettings);
40 const [showSettings, setShowSettings] = useState(false);
42 useEffect(() => {
43 listRecordings().then((r) => {
44 setRecs(r);
45 setLoaded(true);
46 if (r.length) setSelected(sortSamples(r)[0].id);
47 });
48 navigator.storage?.persist?.().catch(() => {});
49 }, []);
51 const samples = useMemo(() => sortSamples(recs), [recs]);
53 const setSettings = (s: AnalysisSettings) => {
54 setSettingsState(s);
55 storeSettings(s);
56 };
58 // Ranges found automatically follow the analysis band and the finder: find them again when
59 // either changes. Ranges set by hand are left alone.
60 const { energyLow, energyHigh } = settings;
61 useEffect(() => {
62 if (!loaded) return;
63 let live = true;
64 (async () => {
65 for (const m of recs) {
66 if (m.segmentManual || (m.detectBand?.lo === energyLow && m.detectBand?.hi === energyHigh && m.detectVersion === DETECT_VERSION)) continue;
67 const x = await getAudio(m.id);
68 if (!live) return;
69 const band = { lo: energyLow, hi: energyHigh };
70 const updated = { ...m, segment: detectSegment(x, m.sampleRate, band), detectBand: band, detectVersion: DETECT_VERSION };
71 await updateMeta(updated);
72 setRecs((r) => r.map((q) => (q.id === m.id ? updated : q)));
73 }
74 })();
75 return () => {
76 live = false;
77 };
78 }, [loaded, recs, energyLow, energyHigh]);
80 // A new take: either a new sample, or a replacement for `replaces` (keeping its name and notes).
81 const onDone = async (replaces: RecordingMeta | null, x: Float32Array, fs: number, info: CaptureInfo | null, fileName?: string) => {
82 const band = energyBand(settings);
83 const meta: RecordingMeta = {
84 id: newId(),
85 createdAt: Date.now(),
86 label: replaces?.label ?? "",
87 notes: replaces?.notes ?? "",
88 material: "paper",
89 source: fileName ? "file" : "mic",
90 fileName,
91 sampleRate: fs,
92 length: x.length,
93 segment: detectSegment(x, fs, band),
94 segmentManual: false,
95 detectBand: band,
96 detectVersion: DETECT_VERSION,
97 capture: info ?? undefined,
98 };
99 await saveRecording(meta, x);
100 putAudio(meta.id, x);
101 if (replaces) {
102 await deleteRecording(replaces.id);
103 forgetAudio(replaces.id);
104 }
105 setRecs((r) => [...r.filter((m) => m.id !== replaces?.id), meta]);
106 setRerecording(null);
107 setSelected(meta.id);
108 };
110 const onUpdate = async (meta: RecordingMeta) => {
111 await updateMeta(meta);
112 setRecs((r) => r.map((m) => (m.id === meta.id ? meta : m)));
113 };
115 const remove = async (m: RecordingMeta) => {
116 if (!confirm(`Delete this sample (${sampleTitle(m)})? This cannot be undone.`)) return;
117 await deleteRecording(m.id);
118 forgetAudio(m.id);
119 const rest = samples.filter((q) => q.id !== m.id);
120 setRecs((r) => r.filter((q) => q.id !== m.id));
121 setSelected(rest.length ? rest[Math.min(samples.indexOf(m), rest.length - 1)].id : NEW);
122 };
124 const clearEverything = async () => {
125 if (!samples.length) return;
126 if (!confirm(`Delete all ${samples.length} sample${samples.length > 1 ? "s" : ""} from this browser? This cannot be undone. Download WAVs first if you want to keep any.`)) return;
127 await clearAll();
128 forgetAllAudio();
129 setRecs([]);
130 setRerecording(null);
131 setSelected(NEW);
132 };
134 const [busy, setBusy] = useState<string | null>(null);
136 const doExport = async () => {
137 setBusy("Exporting…");
138 try {
139 const blob = await exportDataset(samples, settings, getAudio);
140 download(blob, `rip-sound-dataset-${new Date().toISOString().slice(0, 10)}.zip`);
141 } catch (e) {
142 alert(`Export failed: ${(e as Error).message}`);
143 } finally {
144 setBusy(null);
145 }
146 };
148 const doImport = async (file: File | undefined) => {
149 if (!file) return;
150 setBusy("Reading…");
151 try {
152 const ds = await readDataset(file);
153 const n = ds.samples.length;
154 const when = ds.exportedAt ? ` (exported ${fmtDate(Date.parse(ds.exportedAt))})` : "";
155 const msg =
156 `Replace everything in this browser with “${file.name}”${when}?\n\n` +
157 `${samples.length} current sample${samples.length === 1 ? "" : "s"} will be deleted and ${n} sample${n === 1 ? "" : "s"} loaded from the file. ` +
158 "The analysis settings saved in the file will be restored too. This cannot be undone.";
159 if (!confirm(msg)) return;
160 setBusy("Importing…");
161 await clearAll();
162 forgetAllAudio();
163 for (const { meta, audio } of ds.samples) {
164 await saveRecording(meta, audio);
165 putAudio(meta.id, audio);
166 }
167 if (ds.settings) setSettings({ ...DEFAULT_SETTINGS, ...ds.settings });
168 const metas = ds.samples.map((d) => d.meta);
169 setRecs(metas);
170 setRerecording(null);
171 setSelected(metas.length ? sortSamples(metas)[0].id : NEW);
172 } catch (e) {
173 alert(`Could not import “${file.name}”: ${(e as Error).message}`);
174 } finally {
175 setBusy(null);
176 }
177 };
179 const current = recs.find((r) => r.id === selected) ?? null;
180 const th = readTheme(document.documentElement);
181 const dur = current ? tearDuration(current) : null;
183 return (
184 <div className="app">
185 <header className="topbar">
186 <h1>Rip Sound Analyzer</h1>
187 <nav className="tabs" role="tablist">
188 {(
189 [
190 ["record", "Record"],
191 ["compare", `Compare (${samples.length})`],
192 ["about", "What this can tell you"],
193 ] as [Tab, string][]
194 ).map(([t, name]) => (
195 <button key={t} role="tab" aria-selected={tab === t} className={tab === t ? "on" : ""} onClick={() => setTab(t)}>
196 {name}
197 </button>
198 ))}
199 </nav>
200 <button className="settings-btn" onClick={() => setShowSettings((s) => !s)} aria-expanded={showSettings}>
201 Analysis settings
202 </button>
203 </header>
205 {showSettings && <SettingsPanel settings={settings} setSettings={setSettings} />}
207 {tab === "record" && (
208 <div className="layout">
209 <aside className="sidebar" aria-label="Samples">
210 <div className="side-head">
211 Samples <span className="muted">slowest first</span>
212 </div>
213 <button
214 className={`speed-item new-item ${selected === NEW ? "sel" : ""}`}
215 onClick={() => {
216 setSelected(NEW);
217 setRerecording(null);
218 }}
219 >
220 <span className="plus">+</span>
221 <span className="speed-name">New sample</span>
222 </button>
223 {samples.map((m) => {
224 const d = tearDuration(m);
225 return (
226 <button
227 key={m.id}
228 className={`speed-item ${m.id === selected ? "sel" : ""}`}
229 onClick={() => {
230 setSelected(m.id);
231 setRerecording(null);
232 }}
233 >
234 <span className="dot done" style={{ background: durationColor(d, th) }} />
235 <span className="speed-text">
236 <span className="speed-name">
237 {sampleTitle(m)}
238 {d !== null && <span className="muted"> · {(settings.sheetLengthIn / d).toFixed(1)} in/s</span>}
239 </span>
240 <span className="muted small">{m.label || fmtDate(m.createdAt)}</span>
241 </span>
242 </button>
243 );
244 })}
245 {loaded && !samples.length && <p className="muted pad small">No samples yet.</p>}
246 <p className="muted pad small">Recordings are stored only in this browser.</p>
247 <div className="data-actions pad">
248 <button onClick={doExport} disabled={!samples.length || !!busy} title="Save every sample and the analysis settings to one .zip file">
249 Export dataset
250 </button>
251 <label className={`button-like ${busy ? "disabled" : ""}`} title="Replace everything in this browser with a dataset file">
252 Import dataset…
253 <input
254 type="file"
255 accept=".zip,application/zip"
256 disabled={!!busy}
257 onChange={(e) => {
258 void doImport(e.target.files?.[0]);
259 e.target.value = "";
260 }}
261 />
262 </label>
263 {samples.length > 0 && (
264 <button className="danger" onClick={clearEverything} disabled={!!busy}>
265 Clear all data…
266 </button>
267 )}
268 {busy && <span className="muted small">{busy}</span>}
269 </div>
270 </aside>
272 <main className="main">
273 {selected === NEW || !current ? (
274 <>
275 <div className="speed-head">
276 <div>
277 <h2>New sample</h2>
278 <div className="muted small">Record a tear at any speed. It is added to the list when you stop.</div>
279 </div>
280 </div>
281 {loaded && <RecordPanel key="new" replacing={false} onDone={(x, fs, info, fileName) => onDone(null, x, fs, info, fileName)} onCancel={null} />}
282 </>
283 ) : (
284 <>
285 <div className="speed-head">
286 <div>
287 <h2>
288 {sampleTitle(current)}
289 {dur !== null && <span className="muted"> · {(settings.sheetLengthIn / dur).toFixed(2)} in/s</span>}
290 </h2>
291 <div className="muted small">
292 Recorded {fmtDate(current.createdAt)} · {fmtSec(current.length / current.sampleRate)} long
293 {current.fileName ? ` · from ${current.fileName}` : ""}
294 </div>
295 </div>
296 {rerecording !== current.id && (
297 <div className="toolbar">
298 <button onClick={() => setRerecording(current.id)}>Re-record</button>
299 <button
300 onClick={async () => {
301 const x = await getAudio(current.id);
302 const stamp = new Date(current.createdAt).toISOString().slice(0, 19).replace(/:/g, "-");
303 download(encodeWavFloat32(x, current.sampleRate), `tear_${stamp}${current.label ? "_" + safeName(current.label) : ""}.wav`);
304 }}
305 >
306 Download WAV
307 </button>
308 <button className="danger" onClick={() => remove(current)}>
309 Delete
310 </button>
311 </div>
312 )}
313 </div>
314 <NameField key={`name-${current.id}`} meta={current} onUpdate={onUpdate} />
316 {rerecording === current.id ? (
317 <RecordPanel
318 key={`re-${current.id}`}
319 replacing
320 onDone={(x, fs, info, fileName) => onDone(current, x, fs, info, fileName)}
321 onCancel={() => setRerecording(null)}
322 />
323 ) : (
324 <TearView key={`tear-${current.id}`} meta={current} settings={settings} onUpdate={onUpdate} />
325 )}
326 </>
327 )}
328 </main>
329 </div>
330 )}
332 {tab === "compare" && (
333 <main className="main solo">
334 <CompareView
335 recs={samples}
336 settings={settings}
337 onOpen={(id) => {
338 setSelected(id);
339 setRerecording(null);
340 setTab("record");
341 }}
342 />
343 </main>
344 )}
345 {tab === "about" && (
346 <main className="main solo">
347 <About settings={settings} />
348 </main>
349 )}
350 </div>
351 );
352}
354// Optional free-text name and notes for a sample.
355function NameField({ meta, onUpdate }: { meta: RecordingMeta; onUpdate: (m: RecordingMeta) => void }) {
356 const [label, setLabel] = useState(meta.label);
357 const [notes, setNotes] = useState(meta.notes);
358 return (
359 <div className="name-row">
360 <input
361 value={label}
362 placeholder="Name (optional)"
363 onChange={(e) => setLabel(e.target.value)}
364 onBlur={() => label !== meta.label && onUpdate({ ...meta, label: label.trim() })}
365 onKeyDown={(e) => e.key === "Enter" && (e.target as HTMLInputElement).blur()}
366 aria-label="Sample name"
367 />
368 <input
369 className="notes-input"
370 value={notes}
371 placeholder="Notes (paper, how it was torn, anything unusual)"
372 onChange={(e) => setNotes(e.target.value)}
373 onBlur={() => notes !== meta.notes && onUpdate({ ...meta, notes })}
374 onKeyDown={(e) => e.key === "Enter" && (e.target as HTMLInputElement).blur()}
375 aria-label="Notes"
376 />
377 </div>
378 );
379}
381function SettingsPanel({ settings, setSettings }: { settings: AnalysisSettings; setSettings: (s: AnalysisSettings) => void }) {
382 const [d, setD] = useState(settings);
383 const changed = JSON.stringify(d) !== JSON.stringify(settings);
384 const field = (k: keyof AnalysisSettings, label: string, unit: string) => (
385 <label>
386 {label}
387 <input type="number" value={d[k]} min={0} onChange={(e) => setD({ ...d, [k]: +e.target.value })} />
388 {unit}
389 </label>
390 );
391 return (
392 <div className="settings card">
393 <div className="settings-row">
394 <b>Analysis band</b>
395 {field("energyLow", "from", "Hz")}
396 {field("energyHigh", "to", "Hz")}
397 <span className="muted small">Used for total energy, finding the tear, the level plot, the filtered waveform and the background comparison.</span>
398 </div>
399 <div className="settings-row">
400 {field("sheetLengthIn", "Tear length", "in")}
401 <button
402 className="primary"
403 disabled={!changed || d.energyHigh <= d.energyLow || d.sheetLengthIn <= 0}
404 onClick={() => setSettings(d)}
405 >
406 Apply
407 </button>
408 <button onClick={() => setD({ ...DEFAULT_SETTINGS })}>Defaults</button>
409 </div>
410 </div>
411 );
412}