@arraypress/waveform-sounds 2.0.0 → 2.2.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 (79) hide show
  1. package/README.md +44 -2
  2. package/dist/waveform-sounds-no-autoinit.esm.js +914 -208
  3. package/dist/waveform-sounds-render.esm.js +274 -82
  4. package/dist/waveform-sounds.css +92 -17
  5. package/dist/waveform-sounds.esm.js +917 -210
  6. package/dist/waveform-sounds.js +913 -210
  7. package/dist/waveform-sounds.min.css +1 -1
  8. package/dist/waveform-sounds.min.js +3 -3
  9. package/package.json +1 -1
  10. package/src/css/waveform-sounds.css +92 -17
  11. package/src/js/core/WaveformSounds.ts +540 -120
  12. package/src/js/core/element.ts +208 -0
  13. package/src/js/core/engine.ts +9 -3
  14. package/src/js/core/options.ts +1 -5
  15. package/src/js/data/bpm.ts +14 -4
  16. package/src/js/data/keys.ts +156 -0
  17. package/src/js/data/navigation.ts +51 -11
  18. package/src/js/data/sounds.ts +73 -36
  19. package/src/js/data/url-state.ts +39 -12
  20. package/src/js/dom/colors.ts +28 -1
  21. package/src/js/dom/draw.ts +16 -3
  22. package/src/js/dom/menus.ts +2 -3
  23. package/src/js/dom/rows.ts +38 -15
  24. package/src/js/entry.ts +13 -3
  25. package/src/js/index.ts +7 -3
  26. package/src/js/render/html.ts +0 -2
  27. package/src/js/render/icons.ts +59 -17
  28. package/src/js/render/markup.ts +156 -62
  29. package/src/js/render/options.ts +29 -5
  30. package/src/js/render/strings.ts +57 -4
  31. package/src/js/render-entry.ts +1 -1
  32. package/src/js/shared/utils.ts +4 -4
  33. package/src/js/types.ts +54 -3
  34. package/types/core/WaveformSounds.d.ts +41 -11
  35. package/types/core/WaveformSounds.d.ts.map +1 -1
  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 +8 -3
  39. package/types/core/engine.d.ts.map +1 -1
  40. package/types/core/options.d.ts +0 -5
  41. package/types/core/options.d.ts.map +1 -1
  42. package/types/data/bpm.d.ts +17 -4
  43. package/types/data/bpm.d.ts.map +1 -1
  44. package/types/data/keys.d.ts +88 -0
  45. package/types/data/keys.d.ts.map +1 -0
  46. package/types/data/navigation.d.ts +38 -11
  47. package/types/data/navigation.d.ts.map +1 -1
  48. package/types/data/sounds.d.ts +33 -17
  49. package/types/data/sounds.d.ts.map +1 -1
  50. package/types/data/url-state.d.ts +38 -7
  51. package/types/data/url-state.d.ts.map +1 -1
  52. package/types/dom/colors.d.ts +13 -0
  53. package/types/dom/colors.d.ts.map +1 -1
  54. package/types/dom/draw.d.ts +5 -3
  55. package/types/dom/draw.d.ts.map +1 -1
  56. package/types/dom/menus.d.ts +0 -2
  57. package/types/dom/menus.d.ts.map +1 -1
  58. package/types/dom/rows.d.ts +19 -11
  59. package/types/dom/rows.d.ts.map +1 -1
  60. package/types/entry.d.ts +10 -4
  61. package/types/entry.d.ts.map +1 -1
  62. package/types/index.d.ts +2 -2
  63. package/types/index.d.ts.map +1 -1
  64. package/types/render/html.d.ts +0 -2
  65. package/types/render/html.d.ts.map +1 -1
  66. package/types/render/icons.d.ts +41 -3
  67. package/types/render/icons.d.ts.map +1 -1
  68. package/types/render/markup.d.ts +44 -12
  69. package/types/render/markup.d.ts.map +1 -1
  70. package/types/render/options.d.ts +18 -5
  71. package/types/render/options.d.ts.map +1 -1
  72. package/types/render/strings.d.ts +22 -4
  73. package/types/render/strings.d.ts.map +1 -1
  74. package/types/render-entry.d.ts +1 -1
  75. package/types/render-entry.d.ts.map +1 -1
  76. package/types/shared/utils.d.ts +3 -3
  77. package/types/shared/utils.d.ts.map +1 -1
  78. package/types/types.d.ts +53 -3
  79. package/types/types.d.ts.map +1 -1
@@ -26,24 +26,29 @@
26
26
  * @module core
27
27
  */
28
28
 
29
- import {availableSorts, facets, matches, normalizeSounds, parseManifest, sortSounds, SORTS} from '../data/sounds.js';
29
+ import {availableSorts, facets, formatClock, formatDuration, matches, normalizeKey, normalizeSounds, parseManifest, sortSounds, SORTS} from '../data/sounds.js';
30
+ import {keyEntry} from '../data/keys.js';
30
31
  import {drawRowWaveform, resample} from '../dom/draw.js';
31
32
  import {engineOptions, engineTrack} from './engine.js';
32
33
  import {Menus} from '../dom/menus.js';
33
- import {limitToReveal, pageWindow, rowTarget, seekTarget} from '../data/navigation.js';
34
+ import {budgetToReveal, limitToReveal, RENDER_CHUNK, renderedCount, rowTarget, seekTarget, sliderEdgeTarget} from '../data/navigation.js';
34
35
  import {DEFAULT_OPTIONS, mergeOptions, readDataOptions} from './options.js';
35
36
  import {resolveRenderOptions} from '../render/options.js';
36
- import {loopsByDefault, renderSounds} from '../render/markup.js';
37
- import {indexRows, orderRows, readRows, visibleRows} from '../dom/rows.js';
37
+ import {idBase, loopsByDefault, renderList, renderRow} from '../render/markup.js';
38
+ import type {renderSounds} from '../render/markup.js';
39
+ import {ICON_NAMES, iconSprite} from '../render/icons.js';
40
+ import {indexRows, layoutRows, readRows, readSoundsData, visibleRows} from '../dom/rows.js';
38
41
  import {bpmLabel, countText, DEFAULT_STRINGS, fill} from '../render/strings.js';
39
- import {bpmFilterFromRange, bpmFraction, bpmRangeFromFilter} from '../data/bpm.js';
40
- import {pageSurface, resolveCssColor} from '../dom/colors.js';
42
+ import {bpmExtent, bpmFilterFromRange, bpmFraction, bpmRangeFromFilter} from '../data/bpm.js';
43
+ import {ancestorsOf, forcedColors, pageSurface, resolveCssColor} from '../dom/colors.js';
41
44
  import {readUrlState, urlKeys, writeUrlState} from '../data/url-state.js';
42
45
  import {emit, isTyping, LOG, pointerFraction} from '../shared/utils.js';
43
- import type {decodePeaks, encodePeaks, formatDuration, normalizeKey} from '../data/sounds.js';
46
+ import {h, text} from '../render/html.js';
47
+ import type {decodePeaks, encodePeaks} from '../data/sounds.js';
44
48
  import type {EngineTrack} from './engine.js';
49
+ import type {WaveformPlayer} from '@arraypress/waveform-player';
45
50
  import type {RenderOptions} from '../render/options.js';
46
- import type {Sound, SoundInput, SoundsFilter, SoundsLoopFilter, SoundsSort, WaveformSoundsOptions, WaveformSoundsStrings} from '../types.js';
51
+ import type {Sound, SoundsFilter, SoundsLoopFilter, SoundsSort, WaveformSoundsInstanceEventMap, WaveformSoundsOptions, WaveformSoundsStrings} from '../types.js';
47
52
 
48
53
  /** The engine `WaveformPlayer`, as far as the list uses it. */
