Rip Sound Analyzer: record tears, inspect one, compare across speeds
25 changed files+5339−0
.gitignoreadded+3−0View file
@@ -0,0 +1,3 @@
1+node_modules
2+dist
3+.DS_Store
README.mdadded+39−0View file
@@ -0,0 +1,39 @@
1+# Rip Sound Analyzer
2+
3+A small browser app for studying the sound of tearing paper. Record yourself tearing a strip off an 11 inch sheet at different speeds, label each recording with its speed, and compare.
4+
5+The working idea: a tear is a rapid sum of tiny, similar clicks. If so, tearing faster packs the same clicks into less time, and two things should not depend on speed:
6+
7+1. the total sound energy of the tear, and
8+2. its frequency makeup.
9+
10+The app measures both for every recording and shows how they change with tear duration.
11+
12+## Running
13+
14+```bash
15+npm install
16+npm run dev
17+```
18+
19+Open the printed localhost URL in Chrome. Everything runs in the browser; recordings are stored in the browser's IndexedDB. There is no server and no account.
20+
21+`npm run build` produces a static site in `dist/` that can be hosted anywhere (HTTPS is required for microphone access, except on localhost).
22+
23+`npm test` runs sanity checks of the analysis (Parseval, synthetic tears of different durations giving the same energy and spectrum, WAV round trip).
24+
25+## What it does
26+
27+- **Record**: raw capture from the microphone, with Chrome's echo cancellation, noise suppression and auto gain turned off. Samples come straight from the audio graph via an AudioWorklet at the mic's own sample rate (32-bit float, no compression). The settings the browser actually applied are shown.
28+- **Inspect one recording**: level over time, waveform and spectrogram on a shared, zoomable time axis; the tear segment (auto-detected, adjustable by dragging its edges); the tear's energy spectral density against the background; summary numbers (duration, speed, energy, median frequency, centroid, peak, clipping, level above background).
29+- **Compare**: energy vs tear duration, median frequency / centroid / mean power vs duration, spectra overlaid per label (optionally normalised to compare shape only), straight-line trends with standard errors, and tables. CSV export.
30+- **Synthetic tears**: built exactly as the hypothesis says, to check the analysis gives flat energy and identical spectra.
31+
32+The “What this can tell you” tab in the app explains the method and its limits.
33+
34+## Layout
35+
36+- `src/analysis/` – FFT, tear detection, Welch spectra, energy and spectral statistics
37+- `src/audio/` – microphone capture, WAV encode/decode, synthetic tears
38+- `src/storage/` – IndexedDB
39+- `src/components/` – UI, including a small canvas plotting component
index.htmladded+12−0View file
@@ -0,0 +1,12 @@
1+<!doctype html>
2+<html lang="en">
3+ <head>
4+ <meta charset="UTF-8" />
5+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6+ <title>Rip Sound Analyzer</title>
7+ </head>
8+ <body>
9+ <div id="root"></div>
10+ <script type="module" src="/src/main.tsx"></script>
11+ </body>
12+</html>
package-lock.jsonadded+1390−0View file
@@ -0,0 +1,1390 @@
1+{
2+ "name": "rip-sound-analyzer",
3+ "version": "0.1.0",
4+ "lockfileVersion": 3,
5+ "requires": true,
6+ "packages": {
7+ "": {
8+ "name": "rip-sound-analyzer",
9+ "version": "0.1.0",
10+ "dependencies": {
11+ "react": "^19.3.1",
12+ "react-dom": "^19.3.1"
13+ },
14+ "devDependencies": {
15+ "@types/react": "^19.0.0",
16+ "@types/react-dom": "^19.0.0",
17+ "@vitejs/plugin-react": "^6.3.0",
18+ "typescript": "^7.0.2",
19+ "vite": "^8.3.8"
20+ }
21+ },
22+ "node_modules/@emnapi/core": {
23+ "version": "2.0.0-beta.2",
24+ "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz",
25+ "integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==",
26+ "dev": true,
27+ "license": "MIT",
28+ "optional": true,
29+ "dependencies": {
30+ "@emnapi/wasi-threads": "2.2.0",
31+ "tslib": "^2.4.0"
32+ }
33+ },
34+ "node_modules/@emnapi/runtime": {
35+ "version": "2.0.0-beta.2",
36+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz",
37+ "integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==",
38+ "dev": true,
39+ "license": "MIT",
40+ "optional": true,
41+ "dependencies": {
42+ "tslib": "^2.4.0"
43+ }
44+ },
45+ "node_modules/@emnapi/wasi-threads": {
46+ "version": "2.2.0",
47+ "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz",
48+ "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==",
49+ "dev": true,
50+ "license": "MIT",
51+ "optional": true,
52+ "dependencies": {
53+ "tslib": "^2.4.0"
54+ }
55+ },
56+ "node_modules/@napi-rs/wasm-runtime": {
57+ "version": "1.2.6",
58+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz",
59+ "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==",
60+ "dev": true,
61+ "license": "MIT",
62+ "optional": true,
63+ "dependencies": {
64+ "@tybys/wasm-util": "^0.10.3"
65+ },
66+ "engines": {
67+ "node": "^20.19.0 || ^22.13.0 || >=23.5.0"
68+ },
69+ "funding": {
70+ "type": "github",
71+ "url": "https://github.com/sponsors/Brooooooklyn"
72+ },
73+ "peerDependencies": {
74+ "@emnapi/core": "^1.7.1 || 2.0.0-beta.2",
75+ "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2"
76+ }
77+ },
78+ "node_modules/@oxc-project/types": {
79+ "version": "0.156.0",
80+ "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz",
81+ "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==",
82+ "dev": true,
83+ "license": "MIT",
84+ "funding": {
85+ "url": "https://github.com/sponsors/oxc-project"
86+ }
87+ },
88+ "node_modules/@rolldown/binding-android-arm-eabi": {
89+ "version": "1.2.19",
90+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz",
91+ "integrity": "sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==",
92+ "cpu": [
93+ "arm"
94+ ],
95+ "dev": true,
96+ "license": "MIT",
97+ "optional": true,
98+ "os": [
99+ "android"
100+ ],
101+ "engines": {
102+ "node": "^20.19.0 || >=22.12.0"
103+ }
104+ },
105+ "node_modules/@rolldown/binding-android-arm64": {
106+ "version": "1.2.19",
107+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.19.tgz",
108+ "integrity": "sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==",
109+ "cpu": [
110+ "arm64"
111+ ],
112+ "dev": true,
113+ "license": "MIT",
114+ "optional": true,
115+ "os": [
116+ "android"
117+ ],
118+ "engines": {
119+ "node": "^20.19.0 || >=22.12.0"
120+ }
121+ },
122+ "node_modules/@rolldown/binding-darwin-arm64": {
123+ "version": "1.2.19",
124+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.19.tgz",
125+ "integrity": "sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==",
126+ "cpu": [
127+ "arm64"
128+ ],
129+ "dev": true,
130+ "license": "MIT",
131+ "optional": true,
132+ "os": [
133+ "darwin"
134+ ],
135+ "engines": {
136+ "node": "^20.19.0 || >=22.12.0"
137+ }
138+ },
139+ "node_modules/@rolldown/binding-darwin-x64": {
140+ "version": "1.2.19",
141+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.19.tgz",
142+ "integrity": "sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==",
143+ "cpu": [
144+ "x64"
145+ ],
146+ "dev": true,
147+ "license": "MIT",
148+ "optional": true,
149+ "os": [
150+ "darwin"
151+ ],
152+ "engines": {
153+ "node": "^20.19.0 || >=22.12.0"
154+ }
155+ },
156+ "node_modules/@rolldown/binding-freebsd-x64": {
157+ "version": "1.2.19",
158+ "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.19.tgz",
159+ "integrity": "sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==",
160+ "cpu": [
161+ "x64"
162+ ],
163+ "dev": true,
164+ "license": "MIT",
165+ "optional": true,
166+ "os": [
167+ "freebsd"
168+ ],
169+ "engines": {
170+ "node": "^20.19.0 || >=22.12.0"
171+ }
172+ },
173+ "node_modules/@rolldown/binding-linux-arm-gnueabihf": {
174+ "version": "1.2.19",
175+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.19.tgz",
176+ "integrity": "sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==",
177+ "cpu": [
178+ "arm"
179+ ],
180+ "dev": true,
181+ "license": "MIT",
182+ "optional": true,
183+ "os": [
184+ "linux"
185+ ],
186+ "engines": {
187+ "node": "^20.19.0 || >=22.12.0"
188+ }
189+ },
190+ "node_modules/@rolldown/binding-linux-arm64-gnu": {
191+ "version": "1.2.19",
192+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.19.tgz",
193+ "integrity": "sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==",
194+ "cpu": [
195+ "arm64"
196+ ],
197+ "dev": true,
198+ "libc": [
199+ "glibc"
200+ ],
201+ "license": "MIT",
202+ "optional": true,
203+ "os": [
204+ "linux"
205+ ],
206+ "engines": {
207+ "node": "^20.19.0 || >=22.12.0"
208+ }
209+ },
210+ "node_modules/@rolldown/binding-linux-arm64-musl": {
211+ "version": "1.2.19",
212+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.19.tgz",
213+ "integrity": "sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==",
214+ "cpu": [
215+ "arm64"
216+ ],
217+ "dev": true,
218+ "libc": [
219+ "musl"
220+ ],
221+ "license": "MIT",
222+ "optional": true,
223+ "os": [
224+ "linux"
225+ ],
226+ "engines": {
227+ "node": "^20.19.0 || >=22.12.0"
228+ }
229+ },
230+ "node_modules/@rolldown/binding-linux-ppc64-gnu": {
231+ "version": "1.2.19",
232+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.19.tgz",
233+ "integrity": "sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==",
234+ "cpu": [
235+ "ppc64"
236+ ],
237+ "dev": true,
238+ "libc": [
239+ "glibc"
240+ ],
241+ "license": "MIT",
242+ "optional": true,
243+ "os": [
244+ "linux"
245+ ],
246+ "engines": {
247+ "node": "^20.19.0 || >=22.12.0"
248+ }
249+ },
250+ "node_modules/@rolldown/binding-linux-s390x-gnu": {
251+ "version": "1.2.19",
252+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.19.tgz",
253+ "integrity": "sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==",
254+ "cpu": [
255+ "s390x"
256+ ],
257+ "dev": true,
258+ "libc": [
259+ "glibc"
260+ ],
261+ "license": "MIT",
262+ "optional": true,
263+ "os": [
264+ "linux"
265+ ],
266+ "engines": {
267+ "node": "^20.19.0 || >=22.12.0"
268+ }
269+ },
270+ "node_modules/@rolldown/binding-linux-x64-gnu": {
271+ "version": "1.2.19",
272+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.19.tgz",
273+ "integrity": "sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==",
274+ "cpu": [
275+ "x64"
276+ ],
277+ "dev": true,
278+ "libc": [
279+ "glibc"
280+ ],
281+ "license": "MIT",
282+ "optional": true,
283+ "os": [
284+ "linux"
285+ ],
286+ "engines": {
287+ "node": "^20.19.0 || >=22.12.0"
288+ }
289+ },
290+ "node_modules/@rolldown/binding-linux-x64-musl": {
291+ "version": "1.2.19",
292+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.19.tgz",
293+ "integrity": "sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==",
294+ "cpu": [
295+ "x64"
296+ ],
297+ "dev": true,
298+ "libc": [
299+ "musl"
300+ ],
301+ "license": "MIT",
302+ "optional": true,
303+ "os": [
304+ "linux"
305+ ],
306+ "engines": {
307+ "node": "^20.19.0 || >=22.12.0"
308+ }
309+ },
310+ "node_modules/@rolldown/binding-openharmony-arm64": {
311+ "version": "1.2.19",
312+ "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.19.tgz",
313+ "integrity": "sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==",
314+ "cpu": [
315+ "arm64"
316+ ],
317+ "dev": true,
318+ "license": "MIT",
319+ "optional": true,
320+ "os": [
321+ "openharmony"
322+ ],
323+ "engines": {
324+ "node": "^20.19.0 || >=22.12.0"
325+ }
326+ },
327+ "node_modules/@rolldown/binding-wasm32-wasi": {
328+ "version": "1.2.19",
329+ "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.19.tgz",
330+ "integrity": "sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==",
331+ "cpu": [
332+ "wasm32"
333+ ],
334+ "dev": true,
335+ "license": "MIT",
336+ "optional": true,
337+ "dependencies": {
338+ "@emnapi/core": "2.0.0-beta.2",
339+ "@emnapi/runtime": "2.0.0-beta.2",
340+ "@napi-rs/wasm-runtime": "1.2.6"
341+ },
342+ "engines": {
343+ "node": "^20.19.0 || ^22.13.0 || >=23.5.0"
344+ }
345+ },
346+ "node_modules/@rolldown/binding-win32-arm64-msvc": {
347+ "version": "1.2.19",
348+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.19.tgz",
349+ "integrity": "sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==",
350+ "cpu": [
351+ "arm64"
352+ ],
353+ "dev": true,
354+ "license": "MIT",
355+ "optional": true,
356+ "os": [
357+ "win32"
358+ ],
359+ "engines": {
360+ "node": "^20.19.0 || >=22.12.0"
361+ }
362+ },
363+ "node_modules/@rolldown/binding-win32-x64-msvc": {
364+ "version": "1.2.19",
365+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.19.tgz",
366+ "integrity": "sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==",
367+ "cpu": [
368+ "x64"
369+ ],
370+ "dev": true,
371+ "license": "MIT",
372+ "optional": true,
373+ "os": [
374+ "win32"
375+ ],
376+ "engines": {
377+ "node": "^20.19.0 || >=22.12.0"
378+ }
379+ },
380+ "node_modules/@rolldown/pluginutils": {
381+ "version": "1.1.1",
382+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz",
383+ "integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==",
384+ "dev": true,
385+ "license": "MIT"
386+ },
387+ "node_modules/@tybys/wasm-util": {
388+ "version": "0.10.5",
389+ "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz",
390+ "integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==",
391+ "dev": true,
392+ "license": "MIT",
393+ "optional": true,
394+ "dependencies": {
395+ "tslib": "^2.4.0"
396+ }
397+ },
398+ "node_modules/@types/react": {
399+ "version": "19.3.0",
400+ "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz",
401+ "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==",
402+ "dev": true,
403+ "license": "MIT",
404+ "dependencies": {
405+ "csstype": "^3.2.2"
406+ }
407+ },
408+ "node_modules/@types/react-dom": {
409+ "version": "19.3.0",
410+ "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz",
411+ "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==",
412+ "dev": true,
413+ "license": "MIT",
414+ "peerDependencies": {
415+ "@types/react": "^19.3.0"
416+ }
417+ },
418+ "node_modules/@typescript/typescript-aix-ppc64": {
419+ "version": "7.0.2",
420+ "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",
421+ "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==",
422+ "cpu": [
423+ "ppc64"
424+ ],
425+ "dev": true,
426+ "license": "Apache-2.0",
427+ "optional": true,
428+ "os": [
429+ "aix"
430+ ],
431+ "engines": {
432+ "node": ">=16.20.0"
433+ }
434+ },
435+ "node_modules/@typescript/typescript-darwin-arm64": {
436+ "version": "7.0.2",
437+ "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz",
438+ "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==",
439+ "cpu": [
440+ "arm64"
441+ ],
442+ "dev": true,
443+ "license": "Apache-2.0",
444+ "optional": true,
445+ "os": [
446+ "darwin"
447+ ],
448+ "engines": {
449+ "node": ">=16.20.0"
450+ }
451+ },
452+ "node_modules/@typescript/typescript-darwin-x64": {
453+ "version": "7.0.2",
454+ "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz",
455+ "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==",
456+ "cpu": [
457+ "x64"
458+ ],
459+ "dev": true,
460+ "license": "Apache-2.0",
461+ "optional": true,
462+ "os": [
463+ "darwin"
464+ ],
465+ "engines": {
466+ "node": ">=16.20.0"
467+ }
468+ },
469+ "node_modules/@typescript/typescript-freebsd-arm64": {
470+ "version": "7.0.2",
471+ "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz",
472+ "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==",
473+ "cpu": [
474+ "arm64"
475+ ],
476+ "dev": true,
477+ "license": "Apache-2.0",
478+ "optional": true,
479+ "os": [
480+ "freebsd"
481+ ],
482+ "engines": {
483+ "node": ">=16.20.0"
484+ }
485+ },
486+ "node_modules/@typescript/typescript-freebsd-x64": {
487+ "version": "7.0.2",
488+ "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz",
489+ "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==",
490+ "cpu": [
491+ "x64"
492+ ],
493+ "dev": true,
494+ "license": "Apache-2.0",
495+ "optional": true,
496+ "os": [
497+ "freebsd"
498+ ],
499+ "engines": {
500+ "node": ">=16.20.0"
501+ }
502+ },
503+ "node_modules/@typescript/typescript-linux-arm": {
504+ "version": "7.0.2",
505+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz",
506+ "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==",
507+ "cpu": [
508+ "arm"
509+ ],
510+ "dev": true,
511+ "license": "Apache-2.0",
512+ "optional": true,
513+ "os": [
514+ "linux"
515+ ],
516+ "engines": {
517+ "node": ">=16.20.0"
518+ }
519+ },
520+ "node_modules/@typescript/typescript-linux-arm64": {
521+ "version": "7.0.2",
522+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz",
523+ "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==",
524+ "cpu": [
525+ "arm64"
526+ ],
527+ "dev": true,
528+ "license": "Apache-2.0",
529+ "optional": true,
530+ "os": [
531+ "linux"
532+ ],
533+ "engines": {
534+ "node": ">=16.20.0"
535+ }
536+ },
537+ "node_modules/@typescript/typescript-linux-loong64": {
538+ "version": "7.0.2",
539+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz",
540+ "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==",
541+ "cpu": [
542+ "loong64"
543+ ],
544+ "dev": true,
545+ "license": "Apache-2.0",
546+ "optional": true,
547+ "os": [
548+ "linux"
549+ ],
550+ "engines": {
551+ "node": ">=16.20.0"
552+ }
553+ },
554+ "node_modules/@typescript/typescript-linux-mips64el": {
555+ "version": "7.0.2",
556+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz",
557+ "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==",
558+ "cpu": [
559+ "mips64el"
560+ ],
561+ "dev": true,
562+ "license": "Apache-2.0",
563+ "optional": true,
564+ "os": [
565+ "linux"
566+ ],
567+ "engines": {
568+ "node": ">=16.20.0"
569+ }
570+ },
571+ "node_modules/@typescript/typescript-linux-ppc64": {
572+ "version": "7.0.2",
573+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz",
574+ "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==",
575+ "cpu": [
576+ "ppc64"
577+ ],
578+ "dev": true,
579+ "license": "Apache-2.0",
580+ "optional": true,
581+ "os": [
582+ "linux"
583+ ],
584+ "engines": {
585+ "node": ">=16.20.0"
586+ }
587+ },
588+ "node_modules/@typescript/typescript-linux-riscv64": {
589+ "version": "7.0.2",
590+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz",
591+ "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==",
592+ "cpu": [
593+ "riscv64"
594+ ],
595+ "dev": true,
596+ "license": "Apache-2.0",
597+ "optional": true,
598+ "os": [
599+ "linux"
600+ ],
601+ "engines": {
602+ "node": ">=16.20.0"
603+ }
604+ },
605+ "node_modules/@typescript/typescript-linux-s390x": {
606+ "version": "7.0.2",
607+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz",
608+ "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==",
609+ "cpu": [
610+ "s390x"
611+ ],
612+ "dev": true,
613+ "license": "Apache-2.0",
614+ "optional": true,
615+ "os": [
616+ "linux"
617+ ],
618+ "engines": {
619+ "node": ">=16.20.0"
620+ }
621+ },
622+ "node_modules/@typescript/typescript-linux-x64": {
623+ "version": "7.0.2",
624+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz",
625+ "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==",
626+ "cpu": [
627+ "x64"
628+ ],
629+ "dev": true,
630+ "license": "Apache-2.0",
631+ "optional": true,
632+ "os": [
633+ "linux"
634+ ],
635+ "engines": {
636+ "node": ">=16.20.0"
637+ }
638+ },
639+ "node_modules/@typescript/typescript-netbsd-arm64": {
640+ "version": "7.0.2",
641+ "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz",
642+ "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==",
643+ "cpu": [
644+ "arm64"
645+ ],
646+ "dev": true,
647+ "license": "Apache-2.0",
648+ "optional": true,
649+ "os": [
650+ "netbsd"
651+ ],
652+ "engines": {
653+ "node": ">=16.20.0"
654+ }
655+ },
656+ "node_modules/@typescript/typescript-netbsd-x64": {
657+ "version": "7.0.2",
658+ "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz",
659+ "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==",
660+ "cpu": [
661+ "x64"
662+ ],
663+ "dev": true,
664+ "license": "Apache-2.0",
665+ "optional": true,
666+ "os": [
667+ "netbsd"
668+ ],
669+ "engines": {
670+ "node": ">=16.20.0"
671+ }
672+ },
673+ "node_modules/@typescript/typescript-openbsd-arm64": {
674+ "version": "7.0.2",
675+ "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz",
676+ "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==",
677+ "cpu": [
678+ "arm64"
679+ ],
680+ "dev": true,
681+ "license": "Apache-2.0",
682+ "optional": true,
683+ "os": [
684+ "openbsd"
685+ ],
686+ "engines": {
687+ "node": ">=16.20.0"
688+ }
689+ },
690+ "node_modules/@typescript/typescript-openbsd-x64": {
691+ "version": "7.0.2",
692+ "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz",
693+ "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==",
694+ "cpu": [
695+ "x64"
696+ ],
697+ "dev": true,
698+ "license": "Apache-2.0",
699+ "optional": true,
700+ "os": [
701+ "openbsd"
702+ ],
703+ "engines": {
704+ "node": ">=16.20.0"
705+ }
706+ },
707+ "node_modules/@typescript/typescript-sunos-x64": {
708+ "version": "7.0.2",
709+ "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz",
710+ "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==",
711+ "cpu": [
712+ "x64"
713+ ],
714+ "dev": true,
715+ "license": "Apache-2.0",
716+ "optional": true,
717+ "os": [
718+ "sunos"
719+ ],
720+ "engines": {
721+ "node": ">=16.20.0"
722+ }
723+ },
724+ "node_modules/@typescript/typescript-win32-arm64": {
725+ "version": "7.0.2",
726+ "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz",
727+ "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==",
728+ "cpu": [
729+ "arm64"
730+ ],
731+ "dev": true,
732+ "license": "Apache-2.0",
733+ "optional": true,
734+ "os": [
735+ "win32"
736+ ],
737+ "engines": {
738+ "node": ">=16.20.0"
739+ }
740+ },
741+ "node_modules/@typescript/typescript-win32-x64": {
742+ "version": "7.0.2",
743+ "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz",
744+ "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==",
745+ "cpu": [
746+ "x64"
747+ ],
748+ "dev": true,
749+ "license": "Apache-2.0",
750+ "optional": true,
751+ "os": [
752+ "win32"
753+ ],
754+ "engines": {
755+ "node": ">=16.20.0"
756+ }
757+ },
758+ "node_modules/@vitejs/plugin-react": {
759+ "version": "6.3.0",
760+ "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.3.0.tgz",
761+ "integrity": "sha512-H9E955aVvD2F4zNHCw4eIZbIfF6xKldlh7MNu+hSU7xwQzh65lI/N+CJWqmfhi0PEjDXIt/H7T7J/4wU63KJiw==",
762+ "dev": true,
763+ "license": "MIT",
764+ "dependencies": {
765+ "@rolldown/pluginutils": "^1.0.1"
766+ },
767+ "engines": {
768+ "node": "^20.19.0 || >=22.12.0"
769+ },
770+ "peerDependencies": {
771+ "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0 || ^0.3.0",
772+ "babel-plugin-react-compiler": "^1.0.0",
773+ "oxc-transform-react": ">=0.152.0 <0.157.0",
774+ "vite": "^8.0.0"
775+ },
776+ "peerDependenciesMeta": {
777+ "@rolldown/plugin-babel": {
778+ "optional": true
779+ },
780+ "babel-plugin-react-compiler": {
781+ "optional": true
782+ },
783+ "oxc-transform-react": {
784+ "optional": true
785+ }
786+ }
787+ },
788+ "node_modules/csstype": {
789+ "version": "3.2.4",
790+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.4.tgz",
791+ "integrity": "sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ==",
792+ "dev": true,
793+ "license": "MIT"
794+ },
795+ "node_modules/detect-libc": {
796+ "version": "2.1.2",
797+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
798+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
799+ "dev": true,
800+ "license": "Apache-2.0",
801+ "engines": {
802+ "node": ">=8"
803+ }
804+ },
805+ "node_modules/fdir": {
806+ "version": "6.5.0",
807+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
808+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
809+ "dev": true,
810+ "license": "MIT",
811+ "engines": {
812+ "node": ">=12.0.0"
813+ },
814+ "peerDependencies": {
815+ "picomatch": "^3 || ^4"
816+ },
817+ "peerDependenciesMeta": {
818+ "picomatch": {
819+ "optional": true
820+ }
821+ }
822+ },
823+ "node_modules/fsevents": {
824+ "version": "2.3.3",
825+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
826+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
827+ "dev": true,
828+ "hasInstallScript": true,
829+ "license": "MIT",
830+ "optional": true,
831+ "os": [
832+ "darwin"
833+ ],
834+ "engines": {
835+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
836+ }
837+ },
838+ "node_modules/lightningcss": {
839+ "version": "1.33.0",
840+ "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
841+ "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==",
842+ "dev": true,
843+ "license": "MPL-2.0",
844+ "dependencies": {
845+ "detect-libc": "^2.0.3"
846+ },
847+ "engines": {
848+ "node": ">= 12.0.0"
849+ },
850+ "funding": {
851+ "type": "opencollective",
852+ "url": "https://opencollective.com/parcel"
853+ },
854+ "optionalDependencies": {
855+ "lightningcss-android-arm64": "1.33.0",
856+ "lightningcss-darwin-arm64": "1.33.0",
857+ "lightningcss-darwin-x64": "1.33.0",
858+ "lightningcss-freebsd-x64": "1.33.0",
859+ "lightningcss-linux-arm-gnueabihf": "1.33.0",
860+ "lightningcss-linux-arm64-gnu": "1.33.0",
861+ "lightningcss-linux-arm64-musl": "1.33.0",
862+ "lightningcss-linux-x64-gnu": "1.33.0",
863+ "lightningcss-linux-x64-musl": "1.33.0",
864+ "lightningcss-win32-arm64-msvc": "1.33.0",
865+ "lightningcss-win32-x64-msvc": "1.33.0"
866+ }
867+ },
868+ "node_modules/lightningcss-android-arm64": {
869+ "version": "1.33.0",
870+ "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz",
871+ "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==",
872+ "cpu": [
873+ "arm64"
874+ ],
875+ "dev": true,
876+ "license": "MPL-2.0",
877+ "optional": true,
878+ "os": [
879+ "android"
880+ ],
881+ "engines": {
882+ "node": ">= 12.0.0"
883+ },
884+ "funding": {
885+ "type": "opencollective",
886+ "url": "https://opencollective.com/parcel"
887+ }
888+ },
889+ "node_modules/lightningcss-darwin-arm64": {
890+ "version": "1.33.0",
891+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz",
892+ "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==",
893+ "cpu": [
894+ "arm64"
895+ ],
896+ "dev": true,
897+ "license": "MPL-2.0",
898+ "optional": true,
899+ "os": [
900+ "darwin"
901+ ],
902+ "engines": {
903+ "node": ">= 12.0.0"
904+ },
905+ "funding": {
906+ "type": "opencollective",
907+ "url": "https://opencollective.com/parcel"
908+ }
909+ },
910+ "node_modules/lightningcss-darwin-x64": {
911+ "version": "1.33.0",
912+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz",
913+ "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==",
914+ "cpu": [
915+ "x64"
916+ ],
917+ "dev": true,
918+ "license": "MPL-2.0",
919+ "optional": true,
920+ "os": [
921+ "darwin"
922+ ],
923+ "engines": {
924+ "node": ">= 12.0.0"
925+ },
926+ "funding": {
927+ "type": "opencollective",
928+ "url": "https://opencollective.com/parcel"
929+ }
930+ },
931+ "node_modules/lightningcss-freebsd-x64": {
932+ "version": "1.33.0",
933+ "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz",
934+ "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==",
935+ "cpu": [
936+ "x64"
937+ ],
938+ "dev": true,
939+ "license": "MPL-2.0",
940+ "optional": true,
941+ "os": [
942+ "freebsd"
943+ ],
944+ "engines": {
945+ "node": ">= 12.0.0"
946+ },
947+ "funding": {
948+ "type": "opencollective",
949+ "url": "https://opencollective.com/parcel"
950+ }
951+ },
952+ "node_modules/lightningcss-linux-arm-gnueabihf": {
953+ "version": "1.33.0",
954+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz",
955+ "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==",
956+ "cpu": [
957+ "arm"
958+ ],
959+ "dev": true,
960+ "license": "MPL-2.0",
961+ "optional": true,
962+ "os": [
963+ "linux"
964+ ],
965+ "engines": {
966+ "node": ">= 12.0.0"
967+ },
968+ "funding": {
969+ "type": "opencollective",
970+ "url": "https://opencollective.com/parcel"
971+ }
972+ },
973+ "node_modules/lightningcss-linux-arm64-gnu": {
974+ "version": "1.33.0",
975+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz",
976+ "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==",
977+ "cpu": [
978+ "arm64"
979+ ],
980+ "dev": true,
981+ "libc": [
982+ "glibc"
983+ ],
984+ "license": "MPL-2.0",
985+ "optional": true,
986+ "os": [
987+ "linux"
988+ ],
989+ "engines": {
990+ "node": ">= 12.0.0"
991+ },
992+ "funding": {
993+ "type": "opencollective",
994+ "url": "https://opencollective.com/parcel"
995+ }
996+ },
997+ "node_modules/lightningcss-linux-arm64-musl": {
998+ "version": "1.33.0",
999+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz",
1000+ "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==",
1001+ "cpu": [
1002+ "arm64"
1003+ ],
1004+ "dev": true,
1005+ "libc": [
1006+ "musl"
1007+ ],
1008+ "license": "MPL-2.0",
1009+ "optional": true,
1010+ "os": [
1011+ "linux"
1012+ ],
1013+ "engines": {
1014+ "node": ">= 12.0.0"
1015+ },
1016+ "funding": {
1017+ "type": "opencollective",
1018+ "url": "https://opencollective.com/parcel"
1019+ }
1020+ },
1021+ "node_modules/lightningcss-linux-x64-gnu": {
1022+ "version": "1.33.0",
1023+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz",
1024+ "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==",
1025+ "cpu": [
1026+ "x64"
1027+ ],
1028+ "dev": true,
1029+ "libc": [
1030+ "glibc"
1031+ ],
1032+ "license": "MPL-2.0",
1033+ "optional": true,
1034+ "os": [
1035+ "linux"
1036+ ],
1037+ "engines": {
1038+ "node": ">= 12.0.0"
1039+ },
1040+ "funding": {
1041+ "type": "opencollective",
1042+ "url": "https://opencollective.com/parcel"
1043+ }
1044+ },
1045+ "node_modules/lightningcss-linux-x64-musl": {
1046+ "version": "1.33.0",
1047+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz",
1048+ "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==",
1049+ "cpu": [
1050+ "x64"
1051+ ],
1052+ "dev": true,
1053+ "libc": [
1054+ "musl"
1055+ ],
1056+ "license": "MPL-2.0",
1057+ "optional": true,
1058+ "os": [
1059+ "linux"
1060+ ],
1061+ "engines": {
1062+ "node": ">= 12.0.0"
1063+ },
1064+ "funding": {
1065+ "type": "opencollective",
1066+ "url": "https://opencollective.com/parcel"
1067+ }
1068+ },
1069+ "node_modules/lightningcss-win32-arm64-msvc": {
1070+ "version": "1.33.0",
1071+ "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz",
1072+ "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==",
1073+ "cpu": [
1074+ "arm64"
1075+ ],
1076+ "dev": true,
1077+ "license": "MPL-2.0",
1078+ "optional": true,
1079+ "os": [
1080+ "win32"
1081+ ],
1082+ "engines": {
1083+ "node": ">= 12.0.0"
1084+ },
1085+ "funding": {
1086+ "type": "opencollective",
1087+ "url": "https://opencollective.com/parcel"
1088+ }
1089+ },
1090+ "node_modules/lightningcss-win32-x64-msvc": {
1091+ "version": "1.33.0",
1092+ "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz",
1093+ "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==",
1094+ "cpu": [
1095+ "x64"
1096+ ],
1097+ "dev": true,
1098+ "license": "MPL-2.0",
1099+ "optional": true,
1100+ "os": [
1101+ "win32"
1102+ ],
1103+ "engines": {
1104+ "node": ">= 12.0.0"
1105+ },
1106+ "funding": {
1107+ "type": "opencollective",
1108+ "url": "https://opencollective.com/parcel"
1109+ }
1110+ },
1111+ "node_modules/nanoid": {
1112+ "version": "3.3.20",
1113+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
1114+ "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
1115+ "dev": true,
1116+ "funding": [
1117+ {
1118+ "type": "github",
1119+ "url": "https://github.com/sponsors/ai"
1120+ }
1121+ ],
1122+ "license": "MIT",
1123+ "bin": {
1124+ "nanoid": "bin/nanoid.cjs"
1125+ },
1126+ "engines": {
1127+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
1128+ }
1129+ },
1130+ "node_modules/picocolors": {
1131+ "version": "1.1.1",
1132+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
1133+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
1134+ "dev": true,
1135+ "license": "ISC"
1136+ },
1137+ "node_modules/picomatch": {
1138+ "version": "4.0.7",
1139+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
1140+ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
1141+ "dev": true,
1142+ "license": "MIT",
1143+ "engines": {
1144+ "node": ">=12"
1145+ },
1146+ "funding": {
1147+ "url": "https://github.com/sponsors/jonschlinkert"
1148+ }
1149+ },
1150+ "node_modules/postcss": {
1151+ "version": "8.5.33",
1152+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz",
1153+ "integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==",
1154+ "dev": true,
1155+ "funding": [
1156+ {
1157+ "type": "opencollective",
1158+ "url": "https://opencollective.com/postcss/"
1159+ },
1160+ {
1161+ "type": "tidelift",
1162+ "url": "https://tidelift.com/funding/github/npm/postcss"
1163+ },
1164+ {
1165+ "type": "github",
1166+ "url": "https://github.com/sponsors/ai"
1167+ }
1168+ ],
1169+ "license": "MIT",
1170+ "dependencies": {
1171+ "nanoid": "^3.3.20",
1172+ "picocolors": "^1.1.1",
1173+ "source-map-js": "^1.2.2"
1174+ },
1175+ "engines": {
1176+ "node": "^10 || ^12 || >=14"
1177+ }
1178+ },
1179+ "node_modules/react": {
1180+ "version": "19.3.1",
1181+ "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz",
1182+ "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==",
1183+ "license": "MIT",
1184+ "engines": {
1185+ "node": ">=0.10.0"
1186+ }
1187+ },
1188+ "node_modules/react-dom": {
1189+ "version": "19.3.1",
1190+ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz",
1191+ "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==",
1192+ "license": "MIT",
1193+ "dependencies": {
1194+ "scheduler": "^0.28.0"
1195+ },
1196+ "peerDependencies": {
1197+ "react": "^19.3.1"
1198+ }
1199+ },
1200+ "node_modules/rolldown": {
1201+ "version": "1.2.19",
1202+ "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz",
1203+ "integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==",
1204+ "dev": true,
1205+ "license": "MIT",
1206+ "dependencies": {
1207+ "@oxc-project/types": "=0.156.0",
1208+ "@rolldown/pluginutils": "^1.0.0"
1209+ },
1210+ "bin": {
1211+ "rolldown": "bin/cli.mjs"
1212+ },
1213+ "engines": {
1214+ "node": "^20.19.0 || >=22.12.0"
1215+ },
1216+ "optionalDependencies": {
1217+ "@rolldown/binding-android-arm-eabi": "1.2.19",
1218+ "@rolldown/binding-android-arm64": "1.2.19",
1219+ "@rolldown/binding-darwin-arm64": "1.2.19",
1220+ "@rolldown/binding-darwin-x64": "1.2.19",
1221+ "@rolldown/binding-freebsd-x64": "1.2.19",
1222+ "@rolldown/binding-linux-arm-gnueabihf": "1.2.19",
1223+ "@rolldown/binding-linux-arm64-gnu": "1.2.19",
1224+ "@rolldown/binding-linux-arm64-musl": "1.2.19",
1225+ "@rolldown/binding-linux-ppc64-gnu": "1.2.19",
1226+ "@rolldown/binding-linux-s390x-gnu": "1.2.19",
1227+ "@rolldown/binding-linux-x64-gnu": "1.2.19",
1228+ "@rolldown/binding-linux-x64-musl": "1.2.19",
1229+ "@rolldown/binding-openharmony-arm64": "1.2.19",
1230+ "@rolldown/binding-wasm32-wasi": "1.2.19",
1231+ "@rolldown/binding-win32-arm64-msvc": "1.2.19",
1232+ "@rolldown/binding-win32-x64-msvc": "1.2.19"
1233+ }
1234+ },
1235+ "node_modules/scheduler": {
1236+ "version": "0.28.0",
1237+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz",
1238+ "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==",
1239+ "license": "MIT"
1240+ },
1241+ "node_modules/source-map-js": {
1242+ "version": "1.2.3",
1243+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.3.tgz",
1244+ "integrity": "sha512-xj+WrAkyv5Qp+t7r9N5HvCBu7g1qOe6CKRNpq22X1GGcPEQADFU54v5qsPVs3/vrUFQ7XivFrcAVKA2stI0kWA==",
1245+ "dev": true,
1246+ "license": "BSD-3-Clause",
1247+ "engines": {
1248+ "node": ">=0.10.0"
1249+ }
1250+ },
1251+ "node_modules/tinyglobby": {
1252+ "version": "0.2.17",
1253+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
1254+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
1255+ "dev": true,
1256+ "license": "MIT",
1257+ "dependencies": {
1258+ "fdir": "^6.5.0",
1259+ "picomatch": "^4.0.4"
1260+ },
1261+ "engines": {
1262+ "node": ">=12.0.0"
1263+ },
1264+ "funding": {
1265+ "url": "https://github.com/sponsors/SuperchupuDev"
1266+ }
1267+ },
1268+ "node_modules/tslib": {
1269+ "version": "2.9.1",
1270+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz",
1271+ "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==",
1272+ "dev": true,
1273+ "license": "0BSD",
1274+ "optional": true
1275+ },
1276+ "node_modules/typescript": {
1277+ "version": "7.0.2",
1278+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz",
1279+ "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==",
1280+ "dev": true,
1281+ "license": "Apache-2.0",
1282+ "bin": {
1283+ "tsc": "bin/tsc"
1284+ },
1285+ "engines": {
1286+ "node": ">=16.20.0"
1287+ },
1288+ "optionalDependencies": {
1289+ "@typescript/typescript-aix-ppc64": "7.0.2",
1290+ "@typescript/typescript-darwin-arm64": "7.0.2",
1291+ "@typescript/typescript-darwin-x64": "7.0.2",
1292+ "@typescript/typescript-freebsd-arm64": "7.0.2",
1293+ "@typescript/typescript-freebsd-x64": "7.0.2",
1294+ "@typescript/typescript-linux-arm": "7.0.2",
1295+ "@typescript/typescript-linux-arm64": "7.0.2",
1296+ "@typescript/typescript-linux-loong64": "7.0.2",
1297+ "@typescript/typescript-linux-mips64el": "7.0.2",
1298+ "@typescript/typescript-linux-ppc64": "7.0.2",
1299+ "@typescript/typescript-linux-riscv64": "7.0.2",
1300+ "@typescript/typescript-linux-s390x": "7.0.2",
1301+ "@typescript/typescript-linux-x64": "7.0.2",
1302+ "@typescript/typescript-netbsd-arm64": "7.0.2",
1303+ "@typescript/typescript-netbsd-x64": "7.0.2",
1304+ "@typescript/typescript-openbsd-arm64": "7.0.2",
1305+ "@typescript/typescript-openbsd-x64": "7.0.2",
1306+ "@typescript/typescript-sunos-x64": "7.0.2",
1307+ "@typescript/typescript-win32-arm64": "7.0.2",
1308+ "@typescript/typescript-win32-x64": "7.0.2"
1309+ }
1310+ },
1311+ "node_modules/vite": {
1312+ "version": "8.3.8",
1313+ "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz",
1314+ "integrity": "sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==",
1315+ "dev": true,
1316+ "license": "MIT",
1317+ "dependencies": {
1318+ "lightningcss": "^1.33.0",
1319+ "picomatch": "^4.0.7",
1320+ "postcss": "^8.5.32",
1321+ "rolldown": "~1.2.18",
1322+ "tinyglobby": "^0.2.17"
1323+ },
1324+ "bin": {
1325+ "vite": "bin/vite.js"
1326+ },
1327+ "engines": {
1328+ "node": "^20.19.0 || >=22.12.0"
1329+ },
1330+ "funding": {
1331+ "url": "https://github.com/vitejs/vite?sponsor=1"
1332+ },
1333+ "optionalDependencies": {
1334+ "fsevents": "~2.3.3"
1335+ },
1336+ "peerDependencies": {
1337+ "@types/node": "^20.19.0 || >=22.12.0",
1338+ "@vitejs/devtools": "^0.7.1 || ^0.8.0",
1339+ "esbuild": "^0.27.0 || ^0.28.0",
1340+ "jiti": ">=1.21.0",
1341+ "less": "^4.0.0",
1342+ "sass": "^1.70.0",
1343+ "sass-embedded": "^1.70.0",
1344+ "stylus": ">=0.54.8",
1345+ "sugarss": "^5.0.0",
1346+ "terser": "^5.16.0",
1347+ "tsx": "^4.8.1",
1348+ "yaml": "^2.4.2"
1349+ },
1350+ "peerDependenciesMeta": {
1351+ "@types/node": {
1352+ "optional": true
1353+ },
1354+ "@vitejs/devtools": {
1355+ "optional": true
1356+ },
1357+ "esbuild": {
1358+ "optional": true
1359+ },
1360+ "jiti": {
1361+ "optional": true
1362+ },
1363+ "less": {
1364+ "optional": true
1365+ },
1366+ "sass": {
1367+ "optional": true
1368+ },
1369+ "sass-embedded": {
1370+ "optional": true
1371+ },
1372+ "stylus": {
1373+ "optional": true
1374+ },
1375+ "sugarss": {
1376+ "optional": true
1377+ },
1378+ "terser": {
1379+ "optional": true
1380+ },
1381+ "tsx": {
1382+ "optional": true
1383+ },
1384+ "yaml": {
1385+ "optional": true
1386+ }
1387+ }
1388+ }
1389+ }
1390+}
package.jsonadded+24−0View file
@@ -0,0 +1,24 @@
1+{
2+ "name": "rip-sound-analyzer",
3+ "private": true,
4+ "version": "0.1.0",
5+ "type": "module",
6+ "scripts": {
7+ "dev": "vite",
8+ "build": "tsc --noEmit && vite build",
9+ "preview": "vite preview",
10+ "typecheck": "tsc --noEmit",
11+ "test": "node --experimental-strip-types scripts/check-analysis.ts"
12+ },
13+ "dependencies": {
14+ "react": "^19.3.1",
15+ "react-dom": "^19.3.1"
16+ },
17+ "devDependencies": {
18+ "@types/react": "^19.0.0",
19+ "@types/react-dom": "^19.0.0",
20+ "@vitejs/plugin-react": "^6.3.0",
21+ "typescript": "^7.0.2",
22+ "vite": "^8.3.8"
23+ }
24+}
scripts/check-analysis.tsadded+56−0View file
@@ -0,0 +1,56 @@
1+// Sanity checks for the analysis, run with `npm test`.
2+import { analyze, detectSegment, DEFAULT_SETTINGS } from "../src/analysis/analyze.ts";
3+import { syntheticTear } from "../src/audio/synthetic.ts";
4+import { decodeWav, encodeWavFloat32 } from "../src/audio/wav.ts";
5+
6+let failed = 0;
7+function check(name: string, ok: boolean, detail = "") {
8+ console.log(`${ok ? "ok " : "FAIL"} ${name}${detail ? " " + detail : ""}`);
9+ if (!ok) failed++;
10+}
11+
12+const fs = 48000;
13+
14+// Parseval: white noise of known power, full band
15+{
16+ const x = new Float32Array(fs * 2);
17+ let s = 7;
18+ for (let i = 0; i < x.length; i++) {
19+ s = (s * 1103515245 + 12345) & 0x7fffffff;
20+ x[i] = (s / 0x7fffffff - 0.5) * 0.2;
21+ }
22+ let e = 0;
23+ for (const v of x) e += v * v;
24+ e /= fs;
25+ const a = analyze(x, fs, { start: 0, end: 2 }, { ...DEFAULT_SETTINGS, bandLow: 0, bandHigh: fs / 2 });
26+ check("Parseval (energy of white noise)", Math.abs(a.energyRaw / e - 1) < 0.02, `${a.energyRaw.toExponential(3)} vs ${e.toExponential(3)}`);
27+}
28+
29+// Synthetic tears: same clicks at different durations
30+const results: { T: number; energyDb: number; median: number; seg: [number, number] }[] = [];
31+for (const T of [0.3, 1, 3, 10]) {
32+ const x = syntheticTear({ tearSeconds: T, seed: 3 });
33+ const seg = detectSegment(x, fs);
34+ check(`detect segment T=${T}`, !!seg && Math.abs(seg.start - 1) < 0.08 && Math.abs(seg.end - (1 + T)) < 0.08, seg ? `${seg.start.toFixed(3)}–${seg.end.toFixed(3)}` : "none");
35+ if (!seg) continue;
36+ const a = analyze(x, fs, seg, DEFAULT_SETTINGS);
37+ results.push({ T, energyDb: 10 * Math.log10(a.energy), median: a.medianFreq, seg: [seg.start, seg.end] });
38+ console.log(` T=${T}s energy=${(10 * Math.log10(a.energy)).toFixed(2)} dB snr=${a.snrDb.toFixed(1)} dB median=${a.medianFreq.toFixed(0)} Hz centroid=${a.centroid.toFixed(0)} Hz peak=${a.peakDbfs.toFixed(1)} dBFS`);
39+}
40+const es = results.map((r) => r.energyDb);
41+check("synthetic energy independent of duration (range < 1 dB)", Math.max(...es) - Math.min(...es) < 1);
42+const ms = results.map((r) => r.median);
43+check("synthetic median frequency independent of duration (range < 10%)", Math.max(...ms) / Math.min(...ms) < 1.1);
44+
45+// WAV round trip
46+{
47+ const x = syntheticTear({ tearSeconds: 0.5 });
48+ const blob = encodeWavFloat32(x, fs);
49+ const d = decodeWav(await blob.arrayBuffer());
50+ check("WAV float32 round trip", !!d && d.sampleRate === fs && d.samples.length === x.length && d.samples.every((v, i) => v === x[i]));
51+}
52+
53+if (failed) {
54+ console.log(`${failed} check(s) failed`);
55+ throw new Error("checks failed");
56+}
src/App.tsxadded+213−0View file
@@ -0,0 +1,213 @@
1+import { useEffect, useMemo, useState } from "react";
2+import { RecordBar } from "./components/RecordBar.tsx";
3+import { RecordingView } from "./components/RecordingView.tsx";
4+import { CompareView } from "./components/CompareView.tsx";
5+import { About } from "./components/About.tsx";
6+import { readTheme } from "./components/CanvasPlot.tsx";
7+import { deleteRecording, listRecordings, saveRecording, updateMeta, type RecordingMeta } from "./storage/db.ts";
8+import { colorFor, fmtSec, forgetAudio, groupOrder, groupStyle, loadSettings, PRESET_LABELS, putAudio, storeSettings } from "./model.ts";
9+import type { AnalysisSettings } from "./analysis/analyze.ts";
10+
11+type Tab = "record" | "compare" | "about";
12+
13+function loadExcluded(): Set<string> {
14+ try {
15+ return new Set(JSON.parse(localStorage.getItem("rsa-excluded") ?? "[]"));
16+ } catch {
17+ return new Set();
18+ }
19+}
20+
21+export 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);
30+
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+ }, []);
39+
40+ useEffect(() => {
41+ try {
42+ localStorage.setItem("rsa-excluded", JSON.stringify([...excluded]));
43+ } catch {
44+ /* ignore */
45+ }
46+ }, [excluded]);
47+
48+ const setSettings = (s: AnalysisSettings) => {
49+ setSettingsState(s);
50+ storeSettings(s);
51+ };
52+
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+ };
74+
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);
80+
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+ });
87+
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>
109+
110+ {showSettings && <SettingsPanel settings={settings} setSettings={setSettings} />}
111+
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>
159+
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+ );
187+}
188+
189+function 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+ );
213+}
src/analysis/analyze.tsadded+362−0View file
@@ -0,0 +1,362 @@
1+import { fft, hann } from "./fft.ts";
2+
3+export interface Segment {
4+ start: number; // seconds
5+ end: number;
6+}
7+
8+export interface AnalysisSettings {
9+ bandLow: number; // Hz
10+ bandHigh: number; // Hz
11+ sheetLengthIn: number; // length of the tear, inches
12+}
13+
14+export const DEFAULT_SETTINGS: AnalysisSettings = {
15+ bandLow: 100,
16+ bandHigh: 20000,
17+ sheetLengthIn: 11,
18+};
19+
20+export const NFFT = 2048;
21+
22+// ---------- level over time ----------
23+
24+export interface Levels {
25+ frameSec: number;
26+ power: Float64Array; // mean square per frame (FS^2)
27+}
28+
29+export function frameLevels(x: Float32Array, fs: number, frameSec = 0.01): Levels {
30+ const n = Math.max(1, Math.round(frameSec * fs));
31+ const count = Math.ceil(x.length / n);
32+ const power = new Float64Array(count);
33+ for (let f = 0; f < count; f++) {
34+ let s = 0;
35+ const a = f * n;
36+ const b = Math.min(x.length, a + n);
37+ for (let i = a; i < b; i++) s += x[i] * x[i];
38+ power[f] = s / Math.max(1, b - a);
39+ }
40+ return { frameSec: n / fs, power };
41+}
42+
43+function percentile(values: ArrayLike<number>, p: number): number {
44+ const a = Array.from(values).sort((u, v) => u - v);
45+ if (!a.length) return 0;
46+ return a[Math.min(a.length - 1, Math.max(0, Math.floor(p * (a.length - 1))))];
47+}
48+
49+// Finds the tear: the most energetic stretch of sound well above the background.
50+// Short gaps (< 0.6 s) inside the tear are bridged. Returns null if nothing stands out.
51+export function detectSegment(x: Float32Array, fs: number): Segment | null {
52+ const { frameSec, power } = frameLevels(x, fs, 0.01);
53+ const m = power.length;
54+ if (m < 10) return null;
55+ const smoothN = 5; // 50 ms moving average
56+ const s = new Float64Array(m);
57+ let acc = 0;
58+ for (let i = 0; i < m; i++) {
59+ acc += power[i];
60+ if (i >= smoothN) acc -= power[i - smoothN];
61+ s[i] = acc / Math.min(i + 1, smoothN);
62+ }
63+ const noise = Math.max(percentile(s, 0.1), 1e-14);
64+ const thresh = noise * 10 ** (12 / 10);
65+ const maxGap = Math.round(0.6 / frameSec);
66+ const regions: { a: number; b: number; e: number }[] = [];
67+ let cur: { a: number; b: number; e: number } | null = null;
68+ for (let i = 0; i < m; i++) {
69+ if (s[i] > thresh) {
70+ if (cur && i - cur.b <= maxGap) cur.b = i;
71+ else {
72+ if (cur) regions.push(cur);
73+ cur = { a: i, b: i, e: 0 };
74+ }
75+ }
76+ }
77+ if (cur) regions.push(cur);
78+ if (!regions.length) return null;
79+ for (const r of regions) {
80+ let e = 0;
81+ for (let i = r.a; i <= r.b; i++) e += Math.max(0, power[i] - noise);
82+ r.e = e;
83+ }
84+ regions.sort((u, v) => v.e - u.e);
85+ const best = regions[0];
86+ // smoothing shifts the onset earlier by up to one window; trim back to raw frames above threshold
87+ let a = best.a;
88+ let b = best.b;
89+ while (a < b && power[a] <= thresh) a++;
90+ while (b > a && power[b] <= thresh) b--;
91+ const pad = 0.03;
92+ const dur = x.length / fs;
93+ return {
94+ start: Math.max(0, a * frameSec - pad),
95+ end: Math.min(dur, (b + 1) * frameSec + pad),
96+ };
97+}
98+
99+// ---------- spectra ----------
100+
101+// One-sided periodograms (FS^2/Hz) of Hann-windowed frames of x[a..b), hop = half frame.
102+// Frames shorter than NFFT (only when the range itself is short) are zero-padded so the
103+// frequency grid is always the same.
104+function periodograms(x: Float32Array, fs: number, a: number, b: number, nfft: number): Float64Array[] {
105+ const len = b - a;
106+ if (len < 64) return [];
107+ const frameLen = Math.min(nfft, len);
108+ const hop = Math.max(1, Math.floor(frameLen / 2));
109+ const w = hann(frameLen);
110+ let u = 0;
111+ for (let i = 0; i < frameLen; i++) u += w[i] * w[i];
112+ const nb = nfft / 2 + 1;
113+ const out: Float64Array[] = [];
114+ const re = new Float64Array(nfft);
115+ const im = new Float64Array(nfft);
116+ const count = Math.max(1, Math.floor((len - frameLen) / hop) + 1);
117+ // spread frames to cover the full range evenly
118+ const span = len - frameLen;
119+ for (let f = 0; f < count; f++) {
120+ const off = a + (count > 1 ? Math.round((f * span) / (count - 1)) : 0);
121+ re.fill(0);
122+ im.fill(0);
123+ for (let i = 0; i < frameLen; i++) re[i] = x[off + i] * w[i];
124+ fft(re, im);
125+ const p = new Float64Array(nb);
126+ for (let k = 0; k < nb; k++) {
127+ const v = (re[k] * re[k] + im[k] * im[k]) / (fs * u);
128+ p[k] = k === 0 || k === nfft / 2 ? v : 2 * v;
129+ }
130+ out.push(p);
131+ }
132+ return out;
133+}
134+
135+function meanOf(ps: Float64Array[], nb: number): Float64Array {
136+ const out = new Float64Array(nb);
137+ for (const p of ps) for (let k = 0; k < nb; k++) out[k] += p[k];
138+ for (let k = 0; k < nb; k++) out[k] /= ps.length;
139+ return out;
140+}
141+
142+// Per-bin median divided by ln 2 (median of an exponential distribution is mean * ln 2).
143+// Robust to occasional transients such as a key press.
144+function medianOf(ps: Float64Array[], nb: number): Float64Array {
145+ const out = new Float64Array(nb);
146+ const tmp = new Float64Array(ps.length);
147+ for (let k = 0; k < nb; k++) {
148+ for (let j = 0; j < ps.length; j++) tmp[j] = ps[j][k];
149+ tmp.sort();
150+ const mid = ps.length >> 1;
151+ const med = ps.length % 2 ? tmp[mid] : 0.5 * (tmp[mid - 1] + tmp[mid]);
152+ out[k] = med / Math.LN2;
153+ }
154+ return out;
155+}
156+
157+export interface Analysis {
158+ segment: Segment;
159+ duration: number; // s
160+ speedInPerSec: number;
161+ fs: number;
162+ df: number;
163+ freqs: Float64Array;
164+ esd: Float64Array; // energy spectral density of the tear segment, FS^2·s/Hz
165+ noiseEsd: Float64Array | null; // background PSD × segment duration (what background alone would contribute)
166+ netEsd: Float64Array; // max(esd - noiseEsd, 0)
167+ noiseSeconds: number; // how much background audio the noise estimate is based on
168+ energyRaw: number; // in band, FS^2·s
169+ energyNoise: number;
170+ energy: number; // energyRaw - energyNoise
171+ snrDb: number; // 10 log10(energyRaw / energyNoise)
172+ centroid: number; // Hz, of net ESD in band
173+ medianFreq: number;
174+ f10: number;
175+ f90: number;
176+ peakDbfs: number; // in the segment
177+ nearClip: number; // samples with |x| >= 0.99 in the segment
178+ backgroundDbfs: number | null; // RMS level of background in band
179+}
180+
181+export function analyze(
182+ x: Float32Array,
183+ fs: number,
184+ segment: Segment,
185+ settings: AnalysisSettings,
186+): Analysis {
187+ const nfft = NFFT;
188+ const nb = nfft / 2 + 1;
189+ const df = fs / nfft;
190+ const freqs = new Float64Array(nb);
191+ for (let k = 0; k < nb; k++) freqs[k] = k * df;
192+
193+ const a = Math.max(0, Math.floor(segment.start * fs));
194+ const b = Math.min(x.length, Math.ceil(segment.end * fs));
195+ const duration = (b - a) / fs;
196+
197+ const tearPs = periodograms(x, fs, a, b, nfft);
198+ const psd = tearPs.length ? meanOf(tearPs, nb) : new Float64Array(nb);
199+ const esd = psd.map((v) => v * duration);
200+
201+ // background: everything outside the segment, keeping clear of its edges and the file ends
202+ const margin = Math.round(0.05 * fs);
203+ const noisePs: Float64Array[] = [];
204+ let noiseSamples = 0;
205+ const ranges: [number, number][] = [
206+ [margin, a - margin],
207+ [b + margin, x.length - margin],
208+ ];
209+ for (const [ra, rb] of ranges) {
210+ if (rb - ra >= nfft) {
211+ noisePs.push(...periodograms(x, fs, ra, rb, nfft));
212+ noiseSamples += rb - ra;
213+ }
214+ }
215+ let noiseEsd: Float64Array | null = null;
216+ if (noisePs.length >= 3) noiseEsd = medianOf(noisePs, nb).map((v) => v * duration);
217+
218+ const kLo = Math.max(1, Math.ceil(settings.bandLow / df));
219+ const kHi = Math.min(nb - 1, Math.floor(Math.min(settings.bandHigh, fs / 2) / df));
220+ const netEsd = new Float64Array(nb);
221+ let energyRaw = 0;
222+ let energyNoise = 0;
223+ for (let k = 0; k < nb; k++) {
224+ netEsd[k] = Math.max(0, esd[k] - (noiseEsd ? noiseEsd[k] : 0));
225+ if (k >= kLo && k <= kHi) {
226+ energyRaw += esd[k] * df;
227+ if (noiseEsd) energyNoise += noiseEsd[k] * df;
228+ }
229+ }
230+ const energy = energyRaw - energyNoise;
231+
232+ let tot = 0;
233+ let mom = 0;
234+ for (let k = kLo; k <= kHi; k++) {
235+ tot += netEsd[k];
236+ mom += netEsd[k] * freqs[k];
237+ }
238+ const quantile = (q: number) => {
239+ let c = 0;
240+ for (let k = kLo; k <= kHi; k++) {
241+ c += netEsd[k];
242+ if (c >= q * tot) return freqs[k];
243+ }
244+ return freqs[kHi];
245+ };
246+
247+ let peak = 0;
248+ let nearClip = 0;
249+ for (let i = a; i < b; i++) {
250+ const v = Math.abs(x[i]);
251+ if (v > peak) peak = v;
252+ if (v >= 0.99) nearClip++;
253+ }
254+
255+ let backgroundDbfs: number | null = null;
256+ if (noiseEsd) {
257+ let p = 0;
258+ for (let k = kLo; k <= kHi; k++) p += (noiseEsd[k] / duration) * df;
259+ backgroundDbfs = 10 * Math.log10(Math.max(p, 1e-20));
260+ }
261+
262+ return {
263+ segment: { start: a / fs, end: b / fs },
264+ duration,
265+ speedInPerSec: settings.sheetLengthIn / duration,
266+ fs,
267+ df,
268+ freqs,
269+ esd,
270+ noiseEsd,
271+ netEsd,
272+ noiseSeconds: noiseSamples / fs,
273+ energyRaw,
274+ energyNoise,
275+ energy,
276+ snrDb: noiseEsd ? 10 * Math.log10(energyRaw / Math.max(energyNoise, 1e-30)) : Infinity,
277+ centroid: tot > 0 ? mom / tot : NaN,
278+ medianFreq: tot > 0 ? quantile(0.5) : NaN,
279+ f10: tot > 0 ? quantile(0.1) : NaN,
280+ f90: tot > 0 ? quantile(0.9) : NaN,
281+ peakDbfs: 20 * Math.log10(Math.max(peak, 1e-10)),
282+ nearClip,
283+ backgroundDbfs,
284+ };
285+}
286+
287+// Fractional-octave smoothing onto a log-spaced grid, for readable overlays.
288+export function smoothLog(
289+ freqs: Float64Array,
290+ values: Float64Array,
291+ fLo: number,
292+ fHi: number,
293+ fraction: number, // e.g. 1/6 octave; 0 = no smoothing (returns raw bins in range)
294+): { f: number[]; v: number[] } {
295+ if (fraction <= 0) {
296+ const f: number[] = [];
297+ const v: number[] = [];
298+ for (let k = 0; k < freqs.length; k++)
299+ if (freqs[k] >= fLo && freqs[k] <= fHi) {
300+ f.push(freqs[k]);
301+ v.push(values[k]);
302+ }
303+ return { f, v };
304+ }
305+ const df = freqs[1] - freqs[0];
306+ const points = Math.ceil(Math.log2(fHi / fLo) / fraction) * 2 + 1;
307+ const f: number[] = [];
308+ const v: number[] = [];
309+ for (let i = 0; i < points; i++) {
310+ const fc = fLo * 2 ** ((i * Math.log2(fHi / fLo)) / (points - 1));
311+ const lo = fc * 2 ** (-fraction / 2);
312+ const hi = fc * 2 ** (fraction / 2);
313+ let ka = Math.ceil(lo / df);
314+ let kb = Math.floor(hi / df);
315+ if (kb < ka) ka = kb = Math.round(fc / df);
316+ ka = Math.max(0, ka);
317+ kb = Math.min(freqs.length - 1, kb);
318+ let s = 0;
319+ for (let k = ka; k <= kb; k++) s += values[k];
320+ f.push(fc);
321+ v.push(s / (kb - ka + 1));
322+ }
323+ return { f, v };
324+}
325+
326+// ---------- spectrogram ----------
327+
328+export interface Spectrogram {
329+ cols: number;
330+ bins: number;
331+ dt: number; // seconds per column
332+ t0: number; // centre time of first column
333+ df: number;
334+ db: Float32Array; // cols × bins, column-major (col * bins + bin), dB re FS^2/Hz
335+ maxDb: number;
336+}
337+
338+export function spectrogram(x: Float32Array, fs: number, nfft = 1024, maxCols = 3000): Spectrogram {
339+ const hop = Math.max(nfft / 4, Math.ceil(x.length / maxCols));
340+ const cols = Math.max(1, Math.floor((x.length - nfft) / hop) + 1);
341+ const bins = nfft / 2 + 1;
342+ const w = hann(nfft);
343+ let u = 0;
344+ for (let i = 0; i < nfft; i++) u += w[i] * w[i];
345+ const db = new Float32Array(cols * bins);
346+ const re = new Float64Array(nfft);
347+ const im = new Float64Array(nfft);
348+ let maxDb = -Infinity;
349+ for (let c = 0; c < cols; c++) {
350+ const off = c * hop;
351+ im.fill(0);
352+ for (let i = 0; i < nfft; i++) re[i] = (x[off + i] ?? 0) * w[i];
353+ fft(re, im);
354+ for (let k = 0; k < bins; k++) {
355+ const p = (2 * (re[k] * re[k] + im[k] * im[k])) / (fs * u);
356+ const d = 10 * Math.log10(p + 1e-20);
357+ db[c * bins + k] = d;
358+ if (d > maxDb) maxDb = d;
359+ }
360+ }
361+ return { cols, bins, dt: hop / fs, t0: nfft / 2 / fs, df: fs / nfft, db, maxDb };
362+}
src/analysis/fft.tsadded+66−0View file
@@ -0,0 +1,66 @@
1+// In-place iterative radix-2 complex FFT. n must be a power of two.
2+
3+const twiddleCache = new Map<number, { cos: Float64Array; sin: Float64Array }>();
4+
5+function twiddles(n: number) {
6+ let t = twiddleCache.get(n);
7+ if (!t) {
8+ const cos = new Float64Array(n / 2);
9+ const sin = new Float64Array(n / 2);
10+ for (let i = 0; i < n / 2; i++) {
11+ cos[i] = Math.cos((2 * Math.PI * i) / n);
12+ sin[i] = -Math.sin((2 * Math.PI * i) / n);
13+ }
14+ t = { cos, sin };
15+ twiddleCache.set(n, t);
16+ }
17+ return t;
18+}
19+
20+export function fft(re: Float64Array, im: Float64Array): void {
21+ const n = re.length;
22+ for (let i = 1, j = 0; i < n; i++) {
23+ let bit = n >> 1;
24+ for (; j & bit; bit >>= 1) j ^= bit;
25+ j ^= bit;
26+ if (i < j) {
27+ let t = re[i];
28+ re[i] = re[j];
29+ re[j] = t;
30+ t = im[i];
31+ im[i] = im[j];
32+ im[j] = t;
33+ }
34+ }
35+ const { cos, sin } = twiddles(n);
36+ for (let size = 2; size <= n; size <<= 1) {
37+ const half = size >> 1;
38+ const step = n / size;
39+ for (let start = 0; start < n; start += size) {
40+ for (let k = 0; k < half; k++) {
41+ const wr = cos[k * step];
42+ const wi = sin[k * step];
43+ const a = start + k;
44+ const b = a + half;
45+ const xr = re[b] * wr - im[b] * wi;
46+ const xi = re[b] * wi + im[b] * wr;
47+ re[b] = re[a] - xr;
48+ im[b] = im[a] - xi;
49+ re[a] += xr;
50+ im[a] += xi;
51+ }
52+ }
53+ }
54+}
55+
56+export function hann(n: number): Float64Array {
57+ const w = new Float64Array(n);
58+ for (let i = 0; i < n; i++) w[i] = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / n);
59+ return w;
60+}
61+
62+export function largestPow2AtMost(n: number): number {
63+ let p = 1;
64+ while (p * 2 <= n) p *= 2;
65+ return p;
66+}
src/audio/recorder.tsadded+151−0View file
@@ -0,0 +1,151 @@
1+// Raw microphone capture. Browser processing (echo cancellation, noise suppression,
2+// automatic gain) is switched off and samples are taken straight from the audio graph
3+// with an AudioWorklet, so nothing is compressed or resampled by us.
4+
5+export interface CaptureInfo {
6+ deviceLabel: string;
7+ trackSettings: Record<string, unknown>;
8+ contextSampleRate: number;
9+ userAgent: string;
10+}
11+
12+const WORKLET_SRC = `
13+class Tap extends AudioWorkletProcessor {
14+ constructor() {
15+ super();
16+ this.buf = new Float32Array(4096);
17+ this.n = 0;
18+ this.on = false;
19+ this.port.onmessage = (e) => {
20+ if (e.data === 'start') { this.on = true; this.n = 0; }
21+ else if (e.data === 'stop') { this.flush(); this.on = false; this.port.postMessage({ done: true }); }
22+ };
23+ }
24+ flush() {
25+ if (this.n > 0) {
26+ const out = this.buf.slice(0, this.n);
27+ this.port.postMessage({ chunk: out }, [out.buffer]);
28+ this.n = 0;
29+ }
30+ }
31+ process(inputs) {
32+ const ch = inputs[0] && inputs[0][0];
33+ if (!ch) return true;
34+ let peak = 0;
35+ for (let i = 0; i < ch.length; i++) { const v = Math.abs(ch[i]); if (v > peak) peak = v; }
36+ this.port.postMessage({ peak });
37+ if (this.on) {
38+ for (let i = 0; i < ch.length; i++) {
39+ this.buf[this.n++] = ch[i];
40+ if (this.n === this.buf.length) this.flush();
41+ }
42+ }
43+ return true;
44+ }
45+}
46+registerProcessor('tap', Tap);
47+`;
48+
49+export const RAW_CONSTRAINTS: MediaTrackConstraints = {
50+ echoCancellation: false,
51+ noiseSuppression: false,
52+ autoGainControl: false,
53+ channelCount: 1,
54+};
55+
56+export class MicRecorder {
57+ private ctx: AudioContext | null = null;
58+ private stream: MediaStream | null = null;
59+ private node: AudioWorkletNode | null = null;
60+ private chunks: Float32Array[] = [];
61+ private stopResolve: ((x: Float32Array) => void) | null = null;
62+ onPeak: ((peak: number) => void) | null = null;
63+ info: CaptureInfo | null = null;
64+ recording = false;
65+
66+ async open(deviceId?: string): Promise<CaptureInfo> {
67+ await this.close();
68+ const stream = await navigator.mediaDevices.getUserMedia({
69+ audio: { ...RAW_CONSTRAINTS, ...(deviceId ? { deviceId: { exact: deviceId } } : {}) },
70+ });
71+ const track = stream.getAudioTracks()[0];
72+ const settings = track.getSettings() as Record<string, unknown>;
73+ // run the graph at the microphone's own rate so the browser does not resample
74+ const rate = typeof settings.sampleRate === "number" ? settings.sampleRate : undefined;
75+ const ctx = new AudioContext(rate ? { sampleRate: rate } : {});
76+ const url = URL.createObjectURL(new Blob([WORKLET_SRC], { type: "text/javascript" }));
77+ await ctx.audioWorklet.addModule(url);
78+ URL.revokeObjectURL(url);
79+ const src = ctx.createMediaStreamSource(stream);
80+ const node = new AudioWorkletNode(ctx, "tap", { numberOfInputs: 1, numberOfOutputs: 1, channelCount: 1, channelCountMode: "explicit" });
81+ const mute = ctx.createGain();
82+ mute.gain.value = 0;
83+ src.connect(node).connect(mute).connect(ctx.destination);
84+ node.port.onmessage = (e) => {
85+ const d = e.data;
86+ if (d.chunk) this.chunks.push(d.chunk);
87+ else if (d.peak !== undefined) this.onPeak?.(d.peak);
88+ else if (d.done) {
89+ const total = this.chunks.reduce((s, c) => s + c.length, 0);
90+ const out = new Float32Array(total);
91+ let o = 0;
92+ for (const c of this.chunks) {
93+ out.set(c, o);
94+ o += c.length;
95+ }
96+ this.chunks = [];
97+ this.stopResolve?.(out);
98+ this.stopResolve = null;
99+ }
100+ };
101+ if (ctx.state !== "running") await ctx.resume();
102+ this.ctx = ctx;
103+ this.stream = stream;
104+ this.node = node;
105+ this.info = {
106+ deviceLabel: track.label,
107+ trackSettings: settings,
108+ contextSampleRate: ctx.sampleRate,
109+ userAgent: navigator.userAgent,
110+ };
111+ return this.info;
112+ }
113+
114+ get sampleRate() {
115+ return this.ctx?.sampleRate ?? 0;
116+ }
117+
118+ get isOpen() {
119+ return !!this.ctx;
120+ }
121+
122+ start() {
123+ if (!this.node) throw new Error("Microphone is not open");
124+ this.chunks = [];
125+ this.recording = true;
126+ this.node.port.postMessage("start");
127+ }
128+
129+ stop(): Promise<Float32Array> {
130+ if (!this.node) return Promise.resolve(new Float32Array(0));
131+ this.recording = false;
132+ return new Promise((resolve) => {
133+ this.stopResolve = resolve;
134+ this.node!.port.postMessage("stop");
135+ });
136+ }
137+
138+ async close() {
139+ this.stream?.getTracks().forEach((t) => t.stop());
140+ if (this.ctx) await this.ctx.close();
141+ this.ctx = null;
142+ this.stream = null;
143+ this.node = null;
144+ this.recording = false;
145+ }
146+}
147+
148+export async function listInputs(): Promise<MediaDeviceInfo[]> {
149+ const all = await navigator.mediaDevices.enumerateDevices();
150+ return all.filter((d) => d.kind === "audioinput");
151+}
src/audio/synthetic.tsadded+64−0View file
@@ -0,0 +1,64 @@
1+// Synthetic "tears" built exactly as the hypothesis says: the same set of clicks
2+// (same shape, same amplitude distribution, same count) placed at random times over
3+// the tear duration. Useful for checking that the analysis behaves as expected:
4+// energy and spectrum should not depend on duration.
5+
6+function mulberry32(seed: number) {
7+ return () => {
8+ seed |= 0;
9+ seed = (seed + 0x6d2b79f5) | 0;
10+ let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
11+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
12+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
13+ };
14+}
15+
16+function gauss(rand: () => number) {
17+ const u = Math.max(rand(), 1e-12);
18+ return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * rand());
19+}
20+
21+export interface SyntheticOptions {
22+ tearSeconds: number;
23+ clicks?: number;
24+ sampleRate?: number;
25+ quietSeconds?: number; // before and after the tear
26+ backgroundDbfs?: number;
27+ seed?: number;
28+}
29+
30+export function syntheticTear(opts: SyntheticOptions): Float32Array {
31+ const fs = opts.sampleRate ?? 48000;
32+ const clicks = opts.clicks ?? 4000;
33+ const quiet = opts.quietSeconds ?? 1;
34+ const rand = mulberry32(opts.seed ?? 1);
35+
36+ // one fixed click template (same for every synthetic tear): decaying high-passed noise, ~1 ms
37+ const tRand = mulberry32(12345);
38+ const tl = Math.round(0.002 * fs);
39+ const template = new Float32Array(tl);
40+ let prev = 0;
41+ for (let i = 0; i < tl; i++) {
42+ const g = gauss(tRand);
43+ template[i] = (g - prev) * Math.exp(-i / (0.00025 * fs));
44+ prev = g;
45+ }
46+ let te = 0;
47+ for (const v of template) te += v * v;
48+ for (let i = 0; i < tl; i++) template[i] /= Math.sqrt(te);
49+
50+ const n = Math.round((2 * quiet + opts.tearSeconds) * fs);
51+ const out = new Float32Array(n);
52+ const bg = 10 ** ((opts.backgroundDbfs ?? -75) / 20);
53+ for (let i = 0; i < n; i++) out[i] = bg * gauss(rand);
54+
55+ const start = quiet * fs;
56+ const len = opts.tearSeconds * fs;
57+ for (let c = 0; c < clicks; c++) {
58+ const pos = Math.floor(start + rand() * (len - tl));
59+ // log-normal amplitudes, random polarity
60+ const amp = 0.02 * Math.exp(0.8 * gauss(rand)) * (rand() < 0.5 ? -1 : 1);
61+ for (let i = 0; i < tl; i++) out[pos + i] += amp * template[i];
62+ }
63+ return out;
64+}
src/audio/wav.tsadded+84−0View file
@@ -0,0 +1,84 @@
1+// Minimal WAV encode/decode. Export is 32-bit float so samples round-trip exactly.
2+
3+export function encodeWavFloat32(samples: Float32Array, sampleRate: number): Blob {
4+ const dataBytes = samples.length * 4;
5+ const buf = new ArrayBuffer(44 + dataBytes);
6+ const v = new DataView(buf);
7+ const str = (o: number, s: string) => {
8+ for (let i = 0; i < s.length; i++) v.setUint8(o + i, s.charCodeAt(i));
9+ };
10+ str(0, "RIFF");
11+ v.setUint32(4, 36 + dataBytes, true);
12+ str(8, "WAVE");
13+ str(12, "fmt ");
14+ v.setUint32(16, 16, true);
15+ v.setUint16(20, 3, true); // IEEE float
16+ v.setUint16(22, 1, true); // mono
17+ v.setUint32(24, sampleRate, true);
18+ v.setUint32(28, sampleRate * 4, true);
19+ v.setUint16(32, 4, true);
20+ v.setUint16(34, 32, true);
21+ str(36, "data");
22+ v.setUint32(40, dataBytes, true);
23+ new Float32Array(buf, 44).set(samples);
24+ return new Blob([buf], { type: "audio/wav" });
25+}
26+
27+export interface DecodedWav {
28+ sampleRate: number;
29+ channels: number;
30+ samples: Float32Array; // first channel only
31+}
32+
33+// Parses PCM (16/24/32-bit int) and IEEE float (32/64-bit) WAV files without resampling.
34+// Returns null for anything else.
35+export function decodeWav(buffer: ArrayBuffer): DecodedWav | null {
36+ const v = new DataView(buffer);
37+ const tag = (o: number) =>
38+ String.fromCharCode(v.getUint8(o), v.getUint8(o + 1), v.getUint8(o + 2), v.getUint8(o + 3));
39+ if (buffer.byteLength < 12 || tag(0) !== "RIFF" || tag(8) !== "WAVE") return null;
40+ let off = 12;
41+ let format = 0;
42+ let channels = 0;
43+ let sampleRate = 0;
44+ let bits = 0;
45+ let dataOff = -1;
46+ let dataLen = 0;
47+ while (off + 8 <= buffer.byteLength) {
48+ const id = tag(off);
49+ const len = v.getUint32(off + 4, true);
50+ const body = off + 8;
51+ if (id === "fmt ") {
52+ format = v.getUint16(body, true);
53+ channels = v.getUint16(body + 2, true);
54+ sampleRate = v.getUint32(body + 4, true);
55+ bits = v.getUint16(body + 14, true);
56+ if (format === 0xfffe && len >= 26) format = v.getUint16(body + 24, true); // extensible
57+ } else if (id === "data") {
58+ dataOff = body;
59+ dataLen = Math.min(len, buffer.byteLength - body);
60+ break;
61+ }
62+ off = body + len + (len % 2);
63+ }
64+ if (dataOff < 0 || channels < 1 || !sampleRate) return null;
65+ const bytes = bits / 8;
66+ const frameBytes = bytes * channels;
67+ const n = Math.floor(dataLen / frameBytes);
68+ const out = new Float32Array(n);
69+ for (let i = 0; i < n; i++) {
70+ const p = dataOff + i * frameBytes;
71+ let x: number;
72+ if (format === 3 && bits === 32) x = v.getFloat32(p, true);
73+ else if (format === 3 && bits === 64) x = v.getFloat64(p, true);
74+ else if (format === 1 && bits === 16) x = v.getInt16(p, true) / 32768;
75+ else if (format === 1 && bits === 24) {
76+ let s = v.getUint8(p) | (v.getUint8(p + 1) << 8) | (v.getUint8(p + 2) << 16);
77+ if (s & 0x800000) s -= 0x1000000;
78+ x = s / 8388608;
79+ } else if (format === 1 && bits === 32) x = v.getInt32(p, true) / 2147483648;
80+ else return null;
81+ out[i] = x;
82+ }
83+ return { sampleRate, channels, samples: out };
84+}
src/colormap.tsadded+21−0View file
@@ -0,0 +1,21 @@
1+// Magma colormap (perceptually uniform, dark = quiet, bright = loud), 9 anchors interpolated.
2+const ANCHORS: [number, number, number][] = [
3+ [0, 0, 4],
4+ [28, 16, 68],
5+ [79, 18, 123],
6+ [129, 37, 129],
7+ [181, 54, 122],
8+ [229, 80, 100],
9+ [251, 135, 97],
10+ [254, 194, 135],
11+ [252, 253, 191],
12+];
13+
14+export function magma(t: number): [number, number, number] {
15+ const u = t * (ANCHORS.length - 1);
16+ const i = Math.min(ANCHORS.length - 2, Math.floor(u));
17+ const f = u - i;
18+ const a = ANCHORS[i];
19+ const b = ANCHORS[i + 1];
20+ return [a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f, a[2] + (b[2] - a[2]) * f];
21+}
src/components/About.tsxadded+89−0View file
@@ -0,0 +1,89 @@
1+import type { AnalysisSettings } from "../analysis/analyze.ts";
2+import { fmtHz } from "../model.ts";
3+
4+export function About({ settings }: { settings: AnalysisSettings }) {
5+ return (
6+ <div className="about card">
7+ <h2>The idea</h2>
8+ <p>
9+ A tear may be a rapid sum of tiny, similar clicks, one per fibre or bond that breaks. If so, tearing faster packs the same clicks into less time.
10+ Two things should then stay the same at every speed: the <b>total sound energy</b> of a tear, and its <b>frequency makeup</b>. Their sum gets
11+ louder for a faster tear (more clicks per second) but shorter, and the two effects cancel in the total energy.
12+ </p>
13+ <p>
14+ This holds even when the clicks overlap and blur together, as long as they arrive at random times: the energies of randomly timed clicks add up.
15+ So nothing here depends on picking out individual clicks.
16+ </p>
17+
18+ <h2>What is measured</h2>
19+ <ul>
20+ <li>
21+ <b>Tear segment</b>: found automatically as the loudest stretch well above the background (gaps under 0.6 s are bridged). Check it on the plots and drag
22+ its edges if it is wrong. Duration and speed ({settings.sheetLengthIn} in ÷ duration) come from this segment, not from the label.
23+ </li>
24+ <li>
25+ <b>Energy spectral density</b> of the tear: Welch average of 2048-point Hann-windowed spectra over the segment, times its duration. Units are digital
26+ full scale (FS² · s / Hz).
27+ </li>
28+ <li>
29+ <b>Background</b>: the same spectrum measured on the quiet audio before and after the tear (median across windows, so a stray key click does not
30+ dominate), scaled to the tear's duration and subtracted.
31+ </li>
32+ <li>
33+ <b>Sound energy</b>: the background-subtracted spectrum summed over {fmtHz(settings.bandLow)} – {fmtHz(settings.bandHigh)}. <b>Median frequency</b> and{" "}
34+ <b>centroid</b> describe where that energy sits.
35+ </li>
36+ </ul>
37+
38+ <h2>What it can't tell you</h2>
39+ <ul>
40+ <li>
41+ <b>Only relative numbers.</b> The microphone is not calibrated, so energies are in arbitrary units. Comparisons are meaningful only between recordings
42+ made with the same mic, at the same distance and angle, in the same room. Moving the paper twice as far away lowers the energy by roughly 6 dB, which
43+ is bigger than many of the effects you may be looking for.
44+ </li>
45+ <li>
46+ <b>The mic colours the sound.</b> A laptop microphone has its own frequency response and records little above about 20 kHz. Spectra show the sound as
47+ that mic hears it. That is fine for comparing speeds against each other, but not for absolute spectra.
48+ </li>
49+ <li>
50+ <b>Clipping ruins the energy.</b> If a tear is loud enough to hit full scale, its energy is underestimated. Clipped recordings are flagged.
51+ </li>
52+ <li>
53+ <b>Run-to-run scatter.</b> Two tears at the same speed won't give identical numbers (paper varies, your hands vary). Make several tears per speed and
54+ look at the spread before reading anything into a difference between speeds.
55+ </li>
56+ <li>
57+ <b>Not just the tear.</b> Hand and paper movement, the sheet flapping and the room all add sound. The band setting excludes the lowest frequencies,
58+ where most of this lives, but cannot remove it entirely.
59+ </li>
60+ <li>
61+ <b>Same energy ≠ same clicks.</b> Equal energy and equal spectra are what identical clicks predict, but other explanations could produce them too.
62+ Different energies or spectra, on the other hand, do show something changes with speed.
63+ </li>
64+ </ul>
65+
66+ <h2>How the audio is kept raw</h2>
67+ <ul>
68+ <li>
69+ Chrome's echo cancellation, noise suppression and automatic gain control are turned off. The settings the browser actually applied are shown after
70+ enabling the mic; a warning appears if any are still on.
71+ </li>
72+ <li>
73+ Samples are taken directly from the audio graph (32-bit float), at the microphone's own sample rate, and stored unmodified. Nothing is compressed.
74+ Downloads are 32-bit float WAV files with the exact recorded samples.
75+ </li>
76+ <li>
77+ macOS can apply its own processing outside the browser's control. While recording, open Control Center: if a <b>Mic Mode</b> option is shown,
78+ set it to <b>Standard</b> (not Voice Isolation or Wide Spectrum). Also keep the input volume in System Settings → Sound fixed between sessions.
79+ </li>
80+ </ul>
81+
82+ <h2>Checking the analysis</h2>
83+ <p>
84+ Under “Import a file or add a synthetic test tear” you can add synthetic tears made exactly as the hypothesis says: 4000 clicks of one fixed shape with
85+ random amplitudes, spread over 0.3 to 10 seconds. Their energies and spectra should agree within a fraction of a dB. If they don't, the analysis is wrong.
86+ </p>
87+ </div>
88+ );
89+}
src/components/CanvasPlot.tsxadded+457−0View file
@@ -0,0 +1,457 @@
1+import { useEffect, useLayoutEffect, useRef, useState } from "react";
2+
3+export interface Scales {
4+ x: (v: number) => number;
5+ y: (v: number) => number;
6+ invX: (px: number) => number;
7+ invY: (py: number) => number;
8+ left: number;
9+ right: number;
10+ top: number;
11+ bottom: number;
12+ width: number;
13+ height: number;
14+}
15+
16+export interface Theme {
17+ surface: string;
18+ ink: string;
19+ ink2: string;
20+ muted: string;
21+ grid: string;
22+ axis: string;
23+ seg: string;
24+ series: string[];
25+}
26+
27+export function readTheme(el: Element): Theme {
28+ const cs = getComputedStyle(el);
29+ const v = (n: string) => cs.getPropertyValue(n).trim();
30+ return {
31+ surface: v("--surface"),
32+ ink: v("--ink"),
33+ ink2: v("--ink2"),
34+ muted: v("--muted"),
35+ grid: v("--grid"),
36+ axis: v("--axis"),
37+ seg: v("--seg"),
38+ series: [1, 2, 3, 4, 5, 6, 7, 8].map((i) => v(`--series-${i}`)),
39+ };
40+}
41+
42+export interface PointerInfo {
43+ xv: number;
44+ yv: number;
45+ px: number;
46+ py: number;
47+ scales: Scales;
48+}
49+
50+interface Props {
51+ height: number;
52+ xRange: [number, number];
53+ yRange: [number, number];
54+ xLog?: boolean;
55+ yLog?: boolean;
56+ xLabel: string;
57+ yLabel: string;
58+ xFormat?: (v: number) => string;
59+ yFormat?: (v: number) => string;
60+ hideXTicks?: boolean;
61+ draw: (ctx: CanvasRenderingContext2D, s: Scales, theme: Theme) => void;
62+ // returns tooltip lines for a hover position (null = no tooltip)
63+ hover?: (p: PointerInfo) => { lines: string[]; x?: number; y?: number } | null;
64+ onPointer?: (type: "down" | "move" | "up", p: PointerInfo, ev: PointerEvent) => void;
65+ onWheel?: (p: PointerInfo, ev: WheelEvent) => void;
66+ onDoubleClick?: () => void;
67+ onClick?: (p: PointerInfo) => void;
68+ cursor?: (p: PointerInfo) => string;
69+ ariaLabel: string;
70+}
71+
72+const PAD = { left: 64, right: 14, top: 10, bottom: 40 };
73+
74+export function niceStep(range: number, target: number) {
75+ const raw = range / Math.max(1, target);
76+ const mag = 10 ** Math.floor(Math.log10(raw));
77+ const r = raw / mag;
78+ return (r < 1.5 ? 1 : r < 3.5 ? 2 : r < 7.5 ? 5 : 10) * mag;
79+}
80+
81+function linearTicks(a: number, b: number, target: number): number[] {
82+ if (!(b > a)) return [a];
83+ const step = niceStep(b - a, target);
84+ const out: number[] = [];
85+ for (let v = Math.ceil(a / step) * step; v <= b + step * 1e-9; v += step) out.push(Math.abs(v) < step * 1e-9 ? 0 : v);
86+ return out;
87+}
88+
89+function logTicks(a: number, b: number, widthPx: number): { major: number[]; minor: number[] } {
90+ const major: number[] = [];
91+ const minor: number[] = [];
92+ const decades = Math.log10(b / a);
93+ const mults = widthPx / Math.max(decades, 0.1) > 160 ? [1, 2, 5] : [1];
94+ for (let e = Math.floor(Math.log10(a)); e <= Math.ceil(Math.log10(b)); e++) {
95+ for (let m = 1; m < 10; m++) {
96+ const v = m * 10 ** e;
97+ if (v < a * 0.9999 || v > b * 1.0001) continue;
98+ (mults.includes(m) ? major : minor).push(v);
99+ }
100+ }
101+ return { major, minor };
102+}
103+
104+export function fmtNum(v: number): string {
105+ const a = Math.abs(v);
106+ if (a >= 1000) return `${+(v / 1000).toPrecision(3)}k`;
107+ if (a === 0) return "0";
108+ if (a < 0.01) return v.toExponential(0);
109+ return `${+v.toPrecision(3)}`;
110+}
111+
112+export function CanvasPlot(props: Props) {
113+ const wrapRef = useRef<HTMLDivElement>(null);
114+ const canvasRef = useRef<HTMLCanvasElement>(null);
115+ const overlayRef = useRef<HTMLCanvasElement>(null);
116+ const scalesRef = useRef<Scales | null>(null);
117+ const [width, setWidth] = useState(600);
118+ const [tip, setTip] = useState<{ lines: string[]; left: number; top: number } | null>(null);
119+ const [cursor, setCursor] = useState("crosshair");
120+ const propsRef = useRef(props);
121+ propsRef.current = props;
122+ const [themeTick, setThemeTick] = useState(0);
123+
124+ useLayoutEffect(() => {
125+ const el = wrapRef.current!;
126+ const ro = new ResizeObserver(() => setWidth(Math.max(200, el.clientWidth)));
127+ ro.observe(el);
128+ setWidth(Math.max(200, el.clientWidth));
129+ const mq = matchMedia("(prefers-color-scheme: dark)");
130+ const onScheme = () => setThemeTick((t) => t + 1);
131+ mq.addEventListener("change", onScheme);
132+ return () => {
133+ ro.disconnect();
134+ mq.removeEventListener("change", onScheme);
135+ };
136+ }, []);
137+
138+ const { height, xRange, yRange, xLog, yLog } = props;
139+
140+ useEffect(() => {
141+ const canvas = canvasRef.current!;
142+ const overlay = overlayRef.current!;
143+ const dpr = window.devicePixelRatio || 1;
144+ for (const c of [canvas, overlay]) {
145+ c.width = Math.round(width * dpr);
146+ c.height = Math.round(height * dpr);
147+ c.style.width = `${width}px`;
148+ c.style.height = `${height}px`;
149+ }
150+ const ctx = canvas.getContext("2d")!;
151+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
152+ const theme = readTheme(wrapRef.current!);
153+ const left = PAD.left;
154+ const right = width - PAD.right;
155+ const top = PAD.top;
156+ const bottom = height - (props.hideXTicks ? 12 : PAD.bottom);
157+ const tx = (v: number) => (xLog ? Math.log10(Math.max(v, 1e-30)) : v);
158+ const ty = (v: number) => (yLog ? Math.log10(Math.max(v, 1e-30)) : v);
159+ const [x0, x1] = [tx(xRange[0]), tx(xRange[1])];
160+ const [y0, y1] = [ty(yRange[0]), ty(yRange[1])];
161+ const s: Scales = {
162+ x: (v) => left + ((tx(v) - x0) / (x1 - x0)) * (right - left),
163+ y: (v) => bottom - ((ty(v) - y0) / (y1 - y0)) * (bottom - top),
164+ invX: (px) => {
165+ const u = x0 + ((px - left) / (right - left)) * (x1 - x0);
166+ return xLog ? 10 ** u : u;
167+ },
168+ invY: (py) => {
169+ const u = y0 + ((bottom - py) / (bottom - top)) * (y1 - y0);
170+ return yLog ? 10 ** u : u;
171+ },
172+ left,
173+ right,
174+ top,
175+ bottom,
176+ width,
177+ height,
178+ };
179+ scalesRef.current = s;
180+
181+ ctx.clearRect(0, 0, width, height);
182+ ctx.fillStyle = theme.surface;
183+ ctx.fillRect(0, 0, width, height);
184+ ctx.font = "11px system-ui, -apple-system, sans-serif";
185+ ctx.lineWidth = 1;
186+
187+ // grid + ticks
188+ const xt = xLog ? logTicks(xRange[0], xRange[1], right - left) : { major: linearTicks(xRange[0], xRange[1], (right - left) / 90), minor: [] };
189+ const yt = yLog ? logTicks(yRange[0], yRange[1], (bottom - top) * 2) : { major: linearTicks(yRange[0], yRange[1], (bottom - top) / 40), minor: [] };
190+ ctx.strokeStyle = theme.grid;
191+ ctx.beginPath();
192+ for (const v of xt.major) {
193+ const px = Math.round(s.x(v)) + 0.5;
194+ ctx.moveTo(px, top);
195+ ctx.lineTo(px, bottom);
196+ }
197+ for (const v of yt.major) {
198+ const py = Math.round(s.y(v)) + 0.5;
199+ ctx.moveTo(left, py);
200+ ctx.lineTo(right, py);
201+ }
202+ ctx.stroke();
203+ ctx.globalAlpha = 0.5;
204+ ctx.beginPath();
205+ for (const v of xt.minor) {
206+ const px = Math.round(s.x(v)) + 0.5;
207+ ctx.moveTo(px, top);
208+ ctx.lineTo(px, bottom);
209+ }
210+ ctx.stroke();
211+ ctx.globalAlpha = 1;
212+
213+ ctx.save();
214+ ctx.beginPath();
215+ ctx.rect(left, top, right - left, bottom - top);
216+ ctx.clip();
217+ props.draw(ctx, s, theme);
218+ ctx.restore();
219+
220+ ctx.strokeStyle = theme.axis;
221+ ctx.beginPath();
222+ ctx.moveTo(left + 0.5, top);
223+ ctx.lineTo(left + 0.5, bottom + 0.5);
224+ ctx.lineTo(right, bottom + 0.5);
225+ ctx.stroke();
226+
227+ ctx.fillStyle = theme.muted;
228+ const xf = props.xFormat ?? fmtNum;
229+ const yf = props.yFormat ?? fmtNum;
230+ if (!props.hideXTicks) {
231+ ctx.textAlign = "center";
232+ ctx.textBaseline = "top";
233+ for (const v of xt.major) ctx.fillText(xf(v), s.x(v), bottom + 5);
234+ ctx.fillStyle = theme.ink2;
235+ ctx.fillText(props.xLabel, (left + right) / 2, bottom + 22);
236+ }
237+ ctx.fillStyle = theme.muted;
238+ ctx.textAlign = "right";
239+ ctx.textBaseline = "middle";
240+ for (const v of yt.major) ctx.fillText(yf(v), left - 6, s.y(v));
241+ ctx.save();
242+ ctx.translate(14, (top + bottom) / 2);
243+ ctx.rotate(-Math.PI / 2);
244+ ctx.textAlign = "center";
245+ ctx.fillStyle = theme.ink2;
246+ ctx.fillText(props.yLabel, 0, 0);
247+ ctx.restore();
248+ // eslint-disable-next-line react-hooks/exhaustive-deps
249+ }, [width, height, xRange[0], xRange[1], yRange[0], yRange[1], xLog, yLog, props.draw, themeTick]);
250+
251+ // pointer handling
252+ useEffect(() => {
253+ const el = overlayRef.current!;
254+ const info = (ev: MouseEvent): PointerInfo | null => {
255+ const s = scalesRef.current;
256+ if (!s) return null;
257+ const r = el.getBoundingClientRect();
258+ const px = ev.clientX - r.left;
259+ const py = ev.clientY - r.top;
260+ return { xv: s.invX(px), yv: s.invY(py), px, py, scales: s };
261+ };
262+ const drawCrosshair = (p: PointerInfo | null, mark?: { x?: number; y?: number }) => {
263+ const ctx = el.getContext("2d")!;
264+ const dpr = window.devicePixelRatio || 1;
265+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
266+ ctx.clearRect(0, 0, el.width, el.height);
267+ if (!p) return;
268+ const s = p.scales;
269+ if (p.px < s.left || p.px > s.right || p.py < s.top || p.py > s.bottom) return;
270+ const theme = readTheme(wrapRef.current!);
271+ ctx.strokeStyle = theme.muted;
272+ ctx.setLineDash([3, 3]);
273+ ctx.beginPath();
274+ const cx = mark?.x !== undefined ? s.x(mark.x) : p.px;
275+ ctx.moveTo(Math.round(cx) + 0.5, s.top);
276+ ctx.lineTo(Math.round(cx) + 0.5, s.bottom);
277+ ctx.stroke();
278+ ctx.setLineDash([]);
279+ if (mark?.y !== undefined) {
280+ ctx.fillStyle = theme.surface;
281+ ctx.strokeStyle = theme.ink;
282+ ctx.lineWidth = 2;
283+ ctx.beginPath();
284+ ctx.arc(cx, s.y(mark.y), 5, 0, 2 * Math.PI);
285+ ctx.fill();
286+ ctx.stroke();
287+ }
288+ };
289+ let down = false;
290+ const onMove = (ev: PointerEvent) => {
291+ const p = info(ev);
292+ if (!p) return;
293+ const pr = propsRef.current;
294+ if (down) pr.onPointer?.("move", p, ev);
295+ else if (pr.cursor) setCursor(pr.cursor(p));
296+ const h = pr.hover?.(p) ?? null;
297+ const s = p.scales;
298+ const inside = p.px >= s.left && p.px <= s.right && p.py >= s.top && p.py <= s.bottom;
299+ drawCrosshair(inside && !down ? p : null, h ?? undefined);
300+ if (h && inside && !down) {
301+ const w = el.clientWidth;
302+ setTip({ lines: h.lines, left: p.px > w * 0.6 ? p.px - 12 : p.px + 12, top: Math.max(4, p.py - 10) });
303+ el.dataset.tipSide = p.px > w * 0.6 ? "left" : "right";
304+ } else setTip(null);
305+ };
306+ const onDown = (ev: PointerEvent) => {
307+ const p = info(ev);
308+ if (!p || !propsRef.current.onPointer) return;
309+ down = true;
310+ el.setPointerCapture(ev.pointerId);
311+ propsRef.current.onPointer("down", p, ev);
312+ };
313+ const onUp = (ev: PointerEvent) => {
314+ const p = info(ev);
315+ if (down && p) propsRef.current.onPointer?.("up", p, ev);
316+ down = false;
317+ };
318+ const onLeave = () => {
319+ if (!down) {
320+ drawCrosshair(null);
321+ setTip(null);
322+ }
323+ };
324+ const onWheel = (ev: WheelEvent) => {
325+ const p = info(ev);
326+ if (!p || !propsRef.current.onWheel) return;
327+ ev.preventDefault();
328+ propsRef.current.onWheel(p, ev);
329+ };
330+ const onDbl = () => propsRef.current.onDoubleClick?.();
331+ const onClick = (ev: MouseEvent) => {
332+ const p = info(ev);
333+ if (p) propsRef.current.onClick?.(p);
334+ };
335+ el.addEventListener("pointermove", onMove);
336+ el.addEventListener("pointerdown", onDown);
337+ el.addEventListener("pointerup", onUp);
338+ el.addEventListener("pointerleave", onLeave);
339+ el.addEventListener("wheel", onWheel, { passive: false });
340+ el.addEventListener("dblclick", onDbl);
341+ el.addEventListener("click", onClick);
342+ return () => {
343+ el.removeEventListener("pointermove", onMove);
344+ el.removeEventListener("pointerdown", onDown);
345+ el.removeEventListener("pointerup", onUp);
346+ el.removeEventListener("pointerleave", onLeave);
347+ el.removeEventListener("wheel", onWheel);
348+ el.removeEventListener("dblclick", onDbl);
349+ el.removeEventListener("click", onClick);
350+ };
351+ }, []);
352+
353+ return (
354+ <div ref={wrapRef} className="plot" style={{ height }} role="img" aria-label={props.ariaLabel}>
355+ <canvas ref={canvasRef} />
356+ <canvas ref={overlayRef} className="plot-overlay" style={{ cursor }} />
357+ {tip && (
358+ <div
359+ className="plot-tip"
360+ style={{
361+ left: tip.left,
362+ top: tip.top,
363+ transform: overlayRef.current?.dataset.tipSide === "left" ? "translateX(-100%)" : undefined,
364+ }}
365+ >
366+ {tip.lines.map((l, i) => (
367+ <div key={i} className={i === 0 ? "plot-tip-head" : undefined}>
368+ {l}
369+ </div>
370+ ))}
371+ </div>
372+ )}
373+ </div>
374+ );
375+}
376+
377+// ---------- drawing helpers ----------
378+
379+export function drawLine(
380+ ctx: CanvasRenderingContext2D,
381+ s: Scales,
382+ xs: ArrayLike<number>,
383+ ys: ArrayLike<number>,
384+ color: string,
385+ width = 2,
386+ dash: number[] = [],
387+) {
388+ ctx.strokeStyle = color;
389+ ctx.lineWidth = width;
390+ ctx.lineJoin = "round";
391+ ctx.setLineDash(dash);
392+ ctx.beginPath();
393+ let pen = false;
394+ for (let i = 0; i < xs.length; i++) {
395+ const y = ys[i];
396+ if (!Number.isFinite(y)) {
397+ pen = false;
398+ continue;
399+ }
400+ const px = s.x(xs[i]);
401+ const py = s.y(y);
402+ if (pen) ctx.lineTo(px, py);
403+ else ctx.moveTo(px, py);
404+ pen = true;
405+ }
406+ ctx.stroke();
407+ ctx.setLineDash([]);
408+}
409+
410+export type MarkerShape = "circle" | "square" | "triangle" | "diamond" | "cross";
411+export const SHAPES: MarkerShape[] = ["circle", "square", "triangle", "diamond", "cross"];
412+
413+export function drawMarker(
414+ ctx: CanvasRenderingContext2D,
415+ px: number,
416+ py: number,
417+ shape: MarkerShape,
418+ color: string,
419+ ring: string,
420+ r = 5,
421+) {
422+ ctx.beginPath();
423+ if (shape === "circle") ctx.arc(px, py, r, 0, 2 * Math.PI);
424+ else if (shape === "square") ctx.rect(px - r * 0.9, py - r * 0.9, r * 1.8, r * 1.8);
425+ else if (shape === "triangle") {
426+ ctx.moveTo(px, py - r * 1.15);
427+ ctx.lineTo(px + r * 1.05, py + r * 0.75);
428+ ctx.lineTo(px - r * 1.05, py + r * 0.75);
429+ ctx.closePath();
430+ } else if (shape === "diamond") {
431+ ctx.moveTo(px, py - r * 1.25);
432+ ctx.lineTo(px + r * 1.05, py);
433+ ctx.lineTo(px, py + r * 1.25);
434+ ctx.lineTo(px - r * 1.05, py);
435+ ctx.closePath();
436+ } else {
437+ const k = r * 0.45;
438+ ctx.moveTo(px - k, py - r);
439+ ctx.lineTo(px + k, py - r);
440+ ctx.lineTo(px + k, py - k);
441+ ctx.lineTo(px + r, py - k);
442+ ctx.lineTo(px + r, py + k);
443+ ctx.lineTo(px + k, py + k);
444+ ctx.lineTo(px + k, py + r);
445+ ctx.lineTo(px - k, py + r);
446+ ctx.lineTo(px - k, py + k);
447+ ctx.lineTo(px - r, py + k);
448+ ctx.lineTo(px - r, py - k);
449+ ctx.lineTo(px - k, py - k);
450+ ctx.closePath();
451+ }
452+ ctx.fillStyle = color;
453+ ctx.fill();
454+ ctx.strokeStyle = ring;
455+ ctx.lineWidth = 2;
456+ ctx.stroke();
457+}
src/components/CompareView.tsxadded+528−0View file
@@ -0,0 +1,528 @@
1+import { useCallback, useEffect, useMemo, useState } from "react";
2+import { CanvasPlot, drawLine, drawMarker, readTheme, type MarkerShape, type PointerInfo, type Scales, type Theme } from "./CanvasPlot.tsx";
3+import { smoothLog, type Analysis, type AnalysisSettings } from "../analysis/analyze.ts";
4+import type { RecordingMeta } from "../storage/db.ts";
5+import { colorFor, db10, download, fmtHz, fmtSec, getAnalysis, groupOrder, groupStyle, linearFit } from "../model.ts";
6+
7+interface Props {
8+ recs: RecordingMeta[]; // recordings included in the comparison
9+ all: RecordingMeta[];
10+ settings: AnalysisSettings;
11+ onOpen: (id: string) => void;
12+}
13+
14+interface Row {
15+ meta: RecordingMeta;
16+ a: Analysis;
17+}
18+
19+type Metric = "median" | "centroid" | "power";
20+const METRICS: Record<Metric, { label: string; axis: string; get: (a: Analysis) => number; fmt: (v: number) => string; log: boolean }> = {
21+ median: { label: "Median frequency", axis: "median frequency (Hz)", get: (a) => a.medianFreq, fmt: fmtHz, log: false },
22+ centroid: { label: "Spectral centroid", axis: "centroid (Hz)", get: (a) => a.centroid, fmt: fmtHz, log: false },
23+ power: { label: "Mean power", axis: "mean power (dBFS)", get: (a) => db10(a.energy / a.duration), fmt: (v) => `${v.toFixed(1)} dBFS`, log: false },
24+};
25+
26+export function CompareView({ recs, all, settings, onOpen }: Props) {
27+ const [rows, setRows] = useState<Row[]>([]);
28+ const [progress, setProgress] = useState<[number, number]>([0, 0]);
29+ const [metric, setMetric] = useState<Metric>("median");
30+ const [specMode, setSpecMode] = useState<"group" | "each">("group");
31+ const [normalize, setNormalize] = useState(false);
32+ const [smoothing, setSmoothing] = useState(1 / 6);
33+
34+ useEffect(() => {
35+ let live = true;
36+ (async () => {
37+ const out: Row[] = [];
38+ setProgress([0, recs.length]);
39+ for (let i = 0; i < recs.length; i++) {
40+ const a = await getAnalysis(recs[i], settings);
41+ if (!live) return;
42+ if (a && a.energy > 0) out.push({ meta: recs[i], a });
43+ setProgress([i + 1, recs.length]);
44+ await new Promise((r) => setTimeout(r, 0));
45+ }
46+ if (live) setRows(out);
47+ })();
48+ return () => {
49+ live = false;
50+ };
51+ }, [recs, settings]);
52+
53+ const groups = useMemo(() => groupOrder(rows.map((r) => r.meta)), [rows]);
54+ const style = useCallback((label: string) => groupStyle(label, all), [all]);
55+
56+ const skipped = recs.length - rows.length;
57+ const loading = progress[0] < progress[1];
58+
59+ if (!recs.length) return <div className="card empty">No recordings are included in the comparison. Tick some in the list on the left.</div>;
60+
61+ return (
62+ <div className="compare">
63+ {loading && (
64+ <div className="card muted">
65+ Analysing {progress[0]} / {progress[1]}…
66+ </div>
67+ )}
68+ {!loading && skipped > 0 && (
69+ <div className="card warn">
70+ {skipped} recording{skipped > 1 ? "s have" : " has"} no tear segment or no energy above the background and {skipped > 1 ? "are" : "is"} left out.
71+ </div>
72+ )}
73+ <Summary rows={rows} groups={groups} />
74+
75+ <div className="grid2">
76+ <section className="card">
77+ <h3>Total sound energy vs tear duration</h3>
78+ <p className="caption">If every tear contains the same clicks, the points should lie on a flat line.</p>
79+ <Scatter rows={rows} y={(a) => db10(a.energy)} yFmt={(v) => `${v.toFixed(1)} dB`} yLabel="energy (dB re FS²·s)" style={style} onOpen={onOpen} fitUnit="dB" minSpan={10} />
80+ </section>
81+ <section className="card">
82+ <div className="plot-head">
83+ <h3>{METRICS[metric].label} vs tear duration</h3>
84+ <select value={metric} onChange={(e) => setMetric(e.target.value as Metric)} aria-label="Metric">
85+ {(Object.keys(METRICS) as Metric[]).map((k) => (
86+ <option key={k} value={k}>
87+ {METRICS[k].label}
88+ </option>
89+ ))}
90+ </select>
91+ </div>
92+ <p className="caption">
93+ {metric === "power"
94+ ? "Same energy packed into less time means power rises 10 dB for every 10× shorter tear."
95+ : "If the clicks are the same at every speed, this should not depend on duration."}
96+ </p>
97+ <Scatter
98+ rows={rows}
99+ y={METRICS[metric].get}
100+ yFmt={METRICS[metric].fmt}
101+ yLabel={METRICS[metric].axis}
102+ style={style}
103+ onOpen={onOpen}
104+ fitUnit={metric === "power" ? "dB" : "Hz"}
105+ minSpan={metric === "power" ? 10 : 4000}
106+ />
107+ </section>
108+ </div>
109+
110+ <section className="card">
111+ <div className="plot-head">
112+ <h3>Frequency makeup</h3>
113+ <div className="toolbar">
114+ <select value={specMode} onChange={(e) => setSpecMode(e.target.value as "group" | "each")} aria-label="Lines">
115+ <option value="group">average per label</option>
116+ <option value="each">each recording</option>
117+ </select>
118+ <label>
119+ <input type="checkbox" checked={normalize} onChange={(e) => setNormalize(e.target.checked)} /> shape only (scale each to equal energy)
120+ </label>
121+ <label>
122+ smoothing
123+ <select value={smoothing} onChange={(e) => setSmoothing(+e.target.value)}>
124+ <option value={1 / 12}>1/12 octave</option>
125+ <option value={1 / 6}>1/6 octave</option>
126+ <option value={1 / 3}>1/3 octave</option>
127+ </select>
128+ </label>
129+ </div>
130+ </div>
131+ <p className="caption">
132+ Energy spectral density of each tear with the background removed.
133+ {normalize
134+ ? " Each curve is divided by its total energy in the band, so only the shape is compared."
135+ : " If tears at all speeds contain the same clicks, the curves should lie on top of each other."}
136+ </p>
137+ <SpectraOverlay rows={rows} groups={groups} mode={specMode} normalize={normalize} smoothing={smoothing} settings={settings} style={style} />
138+ </section>
139+
140+ <section className="card">
141+ <div className="plot-head">
142+ <h3>All recordings</h3>
143+ <button onClick={() => exportCsv(rows, settings)} disabled={!rows.length}>
144+ Download CSV
145+ </button>
146+ </div>
147+ <Table rows={rows} groups={groups} style={style} onOpen={onOpen} />
148+ </section>
149+ </div>
150+ );
151+}
152+
153+// ---------- summary ----------
154+
155+function Summary({ rows, groups }: { rows: Row[]; groups: string[] }) {
156+ if (rows.length < 3) return <div className="card muted">Add at least three recordings (ideally at a few different speeds) to see trends.</div>;
157+ const lx = rows.map((r) => Math.log10(r.a.duration));
158+ const fe = linearFit(lx, rows.map((r) => db10(r.a.energy)));
159+ const fm = linearFit(lx, rows.map((r) => r.a.medianFreq));
160+ const span = Math.max(...rows.map((r) => r.a.duration)) / Math.min(...rows.map((r) => r.a.duration));
161+ return (
162+ <section className="card summary">
163+ <h3>The two questions</h3>
164+ <div className="q">
165+ <div className="q-title">Same total energy at every speed?</div>
166+ {fe && (
167+ <div>
168+ Energy changes by <b>{fmtSigned(fe.b)} ± {fe.seB.toFixed(2)} dB</b> for each 10× longer tear (straight-line fit, ± one standard error, {fe.n} recordings).
169+ {" "}
170+ {verdict(fe.b, fe.seB)}
171+ </div>
172+ )}
173+ </div>
174+ <div className="q">
175+ <div className="q-title">Same frequency makeup at every speed?</div>
176+ {fm && (
177+ <div>
178+ Median frequency changes by <b>{fmtSigned(fm.b, 0)} ± {fm.seB.toFixed(0)} Hz</b> for each 10× longer tear. Compare the curve shapes below (tick “shape only”).
179+ {" "}
180+ {verdict(fm.b, fm.seB)}
181+ </div>
182+ )}
183+ </div>
184+ <p className="caption">
185+ Durations span {span.toFixed(1)}× across {groups.length} label{groups.length === 1 ? "" : "s"}.
186+ {span < 3 ? " That is a narrow range; trends will be hard to see." : ""} The fit uses measured durations, not labels. A trend within about two standard errors of zero is not distinguishable from no trend. Run-to-run scatter at the same speed tells you how much a single comparison can be trusted.
187+ </p>
188+ </section>
189+ );
190+}
191+
192+function fmtSigned(v: number, digits = 2) {
193+ return `${v >= 0 ? "+" : "−"}${Math.abs(v).toFixed(digits)}`;
194+}
195+
196+function verdict(b: number, se: number) {
197+ if (!Number.isFinite(se)) return null;
198+ return Math.abs(b) < 2 * se ? <span className="muted">(not clearly different from zero)</span> : <span className="muted">(clearly different from zero)</span>;
199+}
200+
201+// ---------- scatter ----------
202+
203+function Scatter({
204+ rows,
205+ y,
206+ yFmt,
207+ yLabel,
208+ style,
209+ onOpen,
210+ fitUnit,
211+ minSpan,
212+}: {
213+ minSpan: number;
214+ rows: Row[];
215+ y: (a: Analysis) => number;
216+ yFmt: (v: number) => string;
217+ yLabel: string;
218+ style: (l: string) => { slot: number | null; shape: MarkerShape };
219+ onOpen: (id: string) => void;
220+ fitUnit: string;
221+}) {
222+ const pts = useMemo(() => rows.map((r) => ({ r, x: r.a.duration, y: y(r.a) })).filter((p) => Number.isFinite(p.y)), [rows, y]);
223+ const xr = useMemo<[number, number]>(() => {
224+ if (!pts.length) return [0.1, 20];
225+ const lo = Math.min(...pts.map((p) => p.x));
226+ const hi = Math.max(...pts.map((p) => p.x));
227+ return [Math.min(lo / 1.5, 0.2), Math.max(hi * 1.5, 15)];
228+ }, [pts]);
229+ const yr = useMemo<[number, number]>(() => {
230+ if (!pts.length) return [0, 1];
231+ const lo = Math.min(...pts.map((p) => p.y));
232+ const hi = Math.max(...pts.map((p) => p.y));
233+ // keep a minimum span so tiny differences are not blown up to fill the plot
234+ const mid = (lo + hi) / 2;
235+ const half = Math.max((hi - lo) * 0.6, minSpan / 2);
236+ return [mid - half, mid + half];
237+ }, [pts, minSpan]);
238+ const fit = useMemo(() => linearFit(pts.map((p) => Math.log10(p.x)), pts.map((p) => p.y)), [pts]);
239+
240+ const draw = useCallback(
241+ (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
242+ if (fit) {
243+ drawLine(ctx, s, [xr[0], xr[1]], [fit.a + fit.b * Math.log10(xr[0]), fit.a + fit.b * Math.log10(xr[1])], th.muted, 1.5, [6, 4]);
244+ }
245+ for (const p of pts) {
246+ const st = style(p.r.meta.label);
247+ drawMarker(ctx, s.x(p.x), s.y(p.y), st.shape, colorFor(st.slot, th.series, th.muted), th.surface, 5);
248+ }
249+ },
250+ [pts, fit, xr, style],
251+ );
252+
253+ const near = (p: PointerInfo) => {
254+ let best: (typeof pts)[number] | null = null;
255+ let bd = 14 * 14;
256+ for (const q of pts) {
257+ const d = (p.scales.x(q.x) - p.px) ** 2 + (p.scales.y(q.y) - p.py) ** 2;
258+ if (d < bd) {
259+ bd = d;
260+ best = q;
261+ }
262+ }
263+ return best;
264+ };
265+
266+ return (
267+ <>
268+ <CanvasPlot
269+ height={280}
270+ xRange={xr}
271+ xLog
272+ yRange={yr}
273+ xLabel="tear duration (s)"
274+ yLabel={yLabel}
275+ draw={draw}
276+ hover={(p) => {
277+ const q = near(p);
278+ if (!q) return null;
279+ return { lines: [q.r.meta.label, `${fmtSec(q.x)} · ${yFmt(q.y)}`, "click to open"], x: q.x, y: q.y };
280+ }}
281+ onClick={(p) => {
282+ const q = near(p);
283+ if (q) onOpen(q.r.meta.id);
284+ }}
285+ cursor={(p) => (near(p) ? "pointer" : "crosshair")}
286+ ariaLabel={`${yLabel} against tear duration`}
287+ />
288+ <Legend labels={groupOrder(rows.map((r) => r.meta))} style={style} extra={fit ? `dashed: straight-line fit, slope ${fmtSigned(fit.b, fitUnit === "Hz" ? 0 : 2)} ${fitUnit} per 10× duration` : undefined} />
289+ </>
290+ );
291+}
292+
293+// ---------- spectra overlay ----------
294+
295+function SpectraOverlay({
296+ rows,
297+ groups,
298+ mode,
299+ normalize,
300+ smoothing,
301+ settings,
302+ style,
303+}: {
304+ rows: Row[];
305+ groups: string[];
306+ mode: "group" | "each";
307+ normalize: boolean;
308+ smoothing: number;
309+ settings: AnalysisSettings;
310+ style: (l: string) => { slot: number | null; shape: MarkerShape };
311+}) {
312+ const fsMin = rows.length ? Math.min(...rows.map((r) => r.a.fs)) : 48000;
313+ const fLo = Math.max(20, settings.bandLow);
314+ const fHi = Math.min(settings.bandHigh, fsMin / 2);
315+
316+ const lines = useMemo(() => {
317+ const per = rows.map((r) => {
318+ const scale = normalize ? 1 / r.a.energy : 1;
319+ const sm = smoothLog(r.a.freqs, r.a.netEsd.map((v) => v * scale), fLo, fHi, smoothing);
320+ return { label: r.meta.label, name: r.meta.label, f: sm.f, v: sm.v };
321+ });
322+ if (mode === "each") return per.map((p) => ({ ...p, db: p.v.map(db10Floor) }));
323+ return groups
324+ .map((g) => {
325+ const members = per.filter((p) => p.label === g);
326+ if (!members.length) return null;
327+ const f = members[0].f;
328+ const v = f.map((_, i) => members.reduce((s, m) => s + (m.v[i] ?? 0), 0) / members.length);
329+ return { label: g, name: `${g} (n=${members.length})`, f, v, db: v.map(db10Floor) };
330+ })
331+ .filter((x): x is NonNullable<typeof x> => !!x);
332+ }, [rows, groups, mode, normalize, smoothing, fLo, fHi]);
333+
334+ const yr = useMemo<[number, number]>(() => {
335+ const all = lines.flatMap((l) => l.db.filter(Number.isFinite));
336+ if (!all.length) return [-100, 0];
337+ const top = Math.max(...all);
338+ return [Math.floor((top - 50) / 10) * 10, Math.ceil((top + 3) / 5) * 5];
339+ }, [lines]);
340+
341+ const draw = useCallback(
342+ (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
343+ for (const l of lines) {
344+ const st = style(l.label);
345+ drawLine(ctx, s, l.f, l.db, colorFor(st.slot, th.series, th.muted), mode === "each" ? 1.5 : 2);
346+ }
347+ },
348+ [lines, style, mode],
349+ );
350+
351+ return (
352+ <>
353+ <CanvasPlot
354+ height={340}
355+ xRange={[fLo, fHi]}
356+ xLog
357+ yRange={yr}
358+ xLabel="frequency (Hz)"
359+ yLabel={normalize ? "relative density (dB re 1/Hz)" : "energy density (dB re FS²·s/Hz)"}
360+ draw={draw}
361+ hover={(p) => {
362+ if (!lines.length) return null;
363+ const f = lines[0].f;
364+ let i = 0;
365+ for (let k = 1; k < f.length; k++) if (Math.abs(Math.log(f[k] / p.xv)) < Math.abs(Math.log(f[i] / p.xv))) i = k;
366+ const vals = lines.slice(0, 10).map((l) => `${l.name}: ${Number.isFinite(l.db[i]) ? l.db[i].toFixed(1) : "–"} dB`);
367+ if (lines.length > 10) vals.push(`… ${lines.length - 10} more`);
368+ return { lines: [fmtHz(f[i]), ...vals], x: f[i] };
369+ }}
370+ ariaLabel="Energy spectral density of tears, overlaid"
371+ />
372+ <Legend labels={groups} style={style} lines />
373+ </>
374+ );
375+}
376+
377+function db10Floor(v: number) {
378+ return v > 0 ? 10 * Math.log10(v) : NaN;
379+}
380+
381+// ---------- legend & table ----------
382+
383+function MarkerIcon({ shape, color, line }: { shape: MarkerShape; color: string; line?: boolean }) {
384+ if (line) return <svg width="18" height="10" aria-hidden><line x1="1" y1="5" x2="17" y2="5" stroke={color} strokeWidth="2.5" strokeLinecap="round" /></svg>;
385+ const d: Record<MarkerShape, string> = {
386+ circle: "M9,4 a5,5 0 1,0 0.01,0",
387+ square: "M4.5,4.5 h9 v9 h-9 z",
388+ triangle: "M9,3.5 L14.2,13 L3.8,13 z",
389+ diamond: "M9,2.8 L14.2,9 L9,15.2 L3.8,9 z",
390+ cross: "M7,4 h4 v3 h3 v4 h-3 v3 h-4 v-3 h-3 v-4 h3 z",
391+ };
392+ return (
393+ <svg width="18" height="18" aria-hidden>
394+ <path d={d[shape]} fill={color} />
395+ </svg>
396+ );
397+}
398+
399+function Legend({ labels, style, lines, extra }: { labels: string[]; style: (l: string) => { slot: number | null; shape: MarkerShape }; lines?: boolean; extra?: string }) {
400+ const th = readTheme(document.documentElement);
401+ return (
402+ <div className="legend">
403+ {labels.map((l) => {
404+ const st = style(l);
405+ return (
406+ <span key={l}>
407+ <MarkerIcon shape={st.shape} color={colorFor(st.slot, th.series, th.muted)} line={lines} /> {l}
408+ </span>
409+ );
410+ })}
411+ {extra && <span className="muted">{extra}</span>}
412+ </div>
413+ );
414+}
415+
416+function Table({ rows, groups, style, onOpen }: { rows: Row[]; groups: string[]; style: (l: string) => { slot: number | null; shape: MarkerShape }; onOpen: (id: string) => void }) {
417+ const th = readTheme(document.documentElement);
418+ const sorted = [...rows].sort((a, b) => groups.indexOf(a.meta.label) - groups.indexOf(b.meta.label) || b.a.duration - a.a.duration);
419+ const groupStats = groups.map((g) => {
420+ const rs = rows.filter((r) => r.meta.label === g);
421+ const e = rs.map((r) => db10(r.a.energy));
422+ const mean = e.reduce((s, v) => s + v, 0) / e.length;
423+ const sd = e.length > 1 ? Math.sqrt(e.reduce((s, v) => s + (v - mean) ** 2, 0) / (e.length - 1)) : NaN;
424+ return {
425+ g,
426+ n: rs.length,
427+ dur: rs.reduce((s, r) => s + r.a.duration, 0) / rs.length,
428+ mean,
429+ sd,
430+ med: rs.reduce((s, r) => s + r.a.medianFreq, 0) / rs.length,
431+ };
432+ });
433+ return (
434+ <div className="table-wrap">
435+ <table>
436+ <thead>
437+ <tr>
438+ <th>Label</th>
439+ <th>n</th>
440+ <th className="num">Mean duration</th>
441+ <th className="num">Energy (dB), mean ± sd</th>
442+ <th className="num">Median freq, mean</th>
443+ </tr>
444+ </thead>
445+ <tbody>
446+ {groupStats.map((s) => {
447+ const st = style(s.g);
448+ return (
449+ <tr key={s.g}>
450+ <td>
451+ <MarkerIcon shape={st.shape} color={colorFor(st.slot, th.series, th.muted)} /> {s.g}
452+ </td>
453+ <td>{s.n}</td>
454+ <td className="num">{fmtSec(s.dur)}</td>
455+ <td className="num">
456+ {s.mean.toFixed(1)}
457+ {Number.isFinite(s.sd) ? ` ± ${s.sd.toFixed(1)}` : ""}
458+ </td>
459+ <td className="num">{fmtHz(s.med)}</td>
460+ </tr>
461+ );
462+ })}
463+ </tbody>
464+ </table>
465+ <table>
466+ <thead>
467+ <tr>
468+ <th>Label</th>
469+ <th className="num">Duration</th>
470+ <th className="num">Speed (in/s)</th>
471+ <th className="num">Energy (dB)</th>
472+ <th className="num">Above bg (dB)</th>
473+ <th className="num">Median freq</th>
474+ <th className="num">Centroid</th>
475+ <th className="num">Peak (dBFS)</th>
476+ <th></th>
477+ </tr>
478+ </thead>
479+ <tbody>
480+ {sorted.map(({ meta, a }) => {
481+ const st = style(meta.label);
482+ return (
483+ <tr key={meta.id} className="clickable" onClick={() => onOpen(meta.id)}>
484+ <td>
485+ <MarkerIcon shape={st.shape} color={colorFor(st.slot, th.series, th.muted)} /> {meta.label}
486+ </td>
487+ <td className="num">{fmtSec(a.duration)}</td>
488+ <td className="num">{a.speedInPerSec.toFixed(2)}</td>
489+ <td className="num">{db10(a.energy).toFixed(1)}</td>
490+ <td className="num">{Number.isFinite(a.snrDb) ? a.snrDb.toFixed(1) : "–"}</td>
491+ <td className="num">{fmtHz(a.medianFreq)}</td>
492+ <td className="num">{fmtHz(a.centroid)}</td>
493+ <td className="num">{a.peakDbfs.toFixed(1)}</td>
494+ <td>{a.nearClip > 0 ? <span className="warn-inline">⚠ clipped</span> : meta.source !== "mic" ? <span className={`badge ${meta.source}`}>{meta.source}</span> : null}</td>
495+ </tr>
496+ );
497+ })}
498+ </tbody>
499+ </table>
500+ </div>
501+ );
502+}
503+
504+function exportCsv(rows: Row[], settings: AnalysisSettings) {
505+ const head = [
506+ "id", "created", "label", "source", "notes", "sample_rate", "tear_start_s", "tear_end_s", "segment_manual", "duration_s", "speed_in_per_s",
507+ "energy_db", "energy_raw_db", "background_db", "above_background_db", "median_hz", "centroid_hz", "f10_hz", "f90_hz", "peak_dbfs", "near_clip_samples",
508+ "band_low_hz", "band_high_hz", "sheet_length_in",
509+ ];
510+ const q = (v: unknown) => {
511+ const s = String(v ?? "");
512+ return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
513+ };
514+ const lines = [head.join(",")];
515+ for (const { meta: m, a } of rows) {
516+ lines.push(
517+ [
518+ m.id, new Date(m.createdAt).toISOString(), m.label, m.source, m.notes, m.sampleRate, a.segment.start.toFixed(4), a.segment.end.toFixed(4), m.segmentManual,
519+ a.duration.toFixed(4), a.speedInPerSec.toFixed(4), db10(a.energy).toFixed(3), db10(a.energyRaw).toFixed(3), db10(a.energyNoise).toFixed(3),
520+ a.snrDb.toFixed(2), a.medianFreq.toFixed(1), a.centroid.toFixed(1), a.f10.toFixed(1), a.f90.toFixed(1), a.peakDbfs.toFixed(2), a.nearClip,
521+ settings.bandLow, settings.bandHigh, settings.sheetLengthIn,
522+ ]
523+ .map(q)
524+ .join(","),
525+ );
526+ }
527+ download(new Blob([lines.join("\n")], { type: "text/csv" }), `rip-sound-summary-${new Date().toISOString().slice(0, 10)}.csv`);
528+}
src/components/RecordBar.tsxadded+313−0View file
@@ -0,0 +1,313 @@
1+import { useEffect, useRef, useState } from "react";
2+import { MicRecorder, listInputs, type CaptureInfo } from "../audio/recorder.ts";
3+import { decodeWav } from "../audio/wav.ts";
4+import { syntheticTear } from "../audio/synthetic.ts";
5+import { detectSegment } from "../analysis/analyze.ts";
6+import { newId, type RecordingMeta } from "../storage/db.ts";
7+import { PRESET_LABELS } from "../model.ts";
8+
9+const MAX_SECONDS = 60;
10+
11+interface Props {
12+ label: string;
13+ setLabel: (l: string) => void;
14+ knownLabels: string[];
15+ onNew: (meta: RecordingMeta, samples: Float32Array) => Promise<void>;
16+}
17+
18+type Status = "closed" | "opening" | "ready" | "recording" | "saving";
19+
20+export function RecordBar({ label, setLabel, knownLabels, onNew }: Props) {
21+ const rec = useRef<MicRecorder>(null);
22+ rec.current ??= new MicRecorder();
23+ const [status, setStatus] = useState<Status>("closed");
24+ const [info, setInfo] = useState<CaptureInfo | null>(null);
25+ const [devices, setDevices] = useState<MediaDeviceInfo[]>([]);
26+ const [deviceId, setDeviceId] = useState<string>("");
27+ const [error, setError] = useState<string | null>(null);
28+ const [level, setLevel] = useState(-120);
29+ const [clipped, setClipped] = useState(false);
30+ const [elapsed, setElapsed] = useState(0);
31+ const [synthT, setSynthT] = useState(1);
32+ const peakAcc = useRef(0);
33+ const peakHold = useRef(0);
34+ const startedAt = useRef(0);
35+ const statusRef = useRef(status);
36+ statusRef.current = status;
37+
38+ // meter: accumulate peaks from the worklet, repaint at display rate
39+ useEffect(() => {
40+ let raf = 0;
41+ const tick = () => {
42+ const p = peakAcc.current;
43+ peakAcc.current = 0;
44+ peakHold.current = Math.max(p, peakHold.current * 0.93);
45+ setLevel(20 * Math.log10(Math.max(peakHold.current, 1e-6)));
46+ if (statusRef.current === "recording") {
47+ const t = (performance.now() - startedAt.current) / 1000;
48+ setElapsed(t);
49+ if (t > MAX_SECONDS) void stop();
50+ }
51+ raf = requestAnimationFrame(tick);
52+ };
53+ raf = requestAnimationFrame(tick);
54+ return () => cancelAnimationFrame(raf);
55+ // eslint-disable-next-line react-hooks/exhaustive-deps
56+ }, []);
57+
58+ useEffect(() => () => void rec.current?.close(), []);
59+
60+ async function open(id?: string) {
61+ setError(null);
62+ setStatus("opening");
63+ try {
64+ const r = rec.current!;
65+ r.onPeak = (p) => {
66+ peakAcc.current = Math.max(peakAcc.current, p);
67+ if (p >= 0.99 && r.recording) setClipped(true);
68+ };
69+ const inf = await r.open(id || undefined);
70+ setInfo(inf);
71+ setDevices(await listInputs());
72+ const dev = (inf.trackSettings.deviceId as string) ?? "";
73+ setDeviceId(dev);
74+ setStatus("ready");
75+ } catch (e) {
76+ setError(`Could not open the microphone: ${(e as Error).message}`);
77+ setStatus("closed");
78+ }
79+ }
80+
81+ function start() {
82+ if (statusRef.current !== "ready") return;
83+ setClipped(false);
84+ setElapsed(0);
85+ startedAt.current = performance.now();
86+ rec.current!.start();
87+ setStatus("recording");
88+ }
89+
90+ async function stop() {
91+ if (statusRef.current !== "recording") return;
92+ setStatus("saving");
93+ const r = rec.current!;
94+ const x = await r.stop();
95+ const fs = r.sampleRate;
96+ if (x.length < fs * 0.5) {
97+ setError("Recording was shorter than half a second and was discarded.");
98+ setStatus("ready");
99+ return;
100+ }
101+ const seg = detectSegment(x, fs);
102+ const meta: RecordingMeta = {
103+ id: newId(),
104+ createdAt: Date.now(),
105+ label: label.trim() || "unlabelled",
106+ notes: "",
107+ material: "paper",
108+ source: "mic",
109+ sampleRate: fs,
110+ length: x.length,
111+ segment: seg,
112+ segmentManual: false,
113+ capture: r.info ?? undefined,
114+ };
115+ await onNew(meta, x);
116+ setStatus("ready");
117+ }
118+
119+ // space bar toggles recording (ignored while typing)
120+ useEffect(() => {
121+ const onKey = (e: KeyboardEvent) => {
122+ if (e.code !== "Space" || e.repeat) return;
123+ const t = e.target as HTMLElement;
124+ if (t.closest("input, textarea, select, button")) return;
125+ if (statusRef.current === "ready") {
126+ e.preventDefault();
127+ start();
128+ } else if (statusRef.current === "recording") {
129+ e.preventDefault();
130+ void stop();
131+ }
132+ };
133+ window.addEventListener("keydown", onKey);
134+ return () => window.removeEventListener("keydown", onKey);
135+ });
136+
137+ async function importFiles(files: FileList | null) {
138+ if (!files) return;
139+ setError(null);
140+ for (const f of Array.from(files)) {
141+ const buf = await f.arrayBuffer();
142+ let fs: number;
143+ let x: Float32Array;
144+ let note = "";
145+ const d = decodeWav(buf);
146+ if (d) {
147+ fs = d.sampleRate;
148+ x = d.samples;
149+ if (d.channels > 1) note = `File had ${d.channels} channels; only the first is used.`;
150+ } else {
151+ // other formats: let the browser decode (this resamples to the context rate)
152+ try {
153+ const ctx = new OfflineAudioContext(1, 1, 48000);
154+ const ab = await ctx.decodeAudioData(buf);
155+ fs = ab.sampleRate;
156+ x = ab.getChannelData(0).slice();
157+ note = "Decoded by the browser (not WAV): may have been resampled or lossy-compressed.";
158+ } catch {
159+ setError(`Could not read ${f.name}.`);
160+ continue;
161+ }
162+ }
163+ const name = f.name.replace(/\.[^.]+$/, "");
164+ await onNew(
165+ {
166+ id: newId(),
167+ createdAt: Date.now(),
168+ label: label.trim() || "unlabelled",
169+ notes: note,
170+ material: "paper",
171+ source: "file",
172+ fileName: f.name || name,
173+ sampleRate: fs,
174+ length: x.length,
175+ segment: detectSegment(x, fs),
176+ segmentManual: false,
177+ },
178+ x,
179+ );
180+ }
181+ }
182+
183+ async function addSynthetic() {
184+ const fs = 48000;
185+ const x = syntheticTear({ tearSeconds: synthT, sampleRate: fs, seed: Math.floor(Math.random() * 1e9) });
186+ await onNew(
187+ {
188+ id: newId(),
189+ createdAt: Date.now(),
190+ label: `synthetic ${synthT} s`,
191+ notes: "Synthetic: 4000 identical-shape clicks with random times and amplitudes. Not a real recording.",
192+ material: "synthetic",
193+ source: "synthetic",
194+ sampleRate: fs,
195+ length: x.length,
196+ segment: detectSegment(x, fs),
197+ segmentManual: false,
198+ },
199+ x,
200+ );
201+ }
202+
203+ const s = info?.trackSettings ?? {};
204+ const processingOn = ["echoCancellation", "noiseSuppression", "autoGainControl"].filter((k) => s[k] === true);
205+ const meterPct = Math.max(0, Math.min(100, ((level + 60) / 60) * 100));
206+
207+ return (
208+ <section className="card recordbar" aria-label="Record">
209+ <div className="rb-row">
210+ <div className="rb-label">
211+ <label htmlFor="speed-label">Speed label for the next recording</label>
212+ <div className="chips">
213+ {PRESET_LABELS.map((l) => (
214+ <button key={l} className={`chip ${l === label ? "on" : ""}`} onClick={() => setLabel(l)}>
215+ {l}
216+ </button>
217+ ))}
218+ </div>
219+ <input
220+ id="speed-label"
221+ list="known-labels"
222+ value={label}
223+ onChange={(e) => setLabel(e.target.value)}
224+ placeholder="or type your own label"
225+ />
226+ <datalist id="known-labels">
227+ {knownLabels.map((l) => (
228+ <option key={l} value={l} />
229+ ))}
230+ </datalist>
231+ </div>
232+
233+ <div className="rb-controls">
234+ {status === "closed" || status === "opening" ? (
235+ <button className="primary big" onClick={() => open()} disabled={status === "opening"}>
236+ {status === "opening" ? "Opening…" : "Enable microphone"}
237+ </button>
238+ ) : (
239+ <>
240+ <button
241+ className={`primary big ${status === "recording" ? "recording" : ""}`}
242+ onClick={() => (status === "recording" ? stop() : start())}
243+ disabled={status === "saving"}
244+ >
245+ {status === "recording" ? `■ Stop ${elapsed.toFixed(1)} s` : status === "saving" ? "Saving…" : "● Record"}
246+ </button>
247+ <div className="hint">Space bar also starts / stops.</div>
248+ <div className="meter" title="Peak level (dBFS)">
249+ <div className="meter-fill" style={{ width: `${meterPct}%` }} />
250+ <span className="meter-text">{level > -119 ? `${level.toFixed(0)} dBFS` : "–"}</span>
251+ </div>
252+ {clipped && <div className="warn">⚠ Clipping in this recording: energy will be underestimated. Move the paper further from the mic.</div>}
253+ </>
254+ )}
255+ </div>
256+ </div>
257+
258+ <p className="howto">
259+ Press record, keep still for about a second, tear one strip off the full 11 inch sheet, keep still for another second, then stop.
260+ Keep the paper at the same distance and position relative to the microphone every time.
261+ </p>
262+
263+ {info && (
264+ <div className="capture-info">
265+ <span>
266+ <b>{info.deviceLabel || "microphone"}</b>
267+ </span>
268+ {devices.length > 1 && (
269+ <select value={deviceId} onChange={(e) => open(e.target.value)} disabled={status === "recording"} aria-label="Input device">
270+ {devices.map((d) => (
271+ <option key={d.deviceId} value={d.deviceId}>
272+ {d.label || d.deviceId}
273+ </option>
274+ ))}
275+ </select>
276+ )}
277+ <span>{info.contextSampleRate} Hz</span>
278+ <span>{String(s.channelCount ?? "?")} ch</span>
279+ {processingOn.length ? (
280+ <span className="warn">⚠ Browser processing still on: {processingOn.join(", ")}</span>
281+ ) : (
282+ <span className="ok">Browser processing off (echo cancellation, noise suppression, auto gain)</span>
283+ )}
284+ {typeof s.sampleRate === "number" && s.sampleRate !== info.contextSampleRate && (
285+ <span className="warn">⚠ Mic rate {String(s.sampleRate)} Hz ≠ capture rate: audio is being resampled</span>
286+ )}
287+ </div>
288+ )}
289+ {error && <div className="warn">{error}</div>}
290+
291+ <details className="more">
292+ <summary>Import a file or add a synthetic test tear</summary>
293+ <div className="more-body">
294+ <label className="filepick">
295+ Import WAV file(s) (labelled with the speed label above)
296+ <input type="file" accept=".wav,audio/*" multiple onChange={(e) => importFiles(e.target.files)} />
297+ </label>
298+ <div className="synth">
299+ <span>Synthetic tear (identical clicks, for checking the analysis):</span>
300+ <select value={synthT} onChange={(e) => setSynthT(+e.target.value)} aria-label="Synthetic tear duration">
301+ {[0.3, 1, 3, 10].map((t) => (
302+ <option key={t} value={t}>
303+ {t} s
304+ </option>
305+ ))}
306+ </select>
307+ <button onClick={addSynthetic}>Add</button>
308+ </div>
309+ </div>
310+ </details>
311+ </section>
312+ );
313+}
src/components/RecordingView.tsxadded+550−0View file
@@ -0,0 +1,550 @@
1+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2+import { CanvasPlot, drawLine, readTheme, type PointerInfo, type Scales, type Theme } from "./CanvasPlot.tsx";
3+import { detectSegment, frameLevels, smoothLog, spectrogram, type Analysis, type AnalysisSettings, type Segment } from "../analysis/analyze.ts";
4+import type { RecordingMeta } from "../storage/db.ts";
5+import { encodeWavFloat32 } from "../audio/wav.ts";
6+import { colorFor, db10, download, fmtDate, fmtHz, fmtSec, getAnalysis, getAudio, groupStyle, PRESET_LABELS, safeName } from "../model.ts";
7+import { magma } from "../colormap.ts";
8+
9+interface Props {
10+ meta: RecordingMeta;
11+ all: RecordingMeta[];
12+ settings: AnalysisSettings;
13+ onUpdate: (m: RecordingMeta) => void;
14+ onDelete: (m: RecordingMeta) => void;
15+}
16+
17+const SMOOTHING: [string, number][] = [
18+ ["none", 0],
19+ ["1/24 octave", 1 / 24],
20+ ["1/12 octave", 1 / 12],
21+ ["1/6 octave", 1 / 6],
22+ ["1/3 octave", 1 / 3],
23+];
24+
25+let playCtx: AudioContext | null = null;
26+let playing: AudioBufferSourceNode | null = null;
27+
28+function play(x: Float32Array, fs: number, a: number, b: number) {
29+ stopPlay();
30+ playCtx ??= new AudioContext();
31+ const s = Math.max(0, Math.floor(a * fs));
32+ const e = Math.min(x.length, Math.ceil(b * fs));
33+ const buf = playCtx.createBuffer(1, Math.max(1, e - s), fs);
34+ buf.copyToChannel(x.subarray(s, e) as Float32Array<ArrayBuffer>, 0);
35+ const src = playCtx.createBufferSource();
36+ src.buffer = buf;
37+ src.connect(playCtx.destination);
38+ src.start();
39+ playing = src;
40+}
41+
42+function stopPlay() {
43+ try {
44+ playing?.stop();
45+ } catch {
46+ /* already stopped */
47+ }
48+ playing = null;
49+}
50+
51+export function RecordingView({ meta, all, settings, onUpdate, onDelete }: Props) {
52+ const [x, setX] = useState<Float32Array | null>(null);
53+ const [analysis, setAnalysis] = useState<Analysis | null>(null);
54+ const dur = meta.length / meta.sampleRate;
55+ const [view, setView] = useState<[number, number]>([0, dur]);
56+ const [seg, setSeg] = useState<Segment | null>(meta.segment);
57+ const [smoothing, setSmoothing] = useState(1 / 12);
58+ const [notes, setNotes] = useState(meta.notes);
59+ const [label, setLabel] = useState(meta.label);
60+
61+ useEffect(() => {
62+ let live = true;
63+ setX(null);
64+ setView([0, meta.length / meta.sampleRate]);
65+ setNotes(meta.notes);
66+ setLabel(meta.label);
67+ getAudio(meta.id).then((a) => live && setX(a));
68+ return () => {
69+ live = false;
70+ stopPlay();
71+ };
72+ }, [meta.id, meta.length, meta.sampleRate, meta.notes, meta.label]);
73+
74+ useEffect(() => setSeg(meta.segment), [meta.segment]);
75+
76+ useEffect(() => {
77+ let live = true;
78+ setAnalysis(null);
79+ getAnalysis(meta, settings).then((a) => live && setAnalysis(a));
80+ return () => {
81+ live = false;
82+ };
83+ }, [meta, settings]);
84+
85+ const fs = meta.sampleRate;
86+ const levels = useMemo(() => (x ? frameLevels(x, fs, 0.005) : null), [x, fs]);
87+ const spec = useMemo(() => (x ? spectrogram(x, fs) : null), [x, fs]);
88+ const specImage = useMemo(() => (spec ? spectrogramImage(spec) : null), [spec]);
89+
90+ const commitSeg = (s: Segment | null) => {
91+ onUpdate({ ...meta, segment: s, segmentManual: true });
92+ };
93+
94+ // ---------- shared time-axis interaction ----------
95+ const drag = useRef<{ kind: "start" | "end" | "pan"; px0: number; view0: [number, number] } | null>(null);
96+ const edgeAt = (p: PointerInfo): "start" | "end" | null => {
97+ if (!seg) return null;
98+ if (Math.abs(p.px - p.scales.x(seg.start)) < 7) return "start";
99+ if (Math.abs(p.px - p.scales.x(seg.end)) < 7) return "end";
100+ return null;
101+ };
102+ const clampView = (a: number, b: number): [number, number] => {
103+ const w = Math.min(dur, Math.max(b - a, 0.002));
104+ let s = Math.max(0, a);
105+ if (s + w > dur) s = dur - w;
106+ return [s, s + w];
107+ };
108+ const timeHandlers = {
109+ onWheel: (p: PointerInfo, ev: WheelEvent) => {
110+ if (Math.abs(ev.deltaX) > Math.abs(ev.deltaY)) {
111+ const shift = (ev.deltaX / (p.scales.right - p.scales.left)) * (view[1] - view[0]);
112+ setView(clampView(view[0] + shift, view[1] + shift));
113+ return;
114+ }
115+ const f = Math.exp(ev.deltaY * 0.0025);
116+ const t = Math.min(Math.max(p.xv, view[0]), view[1]);
117+ setView(clampView(t - (t - view[0]) * f, t + (view[1] - t) * f));
118+ },
119+ onPointer: (type: "down" | "move" | "up", p: PointerInfo) => {
120+ if (type === "down") {
121+ drag.current = { kind: edgeAt(p) ?? "pan", px0: p.px, view0: view };
122+ } else if (type === "move" && drag.current) {
123+ const d = drag.current;
124+ if (d.kind === "pan") {
125+ const dt = ((p.px - d.px0) / (p.scales.right - p.scales.left)) * (d.view0[1] - d.view0[0]);
126+ setView(clampView(d.view0[0] - dt, d.view0[1] - dt));
127+ } else if (seg) {
128+ const t = Math.min(Math.max(p.xv, 0), dur);
129+ setSeg(d.kind === "start" ? { start: Math.min(t, seg.end - 0.005), end: seg.end } : { start: seg.start, end: Math.max(t, seg.start + 0.005) });
130+ }
131+ } else if (type === "up") {
132+ if (drag.current && drag.current.kind !== "pan" && seg) commitSeg(seg);
133+ drag.current = null;
134+ }
135+ },
136+ onDoubleClick: () => setView([0, dur]),
137+ cursor: (p: PointerInfo) => (edgeAt(p) ? "ew-resize" : "grab"),
138+ };
139+
140+ const drawSeg = useCallback(
141+ (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
142+ if (!seg) return;
143+ const a = s.x(seg.start);
144+ const b = s.x(seg.end);
145+ ctx.fillStyle = th.seg;
146+ ctx.fillRect(a, s.top, b - a, s.bottom - s.top);
147+ ctx.strokeStyle = th.ink2;
148+ ctx.lineWidth = 1.5;
149+ ctx.beginPath();
150+ ctx.moveTo(a, s.top);
151+ ctx.lineTo(a, s.bottom);
152+ ctx.moveTo(b, s.top);
153+ ctx.lineTo(b, s.bottom);
154+ ctx.stroke();
155+ },
156+ [seg],
157+ );
158+
159+ const { slot } = groupStyle(meta.label, all);
160+ const mainColor = (th: Theme) => colorFor(slot, th.series, th.ink2);
161+
162+ const levelRange = useMemo<[number, number]>(() => {
163+ if (!levels) return [-100, 0];
164+ const dbs = Array.from(levels.power, (p) => db10(p)).sort((a, b) => a - b);
165+ const lo = dbs[Math.floor(dbs.length * 0.01)] ?? -100;
166+ return [Math.max(-140, Math.floor((lo - 6) / 10) * 10), 0];
167+ }, [levels]);
168+
169+ const drawLevel = useCallback(
170+ (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
171+ drawSeg(ctx, s, th);
172+ if (!levels) return;
173+ const { frameSec, power } = levels;
174+ const i0 = Math.max(0, Math.floor(view[0] / frameSec) - 1);
175+ const i1 = Math.min(power.length, Math.ceil(view[1] / frameSec) + 1);
176+ const step = Math.max(1, Math.floor((i1 - i0) / ((s.right - s.left) * 2)));
177+ const xs: number[] = [];
178+ const ys: number[] = [];
179+ for (let i = i0; i < i1; i += step) {
180+ let m = 0;
181+ for (let j = i; j < Math.min(i + step, i1); j++) m = Math.max(m, power[j]);
182+ xs.push((i + step / 2) * frameSec);
183+ ys.push(db10(m));
184+ }
185+ drawLine(ctx, s, xs, ys, mainColor(th), 1.5);
186+ },
187+ // eslint-disable-next-line react-hooks/exhaustive-deps
188+ [levels, view, drawSeg, slot],
189+ );
190+
191+ const waveMax = useMemo(() => {
192+ if (!x) return 1;
193+ let m = 0;
194+ for (let i = 0; i < x.length; i++) m = Math.max(m, Math.abs(x[i]));
195+ return Math.max(m * 1.05, 1e-4);
196+ }, [x]);
197+
198+ const drawWave = useCallback(
199+ (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
200+ drawSeg(ctx, s, th);
201+ if (!x) return;
202+ const color = mainColor(th);
203+ const a = Math.max(0, Math.floor(view[0] * fs));
204+ const b = Math.min(x.length, Math.ceil(view[1] * fs));
205+ const px = s.right - s.left;
206+ const perPx = (b - a) / px;
207+ if (perPx < 2) {
208+ const xs: number[] = [];
209+ const ys: number[] = [];
210+ for (let i = Math.max(0, a - 1); i < Math.min(x.length, b + 1); i++) {
211+ xs.push(i / fs);
212+ ys.push(x[i]);
213+ }
214+ drawLine(ctx, s, xs, ys, color, 1.5);
215+ if (perPx < 0.15) {
216+ ctx.fillStyle = color;
217+ for (let i = 0; i < xs.length; i++) ctx.fillRect(s.x(xs[i]) - 1.5, s.y(ys[i]) - 1.5, 3, 3);
218+ }
219+ return;
220+ }
221+ ctx.fillStyle = color;
222+ for (let c = 0; c < px; c++) {
223+ const i0 = a + Math.floor(c * perPx);
224+ const i1 = Math.min(b, a + Math.floor((c + 1) * perPx));
225+ let lo = Infinity;
226+ let hi = -Infinity;
227+ for (let i = i0; i < i1; i++) {
228+ const v = x[i];
229+ if (v < lo) lo = v;
230+ if (v > hi) hi = v;
231+ }
232+ if (lo > hi) continue;
233+ const y0 = s.y(hi);
234+ const y1 = s.y(lo);
235+ ctx.fillRect(s.left + c, y0, 1, Math.max(1, y1 - y0));
236+ }
237+ },
238+ // eslint-disable-next-line react-hooks/exhaustive-deps
239+ [x, view, fs, drawSeg, slot],
240+ );
241+
242+ const drawSpec = useCallback(
243+ (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
244+ if (spec && specImage) {
245+ const c0 = (view[0] - spec.t0) / spec.dt;
246+ const c1 = (view[1] - spec.t0) / spec.dt;
247+ ctx.imageSmoothingEnabled = c1 - c0 < s.right - s.left;
248+ const sx0 = Math.max(0, c0);
249+ const sx1 = Math.min(spec.cols, c1);
250+ const dx0 = s.x(spec.t0 + sx0 * spec.dt);
251+ const dx1 = s.x(spec.t0 + sx1 * spec.dt);
252+ if (sx1 > sx0) ctx.drawImage(specImage, sx0, 0, sx1 - sx0, spec.bins, dx0, s.top, dx1 - dx0, s.bottom - s.top);
253+ }
254+ if (seg) {
255+ ctx.strokeStyle = th.surface;
256+ ctx.lineWidth = 1.5;
257+ ctx.setLineDash([4, 3]);
258+ ctx.beginPath();
259+ for (const t of [seg.start, seg.end]) {
260+ ctx.moveTo(s.x(t), s.top);
261+ ctx.lineTo(s.x(t), s.bottom);
262+ }
263+ ctx.stroke();
264+ ctx.setLineDash([]);
265+ }
266+ },
267+ [spec, specImage, view, seg],
268+ );
269+
270+ // ---------- spectrum ----------
271+ const fLo = 20;
272+ const fHi = fs / 2;
273+ const specLines = useMemo(() => {
274+ if (!analysis) return null;
275+ const tear = smoothLog(analysis.freqs, analysis.esd, fLo, fHi, smoothing);
276+ const bg = analysis.noiseEsd ? smoothLog(analysis.freqs, analysis.noiseEsd, fLo, fHi, smoothing) : null;
277+ return { f: tear.f, tear: tear.v.map(db10), bg: bg ? bg.v.map(db10) : null };
278+ }, [analysis, smoothing, fHi]);
279+ const specRange = useMemo<[number, number]>(() => {
280+ if (!specLines) return [-160, -60];
281+ const top = Math.max(...specLines.tear.filter(Number.isFinite));
282+ return [Math.floor((top - 80) / 10) * 10, Math.ceil((top + 3) / 10) * 10];
283+ }, [specLines]);
284+
285+ const drawSpectrum = useCallback(
286+ (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
287+ if (!specLines) return;
288+ // grey out what lies outside the analysis band
289+ ctx.fillStyle = th.seg;
290+ const bl = s.x(settings.bandLow);
291+ const bh = s.x(Math.min(settings.bandHigh, fHi));
292+ ctx.fillRect(s.left, s.top, bl - s.left, s.bottom - s.top);
293+ ctx.fillRect(bh, s.top, s.right - bh, s.bottom - s.top);
294+ if (specLines.bg) drawLine(ctx, s, specLines.f, specLines.bg, th.muted, 2, [5, 4]);
295+ drawLine(ctx, s, specLines.f, specLines.tear, mainColor(th), 2);
296+ },
297+ // eslint-disable-next-line react-hooks/exhaustive-deps
298+ [specLines, settings, fHi, slot],
299+ );
300+
301+ const specHover = (p: PointerInfo) => {
302+ if (!specLines) return null;
303+ let best = 0;
304+ for (let i = 1; i < specLines.f.length; i++) if (Math.abs(Math.log(specLines.f[i] / p.xv)) < Math.abs(Math.log(specLines.f[best] / p.xv))) best = i;
305+ const lines = [fmtHz(specLines.f[best]), `tear: ${specLines.tear[best].toFixed(1)} dB`];
306+ if (specLines.bg) lines.push(`background: ${specLines.bg[best].toFixed(1)} dB`);
307+ return { lines, x: specLines.f[best], y: specLines.tear[best] };
308+ };
309+
310+ const timeHover = (p: PointerInfo) => {
311+ const lines = [`${p.xv.toFixed(p.xv < 10 ? 3 : 2)} s`];
312+ if (levels) {
313+ const i = Math.floor(p.xv / levels.frameSec);
314+ if (i >= 0 && i < levels.power.length) lines.push(`level: ${db10(levels.power[i]).toFixed(1)} dBFS (5 ms RMS)`);
315+ }
316+ return { lines };
317+ };
318+
319+ // ---------- actions ----------
320+ const saveNotes = () => notes !== meta.notes && onUpdate({ ...meta, notes });
321+ const saveLabel = (l: string) => {
322+ setLabel(l);
323+ if (l.trim() && l !== meta.label) onUpdate({ ...meta, label: l.trim() });
324+ };
325+ const autoDetect = () => {
326+ if (!x) return;
327+ const s = detectSegment(x, fs);
328+ onUpdate({ ...meta, segment: s, segmentManual: false });
329+ };
330+ const exportWav = () => {
331+ if (!x) return;
332+ const d = new Date(meta.createdAt).toISOString().replace(/[:]/g, "-").slice(0, 19);
333+ download(encodeWavFloat32(x, fs), `${d}_${safeName(meta.label)}_${meta.id.slice(0, 6)}.wav`);
334+ };
335+
336+ const a = analysis;
337+ const warnings: string[] = [];
338+ if (!seg) warnings.push("No tear was found automatically. Zoom so the tear fills the view and press “Use visible range as tear”.");
339+ if (a && a.nearClip > 0) warnings.push(`${a.nearClip} samples in the tear are at or near full scale (clipping). The energy is underestimated and the spectrum is distorted.`);
340+ if (a && !a.noiseEsd) warnings.push("Not enough quiet audio before or after the tear to estimate the background, so nothing was subtracted.");
341+ else if (a && a.snrDb < 10) warnings.push(`The tear is only ${a.snrDb.toFixed(1)} dB above the background in the analysis band; the energy estimate is sensitive to the background subtraction.`);
342+ if (seg && (seg.start < 0.05 || seg.end > dur - 0.05)) warnings.push("The tear touches the start or end of the recording and may be cut off.");
343+
344+ return (
345+ <div className="recview">
346+ <section className="card">
347+ <div className="rv-head">
348+ <div className="rv-title">
349+ <input
350+ className="label-edit"
351+ list="known-labels"
352+ value={label}
353+ onChange={(e) => setLabel(e.target.value)}
354+ onBlur={(e) => saveLabel(e.target.value)}
355+ onKeyDown={(e) => e.key === "Enter" && (e.target as HTMLInputElement).blur()}
356+ aria-label="Speed label"
357+ />
358+ <select value="" onChange={(e) => e.target.value && saveLabel(e.target.value)} aria-label="Choose a preset label">
359+ <option value="">preset…</option>
360+ {PRESET_LABELS.map((l) => (
361+ <option key={l}>{l}</option>
362+ ))}
363+ </select>
364+ <span className={`badge ${meta.source}`}>{meta.source === "mic" ? "microphone" : meta.source}</span>
365+ <span className="muted">
366+ {fmtDate(meta.createdAt)} · {fmtSec(dur)} · {fs} Hz{meta.fileName ? ` · ${meta.fileName}` : ""}
367+ </span>
368+ </div>
369+ <div className="rv-actions">
370+ <button disabled={!x || !seg} onClick={() => x && seg && play(x, fs, seg.start, seg.end)}>
371+ ▶ Play tear
372+ </button>
373+ <button disabled={!x} onClick={() => x && play(x, fs, 0, dur)}>
374+ ▶ Play all
375+ </button>
376+ <button onClick={stopPlay}>■</button>
377+ <button disabled={!x} onClick={exportWav}>
378+ Download WAV
379+ </button>
380+ <button className="danger" onClick={() => onDelete(meta)}>
381+ Delete
382+ </button>
383+ </div>
384+ </div>
385+ <textarea
386+ className="notes"
387+ placeholder="Notes (paper type, how it was torn, anything unusual)"
388+ value={notes}
389+ onChange={(e) => setNotes(e.target.value)}
390+ onBlur={saveNotes}
391+ rows={1}
392+ />
393+ {warnings.map((w) => (
394+ <div key={w} className="warn">
395+ ⚠ {w}
396+ </div>
397+ ))}
398+ <Stats a={a} settings={settings} manual={meta.segmentManual} />
399+ </section>
400+
401+ <section className="card">
402+ <div className="plot-head">
403+ <h3>Over time</h3>
404+ <div className="toolbar">
405+ <span className="hint">Scroll to zoom, drag to pan, drag the edges of the shaded tear to adjust it, double-click to reset.</span>
406+ <button disabled={!seg} onClick={() => seg && setView(clampView(seg.start - 0.1 * (seg.end - seg.start), seg.end + 0.1 * (seg.end - seg.start)))}>
407+ Zoom to tear
408+ </button>
409+ <button onClick={() => setView([0, dur])}>Full</button>
410+ <button onClick={() => commitSeg({ start: view[0], end: view[1] })}>Use visible range as tear</button>
411+ <button disabled={!x} onClick={autoDetect} title="Re-run automatic tear detection">
412+ Auto-detect tear
413+ </button>
414+ </div>
415+ </div>
416+ <CanvasPlot
417+ height={150}
418+ xRange={view}
419+ yRange={levelRange}
420+ xLabel="time (s)"
421+ yLabel="level (dBFS)"
422+ hideXTicks
423+ draw={drawLevel}
424+ hover={timeHover}
425+ ariaLabel="Sound level over time"
426+ {...timeHandlers}
427+ />
428+ <CanvasPlot
429+ height={150}
430+ xRange={view}
431+ yRange={[-waveMax, waveMax]}
432+ xLabel="time (s)"
433+ yLabel="waveform"
434+ hideXTicks
435+ draw={drawWave}
436+ hover={(p) => ({ lines: [`${p.xv.toFixed(4)} s`] })}
437+ ariaLabel="Waveform"
438+ {...timeHandlers}
439+ />
440+ <CanvasPlot
441+ height={220}
442+ xRange={view}
443+ yRange={[0, fs / 2]}
444+ xLabel="time (s)"
445+ yLabel="frequency (Hz)"
446+ draw={drawSpec}
447+ hover={(p) => ({ lines: [`${p.xv.toFixed(3)} s`, fmtHz(p.yv)] })}
448+ ariaLabel="Spectrogram"
449+ {...timeHandlers}
450+ />
451+ <p className="caption">
452+ Level is the RMS over 5 ms windows. Spectrogram: 1024-point Hann windows, colour spans the top 90 dB of this recording.
453+ </p>
454+ </section>
455+
456+ <section className="card">
457+ <div className="plot-head">
458+ <h3>Frequency makeup of the tear</h3>
459+ <label className="toolbar">
460+ smoothing
461+ <select value={smoothing} onChange={(e) => setSmoothing(+e.target.value)}>
462+ {SMOOTHING.map(([n, v]) => (
463+ <option key={n} value={v}>
464+ {n}
465+ </option>
466+ ))}
467+ </select>
468+ </label>
469+ </div>
470+ <CanvasPlot
471+ height={300}
472+ xRange={[fLo, fHi]}
473+ xLog
474+ yRange={specRange}
475+ xLabel="frequency (Hz)"
476+ yLabel="energy density (dB re FS²·s/Hz)"
477+ draw={drawSpectrum}
478+ hover={specHover}
479+ ariaLabel="Energy spectral density of the tear"
480+ />
481+ <div className="legend">
482+ <span>
483+ <i className="swatch" style={{ background: readThemeColor(slot) }} /> tear (energy spectral density)
484+ </span>
485+ <span>
486+ <i className="swatch dashed" /> background alone over the same duration
487+ </span>
488+ <span>
489+ <i className="swatch shade" /> outside the analysis band ({fmtHz(settings.bandLow)}–{fmtHz(settings.bandHigh)})
490+ </span>
491+ </div>
492+ </section>
493+ </div>
494+ );
495+}
496+
497+function readThemeColor(slot: number | null) {
498+ const th = readTheme(document.documentElement);
499+ return colorFor(slot, th.series, th.ink2);
500+}
501+
502+function Stats({ a, settings, manual }: { a: Analysis | null; settings: AnalysisSettings; manual: boolean }) {
503+ if (!a) return null;
504+ const items: [string, string, string?][] = [
505+ ["Tear duration", fmtSec(a.duration), manual ? "set by hand" : "auto-detected"],
506+ ["Speed", `${a.speedInPerSec.toFixed(2)} in/s`, `${settings.sheetLengthIn} in ÷ duration`],
507+ ["Sound energy", `${db10(a.energy).toFixed(1)} dB`, "re FS²·s, in band, background removed"],
508+ ["Mean power", `${db10(a.energy / a.duration).toFixed(1)} dBFS`, "energy ÷ duration"],
509+ ["Median frequency", fmtHz(a.medianFreq), "half the energy above, half below"],
510+ ["Centroid", fmtHz(a.centroid), "energy-weighted mean frequency"],
511+ ["10–90% of energy", `${fmtHz(a.f10)} – ${fmtHz(a.f90)}`],
512+ ["Peak", `${a.peakDbfs.toFixed(1)} dBFS`, a.nearClip ? `${a.nearClip} samples near clipping` : "no clipping"],
513+ ["Above background", Number.isFinite(a.snrDb) ? `${a.snrDb.toFixed(1)} dB` : "–", a.backgroundDbfs !== null ? `background ${a.backgroundDbfs.toFixed(1)} dBFS, from ${a.noiseSeconds.toFixed(1)} s` : "no background estimate"],
514+ ];
515+ return (
516+ <div className="stats">
517+ {items.map(([k, v, sub]) => (
518+ <div key={k} className="stat">
519+ <div className="stat-k">{k}</div>
520+ <div className="stat-v">{v}</div>
521+ {sub && <div className="stat-sub">{sub}</div>}
522+ </div>
523+ ))}
524+ </div>
525+ );
526+}
527+
528+function spectrogramImage(spec: ReturnType<typeof spectrogram>): HTMLCanvasElement {
529+ const c = document.createElement("canvas");
530+ c.width = spec.cols;
531+ c.height = spec.bins;
532+ const ctx = c.getContext("2d")!;
533+ const img = ctx.createImageData(spec.cols, spec.bins);
534+ const top = spec.maxDb;
535+ const range = 90;
536+ for (let col = 0; col < spec.cols; col++) {
537+ for (let k = 0; k < spec.bins; k++) {
538+ const v = (spec.db[col * spec.bins + k] - (top - range)) / range;
539+ const [r, g, b] = magma(Math.min(1, Math.max(0, v)));
540+ const row = spec.bins - 1 - k;
541+ const o = (row * spec.cols + col) * 4;
542+ img.data[o] = r;
543+ img.data[o + 1] = g;
544+ img.data[o + 2] = b;
545+ img.data[o + 3] = 255;
546+ }
547+ }
548+ ctx.putImageData(img, 0, 0);
549+ return c;
550+}
src/main.tsxadded+10−0View file
@@ -0,0 +1,10 @@
1+import { StrictMode } from "react";
2+import { createRoot } from "react-dom/client";
3+import { App } from "./App.tsx";
4+import "./styles.css";
5+
6+createRoot(document.getElementById("root")!).render(
7+ <StrictMode>
8+ <App />
9+ </StrictMode>,
10+);
src/model.tsadded+147−0View file
@@ -0,0 +1,147 @@
1+import { analyze, DEFAULT_SETTINGS, type Analysis, type AnalysisSettings } from "./analysis/analyze.ts";
2+import { loadAudio, type RecordingMeta } from "./storage/db.ts";
3+import type { MarkerShape } from "./components/CanvasPlot.tsx";
4+import { SHAPES } from "./components/CanvasPlot.tsx";
5+
6+export const PRESET_LABELS = [
7+ "very slow (~10 s)",
8+ "slow (~5 s)",
9+ "medium (~2 s)",
10+ "fast (~1 s)",
11+ "very fast (<0.5 s)",
12+];
13+
14+// Groups in display order: presets first (slow to fast), then custom labels by first use.
15+export function groupOrder(recs: RecordingMeta[]): string[] {
16+ const used = new Set(recs.map((r) => r.label));
17+ const out = PRESET_LABELS.filter((l) => used.has(l));
18+ for (const r of recs) if (!out.includes(r.label)) out.push(r.label);
19+ return out;
20+}
21+
22+// Colour follows the label, not its position in a filtered list: presets own slots 1–5,
23+// custom labels take 6–8 in order of first use, anything beyond shares the muted colour.
24+export function groupStyle(label: string, recs: RecordingMeta[]): { slot: number | null; shape: MarkerShape } {
25+ const p = PRESET_LABELS.indexOf(label);
26+ if (p >= 0) return { slot: p, shape: SHAPES[p % SHAPES.length] };
27+ const custom: string[] = [];
28+ for (const r of recs) if (!PRESET_LABELS.includes(r.label) && !custom.includes(r.label)) custom.push(r.label);
29+ const c = custom.indexOf(label);
30+ const slot = c >= 0 && c < 3 ? 5 + c : null;
31+ return { slot, shape: SHAPES[(5 + Math.max(c, 0)) % SHAPES.length] };
32+}
33+
34+export function colorFor(slot: number | null, series: string[], muted: string) {
35+ return slot === null ? muted : series[slot];
36+}
37+
38+// ---------- settings ----------
39+
40+const SETTINGS_KEY = "rsa-settings";
41+
42+export function loadSettings(): AnalysisSettings {
43+ try {
44+ const s = JSON.parse(localStorage.getItem(SETTINGS_KEY) ?? "null");
45+ if (s) return { ...DEFAULT_SETTINGS, ...s };
46+ } catch {
47+ /* ignore */
48+ }
49+ return { ...DEFAULT_SETTINGS };
50+}
51+
52+export function storeSettings(s: AnalysisSettings) {
53+ try {
54+ localStorage.setItem(SETTINGS_KEY, JSON.stringify(s));
55+ } catch {
56+ /* ignore */
57+ }
58+}
59+
60+// ---------- audio + analysis caches ----------
61+
62+const audioCache = new Map<string, Promise<Float32Array>>();
63+
64+export function getAudio(id: string): Promise<Float32Array> {
65+ let p = audioCache.get(id);
66+ if (!p) {
67+ p = loadAudio(id);
68+ audioCache.set(id, p);
69+ }
70+ return p;
71+}
72+
73+export function putAudio(id: string, x: Float32Array) {
74+ audioCache.set(id, Promise.resolve(x));
75+}
76+
77+export function forgetAudio(id: string) {
78+ audioCache.delete(id);
79+}
80+
81+const analysisCache = new Map<string, Analysis>();
82+
83+function key(m: RecordingMeta, s: AnalysisSettings) {
84+ return JSON.stringify([m.id, m.segment, s]);
85+}
86+
87+export async function getAnalysis(m: RecordingMeta, s: AnalysisSettings): Promise<Analysis | null> {
88+ if (!m.segment) return null;
89+ const k = key(m, s);
90+ const hit = analysisCache.get(k);
91+ if (hit) return hit;
92+ const x = await getAudio(m.id);
93+ const a = analyze(x, m.sampleRate, m.segment, s);
94+ analysisCache.set(k, a);
95+ return a;
96+}
97+
98+// ---------- formatting ----------
99+
100+export const db10 = (v: number) => 10 * Math.log10(Math.max(v, 1e-30));
101+
102+export function fmtHz(v: number) {
103+ if (!Number.isFinite(v)) return "–";
104+ return v >= 1000 ? `${(v / 1000).toFixed(2)} kHz` : `${v.toFixed(0)} Hz`;
105+}
106+
107+export function fmtSec(v: number) {
108+ return v < 1 ? `${(v * 1000).toFixed(0)} ms` : `${v.toFixed(2)} s`;
109+}
110+
111+export function fmtDate(t: number) {
112+ return new Date(t).toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", second: "2-digit" });
113+}
114+
115+export function download(blob: Blob, name: string) {
116+ const url = URL.createObjectURL(blob);
117+ const a = document.createElement("a");
118+ a.href = url;
119+ a.download = name;
120+ a.click();
121+ setTimeout(() => URL.revokeObjectURL(url), 1000);
122+}
123+
124+export function safeName(s: string) {
125+ return s.replace(/[^a-z0-9.~-]+/gi, "_").replace(/^_+|_+$/g, "");
126+}
127+
128+// Simple least-squares fit y = a + b x, with standard error of b.
129+export function linearFit(xs: number[], ys: number[]): { a: number; b: number; seB: number; n: number } | null {
130+ const n = xs.length;
131+ if (n < 3) return null;
132+ const mx = xs.reduce((s, v) => s + v, 0) / n;
133+ const my = ys.reduce((s, v) => s + v, 0) / n;
134+ let sxx = 0;
135+ let sxy = 0;
136+ for (let i = 0; i < n; i++) {
137+ sxx += (xs[i] - mx) ** 2;
138+ sxy += (xs[i] - mx) * (ys[i] - my);
139+ }
140+ if (sxx <= 0) return null;
141+ const b = sxy / sxx;
142+ const a = my - b * mx;
143+ let sse = 0;
144+ for (let i = 0; i < n; i++) sse += (ys[i] - a - b * xs[i]) ** 2;
145+ const seB = Math.sqrt(sse / (n - 2) / sxx);
146+ return { a, b, seB, n };
147+}
src/storage/db.tsadded+87−0View file
@@ -0,0 +1,87 @@
1+// Everything is kept in this browser's IndexedDB. Metadata and audio live in separate
2+// stores so the list can load without pulling in every sample.
3+
4+import type { Segment } from "../analysis/analyze.ts";
5+import type { CaptureInfo } from "../audio/recorder.ts";
6+
7+export interface RecordingMeta {
8+ id: string;
9+ createdAt: number;
10+ label: string; // speed group chosen by the user, e.g. "slow (~5 s)"
11+ notes: string;
12+ material: string;
13+ source: "mic" | "file" | "synthetic";
14+ fileName?: string;
15+ sampleRate: number;
16+ length: number; // samples
17+ segment: Segment | null; // the tear, in seconds
18+ segmentManual: boolean;
19+ capture?: CaptureInfo;
20+}
21+
22+const DB_NAME = "rip-sound-analyzer";
23+
24+function openDb(): Promise<IDBDatabase> {
25+ return new Promise((resolve, reject) => {
26+ const req = indexedDB.open(DB_NAME, 1);
27+ req.onupgradeneeded = () => {
28+ const db = req.result;
29+ db.createObjectStore("recordings", { keyPath: "id" });
30+ db.createObjectStore("audio");
31+ };
32+ req.onsuccess = () => resolve(req.result);
33+ req.onerror = () => reject(req.error);
34+ });
35+}
36+
37+let dbp: Promise<IDBDatabase> | null = null;
38+const db = () => (dbp ??= openDb());
39+
40+function done<T>(req: IDBRequest<T>): Promise<T> {
41+ return new Promise((resolve, reject) => {
42+ req.onsuccess = () => resolve(req.result);
43+ req.onerror = () => reject(req.error);
44+ });
45+}
46+
47+export async function listRecordings(): Promise<RecordingMeta[]> {
48+ const d = await db();
49+ const all = await done(d.transaction("recordings").objectStore("recordings").getAll());
50+ return (all as RecordingMeta[]).sort((a, b) => a.createdAt - b.createdAt);
51+}
52+
53+export async function saveRecording(meta: RecordingMeta, samples: Float32Array): Promise<void> {
54+ const d = await db();
55+ const tx = d.transaction(["recordings", "audio"], "readwrite");
56+ tx.objectStore("recordings").put(meta);
57+ tx.objectStore("audio").put(samples, meta.id);
58+ await new Promise<void>((resolve, reject) => {
59+ tx.oncomplete = () => resolve();
60+ tx.onerror = () => reject(tx.error);
61+ });
62+}
63+
64+export async function updateMeta(meta: RecordingMeta): Promise<void> {
65+ const d = await db();
66+ await done(d.transaction("recordings", "readwrite").objectStore("recordings").put(meta));
67+}
68+
69+export async function loadAudio(id: string): Promise<Float32Array> {
70+ const d = await db();
71+ return (await done(d.transaction("audio").objectStore("audio").get(id))) as Float32Array;
72+}
73+
74+export async function deleteRecording(id: string): Promise<void> {
75+ const d = await db();
76+ const tx = d.transaction(["recordings", "audio"], "readwrite");
77+ tx.objectStore("recordings").delete(id);
78+ tx.objectStore("audio").delete(id);
79+ await new Promise<void>((resolve, reject) => {
80+ tx.oncomplete = () => resolve();
81+ tx.onerror = () => reject(tx.error);
82+ });
83+}
84+
85+export function newId(): string {
86+ return crypto.randomUUID();
87+}
src/styles.cssadded+648−0View file
@@ -0,0 +1,648 @@
1+:root {
2+ color-scheme: light;
3+ --page: #f9f9f7;
4+ --surface: #fcfcfb;
5+ --ink: #0b0b0b;
6+ --ink2: #52514e;
7+ --muted: #898781;
8+ --grid: #e1e0d9;
9+ --axis: #c3c2b7;
10+ --border: rgba(11, 11, 11, 0.1);
11+ --seg: rgba(137, 135, 129, 0.16);
12+ --accent: #2a78d6;
13+ --accent-ink: #ffffff;
14+ --rec: #d03b3b;
15+ --warn-bg: #fff4dc;
16+ --warn-ink: #6b4a00;
17+ --ok: #006300;
18+ --hover: rgba(11, 11, 11, 0.05);
19+ --series-1: #2a78d6;
20+ --series-2: #eb6834;
21+ --series-3: #1baf7a;
22+ --series-4: #eda100;
23+ --series-5: #e87ba4;
24+ --series-6: #008300;
25+ --series-7: #6250d6;
26+ --series-8: #e34948;
27+}
28+@media (prefers-color-scheme: dark) {
29+ :root:not([data-theme="light"]) {
30+ color-scheme: dark;
31+ --page: #0d0d0d;
32+ --surface: #1a1a19;
33+ --ink: #f0efec;
34+ --ink2: #c3c2b7;
35+ --muted: #898781;
36+ --grid: #2c2c2a;
37+ --axis: #383835;
38+ --border: rgba(255, 255, 255, 0.1);
39+ --seg: rgba(195, 194, 183, 0.12);
40+ --accent: #3987e5;
41+ --warn-bg: #3a2c0b;
42+ --warn-ink: #f6d58a;
43+ --ok: #0ca30c;
44+ --hover: rgba(255, 255, 255, 0.06);
45+ --series-1: #3987e5;
46+ --series-2: #d95926;
47+ --series-3: #199e70;
48+ --series-4: #c98500;
49+ --series-5: #d55181;
50+ --series-6: #008300;
51+ --series-7: #9085e9;
52+ --series-8: #e66767;
53+ }
54+}
55+
56+* {
57+ box-sizing: border-box;
58+}
59+html,
60+body {
61+ margin: 0;
62+ background: var(--page);
63+ color: var(--ink);
64+ font: 14px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif;
65+}
66+h1 {
67+ font-size: 17px;
68+ margin: 0;
69+ font-weight: 650;
70+}
71+h2 {
72+ font-size: 16px;
73+ margin: 20px 0 6px;
74+}
75+h2:first-child {
76+ margin-top: 0;
77+}
78+h3 {
79+ font-size: 14px;
80+ margin: 0;
81+ font-weight: 600;
82+}
83+button,
84+select,
85+input,
86+textarea {
87+ font: inherit;
88+ color: inherit;
89+}
90+button {
91+ background: var(--surface);
92+ border: 1px solid var(--border);
93+ border-radius: 6px;
94+ padding: 4px 10px;
95+ cursor: pointer;
96+}
97+button:hover:not(:disabled) {
98+ background: var(--hover);
99+}
100+button:disabled {
101+ opacity: 0.45;
102+ cursor: default;
103+}
104+button.primary {
105+ background: var(--accent);
106+ color: var(--accent-ink);
107+ border-color: transparent;
108+}
109+button.primary:hover:not(:disabled) {
110+ background: var(--accent);
111+ filter: brightness(1.08);
112+}
113+button.big {
114+ font-size: 16px;
115+ padding: 10px 22px;
116+ min-width: 170px;
117+ font-weight: 600;
118+}
119+button.recording {
120+ background: var(--rec);
121+}
122+button.danger {
123+ color: var(--rec);
124+}
125+select,
126+input[type="number"],
127+input:not([type]),
128+textarea {
129+ background: var(--surface);
130+ border: 1px solid var(--border);
131+ border-radius: 6px;
132+ padding: 4px 8px;
133+}
134+.muted {
135+ color: var(--muted);
136+}
137+.small {
138+ font-size: 12px;
139+}
140+.pad {
141+ padding: 8px 12px;
142+}
143+
144+.app {
145+ min-height: 100vh;
146+ display: flex;
147+ flex-direction: column;
148+}
149+.topbar {
150+ display: flex;
151+ align-items: center;
152+ gap: 24px;
153+ padding: 10px 18px;
154+ border-bottom: 1px solid var(--border);
155+ background: var(--surface);
156+ position: sticky;
157+ top: 0;
158+ z-index: 5;
159+ flex-wrap: wrap;
160+}
161+.tabs {
162+ display: flex;
163+ gap: 4px;
164+}
165+.tabs button {
166+ border: none;
167+ background: none;
168+ padding: 6px 12px;
169+ border-radius: 6px;
170+ color: var(--ink2);
171+}
172+.tabs button.on {
173+ background: var(--hover);
174+ color: var(--ink);
175+ font-weight: 600;
176+}
177+.settings-btn {
178+ margin-left: auto;
179+}
180+.settings {
181+ margin: 12px 18px 0;
182+ display: flex;
183+ flex-wrap: wrap;
184+ gap: 12px;
185+ align-items: center;
186+}
187+.settings label {
188+ display: flex;
189+ gap: 6px;
190+ align-items: center;
191+}
192+.settings input {
193+ width: 90px;
194+}
195+
196+.layout {
197+ display: flex;
198+ flex: 1;
199+ min-height: 0;
200+}
201+.sidebar {
202+ width: 250px;
203+ flex-shrink: 0;
204+ border-right: 1px solid var(--border);
205+ padding: 8px 0;
206+ overflow-y: auto;
207+ max-height: calc(100vh - 54px);
208+ position: sticky;
209+ top: 54px;
210+}
211+.side-head {
212+ display: flex;
213+ justify-content: space-between;
214+ padding: 4px 12px 8px;
215+ font-weight: 600;
216+ font-size: 13px;
217+}
218+.side-head .muted {
219+ font-weight: 400;
220+ font-size: 12px;
221+}
222+.group {
223+ margin-bottom: 6px;
224+}
225+.group-head {
226+ display: flex;
227+ align-items: center;
228+ gap: 6px;
229+ padding: 4px 12px;
230+ font-weight: 600;
231+ font-size: 13px;
232+ cursor: pointer;
233+}
234+.group-name {
235+ flex: 1;
236+}
237+.item {
238+ display: flex;
239+ align-items: center;
240+ gap: 6px;
241+ padding: 0 8px 0 28px;
242+}
243+.item.sel {
244+ background: var(--hover);
245+ box-shadow: inset 3px 0 0 var(--accent);
246+}
247+.item-btn {
248+ flex: 1;
249+ display: flex;
250+ justify-content: space-between;
251+ border: none;
252+ background: none;
253+ padding: 4px 4px;
254+ text-align: left;
255+ font-size: 13px;
256+}
257+.item-btn:hover:not(:disabled) {
258+ background: none;
259+ text-decoration: underline;
260+}
261+.swatch {
262+ display: inline-block;
263+ width: 10px;
264+ height: 10px;
265+ border-radius: 3px;
266+ flex-shrink: 0;
267+}
268+.swatch.dashed {
269+ width: 18px;
270+ height: 0;
271+ border-top: 2px dashed var(--muted);
272+ border-radius: 0;
273+}
274+.swatch.shade {
275+ width: 14px;
276+ background: var(--seg);
277+ outline: 1px solid var(--border);
278+}
279+
280+.main {
281+ flex: 1;
282+ min-width: 0;
283+ padding: 14px 18px 40px;
284+ display: flex;
285+ flex-direction: column;
286+ gap: 14px;
287+}
288+.card {
289+ background: var(--surface);
290+ border: 1px solid var(--border);
291+ border-radius: 10px;
292+ padding: 14px 16px;
293+}
294+.card.empty {
295+ color: var(--muted);
296+ text-align: center;
297+ padding: 40px;
298+}
299+.card.warn {
300+ background: var(--warn-bg);
301+ color: var(--warn-ink);
302+}
303+.warn {
304+ background: var(--warn-bg);
305+ color: var(--warn-ink);
306+ border-radius: 6px;
307+ padding: 6px 10px;
308+ margin-top: 8px;
309+ font-size: 13px;
310+}
311+.warn-inline {
312+ color: var(--warn-ink);
313+ font-size: 12px;
314+}
315+.ok {
316+ color: var(--ok);
317+}
318+.hint {
319+ color: var(--muted);
320+ font-size: 12px;
321+}
322+.caption {
323+ color: var(--ink2);
324+ font-size: 12.5px;
325+ margin: 4px 0 8px;
326+}
327+
328+/* record bar */
329+.rb-row {
330+ display: flex;
331+ gap: 24px;
332+ flex-wrap: wrap;
333+ align-items: flex-start;
334+}
335+.rb-label {
336+ flex: 1;
337+ min-width: 300px;
338+ display: flex;
339+ flex-direction: column;
340+ gap: 6px;
341+}
342+.rb-label > label {
343+ font-weight: 600;
344+ font-size: 13px;
345+}
346+.rb-label input {
347+ max-width: 320px;
348+}
349+.chips {
350+ display: flex;
351+ flex-wrap: wrap;
352+ gap: 6px;
353+}
354+.chip {
355+ border-radius: 999px;
356+ font-size: 13px;
357+ padding: 3px 10px;
358+}
359+.chip.on {
360+ background: var(--ink);
361+ color: var(--surface);
362+}
363+.chip.on:hover:not(:disabled) {
364+ background: var(--ink);
365+}
366+.rb-controls {
367+ display: flex;
368+ flex-direction: column;
369+ gap: 6px;
370+ align-items: flex-start;
371+ min-width: 240px;
372+}
373+.meter {
374+ position: relative;
375+ width: 240px;
376+ height: 16px;
377+ background: var(--hover);
378+ border-radius: 4px;
379+ overflow: hidden;
380+}
381+.meter-fill {
382+ position: absolute;
383+ inset: 0 auto 0 0;
384+ background: linear-gradient(90deg, var(--series-3) 0%, var(--series-3) 80%, var(--series-4) 90%, var(--rec) 100%);
385+ background-size: 240px 100%;
386+}
387+.meter-text {
388+ position: absolute;
389+ right: 6px;
390+ top: 0;
391+ font-size: 11px;
392+ line-height: 16px;
393+ font-variant-numeric: tabular-nums;
394+}
395+.howto {
396+ color: var(--ink2);
397+ font-size: 13px;
398+ margin: 10px 0 0;
399+}
400+.capture-info {
401+ display: flex;
402+ flex-wrap: wrap;
403+ gap: 6px 14px;
404+ align-items: center;
405+ margin-top: 10px;
406+ font-size: 12.5px;
407+ color: var(--ink2);
408+}
409+.capture-info .warn {
410+ margin: 0;
411+ padding: 2px 8px;
412+}
413+.more {
414+ margin-top: 10px;
415+ font-size: 13px;
416+}
417+.more summary {
418+ cursor: pointer;
419+ color: var(--ink2);
420+}
421+.more-body {
422+ display: flex;
423+ flex-direction: column;
424+ gap: 8px;
425+ padding: 8px 0 0 14px;
426+}
427+.filepick {
428+ display: flex;
429+ flex-direction: column;
430+ gap: 4px;
431+}
432+.synth {
433+ display: flex;
434+ gap: 8px;
435+ align-items: center;
436+ flex-wrap: wrap;
437+}
438+
439+/* recording view */
440+.recview {
441+ display: flex;
442+ flex-direction: column;
443+ gap: 14px;
444+}
445+.rv-head {
446+ display: flex;
447+ justify-content: space-between;
448+ gap: 12px;
449+ flex-wrap: wrap;
450+ align-items: center;
451+}
452+.rv-title {
453+ display: flex;
454+ gap: 8px;
455+ align-items: center;
456+ flex-wrap: wrap;
457+}
458+.label-edit {
459+ font-size: 16px !important;
460+ font-weight: 600;
461+ width: 220px;
462+}
463+.rv-actions {
464+ display: flex;
465+ gap: 6px;
466+ flex-wrap: wrap;
467+}
468+.badge {
469+ font-size: 11px;
470+ border-radius: 999px;
471+ padding: 1px 8px;
472+ border: 1px solid var(--border);
473+ color: var(--ink2);
474+}
475+.badge.synthetic {
476+ border-style: dashed;
477+}
478+.notes {
479+ width: 100%;
480+ margin-top: 10px;
481+ resize: vertical;
482+}
483+.stats {
484+ display: grid;
485+ grid-template-columns: repeat(auto-fill, minmax(165px, 1fr));
486+ gap: 10px;
487+ margin-top: 12px;
488+}
489+.stat {
490+ border-left: 2px solid var(--grid);
491+ padding-left: 10px;
492+}
493+.stat-k {
494+ font-size: 12px;
495+ color: var(--ink2);
496+}
497+.stat-v {
498+ font-size: 17px;
499+ font-weight: 600;
500+}
501+.stat-sub {
502+ font-size: 11.5px;
503+ color: var(--muted);
504+}
505+.plot-head {
506+ display: flex;
507+ justify-content: space-between;
508+ align-items: center;
509+ gap: 10px;
510+ flex-wrap: wrap;
511+ margin-bottom: 6px;
512+}
513+.toolbar {
514+ display: flex;
515+ gap: 8px;
516+ align-items: center;
517+ flex-wrap: wrap;
518+ font-size: 13px;
519+}
520+.toolbar label {
521+ display: flex;
522+ gap: 6px;
523+ align-items: center;
524+}
525+.plot {
526+ position: relative;
527+ width: 100%;
528+ user-select: none;
529+}
530+.plot canvas {
531+ position: absolute;
532+ inset: 0;
533+ display: block;
534+}
535+.plot-overlay {
536+ touch-action: none;
537+}
538+.plot-tip {
539+ position: absolute;
540+ pointer-events: none;
541+ background: var(--surface);
542+ border: 1px solid var(--border);
543+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
544+ border-radius: 6px;
545+ padding: 5px 8px;
546+ font-size: 12px;
547+ white-space: nowrap;
548+ color: var(--ink2);
549+ font-variant-numeric: tabular-nums;
550+ z-index: 3;
551+}
552+.plot-tip-head {
553+ color: var(--ink);
554+ font-weight: 600;
555+}
556+.legend {
557+ display: flex;
558+ flex-wrap: wrap;
559+ gap: 4px 16px;
560+ font-size: 12.5px;
561+ color: var(--ink2);
562+ margin-top: 6px;
563+}
564+.legend span {
565+ display: inline-flex;
566+ align-items: center;
567+ gap: 5px;
568+}
569+
570+/* compare */
571+.compare {
572+ display: flex;
573+ flex-direction: column;
574+ gap: 14px;
575+}
576+.grid2 {
577+ display: grid;
578+ grid-template-columns: repeat(auto-fit, minmax(380px, 1fr));
579+ gap: 14px;
580+}
581+.summary .q {
582+ margin-top: 10px;
583+}
584+.q-title {
585+ font-weight: 600;
586+}
587+.table-wrap {
588+ overflow-x: auto;
589+ display: flex;
590+ flex-direction: column;
591+ gap: 16px;
592+}
593+table {
594+ border-collapse: collapse;
595+ width: 100%;
596+ font-size: 13px;
597+}
598+th,
599+td {
600+ text-align: left;
601+ padding: 5px 10px;
602+ border-bottom: 1px solid var(--grid);
603+ white-space: nowrap;
604+}
605+th {
606+ font-weight: 600;
607+ color: var(--ink2);
608+ font-size: 12px;
609+}
610+td svg {
611+ vertical-align: middle;
612+}
613+.num {
614+ text-align: right;
615+ font-variant-numeric: tabular-nums;
616+}
617+tr.clickable {
618+ cursor: pointer;
619+}
620+tr.clickable:hover {
621+ background: var(--hover);
622+}
623+
624+.about {
625+ max-width: 820px;
626+}
627+.about li {
628+ margin-bottom: 6px;
629+}
630+
631+@media (max-width: 760px) {
632+ .layout {
633+ flex-direction: column;
634+ }
635+ .sidebar {
636+ width: 100%;
637+ position: static;
638+ max-height: none;
639+ border-right: none;
640+ border-bottom: 1px solid var(--border);
641+ }
642+ .main {
643+ padding: 12px 16px 40px;
644+ }
645+ .grid2 {
646+ grid-template-columns: 1fr;
647+ }
648+}
src/vite-env.d.tsadded+1−0View file
@@ -0,0 +1 @@
1+/// <reference types="vite/client" />
tsconfig.jsonadded+17−0View file
@@ -0,0 +1,17 @@
1+{
2+ "compilerOptions": {
3+ "target": "ES2022",
4+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
5+ "module": "ESNext",
6+ "moduleResolution": "bundler",
7+ "jsx": "react-jsx",
8+ "strict": true,
9+ "noUnusedLocals": true,
10+ "noUnusedParameters": true,
11+ "skipLibCheck": true,
12+ "allowImportingTsExtensions": true,
13+ "noEmit": true,
14+ "types": []
15+ },
16+ "include": ["src", "scripts"]
17+}
vite.config.tsadded+7−0View file
@@ -0,0 +1,7 @@
1+import { defineConfig } from "vite";
2+import react from "@vitejs/plugin-react";
3+
4+export default defineConfig({
5+ plugins: [react()],
6+ base: "./",
7+});