/ magland / rip-sound-analyzer
Sign in
magland / rip-sound-analyzer
rip-sound-analyzer / src / App.tsx
213 lines · 8.3 KBBlameHistoryRaw
1import { useEffect, useMemo, useState } from "react";
2import { RecordBar } from "./components/RecordBar.tsx";
3import { RecordingView } from "./components/RecordingView.tsx";
4import { CompareView } from "./components/CompareView.tsx";
5import { About } from "./components/About.tsx";
6import { readTheme } from "./components/CanvasPlot.tsx";
7import { deleteRecording, listRecordings, saveRecording, updateMeta, type RecordingMeta } from "./storage/db.ts";
8import { colorFor, fmtSec, forgetAudio, groupOrder, groupStyle, loadSettings, PRESET_LABELS, putAudio, storeSettings } from "./model.ts";
9import type { AnalysisSettings } from "./analysis/analyze.ts";
11type Tab = "record" | "compare" | "about";
13function loadExcluded(): Set<string> {
14 try {
15 return new Set(JSON.parse(localStorage.getItem("rsa-excluded") ?? "[]"));
16 } catch {
17 return new Set();
18 }
21export function App() {
22 const [recs, setRecs] = useState<RecordingMeta[]>([]);
23 const [loaded, setLoaded] = useState(false);
24 const [selected, setSelected] = useState<string | null>(null);
25 const [tab, setTab] = useState<Tab>("record");
26 const [label, setLabel] = useState(PRESET_LABELS[2]);
27 const [settings, setSettingsState] = useState<AnalysisSettings>(loadSettings);
28 const [excluded, setExcluded] = useState<Set<string>>(loadExcluded);
29 const [showSettings, setShowSettings] = useState(false);
31 useEffect(() => {
32 listRecordings().then((r) => {
33 setRecs(r);
34 setSelected(r.length ? r[r.length - 1].id : null);
35 setLoaded(true);
36 });
37 navigator.storage?.persist?.().catch(() => {});
38 }, []);
40 useEffect(() => {
41 try {
42 localStorage.setItem("rsa-excluded", JSON.stringify([...excluded]));
43 } catch {
44 /* ignore */
45 }
46 }, [excluded]);
48 const setSettings = (s: AnalysisSettings) => {
49 setSettingsState(s);
50 storeSettings(s);
51 };
53 const onNew = async (meta: RecordingMeta, x: Float32Array) => {
54 await saveRecording(meta, x);
55 putAudio(meta.id, x);
56 setRecs((r) => [...r, meta]);
57 setSelected(meta.id);
58 setTab("record");
59 };
60 const onUpdate = async (meta: RecordingMeta) => {
61 await updateMeta(meta);
62 setRecs((r) => r.map((m) => (m.id === meta.id ? meta : m)));
63 };
64 const onDelete = async (meta: RecordingMeta) => {
65 if (!confirm(`Delete this recording (“${meta.label}”)? This cannot be undone.`)) return;
66 await deleteRecording(meta.id);
67 forgetAudio(meta.id);
68 setRecs((r) => {
69 const next = r.filter((m) => m.id !== meta.id);
70 if (selected === meta.id) setSelected(next.length ? next[next.length - 1].id : null);
71 return next;
72 });
73 };
75 const groups = useMemo(() => groupOrder(recs), [recs]);
76 const knownLabels = useMemo(() => [...new Set([...PRESET_LABELS, ...recs.map((r) => r.label)])], [recs]);
77 const included = useMemo(() => recs.filter((r) => !excluded.has(r.id)), [recs, excluded]);
78 const current = recs.find((r) => r.id === selected) ?? null;
79 const th = readTheme(document.documentElement);
81 const toggle = (ids: string[], on: boolean) =>
82 setExcluded((ex) => {
83 const n = new Set(ex);
84 for (const id of ids) on ? n.delete(id) : n.add(id);
85 return n;
86 });
88 return (
89 <div className="app">
90 <header className="topbar">
91 <h1>Rip Sound Analyzer</h1>
92 <nav className="tabs" role="tablist">
93 {(
94 [
95 ["record", "Record & inspect"],
96 ["compare", `Compare (${included.length})`],
97 ["about", "What this can tell you"],
98 ] as [Tab, string][]
99 ).map(([t, name]) => (
100 <button key={t} role="tab" aria-selected={tab === t} className={tab === t ? "on" : ""} onClick={() => setTab(t)}>
101 {name}
102 </button>
103 ))}
104 </nav>
105 <button className="settings-btn" onClick={() => setShowSettings((s) => !s)} aria-expanded={showSettings}>
106 Analysis settings
107 </button>
108 </header>
110 {showSettings && <SettingsPanel settings={settings} setSettings={setSettings} />}
112 <div className="layout">
113 <aside className="sidebar" aria-label="Recordings">
114 <div className="side-head">
115 <span>Recordings</span>
116 <span className="muted">tick = in comparison</span>
117 </div>
118 {loaded && !recs.length && <p className="muted pad">No recordings yet. Enable the microphone and record a tear.</p>}
119 {groups.map((g) => {
120 const members = recs.filter((r) => r.label === g);
121 const st = groupStyle(g, recs);
122 const allOn = members.every((m) => !excluded.has(m.id));
123 return (
124 <div key={g} className="group">
125 <label className="group-head">
126 <input type="checkbox" checked={allOn} onChange={(e) => toggle(members.map((m) => m.id), e.target.checked)} />
127 <i className="swatch" style={{ background: colorFor(st.slot, th.series, th.muted) }} />
128 <span className="group-name">{g}</span>
129 <span className="muted">{members.length}</span>
130 </label>
131 {members.map((m) => (
132 <div key={m.id} className={`item ${m.id === selected ? "sel" : ""}`}>
133 <input
134 type="checkbox"
135 checked={!excluded.has(m.id)}
136 onChange={(e) => toggle([m.id], e.target.checked)}
137 aria-label="Include in comparison"
138 />
139 <button
140 className="item-btn"
141 onClick={() => {
142 setSelected(m.id);
143 setTab("record");
144 }}
145 >
146 <span>{m.segment ? fmtSec(m.segment.end - m.segment.start) : "no tear found"}</span>
147 <span className="muted">
148 {new Date(m.createdAt).toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" })}
149 {m.source !== "mic" ? ` · ${m.source}` : ""}
150 </span>
151 </button>
152 </div>
153 ))}
154 </div>
155 );
156 })}
157 <p className="muted pad small">Stored only in this browser. Use “Download WAV” to keep copies.</p>
158 </aside>
160 <main className="main">
161 {tab === "record" && (
162 <>
163 <RecordBar label={label} setLabel={setLabel} knownLabels={knownLabels} onNew={onNew} />
164 {current ? (
165 <RecordingView key={current.id} meta={current} all={recs} settings={settings} onUpdate={onUpdate} onDelete={onDelete} />
166 ) : (
167 loaded && <div className="card empty">Your recordings will appear here.</div>
168 )}
169 </>
170 )}
171 {tab === "compare" && (
172 <CompareView
173 recs={included}
174 all={recs}
175 settings={settings}
176 onOpen={(id) => {
177 setSelected(id);
178 setTab("record");
179 }}
180 />
181 )}
182 {tab === "about" && <About settings={settings} />}
183 </main>
184 </div>
185 </div>
186 );
189function SettingsPanel({ settings, setSettings }: { settings: AnalysisSettings; setSettings: (s: AnalysisSettings) => void }) {
190 const [d, setD] = useState(settings);
191 const changed = JSON.stringify(d) !== JSON.stringify(settings);
192 const field = (k: keyof AnalysisSettings, label: string, unit: string) => (
193 <label>
194 {label}
195 <input type="number" value={d[k]} min={0} onChange={(e) => setD({ ...d, [k]: +e.target.value })} />
196 {unit}
197 </label>
198 );
199 return (
200 <div className="settings card">
201 {field("bandLow", "Analysis band from", "Hz")}
202 {field("bandHigh", "to", "Hz")}
203 {field("sheetLengthIn", "Tear length", "in")}
204 <button className="primary" disabled={!changed || d.bandHigh <= d.bandLow || d.sheetLengthIn <= 0} onClick={() => setSettings(d)}>
205 Apply
206 </button>
207 <button onClick={() => setD({ bandLow: 100, bandHigh: 20000, sheetLengthIn: 11 })}>Defaults</button>
208 <span className="muted small">
209 Energy and frequency statistics only count sound inside the band. Low frequencies are mostly handling noise and room rumble; the built-in mic records little above ~20 kHz.
210 </span>
211 </div>
212 );
↑↓ move↵openescclose