49
54
  interface Engine {
@@ -95,7 +100,26 @@ const BPM_DELAY = 200;
95
100
  /** Debounce before the address is rewritten after a change (ms). */
96
101
  const URL_DELAY = 250;
97
102
 
98
- export class WaveformSounds {
103
+ /**
104
+ * Typed listeners for the events a list dispatches on itself (see
105
+ * {@link WaveformSoundsInstanceEventMap}). Types only: merged into the class
106
+ * below, it emits nothing.
107
+ */
108
+ export interface WaveformSounds {
109
+ addEventListener<K extends keyof WaveformSoundsInstanceEventMap>(type: K, listener: (this: WaveformSounds, ev: WaveformSoundsInstanceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
110
+ addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void;
111
+ removeEventListener<K extends keyof WaveformSoundsInstanceEventMap>(type: K, listener: (this: WaveformSounds, ev: WaveformSoundsInstanceEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
112
+ removeEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions): void;
113
+ }
114
+
115
+ /**
116
+ * An `EventTarget`, like the core's player: each moment is dispatched on the
117
+ * instance as a plain event (`ready`, `play`, `pause`, `end`, `filter`,
118
+ * `error`), and on the container as a bubbling, composed
119
+ * `waveformsounds:<name>` CustomEvent carrying the details.
120
+ */
121
+ // biome-ignore lint/suspicious/noUnsafeDeclarationMerging: see the interface above
122
+ export class WaveformSounds extends EventTarget {
99
123
  /** Every live instance, by its element. */
100
124
  static instances: Map<Element, WaveformSounds> = new Map();
101
125
  /** The pure helpers, for `<script>` users (attached in `entry.ts`). */
@@ -111,6 +135,11 @@ export class WaveformSounds {
111
135
  formatDuration: typeof formatDuration;
112
136
  renderSounds: typeof renderSounds;
113
137
  };
138
+ /** Register the `<waveform-sounds>` element (default tag name
139
+ * `waveform-sounds`). The default entry does this on import; this
140
+ * reaches it from a `<script>` page that opted out of auto-init.
141
+ * Attached in `entry.ts`. Since 2.1.0. */
142
+ declare static defineElement: (name?: string) => CustomElementConstructor | undefined;
114
143
  /** Every option with its default (attached in `entry.ts`). */
115
144
  declare static DEFAULT_OPTIONS: WaveformSoundsOptions;
116
145
  /** The English UI strings (attached in `entry.ts`). */
@@ -130,13 +159,19 @@ export class WaveformSounds {
130
159
  declare readonly filter: SoundsFilter;
131
160
  declare readonly sortBy: SoundsSort;
132
161
  declare readonly playing: boolean;
133
- /** The engine `WaveformPlayer`, created on first play. */
134
- declare readonly engine: unknown;
162
+ /** The engine `WaveformPlayer`: built when the list is ready if the
163
+ * player is on the page (else on first play), null before and after. */
164
+ declare readonly engine: WaveformPlayer | null;
135
165
 
136
166
  /** @internal */ declare strings: WaveformSoundsStrings;
137
167
  /** @internal */ declare render: RenderOptions;
138
- /** @internal */ declare rows: HTMLElement[];
168
+ /** @internal Each sound's row, once it has one (in the list or not). */ declare rows: HTMLElement[];
139
169
  /** @internal */ declare limit: number;
170
+ /** @internal Paging off: how many of the matching sounds have rows so far. */ declare _budget: number;
171
+ /** @internal Each sound's index. */ declare _index: Map<Sound, number>;
172
+ /** @internal The list's id prefix (its icons, rows' read-outs). */ declare _iconId: string;
173
+ /** @internal Sounds that failed to load (their rows are marked, rendered or not). */ declare _failed: Set<number>;
174
+ /** @internal Watches the last rendered row, to render the next chunk. */ declare _endIo: IntersectionObserver | undefined;
140
175
  /** @internal */ declare currentIndex: number | null;
141
176
  /** @internal */ declare progress: number;
142
177
  /** @internal */ declare loop: boolean;
@@ -147,33 +182,43 @@ export class WaveformSounds {
147
182
  /** @internal */ declare colors: {wave: string, progress: string} | undefined;
148
183
  /** @internal */ declare _ctl: AbortController;
149
184
  /** @internal */ declare _originalHTML: string | null;
185
+ /** @internal Adopted server markup as it arrived (destroy({restore})). */ declare _adoptedHTML: string | undefined;
150
186
  /** @internal */ declare _pendingSeek: number | null;
151
187
  /** @internal */ declare _raf: number;
152
188
  /** @internal */ declare _addedClasses: string[] | undefined;
153
189
  /** @internal */ declare _loopSet: boolean | undefined;
154
190
  /** @internal */ declare _sortSet: boolean | undefined;
155
191
  /** @internal */ declare _bpmExtent: {min: number, max: number} | null;
192
+ /** @internal What the sounds offer the controls (built once). */ declare _facets: ReturnType<typeof facets> | undefined;
156
193
  /** @internal */ declare _sorts: string[];
157
- /** @internal */ declare _lastSort: string | undefined;
158
194
  /** @internal */ declare _lastPointer: string | undefined;
159
- /** @internal */ declare _drawn: Set<number> | undefined;
195
+ /** @internal Rows drawn at least once. */ declare _drawn: Set<number> | undefined;
196
+ /** @internal Drawn rows whose picture is stale (redrawn when they show). */ declare _dirty: Set<number> | undefined;
197
+ /** @internal Rows near the viewport (undefined without IntersectionObserver). */ declare _onScreen: Set<number> | undefined;
160
198
  /** @internal */ declare _io: IntersectionObserver | undefined;
161
199
  /** @internal */ declare _ro: ResizeObserver | undefined;
162
200
  /** @internal */ declare _mo: MutationObserver | undefined;
163
201
  /** @internal */ declare _autoSurface: boolean | undefined;
164
202
  /** @internal */ declare _urlTimer: number | undefined;
165
203
  /** @internal */ declare _cued: boolean | undefined;
204
+ /** @internal The sounds the last layout shows, in order (see `visible`). */ declare _shown: Sound[] | undefined;
205
+ /** @internal The engine's own `preload` (a cue uses 'none'). */ declare _preload: string | undefined;
206
+ /** @internal The row holding the list's one Tab stop. */ declare _active: HTMLElement | null;
207
+ /** @internal The sound last reported as playing (its pause not yet reported). */ declare _announced: number | null | undefined;
166
208
 
167
209
  /**
168
210
  * @param {HTMLElement|string} container - The element (or a selector).
169
211
  * @param {WaveformSoundsOptions} [options]
170
212
  */
171
213
  constructor(container: HTMLElement | string, options: WaveformSoundsOptions = {}) {
214
+ super();
172
215
  const el = typeof container === 'string' ? document.querySelector<HTMLElement>(container) : container;
173
216
  if (!el) throw new Error(`${LOG} Container not found: ${container}`);
174
217
  this.container = el;
175
218
  // Precedence, as across the family: data-* > constructor > default.
176
- this.options = mergeOptions(DEFAULT_OPTIONS, options, readDataOptions(el)) as Required<WaveformSoundsOptions>;
219
+ // A <waveform-sounds> element reads its plain attributes too.
220
+ const data = (el as {_wsOptions?: () => Record<string, any>})._wsOptions?.() ?? readDataOptions(el);
221
+ this.options = mergeOptions(DEFAULT_OPTIONS, options, data) as Required<WaveformSoundsOptions>;
177
222
  this.options.waveformStyle = this.options.waveformStyle === 'bars' ? 'bars' : 'mirror';
178
223
  this.strings = {...DEFAULT_STRINGS, ...(this.options.strings || {})};
179
224
  this.render = {...resolveRenderOptions(this.options), strings: this.strings};
@@ -183,6 +228,9 @@ export class WaveformSounds {
183
228
  this.filter = {...NO_FILTER};
184
229
  this.sortBy = 'default';
185
230
  this.limit = this._pageSize();
231
+ this._budget = this._firstBudget();
232
+ this._index = new Map();
233
+ this._failed = new Set();
186
234
  this.currentIndex = null;
187
235
  this.playing = false;
188
236
  this.progress = 0;
@@ -204,7 +252,9 @@ export class WaveformSounds {
204
252
  // through onError / `waveformsounds:error`.
205
253
  /** Resolves once the list is built (after a manifest fetch, if any). */
206
254
  this.ready = Promise.resolve().then(() => this._init()).catch((err) => {
255
+ if (this.destroyed) return; // e.g. the manifest fetch, aborted by destroy()
207
256
  console.error(`${LOG} Failed to initialise:`, err);
257
+ this._showLoadError();
208
258
  this._emit('error', {error: err});
209
259
  this.options.onError?.(err, this);
210
260
  });
@@ -221,38 +271,47 @@ export class WaveformSounds {
221
271
  const el = this.container;
222
272
  const adopted = el.querySelector<HTMLElement>('[data-ws-list]');
223
273
  if (adopted) {
224
- (this as Writable<WaveformSounds>).sounds = readRows(adopted);
274
+ // As the server sent it, for destroy({restore: true}).
275
+ this._adoptedHTML = el.innerHTML;
276
+ // Every sound from the markup's JSON (2.2+); before 2.2 every
277
+ // row was in the markup, carrying its sound.
278
+ (this as Writable<WaveformSounds>).sounds = readSoundsData(el) ?? readRows(adopted);
225
279
  } else {
226
280
  this._originalHTML = el.innerHTML;
227
281
  (this as Writable<WaveformSounds>).sounds = await this._loadSounds();
228
282
  if (this.destroyed) return;
229
- el.innerHTML = renderSounds(this.sounds as SoundInput[], {...this.render, idPrefix: this.options.idPrefix || el.id || undefined});
283
+ // The server's markup, less the JSON (the sounds are here).
284
+ el.innerHTML = renderList(this.sounds, {...this.render, idPrefix: this.options.idPrefix || el.id || undefined}, false);
230
285
  }
231
286
  if (this.destroyed) return;
287
+ this._index = new Map(this.sounds.map((sound, i) => [sound, i]));
232
288
 
233
289
  // Remember which classes WE add, so destroy() takes back exactly
234
290
  // those (server-rendered markup already carries them).
235
291
  this._addedClasses = ['waveform-sounds', `waveform-sounds--${this.render.player}`].filter((c) => !el.classList.contains(c));
236
292
  el.classList.add(...this._addedClasses);
237
293
 
294
+ this._facets = facets(this.sounds, this.render);
238
295
  this._cacheRefs();
239
296
  this._bind();
240
297
  this._observe();
241
298
  this._resolveColors();
242
299
  // Unless set (option or an early setLoop()), Loop starts on exactly
243
300
  // when the list marks loops — only those repeat.
244
- if (!this._loopSet) this.loop = loopsByDefault(this.options.loop, facets(this.sounds));
301
+ if (!this._loopSet) this.loop = loopsByDefault(this.options.loop, this._facets);
245
302
  this._setLoop(this.loop);
246
- this._bpmExtent = facets(this.sounds).bpm;
303
+ this._bpmExtent = bpmExtent(this._facets.bpm);
247
304
 
248
305
  // The starting order is the first one offered, unless setSort()
249
306
  // already chose one; then the address may override both.
250
- this._sorts = availableSorts(this.render.sorts, facets(this.sounds));
307
+ this._sorts = availableSorts(this.render.sorts, this._facets);
251
308
  if (!this._sortSet) (this as Writable<WaveformSounds>).sortBy = (this._sorts[0] || 'default') as SoundsSort;
252
309
  this._readUrl();
310
+ // A key set from code before now, in the list's spelling.
311
+ (this as Writable<WaveformSounds>).filter = {...this.filter, key: this._keyEntry(this.filter.key)};
253
312
  // Show any filter/sort set before now (from code or the address).
254
313
  this._syncControls();
255
- this._apply({resort: this.sortBy !== 'default'});
314
+ this._apply();
256
315
 
257
316
  // Build the engine now (no audio loads until a play) when the
258
317
  // player is on the page, so anything that hooks players on their
@@ -270,14 +329,31 @@ export class WaveformSounds {
270
329
 
271
330
  /**
272
331
  * The sounds from the `sounds` option, else the `manifest` URL.
273
- * @returns
274
332
  * @internal
275
333
  */
276
334
  async _loadSounds(): Promise<Sound[]> {
277
335
  if (this.options.sounds || !this.options.manifest) return normalizeSounds(this.options.sounds || []);
278
- const res = await fetch(this.options.manifest);
279
- if (!res.ok) throw new Error(`${LOG} Manifest ${this.options.manifest}: HTTP ${res.status}`);
280
- return parseManifest(await res.json());
336
+ const url = this.options.manifest;
337
+ // destroy() aborts it: a list torn down mid-fetch never builds.
338
+ const res = await fetch(url, {signal: this._ctl.signal});
339
+ if (!res.ok) throw new Error(`${LOG} Manifest ${url}: HTTP ${res.status}`);
340
+ const manifest = await res.json();
341
+ // Not a list of sounds at all is a broken manifest, not an empty pack.
342
+ if (!Array.isArray(manifest) && !Array.isArray(manifest?.sounds)) throw new Error(`${LOG} Manifest ${url}: no "sounds" list`);
343
+ return parseManifest(manifest);
344
+ }
345
+
346
+ /**
347
+ * A build that failed (the manifest 404s, isn't JSON, isn't a manifest)
348
+ * says so where the list would be — unless the container holds the
349
+ * site's own fallback, which stays. destroy() restores what was there.
350
+ * @internal
351
+ */
352
+ _showLoadError(): void {
353
+ const el = this.container;
354
+ if (this.$ || el.querySelector('*')) return;
355
+ this._originalHTML ??= el.innerHTML;
356
+ el.innerHTML = h('p', {class: 'ws-empty ws-load-error', role: 'alert', 'data-ws-load-error': true}, text(this.strings.loadError));
281
357
  }
282
358
 
283
359
  /**
@@ -304,7 +380,76 @@ export class WaveformSounds {
304
380
  chips: [...this.container.querySelectorAll<HTMLElement>('[data-ws-type]')],
305
381
  loopFilter: [...this.container.querySelectorAll<HTMLElement>('[data-ws-loop-filter]')],
306
382
  };
307
- this.rows = indexRows(this.$.list);
383
+ // The id prefix the rows were drawn with (their icons and
384
+ // read-outs); markup from before 2.2 has no sprite, so it gets one
385
+ // for the rows rendered from now on.
386
+ const sprite = q('[data-ws-sprite]');
387
+ this._iconId = sprite?.dataset.wsSprite ?? (this.options.idPrefix || this.container.id || idBase(this.sounds));
388
+ if (!sprite) this.$.list.insertAdjacentHTML('beforebegin', iconSprite(this._iconId, ICON_NAMES));
389
+ this.rows = [];
390
+ // Roving tabindex: the list is ONE Tab stop (the active row's
391
+ // controls); ↑/↓ move between rows. Set here, not in the markup, so
392
+ // server-rendered HTML from any version gets it.
393
+ this._active = null;
394
+ for (const row of indexRows(this.$.list)) if (row) this._adoptRow(row);
395
+ }
396
+
397
+ /**
398
+ * Take a row (server-rendered, or just rendered) into the list's
399
+ * keeping: its index, its Tab stops off, the state of its sound (current,
400
+ * failed), and the observer that draws it.
401
+ * @internal
402
+ */
403
+ _adoptRow(row: HTMLElement): void {
404
+ const i = Number(row.dataset.wsIndex);
405
+ this.rows[i] = row;
406
+ this._rowStops(row, false);
407
+ const wave = row.querySelector<HTMLElement>('.ws-wave');
408
+ // Before 2.2 every row's waveform was a slider: only the current one is.
409
+ if (i === this.currentIndex || this._failed.has(i) || wave?.hasAttribute('role')) this._paintRow(i);
410
+ if (i === this.currentIndex) this._paintSlider();
411
+ if (this._io) this._io.observe(row);
412
+ else this._drawn?.add(i);
413
+ }
414
+
415
+ /**
416
+ * Rows for these sounds, rendered (in one pass) where they have none.
417
+ * @returns The rows, in the order given.
418
+ * @internal
419
+ */
420
+ _rowsFor(indices: number[]): HTMLElement[] {
421
+ const missing = indices.filter((i) => !this.rows[i]);
422
+ if (missing.length) {
423
+ const tpl = document.createElement('template');
424
+ tpl.innerHTML = missing.map((i) => renderRow(this.sounds[i], i, this.render, this._iconId)).join('');
425
+ for (const row of [...tpl.content.children] as HTMLElement[]) this._adoptRow(row);
426
+ }
427
+ return indices.map((i) => this.rows[i]);
428
+ }
429
+
430
+ /**
431
+ * Make a row's own controls (play, download, and the seek slider when it
432
+ * is the current sound) Tab stops, or not.
433
+ * @internal
434
+ */
435
+ _rowStops(row: HTMLElement, on: boolean): void {
436
+ const play = row.querySelector<HTMLElement>('.ws-play');
437
+ if (play) play.tabIndex = on ? 0 : -1;
438
+ const dl = row.querySelector<HTMLElement>('.ws-download');
439
+ if (dl) dl.tabIndex = on ? 0 : -1;
440
+ const wave = row.querySelector<HTMLElement>('.ws-wave');
441
+ if (wave && Number(row.dataset.wsIndex) === this.currentIndex) wave.tabIndex = on ? 0 : -1;
442
+ }
443
+
444
+ /**
445
+ * Move the list's Tab stop to `row` (roving tabindex).
446
+ * @internal
447
+ */
448
+ _rove(row: HTMLElement | null | undefined): void {
449
+ if (!row || row === this._active) return;
450
+ if (this._active) this._rowStops(this._active, false);
451
+ this._active = row;
452
+ this._rowStops(row, true);
308
453
  }
309
454
 
310
455
  /**
@@ -320,6 +465,8 @@ export class WaveformSounds {
320
465
  root.addEventListener('click', (e) => this._onClick(e), sig);
321
466
  root.addEventListener('pointerdown', (e) => this._onPointerDown(e), sig);
322
467
  root.addEventListener('keydown', (e) => this._onKey(e), sig);
468
+ // Whatever row gets focus (arrows, a click, a script) holds the Tab stop.
469
+ $.list.addEventListener('focusin', (e) => this._rove((e.target as Element).closest<HTMLElement>('[data-ws-index]')), sig);
323
470
 
324
471
  let searchTimer = 0, bpmTimer = 0;
325
472
  $.search?.addEventListener('input', () => {
@@ -375,8 +522,15 @@ export class WaveformSounds {
375
522
  if (chip) { this.setFilter({type: chip.dataset.wsType}); return; }
376
523
  const seg = t.closest<HTMLElement>('[data-ws-loop-filter]');
377
524
  if (seg) { this.setFilter({loop: seg.dataset.wsLoopFilter as SoundsLoopFilter}); return; }
378
- if (t.closest('[data-ws-more]')) { this.showMore(); return; }
379
- if (t.closest('[data-ws-clear]')) { this.clearFilters(); return; }
525
+ if (t.closest('[data-ws-more]')) { this._showMoreFromButton(); return; }
526
+ if (t.closest('[data-ws-clear]')) {
527
+ // The button disappears with the empty state: focus goes back
528
+ // to the search (else the first row), never to <body>.
529
+ this.clearFilters();
530
+ if (this.$.search) this.$.search.focus();
531
+ else this._focusRow(visibleRows(this.$.list)[0]);
532
+ return;
533
+ }
380
534
  if (t.closest('[data-ws-loop]')) { this.setLoop(!this.loop); return; }
381
535
  const wave = t.closest<HTMLElement>('.ws-wave');
382
536
  if (wave) {
@@ -391,6 +545,18 @@ export class WaveformSounds {
391
545
  this._focusRowQuietly(row);
392
546
  }
393
547
 
548
+ /**
549
+ * "Show more", pressed: reveal the next page. When that was the last page
550
+ * the button hides, so focus moves to the first row it revealed rather
551
+ * than falling to <body>.
552
+ * @internal
553
+ */
554
+ _showMoreFromButton(): void {
555
+ const before = new Set(visibleRows(this.$.list));
556
+ this.showMore();
557
+ if (this.$.more?.hidden) this._focusRow(visibleRows(this.$.list).find((r) => !before.has(r)));
558
+ }
559
+
394
560
  /**
395
561
  * Mouse and pen seek on PRESS, like every scrubber. Remembers the
396
562
  * pointer type for the click that follows.
@@ -416,7 +582,8 @@ export class WaveformSounds {
416
582
 
417
583
  /**
418
584
  * Keys on the list: `/` focuses search; ↑/↓/Home/End move between rows
419
- * (auditioning while something plays); ←/→ seek the playing row.
585
+ * (auditioning while something plays); ←/→ seek the playing row, and on
586
+ * its seek slider Home/End seek to the start/end.
420
587
  * @internal
421
588
  */
422
589
  _onKey(e: KeyboardEvent): void {
@@ -430,7 +597,10 @@ export class WaveformSounds {
430
597
  if (!row) return;
431
598
 
432
599
  const index = Number(row.dataset.wsIndex);
433
- const seek = seekTarget(this.progress, e.key);
600
+ // On the seek slider, Home / End seek (the slider pattern) rather
601
+ // than jump to the first / last row.
602
+ const edge = (e.target as Element).closest('.ws-wave') ? sliderEdgeTarget(e.key) : null;
603
+ const seek = edge ?? seekTarget(this.progress, e.key);
434
604
  if (seek !== null) {
435
605
  if (index !== this.currentIndex || !this.engine) return;
436
606
  e.preventDefault();
@@ -438,13 +608,35 @@ export class WaveformSounds {
438
608
  return;
439
609
  }
440
610
 
441
- const rows = visibleRows(this.$.list);
442
- const target = rowTarget(e.key, rows.indexOf(row), rows.length);
611
+ // Positions among the sounds the page shows, rows or not: ↓ past
612
+ // the last row rendered (paging off) renders the next ones.
613
+ const shown = this._shown ?? [];
614
+ const target = rowTarget(e.key, shown.indexOf(this.sounds[index]), Math.min(shown.length, this.limit));
443
615
  if (target === null) return;
444
616
  e.preventDefault();
445
617
  if (target === 'search') { this.$.search?.focus(); return; }
446
- this._focusRow(rows[target]);
447
- if (this.options.arrowAudition && this.playing) this.play(Number(rows[target].dataset.wsIndex));
618
+ this._focusRow(this._reveal(target));
619
+ if (this.options.arrowAudition && this.playing) this.play(this._index.get(shown[target]));
620
+ }
621
+
622
+ /**
623
+ * The row at position `pos` of the matching sounds, revealing it first:
624
+ * past the page, the page grows to it (as `next()` always did); with
625
+ * paging off, rows are rendered up to it.
626
+ * @internal
627
+ */
628
+ _reveal(pos: number): HTMLElement | undefined {
629
+ const sound = this._shown?.[pos];
630
+ if (!sound) return undefined;
631
+ const limit = limitToReveal(this.limit, pos);
632
+ if (limit !== this.limit) {
633
+ this.limit = limit;
634
+ this._apply();
635
+ } else if (this.limit === Infinity && pos >= this._budget) {
636
+ this._budget = budgetToReveal(this._budget, pos);
637
+ this._layout();
638
+ }
639
+ return this.rows[this._index.get(sound)!];
448
640
  }
449
641
 
450
642
  /**
@@ -478,11 +670,19 @@ export class WaveformSounds {
478
670
  _observe(): void {
479
671
  if (this.render.player !== 'inline' || typeof window === 'undefined') return;
480
672
  this._drawn = new Set();
673
+ this._dirty = new Set();
481
674
  if ('IntersectionObserver' in window) {
675
+ // Rows near the viewport. A row is drawn the first time it comes
676
+ // near, and again only if it went stale (a resize or a theme flip
677
+ // while it was away): a long list scrolled back and forth
678
+ // repaints nothing it doesn't have to.
679
+ this._onScreen = new Set();
482
680
  this._io = new IntersectionObserver((entries) => {
483
681
  for (const entry of entries) {
484
- if (!entry.isIntersecting) continue;
485
682
  const i = Number((entry.target as HTMLElement).dataset.wsIndex);
683
+ if (!entry.isIntersecting) { this._onScreen!.delete(i); continue; }
684
+ this._onScreen!.add(i);
685
+ if (this._drawn!.has(i) && !this._dirty!.has(i)) continue;
486
686
  this._drawn!.add(i);
487
687
  this._drawRow(i);
488
688
  }
@@ -501,31 +701,51 @@ export class WaveformSounds {
501
701
  });
502
702
  this._ro.observe(this.$.list);
503
703
  }
504
- const refresh = () => requestAnimationFrame(() => { this._resolveColors(); this._redrawAll(); });
704
+ let queued = 0;
705
+ const refresh = () => {
706
+ if (queued) return;
707
+ // A style change on an ancestor can be anything (an animation,
708
+ // a layout tweak): redraw only if the canvas colours moved.
709
+ queued = requestAnimationFrame(() => { queued = 0; if (this._resolveColors()) this._redrawAll(); });
710
+ };
711
+ // A theme can flip on ANY ancestor (a dark section, a themed card,
712
+ // a framework's root div), not just <html> / <body>. The container
713
+ // itself counts for class and theme, not style: the runtime writes
714
+ // --ws-surface there.
505
715
  this._mo = new MutationObserver(refresh);
506
- const watch = {attributes: true, attributeFilter: ['class', 'data-theme', 'data-color-scheme', 'style']};
507
- this._mo.observe(document.documentElement, watch);
508
- if (document.body) this._mo.observe(document.body, watch);
509
- try {
510
- window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', refresh, {signal: this._ctl.signal});
511
- } catch { /* no matchMedia */ }
716
+ this._mo.observe(this.container, {attributes: true, attributeFilter: ['class', 'data-theme', 'data-color-scheme']});
717
+ for (const node of ancestorsOf(this.container)) {
718
+ this._mo.observe(node, {attributes: true, attributeFilter: ['class', 'data-theme', 'data-color-scheme', 'style']});
719
+ }
720
+ for (const query of ['(prefers-color-scheme: dark)', '(forced-colors: active)']) {
721
+ try {
722
+ window.matchMedia(query).addEventListener('change', refresh, {signal: this._ctl.signal});
723
+ } catch { /* no matchMedia */ }
724
+ }
512
725
  }
513
726
 
514
727
  /**
515
- * Resolve the canvas colours (options, else the CSS custom properties)
516
- * and keep `--ws-surface` current unless the site set it.
728
+ * Resolve the canvas colours (options, else the CSS custom properties;
729
+ * system colours under forced colours) and keep `--ws-surface` current
730
+ * unless the site set it.
731
+ * @returns Whether the canvas colours changed.
517
732
  * @internal
518
733
  */
519
- _resolveColors(): void {
734
+ _resolveColors(): boolean {
735
+ const before = this.colors;
520
736
  if (this._autoSurface || !getComputedStyle(this.container).getPropertyValue('--ws-surface').trim()) {
521
737
  this._autoSurface = true;
522
738
  this.container.style.removeProperty('--ws-surface');
523
739
  this.container.style.setProperty('--ws-surface', pageSurface(this.container));
524
740
  }
741
+ // Forced colours: the system's own text and highlight, whatever the
742
+ // options or the CSS say (as every other part of the list does).
743
+ const forced = forcedColors();
525
744
  this.colors = {
526
- wave: this.options.waveformColor || resolveCssColor(this.container, 'var(--ws-wave-color)') || 'rgba(128,128,128,.5)',
527
- progress: this.options.progressColor || resolveCssColor(this.container, 'var(--ws-progress-color)') || 'currentColor',
745
+ wave: (forced ? resolveCssColor(this.container, 'CanvasText') : this.options.waveformColor || resolveCssColor(this.container, 'var(--ws-wave-color)')) || 'rgba(128,128,128,.5)',
746
+ progress: (forced ? resolveCssColor(this.container, 'Highlight') : this.options.progressColor || resolveCssColor(this.container, 'var(--ws-progress-color)')) || 'currentColor',
528
747
  };
748
+ return !before || before.wave !== this.colors.wave || before.progress !== this.colors.progress;
529
749
  }
530
750
 
531
751
  /**
@@ -536,7 +756,10 @@ export class WaveformSounds {
536
756
  if (this.render.player !== 'inline' || index == null || !this._drawn?.has(index)) return;
537
757
  const row = this.rows[index];
538
758
  const canvas = row?.querySelector('canvas');
539
- if (!canvas || row.hidden) return;
759
+ if (!canvas) return;
760
+ // Out of the list (filtered, or past the page): draw it when it is back.
761
+ if (!row.isConnected) { this._dirty?.add(index); return; }
762
+ this._dirty?.delete(index);
540
763
  const gap = Number(this.options.barGap);
541
764
  drawRowWaveform(canvas, this.sounds[index].peaks, index === this.currentIndex ? this.progress : 0, {
542
765
  style: this.options.waveformStyle,
@@ -548,11 +771,17 @@ export class WaveformSounds {
548
771
  }
549
772
 
550
773
  /**
551
- * Redraw every row drawn so far.
774
+ * After a resize or a theme flip: redraw the rows on screen now, and
775
+ * mark the rest stale — each is redrawn when it scrolls back in. (With
776
+ * 1000 rows drawn, redrawing them all took ~0.4s in Chrome and ~1.9s in
777
+ * WebKit per resize step.)
552
778
  * @internal
553
779
  */
554
780
  _redrawAll(): void {
555
- this._drawn?.forEach((i) => this._drawRow(i));
781
+ this._drawn?.forEach((i) => {
782
+ if (this._onScreen && !this._onScreen.has(i)) this._dirty!.add(i);
783
+ else this._drawRow(i);
784
+ });
556
785
  }
557
786
 
558
787
  /* ── Filters in the address ───────────────────────────────────────── */
@@ -564,7 +793,8 @@ export class WaveformSounds {
564
793
  _readUrl(): void {
565
794
  const keys = urlKeys(this.options.urlState);
566
795
  if (!keys || typeof location === 'undefined') return;
567
- const {filter, sort} = readUrlState(location.search, keys, facets(this.sounds), this._sorts);
796
+ const f = this._facets!;
797
+ const {filter, sort} = readUrlState(location.search, keys, {...f, bpm: bpmExtent(f.bpm)}, this._sorts, this.render);
568
798
  (this as Writable<WaveformSounds>).filter = {...this.filter, ...filter};
569
799
  if (sort) { (this as Writable<WaveformSounds>).sortBy = sort as SoundsSort; this._sortSet = true; }
570
800
  }
@@ -589,7 +819,29 @@ export class WaveformSounds {
589
819
 
590
820
  /** The sounds that pass the filter, in the current sort order. */
591
821
  get visible(): Sound[] {
592
- return sortSounds(this.sounds.filter((s) => matches(s, this.filter)), this.sortBy);
822
+ // Laid out by the last _apply(), which runs on every filter or sort
823
+ // change; computed afresh only before the list is built.
824
+ return [...(this._shown ?? this._match())];
825
+ }
826
+
827
+ /**
828
+ * Filter and sort the sounds now.
829
+ * @internal
830
+ */
831
+ _match(): Sound[] {
832
+ return sortSounds(this.sounds.filter((s) => matches(s, this.filter, this.render)), this.sortBy);
833
+ }
834
+
835
+ /**
836
+ * A key filter in the list's own spelling: with enharmonic keys merged,
837
+ * `A#m` on a list whose entry is `Bbm` becomes `Bbm` (so the menu and
838
+ * the address show the entry). A key the list doesn't have stays as
839
+ * given (it matches nothing, as before).
840
+ * @internal
841
+ */
842
+ _keyEntry(key: string | undefined): string {
843
+ const k = normalizeKey(key);
844
+ return (this._facets && keyEntry(k, this._facets.keys, this.render.mergeEnharmonicKeys)) || k;
593
845
  }
594
846
 
595
847
  /**
@@ -603,9 +855,11 @@ export class WaveformSounds {
603
855
  setFilter(patch: Partial<SoundsFilter>): void;
604
856
  setFilter(patch: Partial<SoundsFilter> = {}): void {
605
857
  (this as Writable<WaveformSounds>).filter = {...this.filter, ...patch};
858
+ if (patch.key) this.filter.key = this._keyEntry(patch.key);
606
859
  this.limit = this._pageSize();
860
+ this._budget = this._firstBudget();
607
861
  this._syncControls();
608
- this._apply({resort: false});
862
+ this._apply();
609
863
  }
610
864
 
611
865
  /** Reset every filter (the sort stays). */
@@ -618,14 +872,14 @@ export class WaveformSounds {
618
872
  this._sortSet = true;
619
873
  (this as Writable<WaveformSounds>).sortBy = SORTS.includes(by) ? by : 'default';
620
874
  this.menus?.setValue('sort', this.sortBy);
621
- this._apply({resort: true});
875
+ this._apply();
622
876
  }
623
877
 
624
878
  /** Reveal the next page of results. */
625
879
  showMore(): void {
626
880
  if (this.limit === Infinity) return;
627
881
  this.limit += this.render.pageSize;
628
- this._apply({resort: false});
882
+ this._apply();
629
883
  }
630
884
 
631
885
  /**
@@ -636,6 +890,16 @@ export class WaveformSounds {
636
890
  return this.render.pageSize > 0 ? this.render.pageSize : Infinity;
637
891
  }
638
892
 
893
+ /**
894
+ * Paging off: the rows a list (or a new filter) starts with — a chunk,
895
+ * more as the list scrolls (see `_watchEnd`); all of them where nothing
896
+ * can tell it scrolled (no IntersectionObserver).
897
+ * @internal
898
+ */
899
+ _firstBudget(): number {
900
+ return typeof IntersectionObserver === 'undefined' ? Infinity : RENDER_CHUNK;
901
+ }
902
+
639
903
  /**
640
904
  * Show the current filter and sort in the controls (they can be set from
641
905
  * code or the address, not only by the controls themselves).
@@ -678,28 +942,27 @@ export class WaveformSounds {
678
942
  }
679
943
 
680
944
  /**
681
- * Lay the rows out for the current filter, sort and page: order, hide,
945
+ * Lay the list out for the current filter, sort and page: its rows,
682
946
  * "Show more", the empty state and the count. Then report it.
683
- *
684
- * @param opts - Reorder the rows even if the sort
685
- * hasn't changed.
686
947
  * @internal
687
948
  */
688
- _apply({resort}: {resort: boolean}): void {
949
+ _apply(): void {
689
950
  const $ = this.$;
690
951
  if (!$) return;
691
- if (resort || this.sortBy !== this._lastSort) {
692
- orderRows($.list, sortSounds(this.sounds, this.sortBy).map((s) => this.rows[this.sounds.indexOf(s)]));
693
- this._lastSort = this.sortBy;
694
- }
695
- const shown = this.visible;
696
- const {visible, remaining} = pageWindow(shown, this.limit);
697
- this.sounds.forEach((s, i) => { if (this.rows[i]) this.rows[i].hidden = !visible.has(s); });
952
+ const shown = this._match();
953
+ this._shown = shown;
954
+ this._layout();
955
+ const remaining = shown.length - Math.min(shown.length, this.limit);
698
956
  if ($.more) {
699
957
  $.more.hidden = remaining <= 0;
700
958
  $.more.textContent = fill(this.strings.showMore, {count: Math.min(remaining, this.render.pageSize || remaining)});
701
959
  }
702
- if ($.empty) $.empty.hidden = shown.length > 0;
960
+ if ($.empty) {
961
+ $.empty.hidden = shown.length > 0;
962
+ // No sounds at all: nothing matches because there is nothing, and
963
+ // there is no filter to clear.
964
+ if (!this.sounds.length && $.empty.textContent !== this.strings.noSounds) $.empty.textContent = this.strings.noSounds;
965
+ }
703
966
  if ($.count) $.count.textContent = countText(shown.length, this.sounds.length, this.strings);
704
967
  // Nothing played yet: keep the cued sound one the list still shows.
705
968
  if (this._cued && !this.playing) this._cueFirst();
@@ -708,6 +971,52 @@ export class WaveformSounds {
708
971
  this.options.onFilter?.(shown, this);
709
972
  }
710
973
 
974
+ /**
975
+ * Put exactly the rows shown in the list, in order: the page (or with
976
+ * paging off the rows rendered so far) of the matching sounds. Rows are
977
+ * rendered the first time they are shown; rows that stop being shown
978
+ * leave the DOM (kept, with their drawing, for when they come back).
979
+ * @internal
980
+ */
981
+ _layout(): void {
982
+ const $ = this.$, shown = this._shown!;
983
+ const count = renderedCount(shown.length, this.limit, this._budget);
984
+ const focused = $.list.contains(document.activeElement) ? document.activeElement as HTMLElement : null;
985
+ const rows = this._rowsFor(shown.slice(0, count).map((sound) => this._index.get(sound)!));
986
+ layoutRows($.list, rows);
987
+ // A re-sort moves rows, and a moved element loses focus: give it back.
988
+ if (focused?.isConnected && document.activeElement !== focused) focused.focus({preventScroll: true});
989
+ if (!this._io && this._drawn) for (const row of rows) this._drawRow(Number(row.dataset.wsIndex));
990
+ // The Tab stop never sits on a row that left the list; and if focus
991
+ // was in it, focus follows the stop instead of falling to <body>.
992
+ if (!this._active || !this._active.isConnected) {
993
+ const first = rows[0];
994
+ if (first) {
995
+ this._rove(first);
996
+ if (focused && !focused.isConnected) this._focusRowQuietly(first);
997
+ } else if (this._active) { this._rowStops(this._active, false); this._active = null; }
998
+ }
999
+ // Paging off and more to render: the next chunk when the last row
1000
+ // nears the viewport.
1001
+ this._watchEnd(count < Math.min(shown.length, this.limit) ? rows[rows.length - 1] : null);
1002
+ }
1003
+
1004
+ /**
1005
+ * Render the next chunk of rows once `row` (the last one rendered) comes
1006
+ * within ~1200px of the viewport; nothing to watch for `null`.
1007
+ * @internal
1008
+ */
1009
+ _watchEnd(row: HTMLElement | null | undefined): void {
1010
+ this._endIo?.disconnect();
1011
+ if (!row || typeof IntersectionObserver === 'undefined') return;
1012
+ this._endIo ??= new IntersectionObserver((entries) => {
1013
+ if (this.destroyed || !entries.some((entry) => entry.isIntersecting)) return;
1014
+ this._budget += RENDER_CHUNK;
1015
+ this._layout();
1016
+ }, {rootMargin: '0px 0px 1200px 0px'});
1017
+ this._endIo.observe(row);
1018
+ }
1019
+
711
1020
  /* ── Playback ─────────────────────────────────────────────────────── */
712
1021
 
713
1022
  /**
@@ -715,32 +1024,41 @@ export class WaveformSounds {
715
1024
  * target means the current sound, else the first visible one.
716
1025
  *
717
1026
  * @param target
718
- * @returns
719
1027
  * @internal
720
1028
  */
721
1029
  _indexOf(target?: number | string | Sound | null): number | null {
722
- if (target == null) return this.currentIndex ?? (this.visible[0] ? this.sounds.indexOf(this.visible[0]) : null);
1030
+ if (target == null) {
1031
+ if (this.currentIndex != null) return this.currentIndex;
1032
+ const first = (this._shown ?? this._match())[0];
1033
+ return first ? this.sounds.indexOf(first) : null;
1034
+ }
723
1035
  if (typeof target === 'number') return this.sounds[target] ? target : null;
724
- const i = typeof target === 'object' ? this.sounds.indexOf(target) : this.sounds.findIndex((s) => s.id === String(target));
1036
+ const i = typeof target === 'object' ? (this._index.get(target) ?? this.sounds.indexOf(target)) : this.sounds.findIndex((s) => s.id === String(target));
725
1037
  return i >= 0 ? i : null;
726
1038
  }
727
1039
 
728
1040
  /**
729
1041
  * The WaveformPlayer class: `playerClass`, else the page's global.
730
- * @returns
731
1042
  * @internal
732
1043
  */
733
1044
  _playerClass(): EngineClass | null {
734
1045
  return (this.options.playerClass || (typeof window !== 'undefined' ? (window as any).WaveformPlayer : null) || null) as EngineClass | null;
735
1046
  }
736
1047
 
1048
+ /**
1049
+ * The engine as the list drives it (fields the core keeps internal).
1050
+ * @internal
1051
+ */
1052
+ _eng(): Engine | null {
1053
+ return this.engine as unknown as Engine | null;
1054
+ }
1055
+
737
1056
  /**
738
1057
  * The element the engine mounts into: a child of the engine slot, never
739
1058
  * the slot itself. WaveformPlayer resets its container's `className`,
740
1059
  * which would strip `ws-engine--strip` (and with it the docked styling).
741
1060
  * Made here rather than in the markup so server-rendered HTML from any
742
1061
  * version works.
743
- * @returns
744
1062
  * @internal
745
1063
  */
746
1064
  _engineMount(): HTMLElement {
@@ -760,21 +1078,23 @@ export class WaveformSounds {
760
1078
  * @internal
761
1079
  */
762
1080
  _ensureEngine(): Engine | null {
763
- if (this.engine) return this.engine as Engine;
1081
+ if (this.engine) return this._eng();
764
1082
  const Player = this._playerClass();
765
1083
  if (!Player) {
766
1084
  console.error(`${LOG} @arraypress/waveform-player is required: load it before playing (or pass playerClass).`);
767
1085
  return null;
768
1086
  }
769
- (this as Writable<WaveformSounds>).engine = new Player(this._engineMount(), engineOptions(this.options.playerOptions, this.render.player, {
1087
+ const options = engineOptions(this.options.playerOptions, this.render.player, {
770
1088
  onLoad: () => this._onEngineLoad(),
771
1089
  onPlay: () => this._setPlaying(true),
772
1090
  onPause: () => this._setPlaying(false),
773
1091
  onEnd: () => this._onEnd(),
774
1092
  onTimeUpdate: (time: number, duration: number) => this._onTime(time, duration),
775
1093
  onError: (err: unknown) => this._onEngineError(err),
776
- }));
777
- return this.engine as Engine;
1094
+ });
1095
+ this._preload = options.preload;
1096
+ (this as Writable<WaveformSounds>).engine = new Player(this._engineMount(), options) as unknown as WaveformPlayer;
1097
+ return this._eng();
778
1098
  }
779
1099
 
780
1100
  /**
@@ -803,32 +1123,46 @@ export class WaveformSounds {
803
1123
  if (previous != null) this._paintRow(previous);
804
1124
  this._paintRow(index);
805
1125
  const sound = this.sounds[index];
806
- engine.loadTrack(sound.url, sound.title, sound.type || null, engineTrack(sound, this.render.player, true));
1126
+ engine.loadTrack(sound.url, sound.title, sound.type || null, engineTrack(sound, this.render.player, true, this._preload));
807
1127
  }
808
1128
 
809
1129
  /**
810
1130
  * Strip layout: load the first sound the list shows into the docked
811
1131
  * player WITHOUT playing it, so the player shows a title and waveform
812
1132
  * (and its play button plays that sound) instead of an empty frame.
813
- * Only metadata is fetched — the browser default for any `<audio>`.
1133
+ * Nothing is fetched (`preload: 'none'`): the player shows the title,
1134
+ * length and peaks from the data, and the audio loads on play — a filter
1135
+ * change re-cues, and each cue used to fetch a file's metadata.
814
1136
  * The row isn't marked current until it plays.
815
1137
  * @internal
816
1138
  */
817
1139
  _cueFirst(): void {
818
- const engine = this.engine as Engine | null;
819
- const first = this.visible[0];
1140
+ const engine = this._eng();
1141
+ const first = (this._shown ?? this._match())[0];
820
1142
  if (!engine || !first) return;
821
1143
  const index = this.sounds.indexOf(first);
822
1144
  if (index === this.currentIndex) return;
823
1145
  this.currentIndex = index;
824
1146
  this.progress = 0;
825
1147
  this._cued = true;
826
- engine.loadTrack(first.url, first.title, first.type || null, engineTrack(first, 'strip', false));
1148
+ // Firefox fetches a source set in the same task as a script's
1149
+ // load(), whatever `preload` says — and the core's loadTrack() resets
1150
+ // the element with load() before setting the new source. Nothing
1151
+ // plays yet, so that reset can go: setting `src` (which the core
1152
+ // does too) restarts the element's load on its own.
1153
+ const audio = engine.audio;
1154
+ const shim = audio && typeof audio.load === 'function';
1155
+ if (shim) audio!.load = () => {};
1156
+ try {
1157
+ engine.loadTrack(first.url, first.title, first.type || null, engineTrack(first, 'strip', false, 'none'));
1158
+ } finally {
1159
+ if (shim) delete (audio as Partial<HTMLAudioElement>).load;
1160
+ }
827
1161
  }
828
1162
 
829
1163
  /** Pause the current sound. */
830
1164
  pause(): void {
831
- if (this.engine && this.playing) (this.engine as Engine).pause();
1165
+ if (this.engine && this.playing) this._eng()!.pause();
832
1166
  }
833
1167
 
834
1168
  /**
@@ -857,13 +1191,12 @@ export class WaveformSounds {
857
1191
  * @internal
858
1192
  */
859
1193
  _step(dir: 1 | -1): boolean {
860
- const shown = this.visible;
1194
+ const shown = this._shown ?? this._match();
861
1195
  // A cued sound counts as nothing played: next() starts with it.
862
1196
  const at = this.currentIndex == null || this._cued ? -1 : shown.indexOf(this.sounds[this.currentIndex]);
863
1197
  const target = shown[at + dir];
864
1198
  if (!target) return false;
865
- const limit = limitToReveal(this.limit, at + dir);
866
- if (limit !== this.limit) { this.limit = limit; this._apply({resort: false}); }
1199
+ if (this.$) this._reveal(at + dir);
867
1200
  this.play(this.sounds.indexOf(target));
868
1201
  return true;
869
1202
  }
@@ -886,7 +1219,7 @@ export class WaveformSounds {
886
1219
  */
887
1220
  _setLoop(on: boolean): void {
888
1221
  this.$?.loop?.setAttribute('aria-pressed', String(on));
889
- if ((this.engine as Engine | null)?.audio) (this.engine as Engine).audio!.loop = this._repeats();
1222
+ if (this._eng()?.audio) this._eng()!.audio!.loop = this._repeats();
890
1223
  }
891
1224
 
892
1225
  /**
@@ -907,29 +1240,31 @@ export class WaveformSounds {
907
1240
  */
908
1241
  _seekRow(index: number, fraction: number): void {
909
1242
  if (index !== this.currentIndex || !this.engine) { this.play(index, {at: fraction}); return; }
910
- const duration = (this.engine as Engine).audio?.duration;
1243
+ const duration = this._eng()!.audio?.duration;
911
1244
  if (!Number.isFinite(duration) || duration! <= 0) { this._pendingSeek = fraction; return; }
912
- (this.engine as Engine).seekTo(fraction * duration!);
1245
+ this._eng()!.seekTo(fraction * duration!);
913
1246
  this.progress = fraction;
914
1247
  this._paintRow(index);
915
- if (!this.playing) (this.engine as Engine).play();
1248
+ this._paintSlider();
1249
+ if (!this.playing) this._eng()!.play();
916
1250
  }
917
1251
 
918
1252
  /**
919
- * The engine loaded a sound: apply the loop, borrow decoded peaks for a
1253
+ * The engine loaded a sound: clear an earlier failure, apply the loop, borrow decoded peaks for a
920
1254
  * row that had none, and land a pending seek.
921
1255
  * @internal
922
1256
  */
923
1257
  _onEngineLoad(): void {
924
- if ((this.engine as Engine | null)?.audio) (this.engine as Engine).audio!.loop = this._repeats();
1258
+ if (this.currentIndex != null) this._markFailed(this.currentIndex, false);
1259
+ if (this._eng()?.audio) this._eng()!.audio!.loop = this._repeats();
925
1260
  const sound = this.sounds[this.currentIndex!];
926
- if (sound && !sound.peaks && (this.engine as Engine | null)?.waveformData?.length) {
927
- sound.peaks = resample((this.engine as Engine).waveformData, 96);
1261
+ if (sound && !sound.peaks && this._eng()?.waveformData?.length) {
1262
+ sound.peaks = resample(this._eng()!.waveformData, 96);
928
1263
  this._drawRow(this.currentIndex);
929
1264
  }
930
- const duration = (this.engine as Engine | null)?.audio?.duration;
1265
+ const duration = this._eng()?.audio?.duration;
931
1266
  if (this._pendingSeek != null && Number.isFinite(duration) && duration! > 0) {
932
- (this.engine as Engine).seekTo(this._pendingSeek * duration!);
1267
+ this._eng()!.seekTo(this._pendingSeek * duration!);
933
1268
  this.progress = this._pendingSeek;
934
1269
  this._pendingSeek = null;
935
1270
  }
@@ -944,7 +1279,7 @@ export class WaveformSounds {
944
1279
  if (this._pendingSeek != null) {
945
1280
  const fraction = this._pendingSeek;
946
1281
  this._pendingSeek = null;
947
- (this.engine as Engine).seekTo(fraction * duration);
1282
+ this._eng()!.seekTo(fraction * duration);
948
1283
  return;
949
1284
  }
950
1285
  this.progress = Math.min(Math.max(time / duration, 0), 1);
@@ -952,7 +1287,7 @@ export class WaveformSounds {
952
1287
  this._raf = requestAnimationFrame(() => {
953
1288
  this._raf = 0;
954
1289
  this._drawRow(this.currentIndex);
955
- this.rows[this.currentIndex!]?.querySelector('.ws-wave')?.setAttribute('aria-valuenow', String(Math.round(this.progress * 100)));
1290
+ this._paintSlider();
956
1291
  });
957
1292
  }
958
1293
 
@@ -970,33 +1305,62 @@ export class WaveformSounds {
970
1305
  }
971
1306
 
972
1307
  /**
973
- * A sound failed to load or play: mark its row and report it.
1308
+ * A sound failed to load or play: it isn't playing (no stale "Pause"),
1309
+ * its row is marked until it plays, and the live region says so.
974
1310
  * @internal
975
1311
  */
976
1312
  _onEngineError(err: unknown): void {
977
- this.rows[this.currentIndex!]?.classList.add('is-error');
978
- this._emit('error', {error: err, sound: this.sounds[this.currentIndex!], index: this.currentIndex});
1313
+ const index = this.currentIndex;
1314
+ const sound = index == null ? undefined : this.sounds[index];
1315
+ if (index != null) this._markFailed(index, true);
1316
+ this._setPlaying(false);
1317
+ // A cued sound (strip, nothing played) wasn't asked for: no announcement.
1318
+ if (sound && !this._cued && this.$?.status) this.$.status.textContent = fill(this.strings.playError, {title: sound.title});
1319
+ this._emit('error', {error: err, sound, index});
979
1320
  this.options.onError?.(err, this);
980
1321
  }
981
1322
 
982
1323
  /**
983
- * Record play/pause and repaint. Events fire only on a real change: at a
984
- * natural end the browser fires `pause` then `ended`, and `_onEnd()`
985
- * also settles the state — one pause event, not two.
1324
+ * Record play/pause and repaint, and report what the listener hears.
1325
+ * Events follow the SOUND, not the flag: switching sounds while one plays
1326
+ * (↓ audition, `play(i)`, `next()`, auto-advance) never flips `playing`
1327
+ * in some engines (the media element swaps source without a `pause`),
1328
+ * so the last sound announced is tracked — a different one starting
1329
+ * reports `pause` for the outgoing sound, then `play` for the new one.
1330
+ * At a natural end the browser fires `pause` then `ended`, and `_onEnd()`
1331
+ * settles the state again: one pause event, not two.
986
1332
  * @internal
987
1333
  */
988
1334
  _setPlaying(on: boolean): void {
989
- const changed = this.playing !== on;
990
1335
  (this as Writable<WaveformSounds>).playing = on;
991
1336
  if (on) this._cued = false; // the strip's own button played the cued sound
992
1337
  const index = this.currentIndex;
993
1338
  if (index == null) return;
1339
+ if (on) this._markFailed(index, false); // it plays after all
994
1340
  this._paintRow(index);
995
- if (!changed) return;
1341
+ const was = this._announced ?? null;
1342
+ if (on) {
1343
+ if (was === index) return;
1344
+ if (was != null) this._announce('pause', was);
1345
+ this._announced = index;
1346
+ this._announce('play', index);
1347
+ } else if (was != null) {
1348
+ this._announced = null;
1349
+ this._announce('pause', was);
1350
+ }
1351
+ }
1352
+
1353
+ /**
1354
+ * Report a sound starting or stopping: the live region (on play), the
1355
+ * `waveformsounds:play|pause` event and the `onPlay` / `onPause` callback.
1356
+ * @internal
1357
+ */
1358
+ _announce(type: 'play' | 'pause', index: number): void {
996
1359
  const sound = this.sounds[index];
997
- if (on && this.$.status) this.$.status.textContent = fill(this.strings.nowPlaying, {title: sound.title});
998
- this._emit(on ? 'play' : 'pause', {sound, index});
999
- (on ? this.options.onPlay : this.options.onPause)?.(sound, this);
1360
+ if (!sound) return;
1361
+ if (type === 'play' && this.$?.status) this.$.status.textContent = fill(this.strings.nowPlaying, {title: sound.title});
1362
+ this._emit(type, {sound, index});
1363
+ (type === 'play' ? this.options.onPlay : this.options.onPause)?.(sound, this);
1000
1364
  }
1001
1365
 
1002
1366
  /* ── Row painting ─────────────────────────────────────────────────── */
@@ -1017,22 +1381,72 @@ export class WaveformSounds {
1017
1381
  btn.setAttribute('aria-pressed', String(on));
1018
1382
  btn.setAttribute('aria-label', fill(on ? this.strings.pause : this.strings.play, {title: this.sounds[index].title}));
1019
1383
  }
1384
+ row.classList.toggle('is-error', this._failed.has(index));
1020
1385
  const wave = row.querySelector<HTMLElement>('.ws-wave');
1021
- if (wave) {
1022
- wave.tabIndex = current ? 0 : -1;
1023
- if (!current) wave.setAttribute('aria-valuenow', '0');
1024
- }
1386
+ if (wave) this._paintWave(wave, current, row === this._active, this.sounds[index].title);
1025
1387
  this._drawRow(index);
1026
1388
  }
1027
1389
 
1390
+ /**
1391
+ * A row's waveform: the current sound's is THE seek slider (focusable,
1392
+ * labelled, with a value); every other one is a picture, hidden from
1393
+ * assistive tech and out of the Tab order (a pointer still seeks on it).
1394
+ * So a screen reader meets one slider, not one per row. Since 2.2.0.
1395
+ * @internal
1396
+ */
1397
+ _paintWave(wave: HTMLElement, current: boolean, active: boolean, title: string): void {
1398
+ if (!current) {
1399
+ if (wave.getAttribute('aria-hidden') === 'true' && !wave.hasAttribute('role')) return;
1400
+ for (const name of ['role', 'aria-label', 'aria-valuemin', 'aria-valuemax', 'aria-valuenow', 'aria-valuetext', 'tabindex']) wave.removeAttribute(name);
1401
+ wave.setAttribute('aria-hidden', 'true');
1402
+ return;
1403
+ }
1404
+ wave.removeAttribute('aria-hidden');
1405
+ wave.setAttribute('role', 'slider');
1406
+ wave.setAttribute('aria-label', fill(this.strings.seek, {title}));
1407
+ wave.setAttribute('aria-valuemin', '0');
1408
+ wave.setAttribute('aria-valuemax', '100');
1409
+ if (!wave.hasAttribute('aria-valuenow')) wave.setAttribute('aria-valuenow', String(Math.round(this.progress * 100)));
1410
+ wave.tabIndex = active ? 0 : -1;
1411
+ }
1412
+
1413
+ /**
1414
+ * Record that a sound failed (or played after all), on its row if it
1415
+ * has one; a row rendered later picks it up from `_failed`.
1416
+ * @internal
1417
+ */
1418
+ _markFailed(index: number, failed: boolean): void {
1419
+ if (failed) this._failed.add(index);
1420
+ else this._failed.delete(index);
1421
+ this.rows[index]?.classList.toggle('is-error', failed);
1422
+ }
1423
+
1424
+ /**
1425
+ * The current row's seek slider: its position (0–100) and, for a screen
1426
+ * reader, the time ("0:12 of 0:30").
1427
+ * @internal
1428
+ */
1429
+ _paintSlider(): void {
1430
+ const index = this.currentIndex;
1431
+ const wave = index == null ? null : this.rows[index]?.querySelector('.ws-wave');
1432
+ if (!wave) return;
1433
+ wave.setAttribute('aria-valuenow', String(Math.round(this.progress * 100)));
1434
+ const audio = this._eng()?.audio;
1435
+ const duration = Number.isFinite(audio?.duration) && audio!.duration > 0 ? audio!.duration : this.sounds[index!].duration;
1436
+ if (duration) wave.setAttribute('aria-valuetext', fill(this.strings.seekValue, {time: formatClock(this.progress * duration), duration: formatDuration(duration)}));
1437
+ }
1438
+
1028
1439
  /* ── Events & lifecycle ──────────────────────────────────────────── */
1029
1440
 
1030
1441
  /**
1031
- * Emit a `waveformsounds:<name>` event carrying this instance.
1442
+ * Announce a moment both ways: a `waveformsounds:<name>` event on the
1443
+ * container carrying the details and this instance, then a plain `<name>`
1444
+ * event on the instance.
1032
1445
  * @internal
1033
1446
  */
1034
- _emit(name: string, detail: Record<string, any> = {}): void {
1447
+ _emit(name: keyof WaveformSoundsInstanceEventMap, detail: Record<string, any> = {}): void {
1035
1448
  emit(this.container, name, {...detail, instance: this});
1449
+ this.dispatchEvent(new Event(name));
1036
1450
  }
1037
1451
 
1038
1452
  /** The sound playing (or paused) now, or null. */
@@ -1045,22 +1459,29 @@ export class WaveformSounds {
1045
1459
  * Tear down: listeners, observers, timers and the engine. Markup this
1046
1460
  * instance rendered is restored to what the container held before.
1047
1461
  * ADOPTED (server-rendered) markup is left as it is now — rows may be
1048
- * re-sorted, hidden or marked current — so to start again, re-render it
1049
- * rather than constructing a new instance over it.
1462
+ * re-sorted, hidden or marked current — unless `restore` is set: then it
1463
+ * is put back exactly as the server sent it, ready for a new instance
1464
+ * (what a framework re-mounting the same markup wants).
1465
+ *
1466
+ * @param options
1467
+ * @param options.restore - Put adopted server markup back as it was.
1468
+ * Default false. Since 2.1.0.
1050
1469
  */
1051
- destroy(): void {
1470
+ destroy(options: {restore?: boolean} = {}): void {
1052
1471
  if (this.destroyed) return;
1053
1472
  this.destroyed = true;
1054
1473
  this._ctl.abort();
1055
1474
  this._io?.disconnect();
1475
+ this._endIo?.disconnect();
1056
1476
  this._ro?.disconnect();
1057
1477
  this._mo?.disconnect();
1058
1478
  if (this._raf) cancelAnimationFrame(this._raf);
1059
1479
  clearTimeout(this._urlTimer);
1060
- try { (this.engine as Engine | null)?.destroy(); } catch { /* engine already gone */ }
1480
+ try { this._eng()?.destroy(); } catch { /* engine already gone */ }
1061
1481
  (this as Writable<WaveformSounds>).engine = null;
1062
1482
  this.$?.engine?.querySelector(':scope > [data-ws-engine-mount]')?.remove();
1063
1483
  if (this._originalHTML != null) this.container.innerHTML = this._originalHTML;
1484
+ else if (options.restore && this._adoptedHTML != null) this.container.innerHTML = this._adoptedHTML;
1064
1485
  if (this._addedClasses?.length) this.container.classList.remove(...this._addedClasses);
1065
1486
  if (this._autoSurface) this.container.style.removeProperty('--ws-surface');
1066
1487
  delete this.container.dataset.wsInitialized;
@@ -1088,7 +1509,6 @@ export class WaveformSounds {
1088
1509
  /**
1089
1510
  * The instance on an element (or selector), if any.
1090
1511
  * @param el
1091
- * @returns
1092
1512
  */
1093
1513
  static getInstance(el: Element | string): WaveformSounds | null {
1094
1514
  const node = typeof el === 'string' ? document.querySelector(el) : el;