@arraypress/waveform-sounds 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,883 @@
1
+ /**
2
+ * WaveformSounds — a searchable, filterable list of sounds for showcasing
3
+ * the previews inside a sample pack, preset bank or sound library.
4
+ *
5
+ * One `WaveformPlayer` (self mode) is the audio engine for the whole list:
6
+ * every sound plays through it, so it brings the player's seeking (incl.
7
+ * hosts that ignore byte ranges), error handling, Media Session card and
8
+ * hand-off with every other player on the page. The rows are light: a
9
+ * button, some text and, in the `inline` layout, a small canvas drawn from
10
+ * low-resolution peaks only when it scrolls into view. 300 sounds is 300
11
+ * rows, not 300 players.
12
+ *
13
+ * Layouts (`player`):
14
+ * - `'inline'` (default): every row has a mini waveform; the playing row
15
+ * fills with progress and is click-to-seek. The engine is hidden.
16
+ * - `'strip'`: plain rows; the engine is shown docked under the list as a
17
+ * full player for the current sound.
18
+ *
19
+ * This class orchestrates; the pieces live by layer:
20
+ * - `core/` — this class, the engine's configuration, the option surface
21
+ * - `data/` — pure logic: sounds, filtering, the address, navigation
22
+ * - `render/` — server-safe markup (also the `/render` entry)
23
+ * - `dom/` — browser-only behaviour: dropdowns, rows, canvas, colours
24
+ * - `shared/` — small helpers
25
+ *
26
+ * @module core
27
+ */
28
+
29
+ import {availableSorts, facets, matches, normalizeSounds, parseManifest, sortSounds, SORTS} from '../data/sounds.js';
30
+ import {drawRowWaveform, resample} from '../dom/draw.js';
31
+ import {engineOptions, enginePeaks} from './engine.js';
32
+ import {Menus} from '../dom/menus.js';
33
+ import {limitToReveal, pageWindow, rowTarget, seekTarget} from '../data/navigation.js';
34
+ import {DEFAULT_OPTIONS, mergeOptions, readDataOptions} from './options.js';
35
+ import {resolveRenderOptions} from '../render/options.js';
36
+ import {renderSounds} from '../render/markup.js';
37
+ import {indexRows, orderRows, readRows, visibleRows} from '../dom/rows.js';
38
+ import {countText, DEFAULT_STRINGS, fill} from '../render/strings.js';
39
+ import {pageSurface, resolveCssColor} from '../dom/colors.js';
40
+ import {readUrlState, urlKeys, writeUrlState} from '../data/url-state.js';
41
+ import {emit, isTyping, LOG, pointerFraction} from '../shared/utils.js';
42
+
43
+ export {DEFAULT_OPTIONS};
44
+
45
+ /** An empty filter: everything matches. */
46
+ const NO_FILTER = Object.freeze({query: '', type: '', key: '', bpmMin: '', bpmMax: ''});
47
+
48
+ /** Debounce for typing in the search box and the BPM fields (ms). */
49
+ const SEARCH_DELAY = 120;
50
+ const BPM_DELAY = 200;
51
+
52
+ /** Debounce before the address is rewritten after a change (ms). */
53
+ const URL_DELAY = 250;
54
+
55
+ export class WaveformSounds {
56
+ /** @type {Map<Element, WaveformSounds>} */
57
+ static instances = new Map();
58
+
59
+ /**
60
+ * @param {HTMLElement|string} container - The element (or a selector).
61
+ * @param {import('../../../index').WaveformSoundsOptions} [options]
62
+ */
63
+ constructor(container, options = {}) {
64
+ const el = typeof container === 'string' ? document.querySelector(container) : container;
65
+ if (!el) throw new Error(`${LOG} Container not found: ${container}`);
66
+ this.container = el;
67
+ // Precedence, as across the family: data-* > constructor > default.
68
+ this.options = mergeOptions(DEFAULT_OPTIONS, options, readDataOptions(el));
69
+ this.options.waveformStyle = this.options.waveformStyle === 'bars' ? 'bars' : 'mirror';
70
+ this.strings = {...DEFAULT_STRINGS, ...(this.options.strings || {})};
71
+ this.render = {...resolveRenderOptions(this.options), strings: this.strings};
72
+
73
+ this.sounds = [];
74
+ this.rows = [];
75
+ this.filter = {...NO_FILTER};
76
+ this.sortBy = 'default';
77
+ this.limit = this._pageSize();
78
+ this.currentIndex = null;
79
+ this.playing = false;
80
+ this.progress = 0;
81
+ this.loop = !!this.options.loop;
82
+ this.engine = null;
83
+ this.menus = null;
84
+ this.destroyed = false;
85
+ this._ctl = new AbortController();
86
+ this._originalHTML = null;
87
+ this._pendingSeek = null;
88
+ this._raf = 0;
89
+
90
+ WaveformSounds.instances.set(el, this);
91
+ el.dataset.wsInitialized = 'true';
92
+ // Build on a later microtask, never inside the constructor: ready /
93
+ // filter events (and onReady) must reach listeners attached right
94
+ // after `new WaveformSounds()`, and `this.ready` must already exist
95
+ // when they fire. It never rejects: a failed build is reported
96
+ // through onError / `waveformsounds:error`.
97
+ /** Resolves once the list is built (after a manifest fetch, if any). */
98
+ this.ready = Promise.resolve().then(() => this._init()).catch((err) => {
99
+ console.error(`${LOG} Failed to initialise:`, err);
100
+ this._emit('error', {error: err});
101
+ this.options.onError?.(err, this);
102
+ });
103
+ }
104
+
105
+ /* ── Setup ─────────────────────────────────────────────────────────── */
106
+
107
+ /**
108
+ * Adopt server-rendered markup or render it (from `sounds` or a fetched
109
+ * manifest), then wire everything up.
110
+ * @private
111
+ */
112
+ async _init() {
113
+ const el = this.container;
114
+ const adopted = el.querySelector('[data-ws-list]');
115
+ if (adopted) {
116
+ this.sounds = readRows(adopted);
117
+ } else {
118
+ this._originalHTML = el.innerHTML;
119
+ this.sounds = await this._loadSounds();
120
+ if (this.destroyed) return;
121
+ el.innerHTML = renderSounds(this.sounds, {...this.render, idPrefix: this.options.idPrefix || el.id || undefined});
122
+ }
123
+ if (this.destroyed) return;
124
+
125
+ // Remember which classes WE add, so destroy() takes back exactly
126
+ // those (server-rendered markup already carries them).
127
+ this._addedClasses = ['waveform-sounds', `waveform-sounds--${this.render.player}`].filter((c) => !el.classList.contains(c));
128
+ el.classList.add(...this._addedClasses);
129
+
130
+ this._cacheRefs();
131
+ this._bind();
132
+ this._observe();
133
+ this._resolveColors();
134
+ this._setLoop(this.loop);
135
+
136
+ // The starting order is the first one offered, unless setSort()
137
+ // already chose one; then the address may override both.
138
+ this._sorts = availableSorts(this.render.sorts, facets(this.sounds));
139
+ if (!this._sortSet) this.sortBy = this._sorts[0] || 'default';
140
+ this._readUrl();
141
+ // Show any filter/sort set before now (from code or the address).
142
+ this._syncControls();
143
+ this._apply({resort: this.sortBy !== 'default'});
144
+
145
+ // Build the engine now (no audio loads until a play) when the
146
+ // player is on the page, so anything that hooks players on their
147
+ // `waveformplayer:ready` (waveform-tracker, analytics) is attached
148
+ // BEFORE the first play — built on first play, that sound went
149
+ // untracked.
150
+ if (this._playerClass()) this._ensureEngine();
151
+
152
+ this._emit('ready', {sounds: this.sounds.length});
153
+ this.options.onReady?.(this);
154
+ }
155
+
156
+ /**
157
+ * The sounds from the `sounds` option, else the `manifest` URL.
158
+ * @returns {Promise<import('../../../index').Sound[]>}
159
+ * @private
160
+ */
161
+ async _loadSounds() {
162
+ if (this.options.sounds || !this.options.manifest) return normalizeSounds(this.options.sounds || []);
163
+ const res = await fetch(this.options.manifest);
164
+ if (!res.ok) throw new Error(`${LOG} Manifest ${this.options.manifest}: HTTP ${res.status}`);
165
+ return parseManifest(await res.json());
166
+ }
167
+
168
+ /**
169
+ * Look up the elements the runtime drives.
170
+ * @private
171
+ */
172
+ _cacheRefs() {
173
+ const q = (sel) => this.container.querySelector(sel);
174
+ this.$ = {
175
+ list: q('[data-ws-list]'),
176
+ search: q('[data-ws-search]'),
177
+ bpmMin: q('[data-ws-bpm-min]'),
178
+ bpmMax: q('[data-ws-bpm-max]'),
179
+ loop: q('[data-ws-loop]'),
180
+ count: q('[data-ws-count]'),
181
+ empty: q('[data-ws-empty]'),
182
+ more: q('[data-ws-more]'),
183
+ engine: q('[data-ws-engine]'),
184
+ status: q('[data-ws-status]'),
185
+ chips: [...this.container.querySelectorAll('[data-ws-type]')],
186
+ };
187
+ this.rows = indexRows(this.$.list);
188
+ }
189
+
190
+ /**
191
+ * Every listener. All are removed by `destroy()` through one
192
+ * AbortController.
193
+ * @private
194
+ */
195
+ _bind() {
196
+ const sig = {signal: this._ctl.signal};
197
+ const $ = this.$;
198
+ const root = this.container;
199
+
200
+ root.addEventListener('click', (e) => this._onClick(e), sig);
201
+ root.addEventListener('pointerdown', (e) => this._onPointerDown(e), sig);
202
+ root.addEventListener('keydown', (e) => this._onKey(e), sig);
203
+
204
+ let searchTimer = 0, bpmTimer = 0;
205
+ $.search?.addEventListener('input', () => {
206
+ clearTimeout(searchTimer);
207
+ searchTimer = setTimeout(() => this.setFilter({query: $.search.value}), SEARCH_DELAY);
208
+ }, sig);
209
+ $.search?.addEventListener('keydown', (e) => {
210
+ if (e.key === 'ArrowDown') { e.preventDefault(); this._focusRow(visibleRows($.list)[0]); }
211
+ if (e.key === 'Escape' && $.search.value) { e.preventDefault(); $.search.value = ''; this.setFilter({query: ''}); }
212
+ }, sig);
213
+ const onBpm = () => {
214
+ clearTimeout(bpmTimer);
215
+ bpmTimer = setTimeout(() => this.setFilter({bpmMin: $.bpmMin?.value ?? '', bpmMax: $.bpmMax?.value ?? ''}), BPM_DELAY);
216
+ };
217
+ $.bpmMin?.addEventListener('input', onBpm, sig);
218
+ $.bpmMax?.addEventListener('input', onBpm, sig);
219
+
220
+ this.menus = new Menus(root, {
221
+ signal: this._ctl.signal,
222
+ onPick: (name, value) => (name === 'sort' ? this.setSort(value) : this.setFilter({[name]: value})),
223
+ });
224
+
225
+ // Any OTHER player starting pauses the list (every WaveformPlayer's
226
+ // play event bubbles to the document). The engine's singlePlay only
227
+ // reaches players that also use singlePlay — a WaveformBar's player
228
+ // doesn't, so without this the bar and the list could play at once.
229
+ document.addEventListener('waveformplayer:play', (e) => {
230
+ const player = e.detail?.player;
231
+ if (player && player !== this.engine && this.playing) this.pause();
232
+ }, sig);
233
+ }
234
+
235
+ /* ── Input ────────────────────────────────────────────────────────── */
236
+
237
+ /**
238
+ * Clicks: type chips, Show more, Clear, Loop, a touch tap on a waveform
239
+ * (seek), and anywhere else on a row (play/pause).
240
+ * @private
241
+ */
242
+ _onClick(e) {
243
+ const t = e.target;
244
+ const chip = t.closest('[data-ws-type]');
245
+ if (chip) { this.setFilter({type: chip.dataset.wsType}); return; }
246
+ if (t.closest('[data-ws-more]')) { this.showMore(); return; }
247
+ if (t.closest('[data-ws-clear]')) { this.clearFilters(); return; }
248
+ if (t.closest('[data-ws-loop]')) { this.setLoop(!this.loop); return; }
249
+ const wave = t.closest('.ws-wave');
250
+ if (wave) {
251
+ // Touch seeks on the TAP (this click): its press may have been
252
+ // the start of a scroll.
253
+ if (this._lastPointer === 'touch') this._seekAt(wave, e.clientX);
254
+ return;
255
+ }
256
+ const row = t.closest('[data-ws-index]');
257
+ if (!row || t.closest('.ws-download')) return;
258
+ this.toggle(Number(row.dataset.wsIndex));
259
+ this._focusRowQuietly(row);
260
+ }
261
+
262
+ /**
263
+ * Mouse and pen seek on PRESS, like every scrubber. Remembers the
264
+ * pointer type for the click that follows.
265
+ * @private
266
+ */
267
+ _onPointerDown(e) {
268
+ this._lastPointer = e.pointerType;
269
+ const wave = e.target.closest('.ws-wave');
270
+ if (!wave || e.button !== 0 || e.pointerType === 'touch') return;
271
+ e.preventDefault();
272
+ this._seekAt(wave, e.clientX);
273
+ }
274
+
275
+ /**
276
+ * Seek (or start) a row's sound where its waveform was pressed.
277
+ * @private
278
+ */
279
+ _seekAt(wave, clientX) {
280
+ const row = wave.closest('[data-ws-index]');
281
+ this._seekRow(Number(row.dataset.wsIndex), pointerFraction(clientX, wave.getBoundingClientRect()));
282
+ this._focusRowQuietly(row);
283
+ }
284
+
285
+ /**
286
+ * Keys on the list: `/` focuses search; ↑/↓/Home/End move between rows
287
+ * (auditioning while something plays); ←/→ seek the playing row.
288
+ * @private
289
+ */
290
+ _onKey(e) {
291
+ if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey) return;
292
+ if (e.key === '/' && !isTyping(e.target) && this.$.search) {
293
+ e.preventDefault();
294
+ this.$.search.focus();
295
+ return;
296
+ }
297
+ const row = e.target.closest?.('[data-ws-index]');
298
+ if (!row) return;
299
+
300
+ const index = Number(row.dataset.wsIndex);
301
+ const seek = seekTarget(this.progress, e.key);
302
+ if (seek !== null) {
303
+ if (index !== this.currentIndex || !this.engine) return;
304
+ e.preventDefault();
305
+ this._seekRow(index, seek);
306
+ return;
307
+ }
308
+
309
+ const rows = visibleRows(this.$.list);
310
+ const target = rowTarget(e.key, rows.indexOf(row), rows.length);
311
+ if (target === null) return;
312
+ e.preventDefault();
313
+ if (target === 'search') { this.$.search?.focus(); return; }
314
+ this._focusRow(rows[target]);
315
+ if (this.options.arrowAudition && this.playing) this.play(Number(rows[target].dataset.wsIndex));
316
+ }
317
+
318
+ /**
319
+ * Focus a row's play button.
320
+ * @private
321
+ */
322
+ _focusRow(row) {
323
+ row?.querySelector('.ws-play')?.focus();
324
+ }
325
+
326
+ /**
327
+ * After a mouse or touch play, put focus on that row's play button so
328
+ * the arrow keys drive the list instead of scrolling the page (a click
329
+ * on the title or waveform left focus on <body>, and Safari never
330
+ * focuses a clicked button). No scroll jump, and no focus ring: the
331
+ * browser shows none for a focus that follows a pointer.
332
+ * @private
333
+ */
334
+ _focusRowQuietly(row) {
335
+ const btn = row?.querySelector('.ws-play');
336
+ if (btn && document.activeElement !== btn) btn.focus({preventScroll: true});
337
+ }
338
+
339
+ /* ── Drawing & colours ────────────────────────────────────────────── */
340
+
341
+ /**
342
+ * Draw row canvases as they scroll into view; redraw on resize and on
343
+ * theme flips (the canvas can't follow CSS by itself).
344
+ * @private
345
+ */
346
+ _observe() {
347
+ if (this.render.player !== 'inline' || typeof window === 'undefined') return;
348
+ this._drawn = new Set();
349
+ if ('IntersectionObserver' in window) {
350
+ this._io = new IntersectionObserver((entries) => {
351
+ for (const entry of entries) {
352
+ if (!entry.isIntersecting) continue;
353
+ const i = Number(entry.target.dataset.wsIndex);
354
+ this._drawn.add(i);
355
+ this._drawRow(i);
356
+ }
357
+ }, {rootMargin: '200px 0px'});
358
+ this.rows.forEach((r) => r && this._io.observe(r));
359
+ } else {
360
+ this.rows.forEach((r, i) => r && this._drawn.add(i));
361
+ }
362
+ if ('ResizeObserver' in window) {
363
+ let width = 0;
364
+ this._ro = new ResizeObserver(([entry]) => {
365
+ const w = Math.round(entry.contentRect.width);
366
+ if (w === width) return;
367
+ width = w;
368
+ this._redrawAll();
369
+ });
370
+ this._ro.observe(this.$.list);
371
+ }
372
+ const refresh = () => requestAnimationFrame(() => { this._resolveColors(); this._redrawAll(); });
373
+ this._mo = new MutationObserver(refresh);
374
+ const watch = {attributes: true, attributeFilter: ['class', 'data-theme', 'data-color-scheme', 'style']};
375
+ this._mo.observe(document.documentElement, watch);
376
+ if (document.body) this._mo.observe(document.body, watch);
377
+ try {
378
+ window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', refresh, {signal: this._ctl.signal});
379
+ } catch { /* no matchMedia */ }
380
+ }
381
+
382
+ /**
383
+ * Resolve the canvas colours (options, else the CSS custom properties)
384
+ * and keep `--ws-surface` current unless the site set it.
385
+ * @private
386
+ */
387
+ _resolveColors() {
388
+ if (this._autoSurface || !getComputedStyle(this.container).getPropertyValue('--ws-surface').trim()) {
389
+ this._autoSurface = true;
390
+ this.container.style.removeProperty('--ws-surface');
391
+ this.container.style.setProperty('--ws-surface', pageSurface(this.container));
392
+ }
393
+ this.colors = {
394
+ wave: this.options.waveformColor || resolveCssColor(this.container, 'var(--ws-wave-color)') || 'rgba(128,128,128,.5)',
395
+ progress: this.options.progressColor || resolveCssColor(this.container, 'var(--ws-progress-color)') || 'currentColor',
396
+ };
397
+ }
398
+
399
+ /**
400
+ * Draw one row's waveform (only once it has been on screen).
401
+ * @private
402
+ */
403
+ _drawRow(index) {
404
+ if (this.render.player !== 'inline' || index == null || !this._drawn?.has(index)) return;
405
+ const row = this.rows[index];
406
+ const canvas = row?.querySelector('canvas');
407
+ if (!canvas || row.hidden) return;
408
+ const gap = Number(this.options.barGap);
409
+ drawRowWaveform(canvas, this.sounds[index].peaks, index === this.currentIndex ? this.progress : 0, {
410
+ style: this.options.waveformStyle,
411
+ color: this.colors?.wave || 'rgba(128,128,128,.5)',
412
+ progressColor: this.colors?.progress || 'currentColor',
413
+ barWidth: Math.max(1, Number(this.options.barWidth) || 2),
414
+ barGap: Number.isFinite(gap) ? Math.max(0, gap) : 1,
415
+ });
416
+ }
417
+
418
+ /**
419
+ * Redraw every row drawn so far.
420
+ * @private
421
+ */
422
+ _redrawAll() {
423
+ this._drawn?.forEach((i) => this._drawRow(i));
424
+ }
425
+
426
+ /* ── Filters in the address ───────────────────────────────────────── */
427
+
428
+ /**
429
+ * Apply the filter and sort from the address (`urlState`).
430
+ * @private
431
+ */
432
+ _readUrl() {
433
+ const keys = urlKeys(this.options.urlState);
434
+ if (!keys || typeof location === 'undefined') return;
435
+ const {filter, sort} = readUrlState(location.search, keys, facets(this.sounds), this._sorts);
436
+ this.filter = {...this.filter, ...filter};
437
+ if (sort) { this.sortBy = sort; this._sortSet = true; }
438
+ }
439
+
440
+ /**
441
+ * Rewrite the address shortly after a change (replaceState: no history
442
+ * entries).
443
+ * @private
444
+ */
445
+ _queueUrl() {
446
+ const keys = urlKeys(this.options.urlState);
447
+ if (!keys || typeof location === 'undefined') return;
448
+ clearTimeout(this._urlTimer);
449
+ this._urlTimer = setTimeout(() => {
450
+ if (this.destroyed) return;
451
+ const next = writeUrlState(location.href, keys, this.filter, this.sortBy, this._sorts?.[0] || 'default');
452
+ if (next !== location.href) history.replaceState(history.state, '', next);
453
+ }, URL_DELAY);
454
+ }
455
+
456
+ /* ── Filtering, sorting, paging ───────────────────────────────────── */
457
+
458
+ /** The sounds that pass the filter, in the current sort order. */
459
+ get visible() {
460
+ return sortSounds(this.sounds.filter((s) => matches(s, this.filter)), this.sortBy);
461
+ }
462
+
463
+ /**
464
+ * Change the filter (merged into the current one) and re-apply. Back to
465
+ * the first page.
466
+ *
467
+ * @param {Partial<import('../../../index').SoundsFilter>} patch
468
+ */
469
+ setFilter(patch = {}) {
470
+ this.filter = {...this.filter, ...patch};
471
+ this.limit = this._pageSize();
472
+ this._syncControls();
473
+ this._apply({resort: false});
474
+ }
475
+
476
+ /** Reset every filter (the sort stays). */
477
+ clearFilters() {
478
+ this.setFilter(NO_FILTER);
479
+ }
480
+
481
+ /** @param {import('../../../index').SoundsSort} by */
482
+ setSort(by) {
483
+ this._sortSet = true;
484
+ this.sortBy = SORTS.includes(by) ? by : 'default';
485
+ this.menus?.setValue('sort', this.sortBy);
486
+ this._apply({resort: true});
487
+ }
488
+
489
+ /** Reveal the next page of results. */
490
+ showMore() {
491
+ if (this.limit === Infinity) return;
492
+ this.limit += this.render.pageSize;
493
+ this._apply({resort: false});
494
+ }
495
+
496
+ /**
497
+ * Rows per page (Infinity when paging is off).
498
+ * @private
499
+ */
500
+ _pageSize() {
501
+ return this.render.pageSize > 0 ? this.render.pageSize : Infinity;
502
+ }
503
+
504
+ /**
505
+ * Show the current filter and sort in the controls (they can be set from
506
+ * code or the address, not only by the controls themselves).
507
+ * @private
508
+ */
509
+ _syncControls() {
510
+ const $ = this.$, f = this.filter;
511
+ if (!$) return;
512
+ if ($.search && $.search.value !== f.query) $.search.value = f.query;
513
+ this.menus?.setValue('type', f.type || '');
514
+ this.menus?.setValue('key', f.key || '');
515
+ this.menus?.setValue('sort', this.sortBy);
516
+ if ($.bpmMin && $.bpmMin.value !== String(f.bpmMin)) $.bpmMin.value = f.bpmMin;
517
+ if ($.bpmMax && $.bpmMax.value !== String(f.bpmMax)) $.bpmMax.value = f.bpmMax;
518
+ $.chips.forEach((c) => c.setAttribute('aria-pressed', String(c.dataset.wsType === (f.type || ''))));
519
+ }
520
+
521
+ /**
522
+ * Lay the rows out for the current filter, sort and page: order, hide,
523
+ * "Show more", the empty state and the count. Then report it.
524
+ *
525
+ * @param {{resort: boolean}} opts - Reorder the rows even if the sort
526
+ * hasn't changed.
527
+ * @private
528
+ */
529
+ _apply({resort}) {
530
+ const $ = this.$;
531
+ if (!$) return;
532
+ if (resort || this.sortBy !== this._lastSort) {
533
+ orderRows($.list, sortSounds(this.sounds, this.sortBy).map((s) => this.rows[this.sounds.indexOf(s)]));
534
+ this._lastSort = this.sortBy;
535
+ }
536
+ const shown = this.visible;
537
+ const {visible, remaining} = pageWindow(shown, this.limit);
538
+ this.sounds.forEach((s, i) => { if (this.rows[i]) this.rows[i].hidden = !visible.has(s); });
539
+ if ($.more) {
540
+ $.more.hidden = remaining <= 0;
541
+ $.more.textContent = fill(this.strings.showMore, {count: Math.min(remaining, this.render.pageSize || remaining)});
542
+ }
543
+ if ($.empty) $.empty.hidden = shown.length > 0;
544
+ if ($.count) $.count.textContent = countText(shown.length, this.sounds.length, this.strings);
545
+ this._queueUrl();
546
+ this._emit('filter', {visible: shown.length, total: this.sounds.length, filter: {...this.filter}, sort: this.sortBy});
547
+ this.options.onFilter?.(shown, this);
548
+ }
549
+
550
+ /* ── Playback ─────────────────────────────────────────────────────── */
551
+
552
+ /**
553
+ * Resolve an index, id or sound to an index in `this.sounds`. No
554
+ * target means the current sound, else the first visible one.
555
+ *
556
+ * @param {number|string|Object} [target]
557
+ * @returns {number|null}
558
+ * @private
559
+ */
560
+ _indexOf(target) {
561
+ if (target == null) return this.currentIndex ?? (this.visible[0] ? this.sounds.indexOf(this.visible[0]) : null);
562
+ if (typeof target === 'number') return this.sounds[target] ? target : null;
563
+ const i = typeof target === 'object' ? this.sounds.indexOf(target) : this.sounds.findIndex((s) => s.id === String(target));
564
+ return i >= 0 ? i : null;
565
+ }
566
+
567
+ /**
568
+ * The WaveformPlayer class: `playerClass`, else the page's global.
569
+ * @returns {Function|null}
570
+ * @private
571
+ */
572
+ _playerClass() {
573
+ return this.options.playerClass || (typeof window !== 'undefined' ? window.WaveformPlayer : null) || null;
574
+ }
575
+
576
+ /**
577
+ * Build the engine once (it holds no audio until a play).
578
+ * @returns {Object|null} The engine, or null without a player class.
579
+ * @private
580
+ */
581
+ _ensureEngine() {
582
+ if (this.engine) return this.engine;
583
+ const Player = this._playerClass();
584
+ if (!Player) {
585
+ console.error(`${LOG} @arraypress/waveform-player is required: load it before playing (or pass playerClass).`);
586
+ return null;
587
+ }
588
+ this.engine = new Player(this.$.engine, engineOptions(this.options.playerOptions, this.render.player, {
589
+ onLoad: () => this._onEngineLoad(),
590
+ onPlay: () => this._setPlaying(true),
591
+ onPause: () => this._setPlaying(false),
592
+ onEnd: () => this._onEnd(),
593
+ onTimeUpdate: (time, duration) => this._onTime(time, duration),
594
+ onError: (err) => this._onEngineError(err),
595
+ }));
596
+ return this.engine;
597
+ }
598
+
599
+ /**
600
+ * Play a sound (by index, id or sound object), or resume the current
601
+ * one. Before the list is built the call waits for it.
602
+ *
603
+ * @param {number|string|Object} [target]
604
+ * @param {{at?: number}} [opts] - `at`: start position 0..1.
605
+ */
606
+ play(target, opts = {}) {
607
+ if (!this.$) { this.ready.then(() => { if (!this.destroyed) this.play(target, opts); }); return; }
608
+ const index = this._indexOf(target);
609
+ if (index == null) return;
610
+ const engine = this._ensureEngine();
611
+ if (!engine) return;
612
+ if (index === this.currentIndex && engine.audio?.src) {
613
+ if (opts.at != null) this._seekRow(index, opts.at);
614
+ if (!this.playing) engine.play();
615
+ return;
616
+ }
617
+ const previous = this.currentIndex;
618
+ this.currentIndex = index;
619
+ this.progress = 0;
620
+ this._pendingSeek = opts.at ?? null;
621
+ if (previous != null) this._paintRow(previous);
622
+ this._paintRow(index);
623
+ const sound = this.sounds[index];
624
+ engine.loadTrack(sound.url, sound.title, sound.type || null, {waveform: enginePeaks(sound, this.render.player), autoplay: true});
625
+ }
626
+
627
+ /** Pause the current sound. */
628
+ pause() {
629
+ if (this.engine && this.playing) this.engine.pause();
630
+ }
631
+
632
+ /**
633
+ * The current sound plays/pauses; another sound starts.
634
+ * @param {number|string|Object} [target]
635
+ */
636
+ toggle(target) {
637
+ const index = this._indexOf(target);
638
+ if (index == null) return;
639
+ if (index === this.currentIndex && this.playing) this.pause();
640
+ else this.play(index);
641
+ }
642
+
643
+ /** Play the next visible sound (no wrap at the end). */
644
+ next() { this._step(1); }
645
+
646
+ /** Play the previous visible sound. */
647
+ previous() { this._step(-1); }
648
+
649
+ /**
650
+ * Play the visible sound `dir` places away, revealing it if it's past
651
+ * the current page.
652
+ *
653
+ * @param {1|-1} dir
654
+ * @returns {boolean} Whether there was one.
655
+ * @private
656
+ */
657
+ _step(dir) {
658
+ const shown = this.visible;
659
+ const at = this.currentIndex == null ? -1 : shown.indexOf(this.sounds[this.currentIndex]);
660
+ const target = shown[at + dir];
661
+ if (!target) return false;
662
+ const limit = limitToReveal(this.limit, at + dir);
663
+ if (limit !== this.limit) { this.limit = limit; this._apply({resort: false}); }
664
+ this.play(this.sounds.indexOf(target));
665
+ return true;
666
+ }
667
+
668
+ /**
669
+ * Loop the current sound (auditioning a loop is the common case).
670
+ * @param {boolean} on
671
+ */
672
+ setLoop(on) {
673
+ this.loop = !!on;
674
+ this._setLoop(this.loop);
675
+ }
676
+
677
+ /**
678
+ * Apply the loop state to the toggle and the engine.
679
+ * @private
680
+ */
681
+ _setLoop(on) {
682
+ this.$?.loop?.setAttribute('aria-pressed', String(on));
683
+ if (this.engine?.audio) this.engine.audio.loop = on;
684
+ }
685
+
686
+ /**
687
+ * Seek a row's sound to `fraction`; a row that isn't current starts
688
+ * there. Before the duration is known the seek waits for it.
689
+ * @private
690
+ */
691
+ _seekRow(index, fraction) {
692
+ if (index !== this.currentIndex || !this.engine) { this.play(index, {at: fraction}); return; }
693
+ const duration = this.engine.audio?.duration;
694
+ if (!Number.isFinite(duration) || duration <= 0) { this._pendingSeek = fraction; return; }
695
+ this.engine.seekTo(fraction * duration);
696
+ this.progress = fraction;
697
+ this._paintRow(index);
698
+ if (!this.playing) this.engine.play();
699
+ }
700
+
701
+ /**
702
+ * The engine loaded a sound: apply the loop, borrow decoded peaks for a
703
+ * row that had none, and land a pending seek.
704
+ * @private
705
+ */
706
+ _onEngineLoad() {
707
+ if (this.engine?.audio) this.engine.audio.loop = this.loop;
708
+ const sound = this.sounds[this.currentIndex];
709
+ if (sound && !sound.peaks && this.engine?.waveformData?.length) {
710
+ sound.peaks = resample(this.engine.waveformData, 96);
711
+ this._drawRow(this.currentIndex);
712
+ }
713
+ const duration = this.engine?.audio?.duration;
714
+ if (this._pendingSeek != null && Number.isFinite(duration) && duration > 0) {
715
+ this.engine.seekTo(this._pendingSeek * duration);
716
+ this.progress = this._pendingSeek;
717
+ this._pendingSeek = null;
718
+ }
719
+ }
720
+
721
+ /**
722
+ * Playback progress: repaint the current row, once per frame.
723
+ * @private
724
+ */
725
+ _onTime(time, duration) {
726
+ if (this.currentIndex == null || !duration) return;
727
+ if (this._pendingSeek != null) {
728
+ const fraction = this._pendingSeek;
729
+ this._pendingSeek = null;
730
+ this.engine.seekTo(fraction * duration);
731
+ return;
732
+ }
733
+ this.progress = Math.min(Math.max(time / duration, 0), 1);
734
+ if (this._raf) return;
735
+ this._raf = requestAnimationFrame(() => {
736
+ this._raf = 0;
737
+ this._drawRow(this.currentIndex);
738
+ this.rows[this.currentIndex]?.querySelector('.ws-wave')?.setAttribute('aria-valuenow', String(Math.round(this.progress * 100)));
739
+ });
740
+ }
741
+
742
+ /**
743
+ * A sound finished: report it, then auto-advance or settle.
744
+ * @private
745
+ */
746
+ _onEnd() {
747
+ const sound = this.sounds[this.currentIndex];
748
+ this._emit('end', {sound, index: this.currentIndex});
749
+ this.options.onEnd?.(sound, this);
750
+ if (this.options.autoAdvance && this._step(1)) return;
751
+ this.progress = 0;
752
+ this._setPlaying(false);
753
+ }
754
+
755
+ /**
756
+ * A sound failed to load or play: mark its row and report it.
757
+ * @private
758
+ */
759
+ _onEngineError(err) {
760
+ this.rows[this.currentIndex]?.classList.add('is-error');
761
+ this._emit('error', {error: err, sound: this.sounds[this.currentIndex], index: this.currentIndex});
762
+ this.options.onError?.(err, this);
763
+ }
764
+
765
+ /**
766
+ * Record play/pause and repaint. Events fire only on a real change: at a
767
+ * natural end the browser fires `pause` then `ended`, and `_onEnd()`
768
+ * also settles the state — one pause event, not two.
769
+ * @private
770
+ */
771
+ _setPlaying(on) {
772
+ const changed = this.playing !== on;
773
+ this.playing = on;
774
+ const index = this.currentIndex;
775
+ if (index == null) return;
776
+ this._paintRow(index);
777
+ if (!changed) return;
778
+ const sound = this.sounds[index];
779
+ if (on && this.$.status) this.$.status.textContent = fill(this.strings.nowPlaying, {title: sound.title});
780
+ this._emit(on ? 'play' : 'pause', {sound, index});
781
+ (on ? this.options.onPlay : this.options.onPause)?.(sound, this);
782
+ }
783
+
784
+ /* ── Row painting ─────────────────────────────────────────────────── */
785
+
786
+ /**
787
+ * A row's state classes, play-button label and waveform.
788
+ * @private
789
+ */
790
+ _paintRow(index) {
791
+ const row = this.rows[index];
792
+ if (!row) return;
793
+ const current = index === this.currentIndex;
794
+ const on = current && this.playing;
795
+ row.classList.toggle('is-current', current);
796
+ row.classList.toggle('is-playing', on);
797
+ const btn = row.querySelector('.ws-play');
798
+ if (btn) {
799
+ btn.setAttribute('aria-pressed', String(on));
800
+ btn.setAttribute('aria-label', fill(on ? this.strings.pause : this.strings.play, {title: this.sounds[index].title}));
801
+ }
802
+ const wave = row.querySelector('.ws-wave');
803
+ if (wave) {
804
+ wave.tabIndex = current ? 0 : -1;
805
+ if (!current) wave.setAttribute('aria-valuenow', '0');
806
+ }
807
+ this._drawRow(index);
808
+ }
809
+
810
+ /* ── Events & lifecycle ──────────────────────────────────────────── */
811
+
812
+ /**
813
+ * Emit a `waveformsounds:<name>` event carrying this instance.
814
+ * @private
815
+ */
816
+ _emit(name, detail = {}) {
817
+ emit(this.container, name, {...detail, instance: this});
818
+ }
819
+
820
+ /** The sound playing (or paused) now, or null. */
821
+ get current() {
822
+ return this.currentIndex == null ? null : this.sounds[this.currentIndex];
823
+ }
824
+
825
+ /**
826
+ * Tear down: listeners, observers, timers and the engine. Markup this
827
+ * instance rendered is restored to what the container held before.
828
+ * ADOPTED (server-rendered) markup is left as it is now — rows may be
829
+ * re-sorted, hidden or marked current — so to start again, re-render it
830
+ * rather than constructing a new instance over it.
831
+ */
832
+ destroy() {
833
+ if (this.destroyed) return;
834
+ this.destroyed = true;
835
+ this._ctl.abort();
836
+ this._io?.disconnect();
837
+ this._ro?.disconnect();
838
+ this._mo?.disconnect();
839
+ if (this._raf) cancelAnimationFrame(this._raf);
840
+ clearTimeout(this._urlTimer);
841
+ try { this.engine?.destroy(); } catch { /* engine already gone */ }
842
+ this.engine = null;
843
+ if (this._originalHTML != null) this.container.innerHTML = this._originalHTML;
844
+ if (this._addedClasses?.length) this.container.classList.remove(...this._addedClasses);
845
+ if (this._autoSurface) this.container.style.removeProperty('--ws-surface');
846
+ delete this.container.dataset.wsInitialized;
847
+ WaveformSounds.instances.delete(this.container);
848
+ }
849
+
850
+ /**
851
+ * Initialise every `[data-waveform-sounds]` under `root` that isn't yet.
852
+ *
853
+ * @param {ParentNode} [root=document]
854
+ * @returns {WaveformSounds[]} The new instances.
855
+ */
856
+ static init(root = document) {
857
+ if (typeof document === 'undefined') return [];
858
+ const scope = root || document;
859
+ const els = [...(scope.matches?.('[data-waveform-sounds]') ? [scope] : []), ...scope.querySelectorAll('[data-waveform-sounds]')];
860
+ const created = [];
861
+ for (const el of els) {
862
+ if (el.dataset.wsInitialized === 'true' || WaveformSounds.instances.has(el)) continue;
863
+ try { created.push(new WaveformSounds(el)); } catch (err) { console.error(`${LOG} Failed to initialise:`, err, el); }
864
+ }
865
+ return created;
866
+ }
867
+
868
+ /**
869
+ * The instance on an element (or selector), if any.
870
+ * @param {Element|string} el
871
+ * @returns {WaveformSounds|null}
872
+ */
873
+ static getInstance(el) {
874
+ const node = typeof el === 'string' ? document.querySelector(el) : el;
875
+ return node ? WaveformSounds.instances.get(node) || null : null;
876
+ }
877
+
878
+ /** Destroy instances whose element has left the document (after a
879
+ * client-side navigation). */
880
+ static prune() {
881
+ for (const [el, inst] of WaveformSounds.instances) if (!el.isConnected) inst.destroy();
882
+ }
883
+ }