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