@arraypress/waveform-sounds 0.0.0-stage → 0.1.1

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