@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
@@ -0,0 +1,1366 @@
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, formatClock, formatDuration, matches, normalizeSounds, parseManifest, sortSounds, SORTS} from '../data/sounds.js';
30
+ import {drawRowWaveform, resample} from '../dom/draw.js';
31
+ import {engineOptions, engineTrack} from './engine.js';
32
+ import {Menus} from '../dom/menus.js';
33
+ import {limitToReveal, pageWindow, rowTarget, seekTarget, sliderEdgeTarget} from '../data/navigation.js';
34
+ import {DEFAULT_OPTIONS, mergeOptions, readDataOptions} from './options.js';
35
+ import {resolveRenderOptions} from '../render/options.js';
36
+ import {loopsByDefault, renderSounds} from '../render/markup.js';
37
+ import {indexRows, orderRows, readRows, visibleRows} from '../dom/rows.js';
38
+ import {bpmLabel, countText, DEFAULT_STRINGS, fill} from '../render/strings.js';
39
+ import {bpmExtent, bpmFilterFromRange, bpmFraction, bpmRangeFromFilter} from '../data/bpm.js';
40
+ import {ancestorsOf, forcedColors, pageSurface, resolveCssColor} from '../dom/colors.js';
41
+ import {readUrlState, urlKeys, writeUrlState} from '../data/url-state.js';
42
+ import {emit, isTyping, LOG, pointerFraction} from '../shared/utils.js';
43
+ import {h, text} from '../render/html.js';
44
+ import type {decodePeaks, encodePeaks, normalizeKey} from '../data/sounds.js';
45
+ import type {EngineTrack} from './engine.js';
46
+ import type {WaveformPlayer} from '@arraypress/waveform-player';
47
+ import type {RenderOptions} from '../render/options.js';
48
+ import type {Sound, SoundInput, SoundsFilter, SoundsLoopFilter, SoundsSort, WaveformSoundsInstanceEventMap, WaveformSoundsOptions, WaveformSoundsStrings} from '../types.js';
49
+
50
+ /** The engine `WaveformPlayer`, as far as the list uses it. */
51
+ interface Engine {
52
+ audio: HTMLAudioElement | null;
53
+ waveformData: number[];
54
+ play(): unknown;
55
+ pause(): unknown;
56
+ seekTo(seconds: number): unknown;
57
+ loadTrack(url: string, title: string, artist: string | null, options: EngineTrack): unknown;
58
+ destroy(): unknown;
59
+ }
60
+
61
+ /** The `WaveformPlayer` class (`playerClass`, or the page's global). */
62
+ type EngineClass = new (container: HTMLElement, options: Record<string, any>) => Engine;
63
+
64
+ /** The elements the runtime drives (`_cacheRefs`). */
65
+ interface Refs {
66
+ list: HTMLElement;
67
+ search: HTMLInputElement | null;
68
+ bpmMin: HTMLInputElement | null;
69
+ bpmMax: HTMLInputElement | null;
70
+ bpmRange: HTMLElement | null;
71
+ bpmReadout: HTMLElement | null;
72
+ bpmClear: HTMLElement | null;
73
+ bpmLabel: HTMLElement | null;
74
+ loop: HTMLElement | null;
75
+ count: HTMLElement | null;
76
+ empty: HTMLElement | null;
77
+ more: HTMLElement | null;
78
+ engine: HTMLElement | null;
79
+ status: HTMLElement | null;
80
+ chips: HTMLElement[];
81
+ loopFilter: HTMLElement[];
82
+ }
83
+
84
+ /** The public fields are readonly to callers; the class itself writes them
85
+ * through this (a cast: it emits nothing). */
86
+ type Writable<T> = {-readonly [K in keyof T]: T[K]};
87
+
88
+ export {DEFAULT_OPTIONS};
89
+
90
+ /** An empty filter: everything matches. */
91
+ const NO_FILTER: Readonly<SoundsFilter> = Object.freeze({query: '', type: '', key: '', bpmMin: '', bpmMax: '', loop: ''});
92
+
93
+ /** Debounce for typing in the search box and the BPM fields (ms). */
94
+ const SEARCH_DELAY = 120;
95
+ const BPM_DELAY = 200;
96
+
97
+ /** Debounce before the address is rewritten after a change (ms). */
98
+ const URL_DELAY = 250;
99
+
100
+ /**
101
+ * Typed listeners for the events a list dispatches on itself (see
102
+ * {@link WaveformSoundsInstanceEventMap}). Types only: merged into the class
103
+ * below, it emits nothing.
104
+ */
105
+ export interface WaveformSounds {
106
+ addEventListener<K extends keyof WaveformSoundsInstanceEventMap>(type: K, listener: (this: WaveformSounds, ev: WaveformSoundsInstanceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
107
+ addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void;
108
+ removeEventListener<K extends keyof WaveformSoundsInstanceEventMap>(type: K, listener: (this: WaveformSounds, ev: WaveformSoundsInstanceEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
109
+ removeEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions): void;
110
+ }
111
+
112
+ /**
113
+ * An `EventTarget`, like the core's player: each moment is dispatched on the
114
+ * instance as a plain event (`ready`, `play`, `pause`, `end`, `filter`,
115
+ * `error`), and on the container as a bubbling, composed
116
+ * `waveformsounds:<name>` CustomEvent carrying the details.
117
+ */
118
+ // biome-ignore lint/suspicious/noUnsafeDeclarationMerging: see the interface above
119
+ export class WaveformSounds extends EventTarget {
120
+ /** Every live instance, by its element. */
121
+ static instances: Map<Element, WaveformSounds> = new Map();
122
+ /** The pure helpers, for `<script>` users (attached in `entry.ts`). */
123
+ declare static utils: {
124
+ encodePeaks: typeof encodePeaks;
125
+ decodePeaks: typeof decodePeaks;
126
+ normalizeKey: typeof normalizeKey;
127
+ normalizeSounds: typeof normalizeSounds;
128
+ parseManifest: typeof parseManifest;
129
+ facets: typeof facets;
130
+ matches: typeof matches;
131
+ sortSounds: typeof sortSounds;
132
+ formatDuration: typeof formatDuration;
133
+ renderSounds: typeof renderSounds;
134
+ };
135
+ /** Register the `<waveform-sounds>` element (default tag name
136
+ * `waveform-sounds`). The default entry does this on import; this
137
+ * reaches it from a `<script>` page that opted out of auto-init.
138
+ * Attached in `entry.ts`. Since 2.1.0. */
139
+ declare static defineElement: (name?: string) => CustomElementConstructor | undefined;
140
+ /** Every option with its default (attached in `entry.ts`). */
141
+ declare static DEFAULT_OPTIONS: WaveformSoundsOptions;
142
+ /** The English UI strings (attached in `entry.ts`). */
143
+ declare static DEFAULT_STRINGS: WaveformSoundsStrings;
144
+
145
+ declare readonly container: HTMLElement;
146
+ declare readonly options: Required<WaveformSoundsOptions>;
147
+ /** Resolves once the list is built (after a manifest fetch, if any).
148
+ * The build always happens after the constructor returns, so listeners
149
+ * attached straight after `new WaveformSounds()` see `ready`. It never
150
+ * rejects: a failed build (e.g. the manifest 404s) resolves it too and
151
+ * is reported through `onError` / `waveformsounds:error`. Calls made
152
+ * before it resolves are honoured: `setFilter`/`setSort` show in the
153
+ * controls once built, and `play()` waits for the list. */
154
+ declare readonly ready: Promise<void>;
155
+ declare readonly sounds: Sound[];
156
+ declare readonly filter: SoundsFilter;
157
+ declare readonly sortBy: SoundsSort;
158
+ declare readonly playing: boolean;
159
+ /** The engine `WaveformPlayer`: built when the list is ready if the
160
+ * player is on the page (else on first play), null before and after. */
161
+ declare readonly engine: WaveformPlayer | null;
162
+
163
+ /** @internal */ declare strings: WaveformSoundsStrings;
164
+ /** @internal */ declare render: RenderOptions;
165
+ /** @internal */ declare rows: HTMLElement[];
166
+ /** @internal */ declare limit: number;
167
+ /** @internal */ declare currentIndex: number | null;
168
+ /** @internal */ declare progress: number;
169
+ /** @internal */ declare loop: boolean;
170
+ /** @internal */ declare menus: Menus | null;
171
+ /** @internal */ declare destroyed: boolean;
172
+ /** @internal Unset until the list is built; code that can run before checks it. */
173
+ declare $: Refs;
174
+ /** @internal */ declare colors: {wave: string, progress: string} | undefined;
175
+ /** @internal */ declare _ctl: AbortController;
176
+ /** @internal */ declare _originalHTML: string | null;
177
+ /** @internal Adopted server markup as it arrived (destroy({restore})). */ declare _adoptedHTML: string | undefined;
178
+ /** @internal */ declare _pendingSeek: number | null;
179
+ /** @internal */ declare _raf: number;
180
+ /** @internal */ declare _addedClasses: string[] | undefined;
181
+ /** @internal */ declare _loopSet: boolean | undefined;
182
+ /** @internal */ declare _sortSet: boolean | undefined;
183
+ /** @internal */ declare _bpmExtent: {min: number, max: number} | null;
184
+ /** @internal */ declare _sorts: string[];
185
+ /** @internal */ declare _lastSort: string | undefined;
186
+ /** @internal */ declare _lastPointer: string | undefined;
187
+ /** @internal Rows drawn at least once. */ declare _drawn: Set<number> | undefined;
188
+ /** @internal Drawn rows whose picture is stale (redrawn when they show). */ declare _dirty: Set<number> | undefined;
189
+ /** @internal Rows near the viewport (undefined without IntersectionObserver). */ declare _onScreen: Set<number> | undefined;
190
+ /** @internal */ declare _io: IntersectionObserver | undefined;
191
+ /** @internal */ declare _ro: ResizeObserver | undefined;
192
+ /** @internal */ declare _mo: MutationObserver | undefined;
193
+ /** @internal */ declare _autoSurface: boolean | undefined;
194
+ /** @internal */ declare _urlTimer: number | undefined;
195
+ /** @internal */ declare _cued: boolean | undefined;
196
+ /** @internal The sounds the last layout shows, in order (see `visible`). */ declare _shown: Sound[] | undefined;
197
+ /** @internal The engine's own `preload` (a cue uses 'none'). */ declare _preload: string | undefined;
198
+ /** @internal The row holding the list's one Tab stop. */ declare _active: HTMLElement | null;
199
+ /** @internal The sound last reported as playing (its pause not yet reported). */ declare _announced: number | null | undefined;
200
+
201
+ /**
202
+ * @param {HTMLElement|string} container - The element (or a selector).
203
+ * @param {WaveformSoundsOptions} [options]
204
+ */
205
+ constructor(container: HTMLElement | string, options: WaveformSoundsOptions = {}) {
206
+ super();
207
+ const el = typeof container === 'string' ? document.querySelector<HTMLElement>(container) : container;
208
+ if (!el) throw new Error(`${LOG} Container not found: ${container}`);
209
+ this.container = el;
210
+ // Precedence, as across the family: data-* > constructor > default.
211
+ // A <waveform-sounds> element reads its plain attributes too.
212
+ const data = (el as {_wsOptions?: () => Record<string, any>})._wsOptions?.() ?? readDataOptions(el);
213
+ this.options = mergeOptions(DEFAULT_OPTIONS, options, data) as Required<WaveformSoundsOptions>;
214
+ this.options.waveformStyle = this.options.waveformStyle === 'bars' ? 'bars' : 'mirror';
215
+ this.strings = {...DEFAULT_STRINGS, ...(this.options.strings || {})};
216
+ this.render = {...resolveRenderOptions(this.options), strings: this.strings};
217
+
218
+ this.sounds = [];
219
+ this.rows = [];
220
+ this.filter = {...NO_FILTER};
221
+ this.sortBy = 'default';
222
+ this.limit = this._pageSize();
223
+ this.currentIndex = null;
224
+ this.playing = false;
225
+ this.progress = 0;
226
+ this.loop = !!this.options.loop;
227
+ this.engine = null;
228
+ this.menus = null;
229
+ this.destroyed = false;
230
+ this._ctl = new AbortController();
231
+ this._originalHTML = null;
232
+ this._pendingSeek = null;
233
+ this._raf = 0;
234
+
235
+ WaveformSounds.instances.set(el, this);
236
+ el.dataset.wsInitialized = 'true';
237
+ // Build on a later microtask, never inside the constructor: ready /
238
+ // filter events (and onReady) must reach listeners attached right
239
+ // after `new WaveformSounds()`, and `this.ready` must already exist
240
+ // when they fire. It never rejects: a failed build is reported
241
+ // through onError / `waveformsounds:error`.
242
+ /** Resolves once the list is built (after a manifest fetch, if any). */
243
+ this.ready = Promise.resolve().then(() => this._init()).catch((err) => {
244
+ if (this.destroyed) return; // e.g. the manifest fetch, aborted by destroy()
245
+ console.error(`${LOG} Failed to initialise:`, err);
246
+ this._showLoadError();
247
+ this._emit('error', {error: err});
248
+ this.options.onError?.(err, this);
249
+ });
250
+ }
251
+
252
+ /* ── Setup ─────────────────────────────────────────────────────────── */
253
+
254
+ /**
255
+ * Adopt server-rendered markup or render it (from `sounds` or a fetched
256
+ * manifest), then wire everything up.
257
+ * @internal
258
+ */
259
+ async _init(): Promise<void> {
260
+ const el = this.container;
261
+ const adopted = el.querySelector<HTMLElement>('[data-ws-list]');
262
+ if (adopted) {
263
+ // As the server sent it, for destroy({restore: true}).
264
+ this._adoptedHTML = el.innerHTML;
265
+ (this as Writable<WaveformSounds>).sounds = readRows(adopted);
266
+ } else {
267
+ this._originalHTML = el.innerHTML;
268
+ (this as Writable<WaveformSounds>).sounds = await this._loadSounds();
269
+ if (this.destroyed) return;
270
+ el.innerHTML = renderSounds(this.sounds as SoundInput[], {...this.render, idPrefix: this.options.idPrefix || el.id || undefined});
271
+ }
272
+ if (this.destroyed) return;
273
+
274
+ // Remember which classes WE add, so destroy() takes back exactly
275
+ // those (server-rendered markup already carries them).
276
+ this._addedClasses = ['waveform-sounds', `waveform-sounds--${this.render.player}`].filter((c) => !el.classList.contains(c));
277
+ el.classList.add(...this._addedClasses);
278
+
279
+ this._cacheRefs();
280
+ this._bind();
281
+ this._observe();
282
+ this._resolveColors();
283
+ // Unless set (option or an early setLoop()), Loop starts on exactly
284
+ // when the list marks loops — only those repeat.
285
+ if (!this._loopSet) this.loop = loopsByDefault(this.options.loop, facets(this.sounds));
286
+ this._setLoop(this.loop);
287
+ this._bpmExtent = bpmExtent(facets(this.sounds).bpm);
288
+
289
+ // The starting order is the first one offered, unless setSort()
290
+ // already chose one; then the address may override both.
291
+ this._sorts = availableSorts(this.render.sorts, facets(this.sounds));
292
+ if (!this._sortSet) (this as Writable<WaveformSounds>).sortBy = (this._sorts[0] || 'default') as SoundsSort;
293
+ this._readUrl();
294
+ // Show any filter/sort set before now (from code or the address).
295
+ this._syncControls();
296
+ this._apply({resort: this.sortBy !== 'default'});
297
+
298
+ // Build the engine now (no audio loads until a play) when the
299
+ // player is on the page, so anything that hooks players on their
300
+ // `waveformplayer:ready` (waveform-tracker, analytics) is attached
301
+ // BEFORE the first play — built on first play, that sound went
302
+ // untracked.
303
+ if (this._playerClass()) this._ensureEngine();
304
+ // Strip: the docked player starts with the first sound cued — its
305
+ // title and waveform, ready to play — rather than an empty frame.
306
+ if (this.render.player === 'strip' && this.engine && this.currentIndex == null) this._cueFirst();
307
+
308
+ this._emit('ready', {sounds: this.sounds.length});
309
+ this.options.onReady?.(this);
310
+ }
311
+
312
+ /**
313
+ * The sounds from the `sounds` option, else the `manifest` URL.
314
+ * @internal
315
+ */
316
+ async _loadSounds(): Promise<Sound[]> {
317
+ if (this.options.sounds || !this.options.manifest) return normalizeSounds(this.options.sounds || []);
318
+ const url = this.options.manifest;
319
+ // destroy() aborts it: a list torn down mid-fetch never builds.
320
+ const res = await fetch(url, {signal: this._ctl.signal});
321
+ if (!res.ok) throw new Error(`${LOG} Manifest ${url}: HTTP ${res.status}`);
322
+ const manifest = await res.json();
323
+ // Not a list of sounds at all is a broken manifest, not an empty pack.
324
+ if (!Array.isArray(manifest) && !Array.isArray(manifest?.sounds)) throw new Error(`${LOG} Manifest ${url}: no "sounds" list`);
325
+ return parseManifest(manifest);
326
+ }
327
+
328
+ /**
329
+ * A build that failed (the manifest 404s, isn't JSON, isn't a manifest)
330
+ * says so where the list would be — unless the container holds the
331
+ * site's own fallback, which stays. destroy() restores what was there.
332
+ * @internal
333
+ */
334
+ _showLoadError(): void {
335
+ const el = this.container;
336
+ if (this.$ || el.querySelector('*')) return;
337
+ this._originalHTML ??= el.innerHTML;
338
+ el.innerHTML = h('p', {class: 'ws-empty ws-load-error', role: 'alert', 'data-ws-load-error': true}, text(this.strings.loadError));
339
+ }
340
+
341
+ /**
342
+ * Look up the elements the runtime drives.
343
+ * @internal
344
+ */
345
+ _cacheRefs() {
346
+ const q = <T extends HTMLElement = HTMLElement>(sel: string) => this.container.querySelector<T>(sel);
347
+ this.$ = {
348
+ list: q('[data-ws-list]')!,
349
+ search: q<HTMLInputElement>('[data-ws-search]'),
350
+ bpmMin: q<HTMLInputElement>('[data-ws-bpm-min]'),
351
+ bpmMax: q<HTMLInputElement>('[data-ws-bpm-max]'),
352
+ bpmRange: q('[data-ws-bpm-range]'),
353
+ bpmReadout: q('[data-ws-bpm-readout]'),
354
+ bpmClear: q('[data-ws-bpm-clear]'),
355
+ bpmLabel: q('[data-ws-menu="bpm"] [data-ws-menu-value]'),
356
+ loop: q('[data-ws-loop]'),
357
+ count: q('[data-ws-count]'),
358
+ empty: q('[data-ws-empty]'),
359
+ more: q('[data-ws-more]'),
360
+ engine: q('[data-ws-engine]'),
361
+ status: q('[data-ws-status]'),
362
+ chips: [...this.container.querySelectorAll<HTMLElement>('[data-ws-type]')],
363
+ loopFilter: [...this.container.querySelectorAll<HTMLElement>('[data-ws-loop-filter]')],
364
+ };
365
+ this.rows = indexRows(this.$.list);
366
+ // Roving tabindex: the list is ONE Tab stop (the active row's
367
+ // controls); ↑/↓ move between rows. Set here, not in the markup, so
368
+ // server-rendered HTML from any version gets it.
369
+ this._active = null;
370
+ for (const row of this.rows) if (row) this._rowStops(row, false);
371
+ }
372
+
373
+ /**
374
+ * Make a row's own controls (play, download, and the seek slider when it
375
+ * is the current sound) Tab stops, or not.
376
+ * @internal
377
+ */
378
+ _rowStops(row: HTMLElement, on: boolean): void {
379
+ const play = row.querySelector<HTMLElement>('.ws-play');
380
+ if (play) play.tabIndex = on ? 0 : -1;
381
+ const dl = row.querySelector<HTMLElement>('.ws-download');
382
+ if (dl) dl.tabIndex = on ? 0 : -1;
383
+ const wave = row.querySelector<HTMLElement>('.ws-wave');
384
+ if (wave) wave.tabIndex = on && Number(row.dataset.wsIndex) === this.currentIndex ? 0 : -1;
385
+ }
386
+
387
+ /**
388
+ * Move the list's Tab stop to `row` (roving tabindex).
389
+ * @internal
390
+ */
391
+ _rove(row: HTMLElement | null | undefined): void {
392
+ if (!row || row === this._active) return;
393
+ if (this._active) this._rowStops(this._active, false);
394
+ this._active = row;
395
+ this._rowStops(row, true);
396
+ }
397
+
398
+ /**
399
+ * Every listener. All are removed by `destroy()` through one
400
+ * AbortController.
401
+ * @internal
402
+ */
403
+ _bind() {
404
+ const sig = {signal: this._ctl.signal};
405
+ const $ = this.$;
406
+ const root = this.container;
407
+
408
+ root.addEventListener('click', (e) => this._onClick(e), sig);
409
+ root.addEventListener('pointerdown', (e) => this._onPointerDown(e), sig);
410
+ root.addEventListener('keydown', (e) => this._onKey(e), sig);
411
+ // Whatever row gets focus (arrows, a click, a script) holds the Tab stop.
412
+ $.list.addEventListener('focusin', (e) => this._rove((e.target as Element).closest<HTMLElement>('[data-ws-index]')), sig);
413
+
414
+ let searchTimer = 0, bpmTimer = 0;
415
+ $.search?.addEventListener('input', () => {
416
+ clearTimeout(searchTimer);
417
+ searchTimer = setTimeout(() => this.setFilter({query: $.search!.value}), SEARCH_DELAY);
418
+ }, sig);
419
+ $.search?.addEventListener('keydown', (e) => {
420
+ if (e.key === 'ArrowDown') { e.preventDefault(); this._focusRow(visibleRows($.list)[0]); }
421
+ if (e.key === 'Escape' && $.search!.value) { e.preventDefault(); $.search!.value = ''; this.setFilter({query: ''}); }
422
+ }, sig);
423
+ // The BPM handles: the label and the track follow the drag at once;
424
+ // the list re-filters once it settles. A handle can't pass the other.
425
+ const onBpm = (moved: HTMLInputElement) => {
426
+ const lo = Number($.bpmMin!.value), hi = Number($.bpmMax!.value);
427
+ if (lo > hi) moved.value = String(moved === $.bpmMin ? hi : lo);
428
+ const f = bpmFilterFromRange(Number($.bpmMin!.value), Number($.bpmMax!.value), this._bpmExtent!);
429
+ this._showBpm(f);
430
+ clearTimeout(bpmTimer);
431
+ bpmTimer = setTimeout(() => this.setFilter(f), BPM_DELAY);
432
+ };
433
+ $.bpmMin?.addEventListener('input', () => onBpm($.bpmMin!), sig);
434
+ $.bpmMax?.addEventListener('input', () => onBpm($.bpmMax!), sig);
435
+ $.bpmClear?.addEventListener('click', () => {
436
+ clearTimeout(bpmTimer);
437
+ this.setFilter({bpmMin: '', bpmMax: ''});
438
+ }, sig);
439
+
440
+ this.menus = new Menus(root, {
441
+ signal: this._ctl.signal,
442
+ onPick: (name, value) => (name === 'sort' ? this.setSort(value as SoundsSort) : this.setFilter({[name]: value})),
443
+ });
444
+
445
+ // Any OTHER player starting pauses the list (every WaveformPlayer's
446
+ // play event bubbles to the document). The engine's singlePlay only
447
+ // reaches players that also use singlePlay — a WaveformBar's player
448
+ // doesn't, so without this the bar and the list could play at once.
449
+ document.addEventListener('waveformplayer:play', (e: Event) => {
450
+ const player = (e as CustomEvent).detail?.player;
451
+ if (player && player !== this.engine && this.playing) this.pause();
452
+ }, sig);
453
+ }
454
+
455
+ /* ── Input ────────────────────────────────────────────────────────── */
456
+
457
+ /**
458
+ * Clicks: type chips, loops or one-shots, Show more, Clear, Loop, a touch tap on a waveform
459
+ * (seek), and anywhere else on a row (play/pause).
460
+ * @internal
461
+ */
462
+ _onClick(e: MouseEvent): void {
463
+ const t = e.target as Element;
464
+ const chip = t.closest<HTMLElement>('[data-ws-type]');
465
+ if (chip) { this.setFilter({type: chip.dataset.wsType}); return; }
466
+ const seg = t.closest<HTMLElement>('[data-ws-loop-filter]');
467
+ if (seg) { this.setFilter({loop: seg.dataset.wsLoopFilter as SoundsLoopFilter}); return; }
468
+ if (t.closest('[data-ws-more]')) { this._showMoreFromButton(); return; }
469
+ if (t.closest('[data-ws-clear]')) {
470
+ // The button disappears with the empty state: focus goes back
471
+ // to the search (else the first row), never to <body>.
472
+ this.clearFilters();
473
+ if (this.$.search) this.$.search.focus();
474
+ else this._focusRow(visibleRows(this.$.list)[0]);
475
+ return;
476
+ }
477
+ if (t.closest('[data-ws-loop]')) { this.setLoop(!this.loop); return; }
478
+ const wave = t.closest<HTMLElement>('.ws-wave');
479
+ if (wave) {
480
+ // Touch seeks on the TAP (this click): its press may have been
481
+ // the start of a scroll.
482
+ if (this._lastPointer === 'touch') this._seekAt(wave, e.clientX);
483
+ return;
484
+ }
485
+ const row = t.closest<HTMLElement>('[data-ws-index]');
486
+ if (!row || t.closest('.ws-download')) return;
487
+ this.toggle(Number(row.dataset.wsIndex));
488
+ this._focusRowQuietly(row);
489
+ }
490
+
491
+ /**
492
+ * "Show more", pressed: reveal the next page. When that was the last page
493
+ * the button hides, so focus moves to the first row it revealed rather
494
+ * than falling to <body>.
495
+ * @internal
496
+ */
497
+ _showMoreFromButton(): void {
498
+ const before = new Set(visibleRows(this.$.list));
499
+ this.showMore();
500
+ if (this.$.more?.hidden) this._focusRow(visibleRows(this.$.list).find((r) => !before.has(r)));
501
+ }
502
+
503
+ /**
504
+ * Mouse and pen seek on PRESS, like every scrubber. Remembers the
505
+ * pointer type for the click that follows.
506
+ * @internal
507
+ */
508
+ _onPointerDown(e: PointerEvent): void {
509
+ this._lastPointer = e.pointerType;
510
+ const wave = (e.target as Element).closest<HTMLElement>('.ws-wave');
511
+ if (!wave || e.button !== 0 || e.pointerType === 'touch') return;
512
+ e.preventDefault();
513
+ this._seekAt(wave, e.clientX);
514
+ }
515
+
516
+ /**
517
+ * Seek (or start) a row's sound where its waveform was pressed.
518
+ * @internal
519
+ */
520
+ _seekAt(wave: HTMLElement, clientX: number): void {
521
+ const row = wave.closest<HTMLElement>('[data-ws-index]')!;
522
+ this._seekRow(Number(row.dataset.wsIndex), pointerFraction(clientX, wave.getBoundingClientRect()));
523
+ this._focusRowQuietly(row);
524
+ }
525
+
526
+ /**
527
+ * Keys on the list: `/` focuses search; ↑/↓/Home/End move between rows
528
+ * (auditioning while something plays); ←/→ seek the playing row, and on
529
+ * its seek slider Home/End seek to the start/end.
530
+ * @internal
531
+ */
532
+ _onKey(e: KeyboardEvent): void {
533
+ if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey) return;
534
+ if (e.key === '/' && !isTyping(e.target as Element | null) && this.$.search) {
535
+ e.preventDefault();
536
+ this.$.search.focus();
537
+ return;
538
+ }
539
+ const row = (e.target as Element).closest?.<HTMLElement>('[data-ws-index]');
540
+ if (!row) return;
541
+
542
+ const index = Number(row.dataset.wsIndex);
543
+ // On the seek slider, Home / End seek (the slider pattern) rather
544
+ // than jump to the first / last row.
545
+ const edge = (e.target as Element).closest('.ws-wave') ? sliderEdgeTarget(e.key) : null;
546
+ const seek = edge ?? seekTarget(this.progress, e.key);
547
+ if (seek !== null) {
548
+ if (index !== this.currentIndex || !this.engine) return;
549
+ e.preventDefault();
550
+ this._seekRow(index, seek);
551
+ return;
552
+ }
553
+
554
+ const rows = visibleRows(this.$.list);
555
+ const target = rowTarget(e.key, rows.indexOf(row), rows.length);
556
+ if (target === null) return;
557
+ e.preventDefault();
558
+ if (target === 'search') { this.$.search?.focus(); return; }
559
+ this._focusRow(rows[target]);
560
+ if (this.options.arrowAudition && this.playing) this.play(Number(rows[target].dataset.wsIndex));
561
+ }
562
+
563
+ /**
564
+ * Focus a row's play button.
565
+ * @internal
566
+ */
567
+ _focusRow(row: HTMLElement | null | undefined): void {
568
+ row?.querySelector<HTMLElement>('.ws-play')?.focus();
569
+ }
570
+
571
+ /**
572
+ * After a mouse or touch play, put focus on that row's play button so
573
+ * the arrow keys drive the list instead of scrolling the page (a click
574
+ * on the title or waveform left focus on <body>, and Safari never
575
+ * focuses a clicked button). No scroll jump, and no focus ring: the
576
+ * browser shows none for a focus that follows a pointer.
577
+ * @internal
578
+ */
579
+ _focusRowQuietly(row: HTMLElement | null | undefined): void {
580
+ const btn = row?.querySelector<HTMLElement>('.ws-play');
581
+ if (btn && document.activeElement !== btn) btn.focus({preventScroll: true});
582
+ }
583
+
584
+ /* ── Drawing & colours ────────────────────────────────────────────── */
585
+
586
+ /**
587
+ * Draw row canvases as they scroll into view; redraw on resize and on
588
+ * theme flips (the canvas can't follow CSS by itself).
589
+ * @internal
590
+ */
591
+ _observe(): void {
592
+ if (this.render.player !== 'inline' || typeof window === 'undefined') return;
593
+ this._drawn = new Set();
594
+ this._dirty = new Set();
595
+ if ('IntersectionObserver' in window) {
596
+ // Rows near the viewport. A row is drawn the first time it comes
597
+ // near, and again only if it went stale (a resize or a theme flip
598
+ // while it was away): a long list scrolled back and forth
599
+ // repaints nothing it doesn't have to.
600
+ this._onScreen = new Set();
601
+ this._io = new IntersectionObserver((entries) => {
602
+ for (const entry of entries) {
603
+ const i = Number((entry.target as HTMLElement).dataset.wsIndex);
604
+ if (!entry.isIntersecting) { this._onScreen!.delete(i); continue; }
605
+ this._onScreen!.add(i);
606
+ if (this._drawn!.has(i) && !this._dirty!.has(i)) continue;
607
+ this._drawn!.add(i);
608
+ this._drawRow(i);
609
+ }
610
+ }, {rootMargin: '200px 0px'});
611
+ this.rows.forEach((r) => r && this._io!.observe(r));
612
+ } else {
613
+ this.rows.forEach((r, i) => r && this._drawn!.add(i));
614
+ }
615
+ if ('ResizeObserver' in window) {
616
+ let width = 0;
617
+ this._ro = new ResizeObserver(([entry]) => {
618
+ const w = Math.round(entry.contentRect.width);
619
+ if (w === width) return;
620
+ width = w;
621
+ this._redrawAll();
622
+ });
623
+ this._ro.observe(this.$.list);
624
+ }
625
+ let queued = 0;
626
+ const refresh = () => {
627
+ if (queued) return;
628
+ // A style change on an ancestor can be anything (an animation,
629
+ // a layout tweak): redraw only if the canvas colours moved.
630
+ queued = requestAnimationFrame(() => { queued = 0; if (this._resolveColors()) this._redrawAll(); });
631
+ };
632
+ // A theme can flip on ANY ancestor (a dark section, a themed card,
633
+ // a framework's root div), not just <html> / <body>. The container
634
+ // itself counts for class and theme, not style: the runtime writes
635
+ // --ws-surface there.
636
+ this._mo = new MutationObserver(refresh);
637
+ this._mo.observe(this.container, {attributes: true, attributeFilter: ['class', 'data-theme', 'data-color-scheme']});
638
+ for (const node of ancestorsOf(this.container)) {
639
+ this._mo.observe(node, {attributes: true, attributeFilter: ['class', 'data-theme', 'data-color-scheme', 'style']});
640
+ }
641
+ for (const query of ['(prefers-color-scheme: dark)', '(forced-colors: active)']) {
642
+ try {
643
+ window.matchMedia(query).addEventListener('change', refresh, {signal: this._ctl.signal});
644
+ } catch { /* no matchMedia */ }
645
+ }
646
+ }
647
+
648
+ /**
649
+ * Resolve the canvas colours (options, else the CSS custom properties;
650
+ * system colours under forced colours) and keep `--ws-surface` current
651
+ * unless the site set it.
652
+ * @returns Whether the canvas colours changed.
653
+ * @internal
654
+ */
655
+ _resolveColors(): boolean {
656
+ const before = this.colors;
657
+ if (this._autoSurface || !getComputedStyle(this.container).getPropertyValue('--ws-surface').trim()) {
658
+ this._autoSurface = true;
659
+ this.container.style.removeProperty('--ws-surface');
660
+ this.container.style.setProperty('--ws-surface', pageSurface(this.container));
661
+ }
662
+ // Forced colours: the system's own text and highlight, whatever the
663
+ // options or the CSS say (as every other part of the list does).
664
+ const forced = forcedColors();
665
+ this.colors = {
666
+ wave: (forced ? resolveCssColor(this.container, 'CanvasText') : this.options.waveformColor || resolveCssColor(this.container, 'var(--ws-wave-color)')) || 'rgba(128,128,128,.5)',
667
+ progress: (forced ? resolveCssColor(this.container, 'Highlight') : this.options.progressColor || resolveCssColor(this.container, 'var(--ws-progress-color)')) || 'currentColor',
668
+ };
669
+ return !before || before.wave !== this.colors.wave || before.progress !== this.colors.progress;
670
+ }
671
+
672
+ /**
673
+ * Draw one row's waveform (only once it has been on screen).
674
+ * @internal
675
+ */
676
+ _drawRow(index: number | null | undefined): void {
677
+ if (this.render.player !== 'inline' || index == null || !this._drawn?.has(index)) return;
678
+ const row = this.rows[index];
679
+ const canvas = row?.querySelector('canvas');
680
+ if (!canvas) return;
681
+ // Hidden (filtered, or past the page): draw it when it shows again.
682
+ if (row.hidden) { this._dirty?.add(index); return; }
683
+ this._dirty?.delete(index);
684
+ const gap = Number(this.options.barGap);
685
+ drawRowWaveform(canvas, this.sounds[index].peaks, index === this.currentIndex ? this.progress : 0, {
686
+ style: this.options.waveformStyle,
687
+ color: this.colors?.wave || 'rgba(128,128,128,.5)',
688
+ progressColor: this.colors?.progress || 'currentColor',
689
+ barWidth: Math.max(1, Number(this.options.barWidth) || 2),
690
+ barGap: Number.isFinite(gap) ? Math.max(0, gap) : 1,
691
+ });
692
+ }
693
+
694
+ /**
695
+ * After a resize or a theme flip: redraw the rows on screen now, and
696
+ * mark the rest stale — each is redrawn when it scrolls back in. (With
697
+ * 1000 rows drawn, redrawing them all took ~0.4s in Chrome and ~1.9s in
698
+ * WebKit per resize step.)
699
+ * @internal
700
+ */
701
+ _redrawAll(): void {
702
+ this._drawn?.forEach((i) => {
703
+ if (this._onScreen && !this._onScreen.has(i)) this._dirty!.add(i);
704
+ else this._drawRow(i);
705
+ });
706
+ }
707
+
708
+ /* ── Filters in the address ───────────────────────────────────────── */
709
+
710
+ /**
711
+ * Apply the filter and sort from the address (`urlState`).
712
+ * @internal
713
+ */
714
+ _readUrl(): void {
715
+ const keys = urlKeys(this.options.urlState);
716
+ if (!keys || typeof location === 'undefined') return;
717
+ const f = facets(this.sounds);
718
+ const {filter, sort} = readUrlState(location.search, keys, {...f, bpm: bpmExtent(f.bpm)}, this._sorts);
719
+ (this as Writable<WaveformSounds>).filter = {...this.filter, ...filter};
720
+ if (sort) { (this as Writable<WaveformSounds>).sortBy = sort as SoundsSort; this._sortSet = true; }
721
+ }
722
+
723
+ /**
724
+ * Rewrite the address shortly after a change (replaceState: no history
725
+ * entries).
726
+ * @internal
727
+ */
728
+ _queueUrl(): void {
729
+ const keys = urlKeys(this.options.urlState);
730
+ if (!keys || typeof location === 'undefined') return;
731
+ clearTimeout(this._urlTimer);
732
+ this._urlTimer = setTimeout(() => {
733
+ if (this.destroyed) return;
734
+ const next = writeUrlState(location.href, keys, this.filter, this.sortBy, this._sorts?.[0] || 'default');
735
+ if (next !== location.href) history.replaceState(history.state, '', next);
736
+ }, URL_DELAY);
737
+ }
738
+
739
+ /* ── Filtering, sorting, paging ───────────────────────────────────── */
740
+
741
+ /** The sounds that pass the filter, in the current sort order. */
742
+ get visible(): Sound[] {
743
+ // Laid out by the last _apply(), which runs on every filter or sort
744
+ // change; computed afresh only before the list is built.
745
+ return [...(this._shown ?? this._match())];
746
+ }
747
+
748
+ /**
749
+ * Filter and sort the sounds now.
750
+ * @internal
751
+ */
752
+ _match(): Sound[] {
753
+ return sortSounds(this.sounds.filter((s) => matches(s, this.filter)), this.sortBy);
754
+ }
755
+
756
+ /**
757
+ * Change the filter (merged into the current one) and re-apply. Back to
758
+ * the first page.
759
+ *
760
+ * @param patch
761
+ */
762
+ // The public signature (as in 0.3.1's index.d.ts: `patch` required); the
763
+ // implementation's default stays, and an overload signature emits nothing.
764
+ setFilter(patch: Partial<SoundsFilter>): void;
765
+ setFilter(patch: Partial<SoundsFilter> = {}): void {
766
+ (this as Writable<WaveformSounds>).filter = {...this.filter, ...patch};
767
+ this.limit = this._pageSize();
768
+ this._syncControls();
769
+ this._apply({resort: false});
770
+ }
771
+
772
+ /** Reset every filter (the sort stays). */
773
+ clearFilters(): void {
774
+ this.setFilter(NO_FILTER);
775
+ }
776
+
777
+ /** @param by */
778
+ setSort(by: SoundsSort): void {
779
+ this._sortSet = true;
780
+ (this as Writable<WaveformSounds>).sortBy = SORTS.includes(by) ? by : 'default';
781
+ this.menus?.setValue('sort', this.sortBy);
782
+ this._apply({resort: true});
783
+ }
784
+
785
+ /** Reveal the next page of results. */
786
+ showMore(): void {
787
+ if (this.limit === Infinity) return;
788
+ this.limit += this.render.pageSize;
789
+ this._apply({resort: false});
790
+ }
791
+
792
+ /**
793
+ * Rows per page (Infinity when paging is off).
794
+ * @internal
795
+ */
796
+ _pageSize(): number {
797
+ return this.render.pageSize > 0 ? this.render.pageSize : Infinity;
798
+ }
799
+
800
+ /**
801
+ * Show the current filter and sort in the controls (they can be set from
802
+ * code or the address, not only by the controls themselves).
803
+ * @internal
804
+ */
805
+ _syncControls(): void {
806
+ const $ = this.$, f = this.filter;
807
+ if (!$) return;
808
+ if ($.search && $.search.value !== f.query) $.search.value = f.query;
809
+ this.menus?.setValue('type', f.type || '');
810
+ this.menus?.setValue('key', f.key || '');
811
+ this.menus?.setValue('sort', this.sortBy);
812
+ if ($.bpmMin && $.bpmMax && this._bpmExtent) {
813
+ const {lo, hi} = bpmRangeFromFilter(f, this._bpmExtent);
814
+ $.bpmMin.value = String(lo);
815
+ $.bpmMax.value = String(hi);
816
+ this._showBpm(f);
817
+ }
818
+ $.chips.forEach((c) => c.setAttribute('aria-pressed', String(c.dataset.wsType === (f.type || ''))));
819
+ $.loopFilter.forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.wsLoopFilter === (f.loop || ''))));
820
+ }
821
+
822
+ /**
823
+ * Show a BPM filter in its menu: the button label, the panel's readout,
824
+ * the filled part of the track, and which handle sits on top (the one
825
+ * that can still move, when they meet).
826
+ * @internal
827
+ */
828
+ _showBpm(f: {bpmMin?: string | number, bpmMax?: string | number}): void {
829
+ const $ = this.$, extent = this._bpmExtent;
830
+ if (!$?.bpmRange || !extent) return;
831
+ const {lo, hi} = bpmRangeFromFilter(f, extent);
832
+ if ($.bpmLabel) $.bpmLabel.textContent = bpmLabel(f, extent, this.strings);
833
+ if ($.bpmReadout) $.bpmReadout.textContent = fill(this.strings.bpmRange, {min: lo, max: hi});
834
+ // CSSOM, not a style attribute: works under a strict CSP.
835
+ $.bpmRange.style.setProperty('--ws-lo', String(bpmFraction(lo, extent)));
836
+ $.bpmRange.style.setProperty('--ws-hi', String(bpmFraction(hi, extent)));
837
+ $.bpmRange.classList.toggle('is-min-top', lo >= hi && lo > extent.min);
838
+ $.bpmRange.classList.toggle('is-active', lo > extent.min || hi < extent.max);
839
+ }
840
+
841
+ /**
842
+ * Lay the rows out for the current filter, sort and page: order, hide,
843
+ * "Show more", the empty state and the count. Then report it.
844
+ *
845
+ * @param opts - Reorder the rows even if the sort
846
+ * hasn't changed.
847
+ * @internal
848
+ */
849
+ _apply({resort}: {resort: boolean}): void {
850
+ const $ = this.$;
851
+ if (!$) return;
852
+ if (resort || this.sortBy !== this._lastSort) {
853
+ // Each sound's row by identity: a Map, not indexOf per sound
854
+ // (quadratic — 1000 sounds was a million comparisons a sort).
855
+ const index = new Map(this.sounds.map((s, i) => [s, i]));
856
+ orderRows($.list, sortSounds(this.sounds, this.sortBy).map((s) => this.rows[index.get(s)!]));
857
+ this._lastSort = this.sortBy;
858
+ }
859
+ const shown = this._match();
860
+ this._shown = shown;
861
+ const {visible, remaining} = pageWindow(shown, this.limit);
862
+ this.sounds.forEach((s, i) => { if (this.rows[i]) this.rows[i].hidden = !visible.has(s); });
863
+ if ($.more) {
864
+ $.more.hidden = remaining <= 0;
865
+ $.more.textContent = fill(this.strings.showMore, {count: Math.min(remaining, this.render.pageSize || remaining)});
866
+ }
867
+ if ($.empty) {
868
+ $.empty.hidden = shown.length > 0;
869
+ // No sounds at all: nothing matches because there is nothing, and
870
+ // there is no filter to clear.
871
+ if (!this.sounds.length && $.empty.textContent !== this.strings.noSounds) $.empty.textContent = this.strings.noSounds;
872
+ }
873
+ if ($.count) $.count.textContent = countText(shown.length, this.sounds.length, this.strings);
874
+ // The Tab stop never sits on a hidden row; and if focus was in the
875
+ // row just filtered away, it follows the stop instead of falling
876
+ // to <body>.
877
+ if (!this._active || this._active.hidden) {
878
+ const lost = !!this._active?.contains(document.activeElement);
879
+ const first = visibleRows($.list)[0];
880
+ if (first) {
881
+ this._rove(first);
882
+ if (lost) this._focusRowQuietly(first);
883
+ } else if (this._active) { this._rowStops(this._active, false); this._active = null; }
884
+ }
885
+ // Nothing played yet: keep the cued sound one the list still shows.
886
+ if (this._cued && !this.playing) this._cueFirst();
887
+ this._queueUrl();
888
+ this._emit('filter', {visible: shown.length, total: this.sounds.length, filter: {...this.filter}, sort: this.sortBy});
889
+ this.options.onFilter?.(shown, this);
890
+ }
891
+
892
+ /* ── Playback ─────────────────────────────────────────────────────── */
893
+
894
+ /**
895
+ * Resolve an index, id or sound to an index in `this.sounds`. No
896
+ * target means the current sound, else the first visible one.
897
+ *
898
+ * @param target
899
+ * @internal
900
+ */
901
+ _indexOf(target?: number | string | Sound | null): number | null {
902
+ if (target == null) {
903
+ if (this.currentIndex != null) return this.currentIndex;
904
+ const first = (this._shown ?? this._match())[0];
905
+ return first ? this.sounds.indexOf(first) : null;
906
+ }
907
+ if (typeof target === 'number') return this.sounds[target] ? target : null;
908
+ const i = typeof target === 'object' ? this.sounds.indexOf(target) : this.sounds.findIndex((s) => s.id === String(target));
909
+ return i >= 0 ? i : null;
910
+ }
911
+
912
+ /**
913
+ * The WaveformPlayer class: `playerClass`, else the page's global.
914
+ * @internal
915
+ */
916
+ _playerClass(): EngineClass | null {
917
+ return (this.options.playerClass || (typeof window !== 'undefined' ? (window as any).WaveformPlayer : null) || null) as EngineClass | null;
918
+ }
919
+
920
+ /**
921
+ * The engine as the list drives it (fields the core keeps internal).
922
+ * @internal
923
+ */
924
+ _eng(): Engine | null {
925
+ return this.engine as unknown as Engine | null;
926
+ }
927
+
928
+ /**
929
+ * The element the engine mounts into: a child of the engine slot, never
930
+ * the slot itself. WaveformPlayer resets its container's `className`,
931
+ * which would strip `ws-engine--strip` (and with it the docked styling).
932
+ * Made here rather than in the markup so server-rendered HTML from any
933
+ * version works.
934
+ * @internal
935
+ */
936
+ _engineMount(): HTMLElement {
937
+ const slot = this.$.engine!;
938
+ let mount = slot.querySelector<HTMLElement>(':scope > [data-ws-engine-mount]');
939
+ if (!mount) {
940
+ mount = document.createElement('div');
941
+ mount.setAttribute('data-ws-engine-mount', '');
942
+ slot.appendChild(mount);
943
+ }
944
+ return mount;
945
+ }
946
+
947
+ /**
948
+ * Build the engine once (it holds no audio until a play).
949
+ * @returns The engine, or null without a player class.
950
+ * @internal
951
+ */
952
+ _ensureEngine(): Engine | null {
953
+ if (this.engine) return this._eng();
954
+ const Player = this._playerClass();
955
+ if (!Player) {
956
+ console.error(`${LOG} @arraypress/waveform-player is required: load it before playing (or pass playerClass).`);
957
+ return null;
958
+ }
959
+ const options = engineOptions(this.options.playerOptions, this.render.player, {
960
+ onLoad: () => this._onEngineLoad(),
961
+ onPlay: () => this._setPlaying(true),
962
+ onPause: () => this._setPlaying(false),
963
+ onEnd: () => this._onEnd(),
964
+ onTimeUpdate: (time: number, duration: number) => this._onTime(time, duration),
965
+ onError: (err: unknown) => this._onEngineError(err),
966
+ });
967
+ this._preload = options.preload;
968
+ (this as Writable<WaveformSounds>).engine = new Player(this._engineMount(), options) as unknown as WaveformPlayer;
969
+ return this._eng();
970
+ }
971
+
972
+ /**
973
+ * Play a sound (by index, id or sound object), or resume the current
974
+ * one. Before the list is built the call waits for it.
975
+ *
976
+ * @param target
977
+ * @param opts - `at`: start position 0..1.
978
+ */
979
+ play(target?: number | string | Sound, opts: {at?: number} = {}): void {
980
+ if (!this.$) { this.ready.then(() => { if (!this.destroyed) this.play(target, opts); }); return; }
981
+ const index = this._indexOf(target);
982
+ if (index == null) return;
983
+ this._cued = false;
984
+ const engine = this._ensureEngine();
985
+ if (!engine) return;
986
+ if (index === this.currentIndex && engine.audio?.src) {
987
+ if (opts.at != null) this._seekRow(index, opts.at);
988
+ if (!this.playing) engine.play();
989
+ return;
990
+ }
991
+ const previous = this.currentIndex;
992
+ this.currentIndex = index;
993
+ this.progress = 0;
994
+ this._pendingSeek = opts.at ?? null;
995
+ if (previous != null) this._paintRow(previous);
996
+ this._paintRow(index);
997
+ const sound = this.sounds[index];
998
+ engine.loadTrack(sound.url, sound.title, sound.type || null, engineTrack(sound, this.render.player, true, this._preload));
999
+ }
1000
+
1001
+ /**
1002
+ * Strip layout: load the first sound the list shows into the docked
1003
+ * player WITHOUT playing it, so the player shows a title and waveform
1004
+ * (and its play button plays that sound) instead of an empty frame.
1005
+ * Nothing is fetched (`preload: 'none'`): the player shows the title,
1006
+ * length and peaks from the data, and the audio loads on play — a filter
1007
+ * change re-cues, and each cue used to fetch a file's metadata.
1008
+ * The row isn't marked current until it plays.
1009
+ * @internal
1010
+ */
1011
+ _cueFirst(): void {
1012
+ const engine = this._eng();
1013
+ const first = (this._shown ?? this._match())[0];
1014
+ if (!engine || !first) return;
1015
+ const index = this.sounds.indexOf(first);
1016
+ if (index === this.currentIndex) return;
1017
+ this.currentIndex = index;
1018
+ this.progress = 0;
1019
+ this._cued = true;
1020
+ // Firefox fetches a source set in the same task as a script's
1021
+ // load(), whatever `preload` says — and the core's loadTrack() resets
1022
+ // the element with load() before setting the new source. Nothing
1023
+ // plays yet, so that reset can go: setting `src` (which the core
1024
+ // does too) restarts the element's load on its own.
1025
+ const audio = engine.audio;
1026
+ const shim = audio && typeof audio.load === 'function';
1027
+ if (shim) audio!.load = () => {};
1028
+ try {
1029
+ engine.loadTrack(first.url, first.title, first.type || null, engineTrack(first, 'strip', false, 'none'));
1030
+ } finally {
1031
+ if (shim) delete (audio as Partial<HTMLAudioElement>).load;
1032
+ }
1033
+ }
1034
+
1035
+ /** Pause the current sound. */
1036
+ pause(): void {
1037
+ if (this.engine && this.playing) this._eng()!.pause();
1038
+ }
1039
+
1040
+ /**
1041
+ * The current sound plays/pauses; another sound starts.
1042
+ * @param target
1043
+ */
1044
+ toggle(target?: number | string | Sound): void {
1045
+ const index = this._indexOf(target);
1046
+ if (index == null) return;
1047
+ if (index === this.currentIndex && this.playing) this.pause();
1048
+ else this.play(index);
1049
+ }
1050
+
1051
+ /** Play the next visible sound (no wrap at the end). */
1052
+ next(): void { this._step(1); }
1053
+
1054
+ /** Play the previous visible sound. */
1055
+ previous(): void { this._step(-1); }
1056
+
1057
+ /**
1058
+ * Play the visible sound `dir` places away, revealing it if it's past
1059
+ * the current page.
1060
+ *
1061
+ * @param dir
1062
+ * @returns Whether there was one.
1063
+ * @internal
1064
+ */
1065
+ _step(dir: 1 | -1): boolean {
1066
+ const shown = this._shown ?? this._match();
1067
+ // A cued sound counts as nothing played: next() starts with it.
1068
+ const at = this.currentIndex == null || this._cued ? -1 : shown.indexOf(this.sounds[this.currentIndex]);
1069
+ const target = shown[at + dir];
1070
+ if (!target) return false;
1071
+ const limit = limitToReveal(this.limit, at + dir);
1072
+ if (limit !== this.limit) { this.limit = limit; this._apply({resort: false}); }
1073
+ this.play(this.sounds.indexOf(target));
1074
+ return true;
1075
+ }
1076
+
1077
+ /**
1078
+ * Loop the current sound (auditioning a loop is the common case). When
1079
+ * the list marks its loops (`loop: true` on any sound), only those
1080
+ * repeat: a one-shot always plays once.
1081
+ * @param on
1082
+ */
1083
+ setLoop(on: boolean): void {
1084
+ this._loopSet = true;
1085
+ this.loop = !!on;
1086
+ this._setLoop(this.loop);
1087
+ }
1088
+
1089
+ /**
1090
+ * Apply the loop state to the toggle and the engine.
1091
+ * @internal
1092
+ */
1093
+ _setLoop(on: boolean): void {
1094
+ this.$?.loop?.setAttribute('aria-pressed', String(on));
1095
+ if (this._eng()?.audio) this._eng()!.audio!.loop = this._repeats();
1096
+ }
1097
+
1098
+ /**
1099
+ * Should the current sound repeat? The Loop toggle is on, and either
1100
+ * the list doesn't say which sounds are loops or this one is.
1101
+ * @internal
1102
+ */
1103
+ _repeats(): boolean {
1104
+ if (!this.loop) return false;
1105
+ const marksLoops = this.sounds.some((s) => s.loop);
1106
+ return !marksLoops || !!this.sounds[this.currentIndex!]?.loop;
1107
+ }
1108
+
1109
+ /**
1110
+ * Seek a row's sound to `fraction`; a row that isn't current starts
1111
+ * there. Before the duration is known the seek waits for it.
1112
+ * @internal
1113
+ */
1114
+ _seekRow(index: number, fraction: number): void {
1115
+ if (index !== this.currentIndex || !this.engine) { this.play(index, {at: fraction}); return; }
1116
+ const duration = this._eng()!.audio?.duration;
1117
+ if (!Number.isFinite(duration) || duration! <= 0) { this._pendingSeek = fraction; return; }
1118
+ this._eng()!.seekTo(fraction * duration!);
1119
+ this.progress = fraction;
1120
+ this._paintRow(index);
1121
+ this._paintSlider();
1122
+ if (!this.playing) this._eng()!.play();
1123
+ }
1124
+
1125
+ /**
1126
+ * The engine loaded a sound: clear an earlier failure, apply the loop, borrow decoded peaks for a
1127
+ * row that had none, and land a pending seek.
1128
+ * @internal
1129
+ */
1130
+ _onEngineLoad(): void {
1131
+ if (this.currentIndex != null) this.rows[this.currentIndex]?.classList.remove('is-error');
1132
+ if (this._eng()?.audio) this._eng()!.audio!.loop = this._repeats();
1133
+ const sound = this.sounds[this.currentIndex!];
1134
+ if (sound && !sound.peaks && this._eng()?.waveformData?.length) {
1135
+ sound.peaks = resample(this._eng()!.waveformData, 96);
1136
+ this._drawRow(this.currentIndex);
1137
+ }
1138
+ const duration = this._eng()?.audio?.duration;
1139
+ if (this._pendingSeek != null && Number.isFinite(duration) && duration! > 0) {
1140
+ this._eng()!.seekTo(this._pendingSeek * duration!);
1141
+ this.progress = this._pendingSeek;
1142
+ this._pendingSeek = null;
1143
+ }
1144
+ }
1145
+
1146
+ /**
1147
+ * Playback progress: repaint the current row, once per frame.
1148
+ * @internal
1149
+ */
1150
+ _onTime(time: number, duration: number): void {
1151
+ if (this.currentIndex == null || !duration) return;
1152
+ if (this._pendingSeek != null) {
1153
+ const fraction = this._pendingSeek;
1154
+ this._pendingSeek = null;
1155
+ this._eng()!.seekTo(fraction * duration);
1156
+ return;
1157
+ }
1158
+ this.progress = Math.min(Math.max(time / duration, 0), 1);
1159
+ if (this._raf) return;
1160
+ this._raf = requestAnimationFrame(() => {
1161
+ this._raf = 0;
1162
+ this._drawRow(this.currentIndex);
1163
+ this._paintSlider();
1164
+ });
1165
+ }
1166
+
1167
+ /**
1168
+ * A sound finished: report it, then auto-advance or settle.
1169
+ * @internal
1170
+ */
1171
+ _onEnd(): void {
1172
+ const sound = this.sounds[this.currentIndex!];
1173
+ this._emit('end', {sound, index: this.currentIndex});
1174
+ this.options.onEnd?.(sound, this);
1175
+ if (this.options.autoAdvance && this._step(1)) return;
1176
+ this.progress = 0;
1177
+ this._setPlaying(false);
1178
+ }
1179
+
1180
+ /**
1181
+ * A sound failed to load or play: it isn't playing (no stale "Pause"),
1182
+ * its row is marked until it plays, and the live region says so.
1183
+ * @internal
1184
+ */
1185
+ _onEngineError(err: unknown): void {
1186
+ const index = this.currentIndex;
1187
+ const sound = index == null ? undefined : this.sounds[index];
1188
+ if (index != null) this.rows[index]?.classList.add('is-error');
1189
+ this._setPlaying(false);
1190
+ // A cued sound (strip, nothing played) wasn't asked for: no announcement.
1191
+ if (sound && !this._cued && this.$?.status) this.$.status.textContent = fill(this.strings.playError, {title: sound.title});
1192
+ this._emit('error', {error: err, sound, index});
1193
+ this.options.onError?.(err, this);
1194
+ }
1195
+
1196
+ /**
1197
+ * Record play/pause and repaint, and report what the listener hears.
1198
+ * Events follow the SOUND, not the flag: switching sounds while one plays
1199
+ * (↓ audition, `play(i)`, `next()`, auto-advance) never flips `playing`
1200
+ * in some engines (the media element swaps source without a `pause`),
1201
+ * so the last sound announced is tracked — a different one starting
1202
+ * reports `pause` for the outgoing sound, then `play` for the new one.
1203
+ * At a natural end the browser fires `pause` then `ended`, and `_onEnd()`
1204
+ * settles the state again: one pause event, not two.
1205
+ * @internal
1206
+ */
1207
+ _setPlaying(on: boolean): void {
1208
+ (this as Writable<WaveformSounds>).playing = on;
1209
+ if (on) this._cued = false; // the strip's own button played the cued sound
1210
+ const index = this.currentIndex;
1211
+ if (index == null) return;
1212
+ if (on) this.rows[index]?.classList.remove('is-error'); // it plays after all
1213
+ this._paintRow(index);
1214
+ const was = this._announced ?? null;
1215
+ if (on) {
1216
+ if (was === index) return;
1217
+ if (was != null) this._announce('pause', was);
1218
+ this._announced = index;
1219
+ this._announce('play', index);
1220
+ } else if (was != null) {
1221
+ this._announced = null;
1222
+ this._announce('pause', was);
1223
+ }
1224
+ }
1225
+
1226
+ /**
1227
+ * Report a sound starting or stopping: the live region (on play), the
1228
+ * `waveformsounds:play|pause` event and the `onPlay` / `onPause` callback.
1229
+ * @internal
1230
+ */
1231
+ _announce(type: 'play' | 'pause', index: number): void {
1232
+ const sound = this.sounds[index];
1233
+ if (!sound) return;
1234
+ if (type === 'play' && this.$?.status) this.$.status.textContent = fill(this.strings.nowPlaying, {title: sound.title});
1235
+ this._emit(type, {sound, index});
1236
+ (type === 'play' ? this.options.onPlay : this.options.onPause)?.(sound, this);
1237
+ }
1238
+
1239
+ /* ── Row painting ─────────────────────────────────────────────────── */
1240
+
1241
+ /**
1242
+ * A row's state classes, play-button label and waveform.
1243
+ * @internal
1244
+ */
1245
+ _paintRow(index: number): void {
1246
+ const row = this.rows[index];
1247
+ if (!row) return;
1248
+ const current = index === this.currentIndex;
1249
+ const on = current && this.playing;
1250
+ row.classList.toggle('is-current', current);
1251
+ row.classList.toggle('is-playing', on);
1252
+ const btn = row.querySelector('.ws-play');
1253
+ if (btn) {
1254
+ btn.setAttribute('aria-pressed', String(on));
1255
+ btn.setAttribute('aria-label', fill(on ? this.strings.pause : this.strings.play, {title: this.sounds[index].title}));
1256
+ }
1257
+ const wave = row.querySelector<HTMLElement>('.ws-wave');
1258
+ if (wave) {
1259
+ wave.tabIndex = current && row === this._active ? 0 : -1;
1260
+ if (!current) {
1261
+ wave.setAttribute('aria-valuenow', '0');
1262
+ wave.removeAttribute('aria-valuetext');
1263
+ }
1264
+ }
1265
+ this._drawRow(index);
1266
+ }
1267
+
1268
+ /**
1269
+ * The current row's seek slider: its position (0–100) and, for a screen
1270
+ * reader, the time ("0:12 of 0:30").
1271
+ * @internal
1272
+ */
1273
+ _paintSlider(): void {
1274
+ const index = this.currentIndex;
1275
+ const wave = index == null ? null : this.rows[index]?.querySelector('.ws-wave');
1276
+ if (!wave) return;
1277
+ wave.setAttribute('aria-valuenow', String(Math.round(this.progress * 100)));
1278
+ const audio = this._eng()?.audio;
1279
+ const duration = Number.isFinite(audio?.duration) && audio!.duration > 0 ? audio!.duration : this.sounds[index!].duration;
1280
+ if (duration) wave.setAttribute('aria-valuetext', fill(this.strings.seekValue, {time: formatClock(this.progress * duration), duration: formatDuration(duration)}));
1281
+ }
1282
+
1283
+ /* ── Events & lifecycle ──────────────────────────────────────────── */
1284
+
1285
+ /**
1286
+ * Announce a moment both ways: a `waveformsounds:<name>` event on the
1287
+ * container carrying the details and this instance, then a plain `<name>`
1288
+ * event on the instance.
1289
+ * @internal
1290
+ */
1291
+ _emit(name: keyof WaveformSoundsInstanceEventMap, detail: Record<string, any> = {}): void {
1292
+ emit(this.container, name, {...detail, instance: this});
1293
+ this.dispatchEvent(new Event(name));
1294
+ }
1295
+
1296
+ /** The sound playing (or paused) now, or null. */
1297
+ get current(): Sound | null {
1298
+ // A cued sound (strip, nothing played yet) isn't "current".
1299
+ return this.currentIndex == null || this._cued ? null : this.sounds[this.currentIndex];
1300
+ }
1301
+
1302
+ /**
1303
+ * Tear down: listeners, observers, timers and the engine. Markup this
1304
+ * instance rendered is restored to what the container held before.
1305
+ * ADOPTED (server-rendered) markup is left as it is now — rows may be
1306
+ * re-sorted, hidden or marked current — unless `restore` is set: then it
1307
+ * is put back exactly as the server sent it, ready for a new instance
1308
+ * (what a framework re-mounting the same markup wants).
1309
+ *
1310
+ * @param options
1311
+ * @param options.restore - Put adopted server markup back as it was.
1312
+ * Default false. Since 2.1.0.
1313
+ */
1314
+ destroy(options: {restore?: boolean} = {}): void {
1315
+ if (this.destroyed) return;
1316
+ this.destroyed = true;
1317
+ this._ctl.abort();
1318
+ this._io?.disconnect();
1319
+ this._ro?.disconnect();
1320
+ this._mo?.disconnect();
1321
+ if (this._raf) cancelAnimationFrame(this._raf);
1322
+ clearTimeout(this._urlTimer);
1323
+ try { this._eng()?.destroy(); } catch { /* engine already gone */ }
1324
+ (this as Writable<WaveformSounds>).engine = null;
1325
+ this.$?.engine?.querySelector(':scope > [data-ws-engine-mount]')?.remove();
1326
+ if (this._originalHTML != null) this.container.innerHTML = this._originalHTML;
1327
+ else if (options.restore && this._adoptedHTML != null) this.container.innerHTML = this._adoptedHTML;
1328
+ if (this._addedClasses?.length) this.container.classList.remove(...this._addedClasses);
1329
+ if (this._autoSurface) this.container.style.removeProperty('--ws-surface');
1330
+ delete this.container.dataset.wsInitialized;
1331
+ WaveformSounds.instances.delete(this.container);
1332
+ }
1333
+
1334
+ /**
1335
+ * Initialise every `[data-waveform-sounds]` under `root` that isn't yet.
1336
+ *
1337
+ * @param root
1338
+ * @returns The new instances.
1339
+ */
1340
+ static init(root: ParentNode = document): WaveformSounds[] {
1341
+ if (typeof document === 'undefined') return [];
1342
+ const scope = root || document;
1343
+ const els = [...((scope as Element).matches?.('[data-waveform-sounds]') ? [scope as HTMLElement] : []), ...scope.querySelectorAll<HTMLElement>('[data-waveform-sounds]')];
1344
+ const created: WaveformSounds[] = [];
1345
+ for (const el of els) {
1346
+ if (el.dataset.wsInitialized === 'true' || WaveformSounds.instances.has(el)) continue;
1347
+ try { created.push(new WaveformSounds(el)); } catch (err) { console.error(`${LOG} Failed to initialise:`, err, el); }
1348
+ }
1349
+ return created;
1350
+ }
1351
+
1352
+ /**
1353
+ * The instance on an element (or selector), if any.
1354
+ * @param el
1355
+ */
1356
+ static getInstance(el: Element | string): WaveformSounds | null {
1357
+ const node = typeof el === 'string' ? document.querySelector(el) : el;
1358
+ return node ? WaveformSounds.instances.get(node) || null : null;
1359
+ }
1360
+
1361
+ /** Destroy instances whose element has left the document (after a
1362
+ * client-side navigation). */
1363
+ static prune(): void {
1364
+ for (const [el, inst] of WaveformSounds.instances) if (!el.isConnected) inst.destroy();
1365
+ }
1366
+ }