import { useEffect, useMemo, useState } from "react"; import { RecordPanel } from "./components/RecordPanel.tsx"; import { TearView } from "./components/TearView.tsx"; import { CompareView } from "./components/CompareView.tsx"; import { About } from "./components/About.tsx"; import { readTheme } from "./components/CanvasPlot.tsx"; import { DEFAULT_SETTINGS, detectSegment, energyBand } from "./analysis/analyze.ts"; import type { CaptureInfo } from "./audio/recorder.ts"; import { encodeWavFloat32 } from "./audio/wav.ts"; import { clearAll, deleteRecording, listRecordings, newId, saveRecording, updateMeta, type RecordingMeta } from "./storage/db.ts"; import { download, durationColor, fmtDate, fmtSec, forgetAllAudio, forgetAudio, getAudio, loadSettings, putAudio, safeName, sampleTitle, sortSamples, storeSettings, tearDuration, } from "./model.ts"; import type { AnalysisSettings } from "./analysis/analyze.ts"; type Tab = "record" | "compare" | "about"; const NEW = "new"; // selection value for the "new sample" page export function App() { const [recs, setRecs] = useState([]); const [loaded, setLoaded] = useState(false); const [selected, setSelected] = useState(NEW); const [rerecording, setRerecording] = useState(null); const [tab, setTab] = useState("record"); const [settings, setSettingsState] = useState(loadSettings); const [showSettings, setShowSettings] = useState(false); useEffect(() => { listRecordings().then((r) => { setRecs(r); setLoaded(true); if (r.length) setSelected(sortSamples(r)[0].id); }); navigator.storage?.persist?.().catch(() => {}); }, []); const samples = useMemo(() => sortSamples(recs), [recs]); const setSettings = (s: AnalysisSettings) => { setSettingsState(s); storeSettings(s); }; // Ranges found automatically follow the energy band: re-detect them when it changes. // Ranges set by hand are left alone. const { energyLow, energyHigh } = settings; useEffect(() => { if (!loaded) return; let live = true; (async () => { for (const m of recs) { if (m.segmentManual || (m.detectBand?.lo === energyLow && m.detectBand?.hi === energyHigh)) continue; const x = await getAudio(m.id); if (!live) return; const band = { lo: energyLow, hi: energyHigh }; const updated = { ...m, segment: detectSegment(x, m.sampleRate, band), detectBand: band }; await updateMeta(updated); setRecs((r) => r.map((q) => (q.id === m.id ? updated : q))); } })(); return () => { live = false; }; }, [loaded, recs, energyLow, energyHigh]); // A new take: either a new sample, or a replacement for `replaces` (keeping its name and notes). const onDone = async (replaces: RecordingMeta | null, x: Float32Array, fs: number, info: CaptureInfo | null, fileName?: string) => { const band = energyBand(settings); const meta: RecordingMeta = { id: newId(), createdAt: Date.now(), label: replaces?.label ?? "", notes: replaces?.notes ?? "", material: "paper", source: fileName ? "file" : "mic", fileName, sampleRate: fs, length: x.length, segment: detectSegment(x, fs, band), segmentManual: false, detectBand: band, capture: info ?? undefined, }; await saveRecording(meta, x); putAudio(meta.id, x); if (replaces) { await deleteRecording(replaces.id); forgetAudio(replaces.id); } setRecs((r) => [...r.filter((m) => m.id !== replaces?.id), meta]); setRerecording(null); setSelected(meta.id); }; const onUpdate = async (meta: RecordingMeta) => { await updateMeta(meta); setRecs((r) => r.map((m) => (m.id === meta.id ? meta : m))); }; const remove = async (m: RecordingMeta) => { if (!confirm(`Delete this sample (${sampleTitle(m)})? This cannot be undone.`)) return; await deleteRecording(m.id); forgetAudio(m.id); const rest = samples.filter((q) => q.id !== m.id); setRecs((r) => r.filter((q) => q.id !== m.id)); setSelected(rest.length ? rest[Math.min(samples.indexOf(m), rest.length - 1)].id : NEW); }; const clearEverything = async () => { if (!samples.length) return; 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; await clearAll(); forgetAllAudio(); setRecs([]); setRerecording(null); setSelected(NEW); }; const current = recs.find((r) => r.id === selected) ?? null; const th = readTheme(document.documentElement); const dur = current ? tearDuration(current) : null; return (

Rip Sound Analyzer

{showSettings && } {tab === "record" && (
{selected === NEW || !current ? ( <>

New sample

Record a tear at any speed. It is added to the list when you stop.
{loaded && onDone(null, x, fs, info, fileName)} onCancel={null} />} ) : ( <>

{sampleTitle(current)} {dur !== null && · {(settings.sheetLengthIn / dur).toFixed(2)} in/s}

Recorded {fmtDate(current.createdAt)} · {fmtSec(current.length / current.sampleRate)} long {current.fileName ? ` · from ${current.fileName}` : ""}
{rerecording !== current.id && (
)}
{rerecording === current.id ? ( onDone(current, x, fs, info, fileName)} onCancel={() => setRerecording(null)} /> ) : ( )} )}
)} {tab === "compare" && (
{ setSelected(id); setRerecording(null); setTab("record"); }} />
)} {tab === "about" && (
)}
); } // Optional free-text name and notes for a sample. function NameField({ meta, onUpdate }: { meta: RecordingMeta; onUpdate: (m: RecordingMeta) => void }) { const [label, setLabel] = useState(meta.label); const [notes, setNotes] = useState(meta.notes); return (
setLabel(e.target.value)} onBlur={() => label !== meta.label && onUpdate({ ...meta, label: label.trim() })} onKeyDown={(e) => e.key === "Enter" && (e.target as HTMLInputElement).blur()} aria-label="Sample name" /> setNotes(e.target.value)} onBlur={() => notes !== meta.notes && onUpdate({ ...meta, notes })} onKeyDown={(e) => e.key === "Enter" && (e.target as HTMLInputElement).blur()} aria-label="Notes" />
); } function SettingsPanel({ settings, setSettings }: { settings: AnalysisSettings; setSettings: (s: AnalysisSettings) => void }) { const [d, setD] = useState(settings); const changed = JSON.stringify(d) !== JSON.stringify(settings); const field = (k: keyof AnalysisSettings, label: string, unit: string) => ( ); return (
Energy band {field("energyLow", "from", "Hz")} {field("energyHigh", "to", "Hz")} Used for total energy, finding the tear, the level-over-time plot and the background comparison.
Spectrum band {field("shapeLow", "from", "Hz")} {field("shapeHigh", "to", "Hz")} The frequency range shown when comparing spectra.
{field("sheetLengthIn", "Tear length", "in")}
); }