@arraypress/waveform-sounds 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1920 @@
1
+ (() => {
2
+ // ../../Core/text/src/index.js
3
+ var HTML_ESCAPES = Object.freeze({
4
+ "&": "&",
5
+ "<": "&lt;",
6
+ ">": "&gt;",
7
+ '"': "&quot;",
8
+ "'": "&#39;"
9
+ });
10
+ function escapeHtml(input) {
11
+ if (input === null || input === void 0) return "";
12
+ return String(input).replace(/[&<>"']/g, (c) => HTML_ESCAPES[c]);
13
+ }
14
+ var NOT_A_WORD = /[^\p{L}\p{N}]+/u;
15
+ var COMBINING_MARKS = /\p{Mn}+/gu;
16
+ function fold(text2) {
17
+ if (!text2 || typeof text2 !== "string") return "";
18
+ return text2.toLowerCase().normalize("NFD").replace(COMBINING_MARKS, "");
19
+ }
20
+ function words(text2) {
21
+ return fold(text2).split(NOT_A_WORD).filter((word) => word !== "");
22
+ }
23
+ function editDistance(a, b) {
24
+ const s = Array.from(a ?? "");
25
+ const t = Array.from(b ?? "");
26
+ let before = [];
27
+ let previous = Array.from({ length: t.length + 1 }, (_, i) => i);
28
+ for (let i = 1; i <= s.length; i++) {
29
+ const current = [i];
30
+ for (let j = 1; j <= t.length; j++) {
31
+ const cost = s[i - 1] === t[j - 1] ? 0 : 1;
32
+ current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + cost);
33
+ if (i > 1 && j > 1 && s[i - 1] === t[j - 2] && s[i - 2] === t[j - 1]) {
34
+ current[j] = Math.min(current[j], before[j - 2] + 1);
35
+ }
36
+ }
37
+ before = previous;
38
+ previous = current;
39
+ }
40
+ return previous[t.length];
41
+ }
42
+ function matchesAll(name, query, options = {}) {
43
+ const fuzzyFrom = options.fuzzyFrom ?? 4;
44
+ const folded = fold(name);
45
+ const nameWords = words(name);
46
+ return words(query).every((term) => {
47
+ if (folded.includes(term)) return true;
48
+ const length = Array.from(term).length;
49
+ if (length < fuzzyFrom) return false;
50
+ return nameWords.some(
51
+ (word) => editDistance(term, word) <= 1 || editDistance(term, Array.from(word).slice(0, length).join("")) <= 1
52
+ );
53
+ });
54
+ }
55
+
56
+ // src/js/data/sounds.js
57
+ function encodePeaks(peaks) {
58
+ if (!Array.isArray(peaks)) return "";
59
+ let out = "";
60
+ for (const p of peaks) {
61
+ const v = Math.round(Math.min(Math.max(Number(p) || 0, 0), 1) * 255);
62
+ out += (v < 16 ? "0" : "") + v.toString(16);
63
+ }
64
+ return out;
65
+ }
66
+ function decodePeaks(value, scale = 1) {
67
+ if (value == null || value === "") return null;
68
+ if (typeof value === "string") {
69
+ if (!/^[0-9a-f]+$/i.test(value) || value.length % 2) return null;
70
+ const out2 = new Array(value.length / 2);
71
+ for (let i = 0; i < out2.length; i++) out2[i] = parseInt(value.substr(i * 2, 2), 16) / 255;
72
+ return out2;
73
+ }
74
+ if (!Array.isArray(value)) return null;
75
+ const s = Number(scale) > 0 ? Number(scale) : 1;
76
+ const out = value.map((v) => Math.min(Math.max((Number(v) || 0) / s, 0), 1));
77
+ return out.length ? out : null;
78
+ }
79
+ function normalizeKey(key) {
80
+ if (key == null) return "";
81
+ const raw = String(key).trim();
82
+ const m = raw.match(/^([A-Ga-g])[\s_-]*([#♯b♭]?)[\s_-]*(m|min|minor|maj|major)?$/i);
83
+ if (!m) return raw;
84
+ const root = m[1].toUpperCase();
85
+ const acc = m[2] === "\u266F" ? "#" : m[2] === "\u266D" ? "b" : m[2];
86
+ const minor = m[3] && /^m(in(or)?)?$/i.test(m[3]) && m[3] !== "M";
87
+ return root + acc + (minor ? "m" : "");
88
+ }
89
+ var KEY_PITCH = { C: 0, "C#": 1, Db: 1, D: 2, "D#": 3, Eb: 3, E: 4, F: 5, "F#": 6, Gb: 6, G: 7, "G#": 8, Ab: 8, A: 9, "A#": 10, Bb: 10, B: 11 };
90
+ function keyRank(key) {
91
+ if (!key) return Infinity;
92
+ const minor = key.endsWith("m");
93
+ const root = minor ? key.slice(0, -1) : key;
94
+ const p = KEY_PITCH[root];
95
+ return p === void 0 ? 1e3 : p * 2 + (minor ? 1 : 0);
96
+ }
97
+ function formatDuration(seconds) {
98
+ if (seconds == null || seconds === "") return "";
99
+ const s = Number(seconds);
100
+ if (!Number.isFinite(s) || s < 0) return "";
101
+ const total = Math.round(s);
102
+ return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`;
103
+ }
104
+ function parseDuration(value) {
105
+ if (value == null || value === "") return null;
106
+ if (typeof value === "number") return Number.isFinite(value) && value >= 0 ? value : null;
107
+ const str = String(value).trim();
108
+ if (/^\d+(\.\d+)?$/.test(str)) return Number(str);
109
+ const parts = str.split(":").map(Number);
110
+ if (parts.length < 2 || parts.some((n) => !Number.isFinite(n))) return null;
111
+ return parts.reduce((acc, n) => acc * 60 + n, 0);
112
+ }
113
+ function titleFromUrl(url) {
114
+ const file = String(url || "").split(/[?#]/)[0].split("/").pop() || "";
115
+ let name = file.replace(/\.[a-z0-9]+$/i, "");
116
+ try {
117
+ name = decodeURIComponent(name);
118
+ } catch {
119
+ }
120
+ return name.replace(/[_]+/g, " ").replace(/\s+/g, " ").trim();
121
+ }
122
+ function normalizeSound(input, index, peakScale = 1) {
123
+ if (!input || typeof input !== "object" || !input.url) return null;
124
+ const bpm = Number(input.bpm);
125
+ const tags = Array.isArray(input.tags) ? input.tags.map((t) => String(t).trim()).filter(Boolean) : typeof input.tags === "string" ? input.tags.split(",").map((t) => t.trim()).filter(Boolean) : [];
126
+ return {
127
+ id: input.id != null && input.id !== "" ? String(input.id) : `sound-${index + 1}`,
128
+ url: String(input.url),
129
+ title: input.title ? String(input.title) : titleFromUrl(input.url),
130
+ type: input.type ? String(input.type) : "",
131
+ bpm: Number.isFinite(bpm) && bpm > 0 ? Math.round(bpm * 100) / 100 : null,
132
+ key: normalizeKey(input.key),
133
+ duration: parseDuration(input.duration),
134
+ tags,
135
+ peaks: decodePeaks(input.peaks, peakScale),
136
+ waveform: input.waveform ? String(input.waveform) : null,
137
+ download: input.download ? String(input.download) : null
138
+ };
139
+ }
140
+ function parseManifest(manifest) {
141
+ const list = Array.isArray(manifest) ? manifest : Array.isArray(manifest?.sounds) ? manifest.sounds : [];
142
+ const scale = Array.isArray(manifest) ? 1 : Number(manifest?.peakScale) || 1;
143
+ return normalizeSounds(list, scale);
144
+ }
145
+ function normalizeSounds(list, peakScale = 1) {
146
+ const seen = /* @__PURE__ */ new Set();
147
+ const out = [];
148
+ (Array.isArray(list) ? list : []).forEach((item, i) => {
149
+ const s = normalizeSound(item, i, peakScale);
150
+ if (!s) return;
151
+ let id = s.id, n = 2;
152
+ while (seen.has(id)) id = `${s.id}-${n++}`;
153
+ s.id = id;
154
+ seen.add(id);
155
+ out.push(s);
156
+ });
157
+ return out;
158
+ }
159
+ function facets(sounds) {
160
+ const types = /* @__PURE__ */ new Map();
161
+ const keys = /* @__PURE__ */ new Set();
162
+ let min = Infinity, max = -Infinity, hasDuration = false;
163
+ for (const s of sounds) {
164
+ if (s.type) types.set(s.type, (types.get(s.type) || 0) + 1);
165
+ if (s.key) keys.add(s.key);
166
+ if (s.bpm != null) {
167
+ min = Math.min(min, s.bpm);
168
+ max = Math.max(max, s.bpm);
169
+ }
170
+ if (s.duration != null) hasDuration = true;
171
+ }
172
+ return {
173
+ types: [...types].map(([name, count]) => ({ name, count })),
174
+ keys: [...keys].sort((a, b) => keyRank(a) - keyRank(b) || a.localeCompare(b)),
175
+ bpm: min === Infinity ? null : { min, max },
176
+ hasDuration
177
+ };
178
+ }
179
+ function matches(sound, filter = {}) {
180
+ if (filter.type && sound.type !== filter.type) return false;
181
+ if (filter.key && sound.key !== normalizeKey(filter.key)) return false;
182
+ const lo = Number(filter.bpmMin), hi = Number(filter.bpmMax);
183
+ if (filter.bpmMin != null && filter.bpmMin !== "" && Number.isFinite(lo) || filter.bpmMax != null && filter.bpmMax !== "" && Number.isFinite(hi)) {
184
+ if (sound.bpm == null) return false;
185
+ if (filter.bpmMin != null && filter.bpmMin !== "" && sound.bpm < lo) return false;
186
+ if (filter.bpmMax != null && filter.bpmMax !== "" && sound.bpm > hi) return false;
187
+ }
188
+ const terms = words(filter.query || "");
189
+ if (terms.length) {
190
+ const hay = [sound.title, sound.type, sound.key, ...sound.tags || []].join(" ");
191
+ const folded = fold(hay);
192
+ const rest = terms.filter((w) => !(/^\d+$/.test(w) && !folded.includes(w) && sound.bpm != null && Math.round(sound.bpm) === Number(w)));
193
+ if (rest.length && !matchesAll(hay, rest.join(" "))) return false;
194
+ }
195
+ return true;
196
+ }
197
+ var SORTS = ["default", "title", "bpm", "key", "duration"];
198
+ var SORT_NEEDS = {
199
+ default: () => true,
200
+ title: () => true,
201
+ bpm: (f) => f.bpm !== null,
202
+ key: (f) => f.keys.length > 0,
203
+ duration: (f) => f.hasDuration
204
+ };
205
+ function availableSorts(sorts, f) {
206
+ return sorts.filter((sort) => SORT_NEEDS[sort]?.(f));
207
+ }
208
+ function sortSounds(sounds, by = "default") {
209
+ const list = sounds.map((s, i) => ({ s, i }));
210
+ const last = (v) => v == null ? Infinity : v;
211
+ const cmp = {
212
+ title: (a, b) => a.s.title.localeCompare(b.s.title, void 0, { numeric: true, sensitivity: "base" }),
213
+ bpm: (a, b) => last(a.s.bpm) - last(b.s.bpm),
214
+ key: (a, b) => keyRank(a.s.key) - keyRank(b.s.key),
215
+ duration: (a, b) => last(a.s.duration) - last(b.s.duration)
216
+ }[by];
217
+ if (cmp) list.sort((a, b) => cmp(a, b) || a.i - b.i);
218
+ return list.map((x) => x.s);
219
+ }
220
+
221
+ // src/js/dom/draw.js
222
+ function fitCanvas(canvas) {
223
+ const rect = canvas.getBoundingClientRect();
224
+ if (!rect.width || !rect.height) return null;
225
+ const dpr = Math.min(window.devicePixelRatio || 1, 3);
226
+ const w = Math.round(rect.width * dpr), h2 = Math.round(rect.height * dpr);
227
+ if (canvas.width !== w) canvas.width = w;
228
+ if (canvas.height !== h2) canvas.height = h2;
229
+ return { width: rect.width, height: rect.height, dpr };
230
+ }
231
+ function resample(peaks, count) {
232
+ if (!peaks?.length || count <= 0) return [];
233
+ if (peaks.length === count) return peaks;
234
+ const out = new Array(count);
235
+ const step = peaks.length / count;
236
+ for (let i = 0; i < count; i++) {
237
+ const start = Math.floor(i * step);
238
+ const end = Math.max(start + 1, Math.floor((i + 1) * step));
239
+ let m = 0;
240
+ for (let j = start; j < end && j < peaks.length; j++) if (peaks[j] > m) m = peaks[j];
241
+ out[i] = m;
242
+ }
243
+ return out;
244
+ }
245
+ function drawRowWaveform(canvas, peaks, progress, o) {
246
+ const size = fitCanvas(canvas);
247
+ const ctx = size && canvas.getContext && canvas.getContext("2d");
248
+ if (!ctx) return;
249
+ const { width, height, dpr } = size;
250
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
251
+ ctx.clearRect(0, 0, width, height);
252
+ if (!peaks?.length) {
253
+ ctx.fillStyle = o.color;
254
+ ctx.fillRect(0, Math.floor(height / 2), width, 1);
255
+ return;
256
+ }
257
+ const step = o.barWidth + o.barGap;
258
+ const count = Math.max(1, Math.floor((width + o.barGap) / step));
259
+ const bars = resample(peaks, count);
260
+ let max = 0;
261
+ for (const b of bars) if (b > max) max = b;
262
+ const scale = max > 0 ? 1 / max : 1;
263
+ const split = progress * width;
264
+ const mid = height / 2;
265
+ for (let i = 0; i < bars.length; i++) {
266
+ const x = i * step;
267
+ const v = Math.max(bars[i] * scale, 0.04);
268
+ ctx.fillStyle = x + o.barWidth / 2 <= split ? o.progressColor : o.color;
269
+ if (o.style === "bars") {
270
+ const h2 = Math.max(1, v * height);
271
+ ctx.fillRect(x, height - h2, o.barWidth, h2);
272
+ } else {
273
+ const h2 = Math.max(1, v * (height - 2));
274
+ ctx.fillRect(x, mid - h2 / 2, o.barWidth, h2);
275
+ }
276
+ }
277
+ }
278
+
279
+ // src/js/core/engine.js
280
+ var CALLBACKS = ["onLoad", "onPlay", "onPause", "onEnd", "onTimeUpdate", "onError"];
281
+ function engineOptions(user, layout, handlers) {
282
+ const site = user || {};
283
+ const strip = layout === "strip";
284
+ const options = {
285
+ height: strip ? 48 : 32,
286
+ waveformStyle: strip ? "mirror" : "bars",
287
+ preload: "metadata",
288
+ singlePlay: true,
289
+ ...site,
290
+ audioMode: "self"
291
+ };
292
+ for (const name of CALLBACKS) {
293
+ options[name] = (...args) => {
294
+ handlers[name]?.(...args);
295
+ if (typeof site[name] === "function") site[name](...args);
296
+ };
297
+ }
298
+ return options;
299
+ }
300
+ function enginePeaks(sound, layout) {
301
+ return layout === "strip" && sound.waveform || sound.peaks || null;
302
+ }
303
+
304
+ // src/js/dom/menus.js
305
+ function optionMatches(label, query) {
306
+ const q = fold(String(query ?? "")).trim();
307
+ return !q || fold(String(label ?? "")).includes(q);
308
+ }
309
+ function stepIndex(current, delta, length) {
310
+ return Math.max(0, Math.min(length - 1, current + delta));
311
+ }
312
+ function partsOf(menu) {
313
+ return {
314
+ button: menu.querySelector("[data-ws-menu-btn]"),
315
+ pop: menu.querySelector("[data-ws-menu-pop]"),
316
+ search: menu.querySelector("[data-ws-menu-search]"),
317
+ list: menu.querySelector("[data-ws-menu-list]"),
318
+ none: menu.querySelector("[data-ws-menu-none]"),
319
+ value: menu.querySelector("[data-ws-menu-value]")
320
+ };
321
+ }
322
+ var focusOwner = (p) => p.search || p.list;
323
+ var optionsOf = (p, visibleOnly = false) => [...p.list.querySelectorAll('[role="option"]')].filter((o) => !visibleOnly || !o.hidden);
324
+ var Menus = class {
325
+ /**
326
+ * @param {HTMLElement} container - The list's root element.
327
+ * @param {Object} opts
328
+ * @param {(name: string, value: string) => void} opts.onPick - A value was chosen.
329
+ * @param {AbortSignal} opts.signal - Removes every listener on abort.
330
+ */
331
+ constructor(container, { onPick, signal }) {
332
+ this.container = container;
333
+ this.onPick = onPick;
334
+ this.menus = Object.fromEntries([...container.querySelectorAll("[data-ws-menu]")].map((m) => [m.dataset.wsMenu, m]));
335
+ this.openMenu = null;
336
+ this._bind(signal);
337
+ }
338
+ /**
339
+ * Wire every menu, plus closing on an outside press or focus leaving.
340
+ * @param {AbortSignal} signal
341
+ * @private
342
+ */
343
+ _bind(signal) {
344
+ const sig = { signal };
345
+ for (const [name, menu] of Object.entries(this.menus)) {
346
+ const p = partsOf(menu);
347
+ p.button.addEventListener("click", () => this.openMenu === menu ? this.close(true) : this.open(menu), sig);
348
+ p.button.addEventListener("keydown", (e) => {
349
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
350
+ e.preventDefault();
351
+ this.open(menu);
352
+ }
353
+ }, sig);
354
+ p.list.addEventListener("click", (e) => {
355
+ const opt = e.target.closest('[role="option"]');
356
+ if (opt) this._pick(name, opt.dataset.value);
357
+ }, sig);
358
+ p.list.addEventListener("mousedown", (e) => e.preventDefault(), sig);
359
+ p.search?.addEventListener("input", () => this._filter(menu, p.search.value), sig);
360
+ focusOwner(p).addEventListener("keydown", (e) => this._onKey(e, name, menu), sig);
361
+ }
362
+ document.addEventListener("pointerdown", (e) => {
363
+ if (this.openMenu && !this.openMenu.contains(e.target)) this.close(false);
364
+ }, sig);
365
+ this.container.addEventListener("focusout", (e) => {
366
+ if (this.openMenu && !this.openMenu.contains(e.relatedTarget)) this.close(false);
367
+ }, sig);
368
+ }
369
+ /**
370
+ * Open a menu (closing any other), with the selected option active and
371
+ * focus in its search field or list. Flips to open over the end edge
372
+ * when it would overflow the list.
373
+ *
374
+ * @param {HTMLElement} menu
375
+ */
376
+ open(menu) {
377
+ if (this.openMenu && this.openMenu !== menu) this.close(false);
378
+ const p = partsOf(menu);
379
+ p.button.setAttribute("aria-expanded", "true");
380
+ p.pop.hidden = false;
381
+ this.openMenu = menu;
382
+ if (p.search) {
383
+ p.search.value = "";
384
+ this._filter(menu, "");
385
+ }
386
+ menu.classList.remove("ws-menu--end");
387
+ if (p.pop.getBoundingClientRect().right > this.container.getBoundingClientRect().right + 1) menu.classList.add("ws-menu--end");
388
+ this._activate(menu, p.list.querySelector('[role="option"][aria-selected="true"]'));
389
+ focusOwner(p).focus();
390
+ }
391
+ /**
392
+ * Close the open menu, if any.
393
+ *
394
+ * @param {boolean} focusButton - Return focus to its button (after a
395
+ * pick or Esc; not after a click elsewhere).
396
+ */
397
+ close(focusButton) {
398
+ const menu = this.openMenu;
399
+ if (!menu) return;
400
+ this.openMenu = null;
401
+ const p = partsOf(menu);
402
+ p.pop.hidden = true;
403
+ p.button.setAttribute("aria-expanded", "false");
404
+ if (focusButton) p.button.focus();
405
+ }
406
+ /**
407
+ * Show `value` as a menu's choice (button text + `aria-selected`). Used
408
+ * after a pick and when the filter is changed from code.
409
+ *
410
+ * @param {string} name - 'type' | 'key' | 'sort'.
411
+ * @param {string} value
412
+ */
413
+ setValue(name, value) {
414
+ const menu = this.menus[name];
415
+ if (!menu) return;
416
+ const p = partsOf(menu);
417
+ let label = null;
418
+ for (const opt of optionsOf(p)) {
419
+ const on = opt.dataset.value === String(value ?? "");
420
+ opt.setAttribute("aria-selected", String(on));
421
+ if (on) label = opt.querySelector(".ws-menu-text")?.textContent ?? "";
422
+ }
423
+ if (label !== null) p.value.textContent = label;
424
+ }
425
+ /**
426
+ * Narrow a menu to the options matching the search, and make the first
427
+ * match active.
428
+ * @private
429
+ */
430
+ _filter(menu, query) {
431
+ const p = partsOf(menu);
432
+ let first = null;
433
+ for (const opt of optionsOf(p)) {
434
+ opt.hidden = !optionMatches(opt.textContent, query);
435
+ if (!opt.hidden) first ??= opt;
436
+ }
437
+ p.none.hidden = first !== null;
438
+ this._activate(menu, first);
439
+ }
440
+ /**
441
+ * Mark one option active (`aria-activedescendant`) and scroll it into
442
+ * the list's view.
443
+ * @private
444
+ */
445
+ _activate(menu, opt) {
446
+ const p = partsOf(menu);
447
+ for (const o of p.list.querySelectorAll(".is-active")) o.classList.remove("is-active");
448
+ const owner = focusOwner(p);
449
+ if (!opt || opt.hidden) {
450
+ owner.removeAttribute("aria-activedescendant");
451
+ return;
452
+ }
453
+ opt.classList.add("is-active");
454
+ owner.setAttribute("aria-activedescendant", opt.id);
455
+ opt.scrollIntoView?.({ block: "nearest" });
456
+ }
457
+ /**
458
+ * Keys inside an open menu.
459
+ * @private
460
+ */
461
+ _onKey(e, name, menu) {
462
+ const p = partsOf(menu);
463
+ const opts = optionsOf(p, true);
464
+ const at = opts.indexOf(p.list.querySelector(".is-active"));
465
+ const moveTo = (i) => {
466
+ e.preventDefault();
467
+ this._activate(menu, opts[i]);
468
+ };
469
+ const inField = e.target.matches("input");
470
+ switch (e.key) {
471
+ case "ArrowDown":
472
+ return moveTo(stepIndex(at, 1, opts.length));
473
+ case "ArrowUp":
474
+ return moveTo(stepIndex(at, -1, opts.length));
475
+ case "Home":
476
+ return inField ? void 0 : moveTo(0);
477
+ case "End":
478
+ return inField ? void 0 : moveTo(opts.length - 1);
479
+ case "Enter":
480
+ e.preventDefault();
481
+ if (at >= 0) this._pick(name, opts[at].dataset.value);
482
+ return void 0;
483
+ case "Escape":
484
+ e.preventDefault();
485
+ e.stopPropagation();
486
+ return this.close(true);
487
+ case "Tab":
488
+ return this.close(false);
489
+ default:
490
+ return void 0;
491
+ }
492
+ }
493
+ /**
494
+ * A value was chosen: close, then report it.
495
+ * @private
496
+ */
497
+ _pick(name, value) {
498
+ this.close(true);
499
+ this.onPick(name, value);
500
+ }
501
+ };
502
+
503
+ // src/js/shared/utils.js
504
+ var LOG = "[WaveformSounds]";
505
+ function clamp(value, min = 0, max = 1) {
506
+ return Math.min(Math.max(value, min), max);
507
+ }
508
+ function pointerFraction(clientX, rect) {
509
+ return rect && rect.width ? clamp((clientX - rect.left) / rect.width) : 0;
510
+ }
511
+ function isTyping(el) {
512
+ return !!el && (el.isContentEditable || /^(INPUT|SELECT|TEXTAREA)$/.test(el.tagName));
513
+ }
514
+ function emit(target, name, detail) {
515
+ const event = new CustomEvent(`waveformsounds:${name}`, { bubbles: true, detail });
516
+ target.dispatchEvent(event);
517
+ return event;
518
+ }
519
+ function hashString(str) {
520
+ let hash = 5381;
521
+ for (const char of str) hash = hash * 33 + char.codePointAt(0) >>> 0;
522
+ return hash;
523
+ }
524
+
525
+ // src/js/data/navigation.js
526
+ var SEEK_STEP = 0.1;
527
+ function rowTarget(key, at, count) {
528
+ if (!count) return null;
529
+ switch (key) {
530
+ case "ArrowDown":
531
+ return at + 1 < count ? at + 1 : null;
532
+ case "ArrowUp":
533
+ return at > 0 ? at - 1 : "search";
534
+ case "Home":
535
+ return 0;
536
+ case "End":
537
+ return count - 1;
538
+ default:
539
+ return null;
540
+ }
541
+ }
542
+ function seekTarget(progress, key) {
543
+ if (key !== "ArrowRight" && key !== "ArrowLeft") return null;
544
+ return clamp(progress + (key === "ArrowRight" ? SEEK_STEP : -SEEK_STEP), 0, 0.999);
545
+ }
546
+ function pageWindow(shown, limit) {
547
+ const visible = new Set(shown.slice(0, limit));
548
+ return { visible, remaining: shown.length - visible.size };
549
+ }
550
+ function limitToReveal(limit, pos) {
551
+ return pos >= limit ? pos + 1 : limit;
552
+ }
553
+
554
+ // src/js/render/strings.js
555
+ var DEFAULT_STRINGS = {
556
+ search: "Search sounds",
557
+ searchPlaceholder: "Search sounds\u2026",
558
+ all: "All",
559
+ types: "Type",
560
+ key: "Key",
561
+ anyKey: "Any key",
562
+ allTypes: "All types",
563
+ findType: "Find a type\u2026",
564
+ findKey: "Find a key\u2026",
565
+ noMatches: "No matches",
566
+ bpm: "BPM",
567
+ bpmMin: "Min BPM",
568
+ bpmMax: "Max BPM",
569
+ sort: "Sort",
570
+ sortBy: "Sort by",
571
+ sortDefault: "Default",
572
+ sortTitle: "Name",
573
+ sortBpm: "BPM",
574
+ sortKey: "Key",
575
+ sortDuration: "Length",
576
+ loop: "Loop",
577
+ play: "Play {title}",
578
+ pause: "Pause {title}",
579
+ seek: "Seek {title}",
580
+ download: "Download {title}",
581
+ count: "{count} sounds",
582
+ countOne: "1 sound",
583
+ countFiltered: "{count} of {total} sounds",
584
+ showMore: "Show {count} more",
585
+ empty: "No sounds match.",
586
+ clear: "Clear filters",
587
+ nowPlaying: "Playing {title}"
588
+ };
589
+ var SORT_LABEL_KEYS = {
590
+ default: "sortDefault",
591
+ title: "sortTitle",
592
+ bpm: "sortBpm",
593
+ key: "sortKey",
594
+ duration: "sortDuration"
595
+ };
596
+ function fill(template, vars = {}) {
597
+ return String(template).replace(/\{(\w+)\}/g, (match, name) => name in vars ? String(vars[name]) : match);
598
+ }
599
+ function countText(shown, total, strings = DEFAULT_STRINGS) {
600
+ if (shown !== total) return fill(strings.countFiltered, { count: shown, total });
601
+ return total === 1 ? strings.countOne : fill(strings.count, { count: total });
602
+ }
603
+
604
+ // src/js/render/options.js
605
+ var FILTERS = ["type", "key", "bpm"];
606
+ var COLUMNS = ["type", "bpm", "key", "duration"];
607
+ var RENDER_DEFAULTS = {
608
+ player: "inline",
609
+ search: true,
610
+ filters: [...FILTERS],
611
+ sorts: [...SORTS],
612
+ loopToggle: true,
613
+ showCount: true,
614
+ menuSearch: 8,
615
+ pageSize: 50,
616
+ columns: [...COLUMNS],
617
+ maxTypeChips: 10
618
+ };
619
+ function defined(obj) {
620
+ const out = {};
621
+ for (const k in obj ?? {}) if (obj[k] !== void 0) out[k] = obj[k];
622
+ return out;
623
+ }
624
+ function allowedList(values, allowed, fallback) {
625
+ return Array.isArray(values) ? values.filter((v) => allowed.includes(v)) : fallback;
626
+ }
627
+ function wholeNumber(value, fallback) {
628
+ const n = Number(value);
629
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : fallback;
630
+ }
631
+ function resolveRenderOptions(options = {}) {
632
+ const o = { ...RENDER_DEFAULTS, ...defined(options) };
633
+ return {
634
+ ...o,
635
+ player: o.player === "strip" ? "strip" : "inline",
636
+ filters: allowedList(o.filters, FILTERS, RENDER_DEFAULTS.filters),
637
+ sorts: allowedList(o.sorts, SORTS, RENDER_DEFAULTS.sorts),
638
+ columns: allowedList(o.columns, COLUMNS, RENDER_DEFAULTS.columns),
639
+ menuSearch: wholeNumber(o.menuSearch, RENDER_DEFAULTS.menuSearch),
640
+ maxTypeChips: wholeNumber(o.maxTypeChips, RENDER_DEFAULTS.maxTypeChips),
641
+ pageSize: wholeNumber(o.pageSize, RENDER_DEFAULTS.pageSize),
642
+ strings: { ...DEFAULT_STRINGS, ...defined(options.strings) }
643
+ };
644
+ }
645
+
646
+ // src/js/core/options.js
647
+ var DEFAULT_OPTIONS = {
648
+ ...RENDER_DEFAULTS,
649
+ sounds: null,
650
+ manifest: null,
651
+ waveformStyle: "mirror",
652
+ waveformColor: null,
653
+ progressColor: null,
654
+ barWidth: 2,
655
+ barGap: 1,
656
+ loop: false,
657
+ autoAdvance: false,
658
+ arrowAudition: true,
659
+ idPrefix: null,
660
+ urlState: false,
661
+ playerOptions: null,
662
+ playerClass: null,
663
+ strings: null,
664
+ onReady: null,
665
+ onPlay: null,
666
+ onPause: null,
667
+ onEnd: null,
668
+ onFilter: null,
669
+ onError: null
670
+ };
671
+ function parseBool(value) {
672
+ if (value === "" || value === "true") return true;
673
+ if (value === "false") return false;
674
+ return void 0;
675
+ }
676
+ function parseList(value) {
677
+ if (value == null) return void 0;
678
+ return value.split(",").map((x) => x.trim()).filter(Boolean);
679
+ }
680
+ function parseNumber(value) {
681
+ return value === void 0 || value === "" ? void 0 : Number(value);
682
+ }
683
+ function parseUrlState(value) {
684
+ if (value === void 0) return void 0;
685
+ const b = parseBool(value);
686
+ return b === void 0 ? value : b;
687
+ }
688
+ function parseJson(value, name) {
689
+ if (!value) return void 0;
690
+ try {
691
+ return JSON.parse(value);
692
+ } catch {
693
+ console.warn(`${LOG} Ignoring invalid JSON in data-${name}`);
694
+ return void 0;
695
+ }
696
+ }
697
+ function readDataOptions(el) {
698
+ const d = el.dataset || {};
699
+ const out = {
700
+ player: d.player || void 0,
701
+ manifest: d.manifest || void 0,
702
+ search: parseBool(d.search),
703
+ filters: parseList(d.filters),
704
+ sorts: parseList(d.sorts),
705
+ showCount: parseBool(d.showCount),
706
+ menuSearch: parseNumber(d.menuSearch),
707
+ idPrefix: d.idPrefix || void 0,
708
+ urlState: parseUrlState(d.urlState),
709
+ loopToggle: parseBool(d.loopToggle),
710
+ pageSize: parseNumber(d.pageSize),
711
+ maxTypeChips: parseNumber(d.maxTypeChips),
712
+ columns: parseList(d.columns),
713
+ waveformStyle: d.waveformStyle || void 0,
714
+ waveformColor: d.waveformColor || void 0,
715
+ progressColor: d.progressColor || void 0,
716
+ barWidth: parseNumber(d.barWidth),
717
+ barGap: parseNumber(d.barGap),
718
+ loop: parseBool(d.loop),
719
+ autoAdvance: parseBool(d.autoAdvance),
720
+ arrowAudition: parseBool(d.arrowAudition),
721
+ strings: parseJson(d.strings, "strings"),
722
+ playerOptions: parseJson(d.playerOptions, "player-options")
723
+ };
724
+ for (const k of Object.keys(out)) if (out[k] === void 0) delete out[k];
725
+ return out;
726
+ }
727
+ function mergeOptions(...sources) {
728
+ const out = {};
729
+ for (const src of sources) {
730
+ if (!src) continue;
731
+ for (const k in src) if (src[k] !== null && src[k] !== void 0) out[k] = src[k];
732
+ }
733
+ return out;
734
+ }
735
+
736
+ // src/js/render/html.js
737
+ var VOID = /* @__PURE__ */ new Set(["input", "br", "img"]);
738
+ function text(value) {
739
+ return escapeHtml(value ?? "");
740
+ }
741
+ function attrs(map = {}) {
742
+ let out = "";
743
+ for (const [name, value] of Object.entries(map)) {
744
+ if (value === true) out += ` ${name}`;
745
+ else if (value !== false && value != null) out += ` ${name}="${escapeHtml(value)}"`;
746
+ }
747
+ return out;
748
+ }
749
+ function h(tag, attributes = {}, ...children) {
750
+ const open = `<${tag}${attrs(attributes)}>`;
751
+ if (VOID.has(tag)) return open;
752
+ return open + children.flat(Infinity).filter((c) => c != null && c !== false && c !== "").join("") + `</${tag}>`;
753
+ }
754
+
755
+ // src/js/render/icons.js
756
+ function icon(path, extraClass = "") {
757
+ const cls = extraClass ? `ws-icon ${extraClass}` : "ws-icon";
758
+ return `<svg class="${cls}" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="${path}"/></svg>`;
759
+ }
760
+ var ICONS = {
761
+ play: icon("M8 5.5v13l11-6.5z", "ws-icon-play"),
762
+ pause: icon("M7 5h3.5v14H7zM13.5 5H17v14h-3.5z", "ws-icon-pause"),
763
+ search: icon("M10.5 4a6.5 6.5 0 1 0 4.03 11.6l4.43 4.43 1.41-1.41-4.43-4.43A6.5 6.5 0 0 0 10.5 4zm0 2a4.5 4.5 0 1 1 0 9 4.5 4.5 0 0 1 0-9z"),
764
+ chevron: icon("M6.4 8.6 12 14.2l5.6-5.6L19 10l-7 7-7-7z", "ws-menu-chevron"),
765
+ check: icon("M9.5 16.2 5.3 12l-1.4 1.4 5.6 5.6 11-11-1.4-1.4z", "ws-menu-check"),
766
+ download: icon("M11 4h2v8.6l3.3-3.3 1.4 1.4L12 16.4l-5.7-5.7 1.4-1.4 3.3 3.3zM5 18h14v2H5z"),
767
+ loop: icon("M17 4l3 3-3 3V8H8a3 3 0 0 0-3 3v1H3v-1a5 5 0 0 1 5-5h9V4zM7 20l-3-3 3-3v2h9a3 3 0 0 0 3-3v-1h2v1a5 5 0 0 1-5 5H7v2z")
768
+ };
769
+
770
+ // src/js/render/markup.js
771
+ function idBase(sounds) {
772
+ const signature = [sounds.length, ...sounds.map((s) => s.url)].join("|");
773
+ return `ws${hashString(signature).toString(36)}`;
774
+ }
775
+ function toolbarPlan(f, o) {
776
+ const typed = o.filters.includes("type") && f.types.length > 1;
777
+ const sorts = availableSorts(o.sorts, f);
778
+ return {
779
+ types: !typed ? null : f.types.length > o.maxTypeChips ? "menu" : "chips",
780
+ key: o.filters.includes("key") && f.keys.length > 1,
781
+ bpm: o.filters.includes("bpm") && f.bpm !== null && f.bpm.max > f.bpm.min,
782
+ sorts: sorts.length > 1 ? sorts : [],
783
+ search: !!o.search,
784
+ loop: !!o.loopToggle,
785
+ count: !!o.showCount
786
+ };
787
+ }
788
+ function renderSearch(s) {
789
+ return h(
790
+ "label",
791
+ { class: "ws-search" },
792
+ ICONS.search,
793
+ h("span", { class: "ws-sr" }, text(s.search)),
794
+ h("input", { type: "search", class: "ws-search-input", "data-ws-search": true, placeholder: s.searchPlaceholder, autocomplete: "off", spellcheck: "false" })
795
+ );
796
+ }
797
+ function renderMenu(name, m) {
798
+ const listId = `${m.id}-${name}-list`;
799
+ const current = m.options.find((o) => o.value === m.value) ?? m.options[0];
800
+ const searchable = m.placeholder && m.options.length > m.searchFrom;
801
+ const button = h(
802
+ "button",
803
+ { type: "button", class: "ws-menu-btn", "data-ws-menu-btn": true, "aria-haspopup": "listbox", "aria-expanded": "false", "aria-controls": listId },
804
+ m.prefix ? h("span", { class: "ws-menu-prefix" }, text(m.prefix)) : h("span", { class: "ws-sr" }, text(`${m.label}: `)),
805
+ h("span", { class: "ws-menu-value", "data-ws-menu-value": true }, text(current.label)),
806
+ ICONS.chevron
807
+ );
808
+ const search = searchable && h("input", {
809
+ type: "search",
810
+ class: "ws-menu-search",
811
+ "data-ws-menu-search": true,
812
+ role: "combobox",
813
+ "aria-expanded": "true",
814
+ "aria-controls": listId,
815
+ "aria-autocomplete": "list",
816
+ "aria-label": m.placeholder,
817
+ placeholder: m.placeholder,
818
+ autocomplete: "off",
819
+ spellcheck: "false"
820
+ });
821
+ const options = m.options.map((o, i) => h(
822
+ "li",
823
+ { role: "option", id: `${m.id}-${name}-${i}`, class: "ws-menu-option", "data-value": o.value, "aria-selected": String(o === current) },
824
+ ICONS.check,
825
+ h("span", { class: "ws-menu-text" }, text(o.label)),
826
+ o.count != null && h("span", { class: "ws-menu-count" }, text(o.count))
827
+ ));
828
+ return h(
829
+ "div",
830
+ { class: "ws-menu", "data-ws-menu": name },
831
+ button,
832
+ h(
833
+ "div",
834
+ { class: "ws-menu-pop", "data-ws-menu-pop": true, hidden: true },
835
+ search,
836
+ h("ul", { class: "ws-menu-list", role: "listbox", id: listId, "aria-label": m.label, tabindex: "-1", "data-ws-menu-list": true }, options),
837
+ h("p", { class: "ws-menu-none", "data-ws-menu-none": true, hidden: true }, text(m.noMatches))
838
+ )
839
+ );
840
+ }
841
+ function renderBpmRange(s, range) {
842
+ const field = (attr, label, placeholder) => h("input", { type: "number", inputmode: "numeric", [attr]: true, "aria-label": label, placeholder, min: "0", step: "1" });
843
+ return h(
844
+ "span",
845
+ { class: "ws-bpm-range", role: "group", "aria-label": s.bpm },
846
+ field("data-ws-bpm-min", s.bpmMin, range.min),
847
+ h("span", { "aria-hidden": "true" }, "\u2013"),
848
+ field("data-ws-bpm-max", s.bpmMax, range.max),
849
+ h("span", { class: "ws-bpm-unit", "aria-hidden": "true" }, text(s.bpm))
850
+ );
851
+ }
852
+ function renderLoopToggle(s) {
853
+ return h("button", { type: "button", class: "ws-loop", "data-ws-loop": true, "aria-pressed": "false" }, ICONS.loop, h("span", {}, text(s.loop)));
854
+ }
855
+ function renderChip(value, label, count, pressed) {
856
+ return h(
857
+ "button",
858
+ { type: "button", class: "ws-chip", "data-ws-type": value, "aria-pressed": String(pressed) },
859
+ h("span", { class: "ws-chip-label" }, text(label)),
860
+ " ",
861
+ h("span", { class: "ws-chip-count" }, text(count))
862
+ );
863
+ }
864
+ function renderToolbar(plan, { o, s, f, total, id }) {
865
+ const menu = (name, m) => renderMenu(name, { id, searchFrom: o.menuSearch, noMatches: s.noMatches, ...m });
866
+ const controls = [
867
+ plan.types === "menu" && menu("type", {
868
+ label: s.types,
869
+ value: "",
870
+ placeholder: s.findType,
871
+ options: [{ value: "", label: s.allTypes, count: total }, ...f.types.map((t) => ({ value: t.name, label: t.name, count: t.count }))]
872
+ }),
873
+ plan.key && menu("key", {
874
+ label: s.key,
875
+ value: "",
876
+ placeholder: s.findKey,
877
+ options: [{ value: "", label: s.anyKey }, ...f.keys.map((k) => ({ value: k, label: k }))]
878
+ }),
879
+ plan.bpm && renderBpmRange(s, f.bpm),
880
+ plan.sorts.length > 0 && menu("sort", {
881
+ label: s.sort,
882
+ prefix: s.sortBy,
883
+ value: plan.sorts[0],
884
+ options: plan.sorts.map((k) => ({ value: k, label: s[SORT_LABEL_KEYS[k]] }))
885
+ }),
886
+ plan.loop && renderLoopToggle(s)
887
+ ].filter(Boolean);
888
+ const chips = plan.types === "chips" && h(
889
+ "div",
890
+ { class: "ws-types", role: "group", "aria-label": s.types },
891
+ renderChip("", s.all, total, true),
892
+ f.types.map((t) => renderChip(t.name, t.name, t.count, false))
893
+ );
894
+ const count = plan.count && h("p", { class: "ws-count", "data-ws-count": true, "aria-live": "polite" }, text(countText(total, total, s)));
895
+ return h(
896
+ "div",
897
+ { class: "ws-toolbar" },
898
+ plan.search && renderSearch(s),
899
+ controls.length > 0 && h("div", { class: "ws-controls" }, controls),
900
+ // The chips and the count share a row (the count alone without chips).
901
+ (chips || count) && h("div", { class: "ws-meta" }, chips, count)
902
+ );
903
+ }
904
+ var CELLS = {
905
+ type: (sound) => text(sound.type),
906
+ bpm: (sound) => text(sound.bpm ?? ""),
907
+ key: (sound) => text(sound.key),
908
+ duration: (sound) => text(formatDuration(sound.duration))
909
+ };
910
+ function renderRow(sound, index, o, hidden = false) {
911
+ const s = o.strings;
912
+ const vars = { title: sound.title };
913
+ const cells = o.columns.map((c) => h("span", { class: `ws-cell ws-${c}` }, CELLS[c](sound)));
914
+ return h(
915
+ "li",
916
+ {
917
+ class: "ws-row",
918
+ "data-ws-index": index,
919
+ "data-ws-id": sound.id,
920
+ "data-url": sound.url,
921
+ "data-title": sound.title,
922
+ "data-type": sound.type || null,
923
+ "data-bpm": sound.bpm,
924
+ "data-key": sound.key || null,
925
+ "data-duration": sound.duration,
926
+ "data-tags": sound.tags?.length ? sound.tags.join(",") : null,
927
+ "data-peaks": sound.peaks ? encodePeaks(sound.peaks) : null,
928
+ "data-waveform": sound.waveform,
929
+ "data-download": sound.download,
930
+ hidden
931
+ },
932
+ h("button", { type: "button", class: "ws-play", "aria-pressed": "false", "aria-label": fill(s.play, vars) }, ICONS.play, ICONS.pause),
933
+ h("span", { class: "ws-cell ws-title" }, text(sound.title)),
934
+ // Wide rows: `display: contents` makes each cell a column. Narrow
935
+ // rows: one line under the title.
936
+ cells.length > 0 && h("span", { class: "ws-cells" }, cells),
937
+ o.player === "inline" && h(
938
+ "span",
939
+ { class: "ws-wave", role: "slider", "aria-label": fill(s.seek, vars), "aria-valuemin": "0", "aria-valuemax": "100", "aria-valuenow": "0", tabindex: "-1" },
940
+ h("canvas", { class: "ws-canvas", "aria-hidden": "true" })
941
+ ),
942
+ // Optional, per sound: a plain link. Rows without one carry nothing.
943
+ sound.download && h("a", { class: "ws-download", href: sound.download, download: true, "aria-label": fill(s.download, vars) }, ICONS.download)
944
+ );
945
+ }
946
+ function renderFooter({ o, s, total }) {
947
+ const page = o.pageSize > 0 ? o.pageSize : total;
948
+ const more = Math.max(0, total - page);
949
+ const strip = o.player === "strip";
950
+ return [
951
+ h(
952
+ "p",
953
+ { class: "ws-empty", "data-ws-empty": true, hidden: true },
954
+ text(s.empty),
955
+ " ",
956
+ h("button", { type: "button", class: "ws-clear", "data-ws-clear": true }, text(s.clear))
957
+ ),
958
+ h("button", { type: "button", class: "ws-more", "data-ws-more": true, hidden: more === 0 }, text(fill(s.showMore, { count: Math.min(more, page) }))),
959
+ h("div", { class: strip ? "ws-engine ws-engine--strip" : "ws-engine", "data-ws-engine": true, hidden: !strip }),
960
+ h("p", { class: "ws-sr", "data-ws-status": true, "aria-live": "polite" })
961
+ ].join("");
962
+ }
963
+ function renderSounds(sounds, options = {}) {
964
+ const o = resolveRenderOptions(options);
965
+ const list = normalizeSounds(sounds);
966
+ const ctx = { o, s: o.strings, f: facets(list), total: list.length, id: o.idPrefix || idBase(list) };
967
+ const page = o.pageSize > 0 ? o.pageSize : Infinity;
968
+ return renderToolbar(toolbarPlan(ctx.f, o), ctx) + h(
969
+ "ul",
970
+ { class: `ws-list ws-list--${o.player}`, role: "list", "data-ws-list": true },
971
+ list.map((sound, i) => renderRow(sound, i, o, i >= page))
972
+ ) + renderFooter(ctx);
973
+ }
974
+ function renderSoundsElement(sounds, options = {}, className = "") {
975
+ const o = resolveRenderOptions(options);
976
+ const cls = ["waveform-sounds", `waveform-sounds--${o.player}`, className].filter(Boolean).join(" ");
977
+ return h("div", { class: cls, "data-waveform-sounds": true, "data-player": o.player }, renderSounds(sounds, options));
978
+ }
979
+
980
+ // src/js/dom/rows.js
981
+ var ROW = ":scope > [data-ws-index]";
982
+ function readRows(list) {
983
+ const rows = [...list.querySelectorAll(ROW)].sort((a, b) => Number(a.dataset.wsIndex) - Number(b.dataset.wsIndex));
984
+ const sounds = [];
985
+ for (const row of rows) {
986
+ const d = row.dataset;
987
+ const sound = normalizeSound({
988
+ id: d.wsId,
989
+ url: d.url,
990
+ title: d.title,
991
+ type: d.type,
992
+ bpm: d.bpm,
993
+ key: d.key,
994
+ duration: d.duration,
995
+ tags: d.tags,
996
+ peaks: d.peaks,
997
+ waveform: d.waveform,
998
+ download: d.download
999
+ }, sounds.length);
1000
+ if (!sound) {
1001
+ row.remove();
1002
+ continue;
1003
+ }
1004
+ row.dataset.wsIndex = String(sounds.length);
1005
+ sounds.push(sound);
1006
+ }
1007
+ return sounds;
1008
+ }
1009
+ function indexRows(list) {
1010
+ const rows = [];
1011
+ list.querySelectorAll(ROW).forEach((row) => {
1012
+ rows[Number(row.dataset.wsIndex)] = row;
1013
+ });
1014
+ return rows;
1015
+ }
1016
+ function visibleRows(list) {
1017
+ return [...list.querySelectorAll(ROW)].filter((r) => !r.hidden);
1018
+ }
1019
+ function orderRows(list, rows) {
1020
+ const frag = document.createDocumentFragment();
1021
+ for (const row of rows) if (row) frag.appendChild(row);
1022
+ list.appendChild(frag);
1023
+ }
1024
+
1025
+ // src/js/dom/colors.js
1026
+ function parseAlpha(color) {
1027
+ const c = String(color ?? "").trim();
1028
+ if (!c || c === "transparent") return 0;
1029
+ const slash = c.match(/\/\s*([\d.]+)(%?)\s*\)$/);
1030
+ if (slash) return Number(slash[1]) / (slash[2] ? 100 : 1);
1031
+ const rgba = c.match(/^rgba\(\s*[^,]+,[^,]+,[^,]+,\s*([\d.]+)\s*\)$/);
1032
+ if (rgba) return Number(rgba[1]);
1033
+ return 1;
1034
+ }
1035
+ function pageSurface(el, minAlpha = 0.95) {
1036
+ for (let node = el; node && node.nodeType === 1; node = node.parentElement || node.getRootNode?.().host) {
1037
+ const bg = getComputedStyle(node).backgroundColor;
1038
+ if (parseAlpha(bg) > minAlpha) return bg;
1039
+ }
1040
+ return "#fff";
1041
+ }
1042
+ function resolveCssColor(container, value) {
1043
+ const probe = document.createElement("span");
1044
+ probe.style.cssText = "position:absolute;width:0;height:0;overflow:hidden;visibility:hidden";
1045
+ probe.style.color = value;
1046
+ container.appendChild(probe);
1047
+ const color = getComputedStyle(probe).color;
1048
+ probe.remove();
1049
+ return color;
1050
+ }
1051
+
1052
+ // src/js/data/url-state.js
1053
+ function urlKeys(urlState) {
1054
+ if (!urlState) return null;
1055
+ const p = typeof urlState === "string" ? `${urlState}-` : "";
1056
+ return { q: `${p}q`, type: `${p}type`, key: `${p}key`, bpm: `${p}bpm`, sort: `${p}sort` };
1057
+ }
1058
+ function parseBpmRange(value) {
1059
+ const m = String(value ?? "").match(/^(\d*)-(\d*)$/);
1060
+ return m && (m[1] || m[2]) ? { bpmMin: m[1], bpmMax: m[2] } : null;
1061
+ }
1062
+ function formatBpmRange(min, max) {
1063
+ const lo = min ?? "", hi = max ?? "";
1064
+ return lo !== "" || hi !== "" ? `${lo}-${hi}` : "";
1065
+ }
1066
+ function readUrlState(search, keys, available, sorts) {
1067
+ const out = { filter: {}, sort: null };
1068
+ if (!keys) return out;
1069
+ const sp = new URLSearchParams(search);
1070
+ const q = sp.get(keys.q);
1071
+ if (q) out.filter.query = q;
1072
+ const type = sp.get(keys.type);
1073
+ if (type && available.types.some((t) => t.name === type)) out.filter.type = type;
1074
+ const key = normalizeKey(sp.get(keys.key));
1075
+ if (key && available.keys.includes(key)) out.filter.key = key;
1076
+ const bpm = parseBpmRange(sp.get(keys.bpm));
1077
+ if (bpm) Object.assign(out.filter, bpm);
1078
+ const sort = sp.get(keys.sort);
1079
+ if (sort && sorts.includes(sort)) out.sort = sort;
1080
+ return out;
1081
+ }
1082
+ function writeUrlState(href, keys, filter, sort, defaultSort) {
1083
+ if (!keys) return href;
1084
+ const url = new URL(href);
1085
+ const set = (name, v) => v ? url.searchParams.set(name, v) : url.searchParams.delete(name);
1086
+ set(keys.q, String(filter.query ?? "").trim());
1087
+ set(keys.type, filter.type);
1088
+ set(keys.key, filter.key);
1089
+ set(keys.bpm, formatBpmRange(filter.bpmMin, filter.bpmMax));
1090
+ set(keys.sort, sort !== defaultSort ? sort : "");
1091
+ return url.href;
1092
+ }
1093
+
1094
+ // src/js/core/WaveformSounds.js
1095
+ var NO_FILTER = Object.freeze({ query: "", type: "", key: "", bpmMin: "", bpmMax: "" });
1096
+ var SEARCH_DELAY = 120;
1097
+ var BPM_DELAY = 200;
1098
+ var URL_DELAY = 250;
1099
+ var WaveformSounds = class _WaveformSounds {
1100
+ /** @type {Map<Element, WaveformSounds>} */
1101
+ static instances = /* @__PURE__ */ new Map();
1102
+ /**
1103
+ * @param {HTMLElement|string} container - The element (or a selector).
1104
+ * @param {import('../../../index').WaveformSoundsOptions} [options]
1105
+ */
1106
+ constructor(container, options = {}) {
1107
+ const el = typeof container === "string" ? document.querySelector(container) : container;
1108
+ if (!el) throw new Error(`${LOG} Container not found: ${container}`);
1109
+ this.container = el;
1110
+ this.options = mergeOptions(DEFAULT_OPTIONS, options, readDataOptions(el));
1111
+ this.options.waveformStyle = this.options.waveformStyle === "bars" ? "bars" : "mirror";
1112
+ this.strings = { ...DEFAULT_STRINGS, ...this.options.strings || {} };
1113
+ this.render = { ...resolveRenderOptions(this.options), strings: this.strings };
1114
+ this.sounds = [];
1115
+ this.rows = [];
1116
+ this.filter = { ...NO_FILTER };
1117
+ this.sortBy = "default";
1118
+ this.limit = this._pageSize();
1119
+ this.currentIndex = null;
1120
+ this.playing = false;
1121
+ this.progress = 0;
1122
+ this.loop = !!this.options.loop;
1123
+ this.engine = null;
1124
+ this.menus = null;
1125
+ this.destroyed = false;
1126
+ this._ctl = new AbortController();
1127
+ this._originalHTML = null;
1128
+ this._pendingSeek = null;
1129
+ this._raf = 0;
1130
+ _WaveformSounds.instances.set(el, this);
1131
+ el.dataset.wsInitialized = "true";
1132
+ this.ready = Promise.resolve().then(() => this._init()).catch((err) => {
1133
+ console.error(`${LOG} Failed to initialise:`, err);
1134
+ this._emit("error", { error: err });
1135
+ this.options.onError?.(err, this);
1136
+ });
1137
+ }
1138
+ /* ── Setup ─────────────────────────────────────────────────────────── */
1139
+ /**
1140
+ * Adopt server-rendered markup or render it (from `sounds` or a fetched
1141
+ * manifest), then wire everything up.
1142
+ * @private
1143
+ */
1144
+ async _init() {
1145
+ const el = this.container;
1146
+ const adopted = el.querySelector("[data-ws-list]");
1147
+ if (adopted) {
1148
+ this.sounds = readRows(adopted);
1149
+ } else {
1150
+ this._originalHTML = el.innerHTML;
1151
+ this.sounds = await this._loadSounds();
1152
+ if (this.destroyed) return;
1153
+ el.innerHTML = renderSounds(this.sounds, { ...this.render, idPrefix: this.options.idPrefix || el.id || void 0 });
1154
+ }
1155
+ if (this.destroyed) return;
1156
+ this._addedClasses = ["waveform-sounds", `waveform-sounds--${this.render.player}`].filter((c) => !el.classList.contains(c));
1157
+ el.classList.add(...this._addedClasses);
1158
+ this._cacheRefs();
1159
+ this._bind();
1160
+ this._observe();
1161
+ this._resolveColors();
1162
+ this._setLoop(this.loop);
1163
+ this._sorts = availableSorts(this.render.sorts, facets(this.sounds));
1164
+ if (!this._sortSet) this.sortBy = this._sorts[0] || "default";
1165
+ this._readUrl();
1166
+ this._syncControls();
1167
+ this._apply({ resort: this.sortBy !== "default" });
1168
+ if (this._playerClass()) this._ensureEngine();
1169
+ this._emit("ready", { sounds: this.sounds.length });
1170
+ this.options.onReady?.(this);
1171
+ }
1172
+ /**
1173
+ * The sounds from the `sounds` option, else the `manifest` URL.
1174
+ * @returns {Promise<import('../../../index').Sound[]>}
1175
+ * @private
1176
+ */
1177
+ async _loadSounds() {
1178
+ if (this.options.sounds || !this.options.manifest) return normalizeSounds(this.options.sounds || []);
1179
+ const res = await fetch(this.options.manifest);
1180
+ if (!res.ok) throw new Error(`${LOG} Manifest ${this.options.manifest}: HTTP ${res.status}`);
1181
+ return parseManifest(await res.json());
1182
+ }
1183
+ /**
1184
+ * Look up the elements the runtime drives.
1185
+ * @private
1186
+ */
1187
+ _cacheRefs() {
1188
+ const q = (sel) => this.container.querySelector(sel);
1189
+ this.$ = {
1190
+ list: q("[data-ws-list]"),
1191
+ search: q("[data-ws-search]"),
1192
+ bpmMin: q("[data-ws-bpm-min]"),
1193
+ bpmMax: q("[data-ws-bpm-max]"),
1194
+ loop: q("[data-ws-loop]"),
1195
+ count: q("[data-ws-count]"),
1196
+ empty: q("[data-ws-empty]"),
1197
+ more: q("[data-ws-more]"),
1198
+ engine: q("[data-ws-engine]"),
1199
+ status: q("[data-ws-status]"),
1200
+ chips: [...this.container.querySelectorAll("[data-ws-type]")]
1201
+ };
1202
+ this.rows = indexRows(this.$.list);
1203
+ }
1204
+ /**
1205
+ * Every listener. All are removed by `destroy()` through one
1206
+ * AbortController.
1207
+ * @private
1208
+ */
1209
+ _bind() {
1210
+ const sig = { signal: this._ctl.signal };
1211
+ const $ = this.$;
1212
+ const root = this.container;
1213
+ root.addEventListener("click", (e) => this._onClick(e), sig);
1214
+ root.addEventListener("pointerdown", (e) => this._onPointerDown(e), sig);
1215
+ root.addEventListener("keydown", (e) => this._onKey(e), sig);
1216
+ let searchTimer = 0, bpmTimer = 0;
1217
+ $.search?.addEventListener("input", () => {
1218
+ clearTimeout(searchTimer);
1219
+ searchTimer = setTimeout(() => this.setFilter({ query: $.search.value }), SEARCH_DELAY);
1220
+ }, sig);
1221
+ $.search?.addEventListener("keydown", (e) => {
1222
+ if (e.key === "ArrowDown") {
1223
+ e.preventDefault();
1224
+ this._focusRow(visibleRows($.list)[0]);
1225
+ }
1226
+ if (e.key === "Escape" && $.search.value) {
1227
+ e.preventDefault();
1228
+ $.search.value = "";
1229
+ this.setFilter({ query: "" });
1230
+ }
1231
+ }, sig);
1232
+ const onBpm = () => {
1233
+ clearTimeout(bpmTimer);
1234
+ bpmTimer = setTimeout(() => this.setFilter({ bpmMin: $.bpmMin?.value ?? "", bpmMax: $.bpmMax?.value ?? "" }), BPM_DELAY);
1235
+ };
1236
+ $.bpmMin?.addEventListener("input", onBpm, sig);
1237
+ $.bpmMax?.addEventListener("input", onBpm, sig);
1238
+ this.menus = new Menus(root, {
1239
+ signal: this._ctl.signal,
1240
+ onPick: (name, value) => name === "sort" ? this.setSort(value) : this.setFilter({ [name]: value })
1241
+ });
1242
+ document.addEventListener("waveformplayer:play", (e) => {
1243
+ const player = e.detail?.player;
1244
+ if (player && player !== this.engine && this.playing) this.pause();
1245
+ }, sig);
1246
+ }
1247
+ /* ── Input ────────────────────────────────────────────────────────── */
1248
+ /**
1249
+ * Clicks: type chips, Show more, Clear, Loop, a touch tap on a waveform
1250
+ * (seek), and anywhere else on a row (play/pause).
1251
+ * @private
1252
+ */
1253
+ _onClick(e) {
1254
+ const t = e.target;
1255
+ const chip = t.closest("[data-ws-type]");
1256
+ if (chip) {
1257
+ this.setFilter({ type: chip.dataset.wsType });
1258
+ return;
1259
+ }
1260
+ if (t.closest("[data-ws-more]")) {
1261
+ this.showMore();
1262
+ return;
1263
+ }
1264
+ if (t.closest("[data-ws-clear]")) {
1265
+ this.clearFilters();
1266
+ return;
1267
+ }
1268
+ if (t.closest("[data-ws-loop]")) {
1269
+ this.setLoop(!this.loop);
1270
+ return;
1271
+ }
1272
+ const wave = t.closest(".ws-wave");
1273
+ if (wave) {
1274
+ if (this._lastPointer === "touch") this._seekAt(wave, e.clientX);
1275
+ return;
1276
+ }
1277
+ const row = t.closest("[data-ws-index]");
1278
+ if (!row || t.closest(".ws-download")) return;
1279
+ this.toggle(Number(row.dataset.wsIndex));
1280
+ this._focusRowQuietly(row);
1281
+ }
1282
+ /**
1283
+ * Mouse and pen seek on PRESS, like every scrubber. Remembers the
1284
+ * pointer type for the click that follows.
1285
+ * @private
1286
+ */
1287
+ _onPointerDown(e) {
1288
+ this._lastPointer = e.pointerType;
1289
+ const wave = e.target.closest(".ws-wave");
1290
+ if (!wave || e.button !== 0 || e.pointerType === "touch") return;
1291
+ e.preventDefault();
1292
+ this._seekAt(wave, e.clientX);
1293
+ }
1294
+ /**
1295
+ * Seek (or start) a row's sound where its waveform was pressed.
1296
+ * @private
1297
+ */
1298
+ _seekAt(wave, clientX) {
1299
+ const row = wave.closest("[data-ws-index]");
1300
+ this._seekRow(Number(row.dataset.wsIndex), pointerFraction(clientX, wave.getBoundingClientRect()));
1301
+ this._focusRowQuietly(row);
1302
+ }
1303
+ /**
1304
+ * Keys on the list: `/` focuses search; ↑/↓/Home/End move between rows
1305
+ * (auditioning while something plays); ←/→ seek the playing row.
1306
+ * @private
1307
+ */
1308
+ _onKey(e) {
1309
+ if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey) return;
1310
+ if (e.key === "/" && !isTyping(e.target) && this.$.search) {
1311
+ e.preventDefault();
1312
+ this.$.search.focus();
1313
+ return;
1314
+ }
1315
+ const row = e.target.closest?.("[data-ws-index]");
1316
+ if (!row) return;
1317
+ const index = Number(row.dataset.wsIndex);
1318
+ const seek = seekTarget(this.progress, e.key);
1319
+ if (seek !== null) {
1320
+ if (index !== this.currentIndex || !this.engine) return;
1321
+ e.preventDefault();
1322
+ this._seekRow(index, seek);
1323
+ return;
1324
+ }
1325
+ const rows = visibleRows(this.$.list);
1326
+ const target = rowTarget(e.key, rows.indexOf(row), rows.length);
1327
+ if (target === null) return;
1328
+ e.preventDefault();
1329
+ if (target === "search") {
1330
+ this.$.search?.focus();
1331
+ return;
1332
+ }
1333
+ this._focusRow(rows[target]);
1334
+ if (this.options.arrowAudition && this.playing) this.play(Number(rows[target].dataset.wsIndex));
1335
+ }
1336
+ /**
1337
+ * Focus a row's play button.
1338
+ * @private
1339
+ */
1340
+ _focusRow(row) {
1341
+ row?.querySelector(".ws-play")?.focus();
1342
+ }
1343
+ /**
1344
+ * After a mouse or touch play, put focus on that row's play button so
1345
+ * the arrow keys drive the list instead of scrolling the page (a click
1346
+ * on the title or waveform left focus on <body>, and Safari never
1347
+ * focuses a clicked button). No scroll jump, and no focus ring: the
1348
+ * browser shows none for a focus that follows a pointer.
1349
+ * @private
1350
+ */
1351
+ _focusRowQuietly(row) {
1352
+ const btn = row?.querySelector(".ws-play");
1353
+ if (btn && document.activeElement !== btn) btn.focus({ preventScroll: true });
1354
+ }
1355
+ /* ── Drawing & colours ────────────────────────────────────────────── */
1356
+ /**
1357
+ * Draw row canvases as they scroll into view; redraw on resize and on
1358
+ * theme flips (the canvas can't follow CSS by itself).
1359
+ * @private
1360
+ */
1361
+ _observe() {
1362
+ if (this.render.player !== "inline" || typeof window === "undefined") return;
1363
+ this._drawn = /* @__PURE__ */ new Set();
1364
+ if ("IntersectionObserver" in window) {
1365
+ this._io = new IntersectionObserver((entries) => {
1366
+ for (const entry of entries) {
1367
+ if (!entry.isIntersecting) continue;
1368
+ const i = Number(entry.target.dataset.wsIndex);
1369
+ this._drawn.add(i);
1370
+ this._drawRow(i);
1371
+ }
1372
+ }, { rootMargin: "200px 0px" });
1373
+ this.rows.forEach((r) => r && this._io.observe(r));
1374
+ } else {
1375
+ this.rows.forEach((r, i) => r && this._drawn.add(i));
1376
+ }
1377
+ if ("ResizeObserver" in window) {
1378
+ let width = 0;
1379
+ this._ro = new ResizeObserver(([entry]) => {
1380
+ const w = Math.round(entry.contentRect.width);
1381
+ if (w === width) return;
1382
+ width = w;
1383
+ this._redrawAll();
1384
+ });
1385
+ this._ro.observe(this.$.list);
1386
+ }
1387
+ const refresh = () => requestAnimationFrame(() => {
1388
+ this._resolveColors();
1389
+ this._redrawAll();
1390
+ });
1391
+ this._mo = new MutationObserver(refresh);
1392
+ const watch = { attributes: true, attributeFilter: ["class", "data-theme", "data-color-scheme", "style"] };
1393
+ this._mo.observe(document.documentElement, watch);
1394
+ if (document.body) this._mo.observe(document.body, watch);
1395
+ try {
1396
+ window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", refresh, { signal: this._ctl.signal });
1397
+ } catch {
1398
+ }
1399
+ }
1400
+ /**
1401
+ * Resolve the canvas colours (options, else the CSS custom properties)
1402
+ * and keep `--ws-surface` current unless the site set it.
1403
+ * @private
1404
+ */
1405
+ _resolveColors() {
1406
+ if (this._autoSurface || !getComputedStyle(this.container).getPropertyValue("--ws-surface").trim()) {
1407
+ this._autoSurface = true;
1408
+ this.container.style.removeProperty("--ws-surface");
1409
+ this.container.style.setProperty("--ws-surface", pageSurface(this.container));
1410
+ }
1411
+ this.colors = {
1412
+ wave: this.options.waveformColor || resolveCssColor(this.container, "var(--ws-wave-color)") || "rgba(128,128,128,.5)",
1413
+ progress: this.options.progressColor || resolveCssColor(this.container, "var(--ws-progress-color)") || "currentColor"
1414
+ };
1415
+ }
1416
+ /**
1417
+ * Draw one row's waveform (only once it has been on screen).
1418
+ * @private
1419
+ */
1420
+ _drawRow(index) {
1421
+ if (this.render.player !== "inline" || index == null || !this._drawn?.has(index)) return;
1422
+ const row = this.rows[index];
1423
+ const canvas = row?.querySelector("canvas");
1424
+ if (!canvas || row.hidden) return;
1425
+ const gap = Number(this.options.barGap);
1426
+ drawRowWaveform(canvas, this.sounds[index].peaks, index === this.currentIndex ? this.progress : 0, {
1427
+ style: this.options.waveformStyle,
1428
+ color: this.colors?.wave || "rgba(128,128,128,.5)",
1429
+ progressColor: this.colors?.progress || "currentColor",
1430
+ barWidth: Math.max(1, Number(this.options.barWidth) || 2),
1431
+ barGap: Number.isFinite(gap) ? Math.max(0, gap) : 1
1432
+ });
1433
+ }
1434
+ /**
1435
+ * Redraw every row drawn so far.
1436
+ * @private
1437
+ */
1438
+ _redrawAll() {
1439
+ this._drawn?.forEach((i) => this._drawRow(i));
1440
+ }
1441
+ /* ── Filters in the address ───────────────────────────────────────── */
1442
+ /**
1443
+ * Apply the filter and sort from the address (`urlState`).
1444
+ * @private
1445
+ */
1446
+ _readUrl() {
1447
+ const keys = urlKeys(this.options.urlState);
1448
+ if (!keys || typeof location === "undefined") return;
1449
+ const { filter, sort } = readUrlState(location.search, keys, facets(this.sounds), this._sorts);
1450
+ this.filter = { ...this.filter, ...filter };
1451
+ if (sort) {
1452
+ this.sortBy = sort;
1453
+ this._sortSet = true;
1454
+ }
1455
+ }
1456
+ /**
1457
+ * Rewrite the address shortly after a change (replaceState: no history
1458
+ * entries).
1459
+ * @private
1460
+ */
1461
+ _queueUrl() {
1462
+ const keys = urlKeys(this.options.urlState);
1463
+ if (!keys || typeof location === "undefined") return;
1464
+ clearTimeout(this._urlTimer);
1465
+ this._urlTimer = setTimeout(() => {
1466
+ if (this.destroyed) return;
1467
+ const next = writeUrlState(location.href, keys, this.filter, this.sortBy, this._sorts?.[0] || "default");
1468
+ if (next !== location.href) history.replaceState(history.state, "", next);
1469
+ }, URL_DELAY);
1470
+ }
1471
+ /* ── Filtering, sorting, paging ───────────────────────────────────── */
1472
+ /** The sounds that pass the filter, in the current sort order. */
1473
+ get visible() {
1474
+ return sortSounds(this.sounds.filter((s) => matches(s, this.filter)), this.sortBy);
1475
+ }
1476
+ /**
1477
+ * Change the filter (merged into the current one) and re-apply. Back to
1478
+ * the first page.
1479
+ *
1480
+ * @param {Partial<import('../../../index').SoundsFilter>} patch
1481
+ */
1482
+ setFilter(patch = {}) {
1483
+ this.filter = { ...this.filter, ...patch };
1484
+ this.limit = this._pageSize();
1485
+ this._syncControls();
1486
+ this._apply({ resort: false });
1487
+ }
1488
+ /** Reset every filter (the sort stays). */
1489
+ clearFilters() {
1490
+ this.setFilter(NO_FILTER);
1491
+ }
1492
+ /** @param {import('../../../index').SoundsSort} by */
1493
+ setSort(by) {
1494
+ this._sortSet = true;
1495
+ this.sortBy = SORTS.includes(by) ? by : "default";
1496
+ this.menus?.setValue("sort", this.sortBy);
1497
+ this._apply({ resort: true });
1498
+ }
1499
+ /** Reveal the next page of results. */
1500
+ showMore() {
1501
+ if (this.limit === Infinity) return;
1502
+ this.limit += this.render.pageSize;
1503
+ this._apply({ resort: false });
1504
+ }
1505
+ /**
1506
+ * Rows per page (Infinity when paging is off).
1507
+ * @private
1508
+ */
1509
+ _pageSize() {
1510
+ return this.render.pageSize > 0 ? this.render.pageSize : Infinity;
1511
+ }
1512
+ /**
1513
+ * Show the current filter and sort in the controls (they can be set from
1514
+ * code or the address, not only by the controls themselves).
1515
+ * @private
1516
+ */
1517
+ _syncControls() {
1518
+ const $ = this.$, f = this.filter;
1519
+ if (!$) return;
1520
+ if ($.search && $.search.value !== f.query) $.search.value = f.query;
1521
+ this.menus?.setValue("type", f.type || "");
1522
+ this.menus?.setValue("key", f.key || "");
1523
+ this.menus?.setValue("sort", this.sortBy);
1524
+ if ($.bpmMin && $.bpmMin.value !== String(f.bpmMin)) $.bpmMin.value = f.bpmMin;
1525
+ if ($.bpmMax && $.bpmMax.value !== String(f.bpmMax)) $.bpmMax.value = f.bpmMax;
1526
+ $.chips.forEach((c) => c.setAttribute("aria-pressed", String(c.dataset.wsType === (f.type || ""))));
1527
+ }
1528
+ /**
1529
+ * Lay the rows out for the current filter, sort and page: order, hide,
1530
+ * "Show more", the empty state and the count. Then report it.
1531
+ *
1532
+ * @param {{resort: boolean}} opts - Reorder the rows even if the sort
1533
+ * hasn't changed.
1534
+ * @private
1535
+ */
1536
+ _apply({ resort }) {
1537
+ const $ = this.$;
1538
+ if (!$) return;
1539
+ if (resort || this.sortBy !== this._lastSort) {
1540
+ orderRows($.list, sortSounds(this.sounds, this.sortBy).map((s) => this.rows[this.sounds.indexOf(s)]));
1541
+ this._lastSort = this.sortBy;
1542
+ }
1543
+ const shown = this.visible;
1544
+ const { visible, remaining } = pageWindow(shown, this.limit);
1545
+ this.sounds.forEach((s, i) => {
1546
+ if (this.rows[i]) this.rows[i].hidden = !visible.has(s);
1547
+ });
1548
+ if ($.more) {
1549
+ $.more.hidden = remaining <= 0;
1550
+ $.more.textContent = fill(this.strings.showMore, { count: Math.min(remaining, this.render.pageSize || remaining) });
1551
+ }
1552
+ if ($.empty) $.empty.hidden = shown.length > 0;
1553
+ if ($.count) $.count.textContent = countText(shown.length, this.sounds.length, this.strings);
1554
+ this._queueUrl();
1555
+ this._emit("filter", { visible: shown.length, total: this.sounds.length, filter: { ...this.filter }, sort: this.sortBy });
1556
+ this.options.onFilter?.(shown, this);
1557
+ }
1558
+ /* ── Playback ─────────────────────────────────────────────────────── */
1559
+ /**
1560
+ * Resolve an index, id or sound to an index in `this.sounds`. No
1561
+ * target means the current sound, else the first visible one.
1562
+ *
1563
+ * @param {number|string|Object} [target]
1564
+ * @returns {number|null}
1565
+ * @private
1566
+ */
1567
+ _indexOf(target) {
1568
+ if (target == null) return this.currentIndex ?? (this.visible[0] ? this.sounds.indexOf(this.visible[0]) : null);
1569
+ if (typeof target === "number") return this.sounds[target] ? target : null;
1570
+ const i = typeof target === "object" ? this.sounds.indexOf(target) : this.sounds.findIndex((s) => s.id === String(target));
1571
+ return i >= 0 ? i : null;
1572
+ }
1573
+ /**
1574
+ * The WaveformPlayer class: `playerClass`, else the page's global.
1575
+ * @returns {Function|null}
1576
+ * @private
1577
+ */
1578
+ _playerClass() {
1579
+ return this.options.playerClass || (typeof window !== "undefined" ? window.WaveformPlayer : null) || null;
1580
+ }
1581
+ /**
1582
+ * Build the engine once (it holds no audio until a play).
1583
+ * @returns {Object|null} The engine, or null without a player class.
1584
+ * @private
1585
+ */
1586
+ _ensureEngine() {
1587
+ if (this.engine) return this.engine;
1588
+ const Player = this._playerClass();
1589
+ if (!Player) {
1590
+ console.error(`${LOG} @arraypress/waveform-player is required: load it before playing (or pass playerClass).`);
1591
+ return null;
1592
+ }
1593
+ this.engine = new Player(this.$.engine, engineOptions(this.options.playerOptions, this.render.player, {
1594
+ onLoad: () => this._onEngineLoad(),
1595
+ onPlay: () => this._setPlaying(true),
1596
+ onPause: () => this._setPlaying(false),
1597
+ onEnd: () => this._onEnd(),
1598
+ onTimeUpdate: (time, duration) => this._onTime(time, duration),
1599
+ onError: (err) => this._onEngineError(err)
1600
+ }));
1601
+ return this.engine;
1602
+ }
1603
+ /**
1604
+ * Play a sound (by index, id or sound object), or resume the current
1605
+ * one. Before the list is built the call waits for it.
1606
+ *
1607
+ * @param {number|string|Object} [target]
1608
+ * @param {{at?: number}} [opts] - `at`: start position 0..1.
1609
+ */
1610
+ play(target, opts = {}) {
1611
+ if (!this.$) {
1612
+ this.ready.then(() => {
1613
+ if (!this.destroyed) this.play(target, opts);
1614
+ });
1615
+ return;
1616
+ }
1617
+ const index = this._indexOf(target);
1618
+ if (index == null) return;
1619
+ const engine = this._ensureEngine();
1620
+ if (!engine) return;
1621
+ if (index === this.currentIndex && engine.audio?.src) {
1622
+ if (opts.at != null) this._seekRow(index, opts.at);
1623
+ if (!this.playing) engine.play();
1624
+ return;
1625
+ }
1626
+ const previous = this.currentIndex;
1627
+ this.currentIndex = index;
1628
+ this.progress = 0;
1629
+ this._pendingSeek = opts.at ?? null;
1630
+ if (previous != null) this._paintRow(previous);
1631
+ this._paintRow(index);
1632
+ const sound = this.sounds[index];
1633
+ engine.loadTrack(sound.url, sound.title, sound.type || null, { waveform: enginePeaks(sound, this.render.player), autoplay: true });
1634
+ }
1635
+ /** Pause the current sound. */
1636
+ pause() {
1637
+ if (this.engine && this.playing) this.engine.pause();
1638
+ }
1639
+ /**
1640
+ * The current sound plays/pauses; another sound starts.
1641
+ * @param {number|string|Object} [target]
1642
+ */
1643
+ toggle(target) {
1644
+ const index = this._indexOf(target);
1645
+ if (index == null) return;
1646
+ if (index === this.currentIndex && this.playing) this.pause();
1647
+ else this.play(index);
1648
+ }
1649
+ /** Play the next visible sound (no wrap at the end). */
1650
+ next() {
1651
+ this._step(1);
1652
+ }
1653
+ /** Play the previous visible sound. */
1654
+ previous() {
1655
+ this._step(-1);
1656
+ }
1657
+ /**
1658
+ * Play the visible sound `dir` places away, revealing it if it's past
1659
+ * the current page.
1660
+ *
1661
+ * @param {1|-1} dir
1662
+ * @returns {boolean} Whether there was one.
1663
+ * @private
1664
+ */
1665
+ _step(dir) {
1666
+ const shown = this.visible;
1667
+ const at = this.currentIndex == null ? -1 : shown.indexOf(this.sounds[this.currentIndex]);
1668
+ const target = shown[at + dir];
1669
+ if (!target) return false;
1670
+ const limit = limitToReveal(this.limit, at + dir);
1671
+ if (limit !== this.limit) {
1672
+ this.limit = limit;
1673
+ this._apply({ resort: false });
1674
+ }
1675
+ this.play(this.sounds.indexOf(target));
1676
+ return true;
1677
+ }
1678
+ /**
1679
+ * Loop the current sound (auditioning a loop is the common case).
1680
+ * @param {boolean} on
1681
+ */
1682
+ setLoop(on) {
1683
+ this.loop = !!on;
1684
+ this._setLoop(this.loop);
1685
+ }
1686
+ /**
1687
+ * Apply the loop state to the toggle and the engine.
1688
+ * @private
1689
+ */
1690
+ _setLoop(on) {
1691
+ this.$?.loop?.setAttribute("aria-pressed", String(on));
1692
+ if (this.engine?.audio) this.engine.audio.loop = on;
1693
+ }
1694
+ /**
1695
+ * Seek a row's sound to `fraction`; a row that isn't current starts
1696
+ * there. Before the duration is known the seek waits for it.
1697
+ * @private
1698
+ */
1699
+ _seekRow(index, fraction) {
1700
+ if (index !== this.currentIndex || !this.engine) {
1701
+ this.play(index, { at: fraction });
1702
+ return;
1703
+ }
1704
+ const duration = this.engine.audio?.duration;
1705
+ if (!Number.isFinite(duration) || duration <= 0) {
1706
+ this._pendingSeek = fraction;
1707
+ return;
1708
+ }
1709
+ this.engine.seekTo(fraction * duration);
1710
+ this.progress = fraction;
1711
+ this._paintRow(index);
1712
+ if (!this.playing) this.engine.play();
1713
+ }
1714
+ /**
1715
+ * The engine loaded a sound: apply the loop, borrow decoded peaks for a
1716
+ * row that had none, and land a pending seek.
1717
+ * @private
1718
+ */
1719
+ _onEngineLoad() {
1720
+ if (this.engine?.audio) this.engine.audio.loop = this.loop;
1721
+ const sound = this.sounds[this.currentIndex];
1722
+ if (sound && !sound.peaks && this.engine?.waveformData?.length) {
1723
+ sound.peaks = resample(this.engine.waveformData, 96);
1724
+ this._drawRow(this.currentIndex);
1725
+ }
1726
+ const duration = this.engine?.audio?.duration;
1727
+ if (this._pendingSeek != null && Number.isFinite(duration) && duration > 0) {
1728
+ this.engine.seekTo(this._pendingSeek * duration);
1729
+ this.progress = this._pendingSeek;
1730
+ this._pendingSeek = null;
1731
+ }
1732
+ }
1733
+ /**
1734
+ * Playback progress: repaint the current row, once per frame.
1735
+ * @private
1736
+ */
1737
+ _onTime(time, duration) {
1738
+ if (this.currentIndex == null || !duration) return;
1739
+ if (this._pendingSeek != null) {
1740
+ const fraction = this._pendingSeek;
1741
+ this._pendingSeek = null;
1742
+ this.engine.seekTo(fraction * duration);
1743
+ return;
1744
+ }
1745
+ this.progress = Math.min(Math.max(time / duration, 0), 1);
1746
+ if (this._raf) return;
1747
+ this._raf = requestAnimationFrame(() => {
1748
+ this._raf = 0;
1749
+ this._drawRow(this.currentIndex);
1750
+ this.rows[this.currentIndex]?.querySelector(".ws-wave")?.setAttribute("aria-valuenow", String(Math.round(this.progress * 100)));
1751
+ });
1752
+ }
1753
+ /**
1754
+ * A sound finished: report it, then auto-advance or settle.
1755
+ * @private
1756
+ */
1757
+ _onEnd() {
1758
+ const sound = this.sounds[this.currentIndex];
1759
+ this._emit("end", { sound, index: this.currentIndex });
1760
+ this.options.onEnd?.(sound, this);
1761
+ if (this.options.autoAdvance && this._step(1)) return;
1762
+ this.progress = 0;
1763
+ this._setPlaying(false);
1764
+ }
1765
+ /**
1766
+ * A sound failed to load or play: mark its row and report it.
1767
+ * @private
1768
+ */
1769
+ _onEngineError(err) {
1770
+ this.rows[this.currentIndex]?.classList.add("is-error");
1771
+ this._emit("error", { error: err, sound: this.sounds[this.currentIndex], index: this.currentIndex });
1772
+ this.options.onError?.(err, this);
1773
+ }
1774
+ /**
1775
+ * Record play/pause and repaint. Events fire only on a real change: at a
1776
+ * natural end the browser fires `pause` then `ended`, and `_onEnd()`
1777
+ * also settles the state — one pause event, not two.
1778
+ * @private
1779
+ */
1780
+ _setPlaying(on) {
1781
+ const changed = this.playing !== on;
1782
+ this.playing = on;
1783
+ const index = this.currentIndex;
1784
+ if (index == null) return;
1785
+ this._paintRow(index);
1786
+ if (!changed) return;
1787
+ const sound = this.sounds[index];
1788
+ if (on && this.$.status) this.$.status.textContent = fill(this.strings.nowPlaying, { title: sound.title });
1789
+ this._emit(on ? "play" : "pause", { sound, index });
1790
+ (on ? this.options.onPlay : this.options.onPause)?.(sound, this);
1791
+ }
1792
+ /* ── Row painting ─────────────────────────────────────────────────── */
1793
+ /**
1794
+ * A row's state classes, play-button label and waveform.
1795
+ * @private
1796
+ */
1797
+ _paintRow(index) {
1798
+ const row = this.rows[index];
1799
+ if (!row) return;
1800
+ const current = index === this.currentIndex;
1801
+ const on = current && this.playing;
1802
+ row.classList.toggle("is-current", current);
1803
+ row.classList.toggle("is-playing", on);
1804
+ const btn = row.querySelector(".ws-play");
1805
+ if (btn) {
1806
+ btn.setAttribute("aria-pressed", String(on));
1807
+ btn.setAttribute("aria-label", fill(on ? this.strings.pause : this.strings.play, { title: this.sounds[index].title }));
1808
+ }
1809
+ const wave = row.querySelector(".ws-wave");
1810
+ if (wave) {
1811
+ wave.tabIndex = current ? 0 : -1;
1812
+ if (!current) wave.setAttribute("aria-valuenow", "0");
1813
+ }
1814
+ this._drawRow(index);
1815
+ }
1816
+ /* ── Events & lifecycle ──────────────────────────────────────────── */
1817
+ /**
1818
+ * Emit a `waveformsounds:<name>` event carrying this instance.
1819
+ * @private
1820
+ */
1821
+ _emit(name, detail = {}) {
1822
+ emit(this.container, name, { ...detail, instance: this });
1823
+ }
1824
+ /** The sound playing (or paused) now, or null. */
1825
+ get current() {
1826
+ return this.currentIndex == null ? null : this.sounds[this.currentIndex];
1827
+ }
1828
+ /**
1829
+ * Tear down: listeners, observers, timers and the engine. Markup this
1830
+ * instance rendered is restored to what the container held before.
1831
+ * ADOPTED (server-rendered) markup is left as it is now — rows may be
1832
+ * re-sorted, hidden or marked current — so to start again, re-render it
1833
+ * rather than constructing a new instance over it.
1834
+ */
1835
+ destroy() {
1836
+ if (this.destroyed) return;
1837
+ this.destroyed = true;
1838
+ this._ctl.abort();
1839
+ this._io?.disconnect();
1840
+ this._ro?.disconnect();
1841
+ this._mo?.disconnect();
1842
+ if (this._raf) cancelAnimationFrame(this._raf);
1843
+ clearTimeout(this._urlTimer);
1844
+ try {
1845
+ this.engine?.destroy();
1846
+ } catch {
1847
+ }
1848
+ this.engine = null;
1849
+ if (this._originalHTML != null) this.container.innerHTML = this._originalHTML;
1850
+ if (this._addedClasses?.length) this.container.classList.remove(...this._addedClasses);
1851
+ if (this._autoSurface) this.container.style.removeProperty("--ws-surface");
1852
+ delete this.container.dataset.wsInitialized;
1853
+ _WaveformSounds.instances.delete(this.container);
1854
+ }
1855
+ /**
1856
+ * Initialise every `[data-waveform-sounds]` under `root` that isn't yet.
1857
+ *
1858
+ * @param {ParentNode} [root=document]
1859
+ * @returns {WaveformSounds[]} The new instances.
1860
+ */
1861
+ static init(root = document) {
1862
+ if (typeof document === "undefined") return [];
1863
+ const scope = root || document;
1864
+ const els = [...scope.matches?.("[data-waveform-sounds]") ? [scope] : [], ...scope.querySelectorAll("[data-waveform-sounds]")];
1865
+ const created = [];
1866
+ for (const el of els) {
1867
+ if (el.dataset.wsInitialized === "true" || _WaveformSounds.instances.has(el)) continue;
1868
+ try {
1869
+ created.push(new _WaveformSounds(el));
1870
+ } catch (err) {
1871
+ console.error(`${LOG} Failed to initialise:`, err, el);
1872
+ }
1873
+ }
1874
+ return created;
1875
+ }
1876
+ /**
1877
+ * The instance on an element (or selector), if any.
1878
+ * @param {Element|string} el
1879
+ * @returns {WaveformSounds|null}
1880
+ */
1881
+ static getInstance(el) {
1882
+ const node = typeof el === "string" ? document.querySelector(el) : el;
1883
+ return node ? _WaveformSounds.instances.get(node) || null : null;
1884
+ }
1885
+ /** Destroy instances whose element has left the document (after a
1886
+ * client-side navigation). */
1887
+ static prune() {
1888
+ for (const [el, inst] of _WaveformSounds.instances) if (!el.isConnected) inst.destroy();
1889
+ }
1890
+ };
1891
+
1892
+ // src/js/entry.js
1893
+ WaveformSounds.utils = { encodePeaks, decodePeaks, normalizeKey, normalizeSounds, parseManifest, facets, matches, sortSounds, formatDuration, renderSounds };
1894
+ WaveformSounds.DEFAULT_OPTIONS = DEFAULT_OPTIONS;
1895
+ WaveformSounds.DEFAULT_STRINGS = DEFAULT_STRINGS;
1896
+ if (typeof window !== "undefined") window.WaveformSounds = WaveformSounds;
1897
+ var entry_default = WaveformSounds;
1898
+
1899
+ // src/js/index.js
1900
+ var index_default = entry_default;
1901
+ if (typeof document !== "undefined" && document.documentElement?.dataset?.waveformAutoinit !== "false") {
1902
+ if (document.readyState === "loading") {
1903
+ document.addEventListener("DOMContentLoaded", () => entry_default.init(), { once: true });
1904
+ } else {
1905
+ entry_default.init();
1906
+ }
1907
+ }
1908
+ })();
1909
+ /**
1910
+ * @arraypress/waveform-sounds
1911
+ * A searchable, filterable list of sounds for WaveformPlayer.
1912
+ *
1913
+ * Importing this entry initialises every `[data-waveform-sounds]` element
1914
+ * once the DOM is ready. Opt out page-wide with
1915
+ * `<html data-waveform-autoinit="false">` (the family's switch), or import
1916
+ * `@arraypress/waveform-sounds/no-autoinit`.
1917
+ *
1918
+ * @author ArrayPress
1919
+ * @license MIT
1920
+ */