@arraypress/waveform-sounds 0.3.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +43 -3
  3. package/dist/waveform-sounds-no-autoinit.esm.js +607 -178
  4. package/dist/waveform-sounds-render.esm.js +79 -15
  5. package/dist/waveform-sounds.css +136 -79
  6. package/dist/waveform-sounds.esm.js +611 -181
  7. package/dist/waveform-sounds.js +608 -181
  8. package/dist/waveform-sounds.min.css +1 -1
  9. package/dist/waveform-sounds.min.js +3 -3
  10. package/package.json +36 -33
  11. package/src/css/waveform-sounds.css +136 -79
  12. package/src/js/core/WaveformSounds.ts +1366 -0
  13. package/src/js/core/element.ts +208 -0
  14. package/src/js/core/engine.ts +107 -0
  15. package/src/js/core/{options.js → options.ts} +28 -28
  16. package/src/js/data/{bpm.js → bpm.ts} +27 -17
  17. package/src/js/data/{navigation.js → navigation.ts} +31 -18
  18. package/src/js/data/{sounds.js → sounds.ts} +97 -66
  19. package/src/js/data/url-state.ts +130 -0
  20. package/src/js/dom/colors.ts +86 -0
  21. package/src/js/dom/{draw.js → draw.ts} +16 -17
  22. package/src/js/dom/{menus.js → menus.ts} +70 -55
  23. package/src/js/dom/{rows.js → rows.ts} +15 -17
  24. package/src/js/entry.ts +60 -0
  25. package/src/js/{index.js → index.ts} +7 -3
  26. package/src/js/render/{html.js → html.ts} +16 -12
  27. package/src/js/render/{icons.js → icons.ts} +3 -4
  28. package/src/js/render/{markup.js → markup.ts} +114 -64
  29. package/src/js/render/options.ts +118 -0
  30. package/src/js/render/{strings.js → strings.ts} +18 -16
  31. package/src/js/{render-entry.js → render-entry.ts} +2 -1
  32. package/src/js/shared/{utils.js → utils.ts} +24 -24
  33. package/{index.d.ts → src/js/types.ts} +40 -88
  34. package/types/core/WaveformSounds.d.ts +175 -0
  35. package/types/core/WaveformSounds.d.ts.map +1 -0
  36. package/types/core/element.d.ts +84 -0
  37. package/types/core/element.d.ts.map +1 -0
  38. package/types/core/engine.d.ts +72 -0
  39. package/types/core/engine.d.ts.map +1 -0
  40. package/types/core/options.d.ts +71 -0
  41. package/types/core/options.d.ts.map +1 -0
  42. package/types/data/bpm.d.ts +80 -0
  43. package/types/data/bpm.d.ts.map +1 -0
  44. package/types/data/navigation.d.ts +62 -0
  45. package/types/data/navigation.d.ts.map +1 -0
  46. package/types/data/sounds.d.ts +168 -0
  47. package/types/data/sounds.d.ts.map +1 -0
  48. package/types/data/url-state.d.ts +109 -0
  49. package/types/data/url-state.d.ts.map +1 -0
  50. package/types/dom/colors.d.ts +48 -0
  51. package/types/dom/colors.d.ts.map +1 -0
  52. package/types/dom/draw.d.ts +72 -0
  53. package/types/dom/draw.d.ts.map +1 -0
  54. package/types/dom/menus.d.ts +75 -0
  55. package/types/dom/menus.d.ts.map +1 -0
  56. package/types/dom/rows.d.ts +39 -0
  57. package/types/dom/rows.d.ts.map +1 -0
  58. package/types/entry.d.ts +28 -0
  59. package/types/entry.d.ts.map +1 -0
  60. package/types/index.d.ts +16 -0
  61. package/types/index.d.ts.map +1 -0
  62. package/types/render/html.d.ts +37 -0
  63. package/types/render/html.d.ts.map +1 -0
  64. package/types/render/icons.d.ts +17 -0
  65. package/types/render/icons.d.ts.map +1 -0
  66. package/types/render/markup.d.ts +141 -0
  67. package/types/render/markup.d.ts.map +1 -0
  68. package/types/render/options.d.ts +69 -0
  69. package/types/render/options.d.ts.map +1 -0
  70. package/types/render/strings.d.ts +43 -0
  71. package/types/render/strings.d.ts.map +1 -0
  72. package/types/render-entry.d.ts +8 -0
  73. package/types/render-entry.d.ts.map +1 -0
  74. package/types/shared/utils.d.ts +57 -0
  75. package/types/shared/utils.d.ts.map +1 -0
  76. package/types/types.d.ts +280 -0
  77. package/types/types.d.ts.map +1 -0
  78. package/types/vendor/arraypress-text.d.ts +250 -0
  79. package/dist/waveform-sounds-no-autoinit.cjs +0 -2159
  80. package/dist/waveform-sounds-render.cjs +0 -614
  81. package/dist/waveform-sounds.cjs +0 -2181
  82. package/no-autoinit.d.ts +0 -2
  83. package/render.d.ts +0 -5
  84. package/src/js/core/WaveformSounds.js +0 -993
  85. package/src/js/core/engine.js +0 -57
  86. package/src/js/data/url-state.js +0 -106
  87. package/src/js/dom/colors.js +0 -59
  88. package/src/js/entry.js +0 -25
  89. package/src/js/render/options.js +0 -90
@@ -1,3 +1,4 @@
1
+ "use strict";
1
2
  (() => {
2
3
  // node_modules/@arraypress/text/src/index.js
3
4
  var HTML_ESCAPES = Object.freeze({
@@ -9,13 +10,31 @@
9
10
  });
10
11
  function escapeHtml(input) {
11
12
  if (input === null || input === void 0) return "";
12
- return String(input).replace(/[&<>"']/g, (c) => HTML_ESCAPES[c]);
13
+ return String(input).replace(/[&<>"']/g, (c) => HTML_ESCAPES[
14
+ /** @type {keyof typeof HTML_ESCAPES} */
15
+ c
16
+ ]);
17
+ }
18
+ var NOT_A_WORD = /[^\p{L}\p{N}\p{M}]+/u;
19
+ var COMBINING_MARK = /\p{Mn}/gu;
20
+ var ACCENTS = Object.freeze([
21
+ [768, 879],
22
+ [1425, 1479],
23
+ [1552, 1562],
24
+ [1611, 1631],
25
+ [1648, 1648],
26
+ [6832, 6911],
27
+ [7616, 7679],
28
+ [8400, 8447],
29
+ [65056, 65071]
30
+ ]);
31
+ function isAccent(mark) {
32
+ const point = mark.codePointAt(0) ?? 0;
33
+ return ACCENTS.some(([from, to]) => point >= from && point <= to);
13
34
  }
14
- var NOT_A_WORD = /[^\p{L}\p{N}]+/u;
15
- var COMBINING_MARKS = /\p{Mn}+/gu;
16
35
  function fold(text2) {
17
36
  if (!text2 || typeof text2 !== "string") return "";
18
- return text2.toLowerCase().normalize("NFD").replace(COMBINING_MARKS, "");
37
+ return text2.toLowerCase().normalize("NFD").replace(COMBINING_MARK, (mark) => isAccent(mark) ? "" : mark).normalize("NFC");
19
38
  }
20
39
  function words(text2) {
21
40
  return fold(text2).split(NOT_A_WORD).filter((word) => word !== "");
@@ -53,7 +72,7 @@
53
72
  });
54
73
  }
55
74
 
56
- // src/js/data/sounds.js
75
+ // src/js/data/sounds.ts
57
76
  function encodePeaks(peaks) {
58
77
  if (!Array.isArray(peaks)) return "";
59
78
  let out = "";
@@ -63,12 +82,25 @@
63
82
  }
64
83
  return out;
65
84
  }
85
+ var COMPACT_PREFIX = "wp1:";
86
+ function decodeCompact(body) {
87
+ if (!body || !/^[\w-]+$/.test(body) || body.length % 4 === 1) return null;
88
+ try {
89
+ const bytes = atob(body.replace(/-/g, "+").replace(/_/g, "/"));
90
+ const out = new Array(bytes.length);
91
+ for (let i = 0; i < bytes.length; i++) out[i] = bytes.charCodeAt(i) / 255;
92
+ return out;
93
+ } catch {
94
+ return null;
95
+ }
96
+ }
66
97
  function decodePeaks(value, scale = 1) {
67
98
  if (value == null || value === "") return null;
68
99
  if (typeof value === "string") {
100
+ if (value.startsWith(COMPACT_PREFIX)) return decodeCompact(value.slice(COMPACT_PREFIX.length));
69
101
  if (!/^[0-9a-f]+$/i.test(value) || value.length % 2) return null;
70
102
  const out2 = new Array(value.length / 2);
71
- for (let i = 0; i < out2.length; i++) out2[i] = parseInt(value.substr(i * 2, 2), 16) / 255;
103
+ for (let i = 0; i < out2.length; i++) out2[i] = parseInt(value.slice(i * 2, i * 2 + 2), 16) / 255;
72
104
  return out2;
73
105
  }
74
106
  if (!Array.isArray(value)) return null;
@@ -102,13 +134,18 @@
102
134
  const total = s < 1 ? Math.ceil(s) : Math.floor(s);
103
135
  return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`;
104
136
  }
137
+ function formatClock(seconds) {
138
+ const total = Number.isFinite(seconds) && seconds > 0 ? Math.floor(seconds) : 0;
139
+ const h2 = Math.floor(total / 3600), m = Math.floor(total % 3600 / 60), sec = String(total % 60).padStart(2, "0");
140
+ return h2 ? `${h2}:${String(m).padStart(2, "0")}:${sec}` : `${m}:${sec}`;
141
+ }
105
142
  function parseDuration(value) {
106
143
  if (value == null || value === "") return null;
107
144
  if (typeof value === "number") return Number.isFinite(value) && value >= 0 ? value : null;
108
145
  const str = String(value).trim();
109
146
  if (/^\d+(\.\d+)?$/.test(str)) return Number(str);
147
+ if (!/^\d+(\.\d+)?(:\d+(\.\d+)?)+$/.test(str)) return null;
110
148
  const parts = str.split(":").map(Number);
111
- if (parts.length < 2 || parts.some((n) => !Number.isFinite(n))) return null;
112
149
  return parts.reduce((acc, n) => acc * 60 + n, 0);
113
150
  }
114
151
  function titleFromUrl(url) {
@@ -229,7 +266,7 @@
229
266
  return list.map((x) => x.s);
230
267
  }
231
268
 
232
- // src/js/dom/draw.js
269
+ // src/js/dom/draw.ts
233
270
  function fitCanvas(canvas) {
234
271
  const rect = canvas.getBoundingClientRect();
235
272
  if (!rect.width || !rect.height) return null;
@@ -296,8 +333,9 @@
296
333
  }
297
334
  }
298
335
 
299
- // src/js/core/engine.js
336
+ // src/js/core/engine.ts
300
337
  var CALLBACKS = ["onLoad", "onPlay", "onPause", "onEnd", "onTimeUpdate", "onError"];
338
+ var PER_TRACK = ["duration", "downloadUrl", "downloadName"];
301
339
  function engineOptions(user, layout, handlers) {
302
340
  const site = user || {};
303
341
  const strip = layout === "strip";
@@ -307,8 +345,11 @@
307
345
  preload: "metadata",
308
346
  singlePlay: true,
309
347
  ...site,
310
- audioMode: "self"
348
+ audioMode: "self",
349
+ loop: false,
350
+ showLoop: false
311
351
  };
352
+ for (const name of PER_TRACK) delete options[name];
312
353
  for (const name of CALLBACKS) {
313
354
  options[name] = (...args) => {
314
355
  handlers[name]?.(...args);
@@ -320,8 +361,15 @@
320
361
  function enginePeaks(sound, layout) {
321
362
  return layout === "strip" && sound.waveform || sound.peaks || null;
322
363
  }
364
+ function engineTrack(sound, layout, autoplay, preload) {
365
+ const track = { waveform: enginePeaks(sound, layout), autoplay };
366
+ if (preload) track.preload = preload;
367
+ if (sound.duration != null && sound.duration > 0) track.duration = sound.duration;
368
+ if (sound.download) track.downloadUrl = sound.download;
369
+ return track;
370
+ }
323
371
 
324
- // src/js/dom/menus.js
372
+ // src/js/dom/menus.ts
325
373
  function optionMatches(label, query) {
326
374
  const q = fold(String(query ?? "")).trim();
327
375
  return !q || fold(String(label ?? "")).includes(q);
@@ -357,8 +405,8 @@
357
405
  }
358
406
  /**
359
407
  * Wire every menu, plus closing on an outside press or focus leaving.
360
- * @param {AbortSignal} signal
361
- * @private
408
+ * @param signal
409
+ * @internal
362
410
  */
363
411
  _bind(signal) {
364
412
  const sig = { signal };
@@ -400,7 +448,7 @@
400
448
  * focus in its search field or list. Flips to open over the end edge
401
449
  * when it would overflow the list.
402
450
  *
403
- * @param {HTMLElement} menu
451
+ * @param menu
404
452
  */
405
453
  open(menu) {
406
454
  if (this.openMenu && this.openMenu !== menu) this.close(false);
@@ -420,7 +468,7 @@
420
468
  /**
421
469
  * Close the open menu, if any.
422
470
  *
423
- * @param {boolean} focusButton - Return focus to its button (after a
471
+ * @param focusButton - Return focus to its button (after a
424
472
  * pick or Esc; not after a click elsewhere).
425
473
  */
426
474
  close(focusButton) {
@@ -436,8 +484,8 @@
436
484
  * Show `value` as a menu's choice (button text + `aria-selected`). Used
437
485
  * after a pick and when the filter is changed from code.
438
486
  *
439
- * @param {string} name - 'type' | 'key' | 'sort'.
440
- * @param {string} value
487
+ * @param name - 'type' | 'key' | 'sort'.
488
+ * @param value
441
489
  */
442
490
  setValue(name, value) {
443
491
  const menu = this.menus[name];
@@ -455,7 +503,7 @@
455
503
  /**
456
504
  * Narrow a menu to the options matching the search, and make the first
457
505
  * match active.
458
- * @private
506
+ * @internal
459
507
  */
460
508
  _filter(menu, query) {
461
509
  const p = partsOf(menu);
@@ -470,7 +518,7 @@
470
518
  /**
471
519
  * Mark one option active (`aria-activedescendant`) and scroll it into
472
520
  * the list's view.
473
- * @private
521
+ * @internal
474
522
  */
475
523
  _activate(menu, opt) {
476
524
  const p = partsOf(menu);
@@ -486,7 +534,7 @@
486
534
  }
487
535
  /**
488
536
  * Keys inside an open menu.
489
- * @private
537
+ * @internal
490
538
  */
491
539
  _onKey(e, name, menu) {
492
540
  const p = partsOf(menu);
@@ -522,7 +570,7 @@
522
570
  }
523
571
  /**
524
572
  * A value was chosen: close, then report it.
525
- * @private
573
+ * @internal
526
574
  */
527
575
  _pick(name, value) {
528
576
  this.close(true);
@@ -530,7 +578,7 @@
530
578
  }
531
579
  };
532
580
 
533
- // src/js/shared/utils.js
581
+ // src/js/shared/utils.ts
534
582
  var LOG = "[WaveformSounds]";
535
583
  function clamp(value, min = 0, max = 1) {
536
584
  return Math.min(Math.max(value, min), max);
@@ -542,7 +590,7 @@
542
590
  return !!el && (el.isContentEditable || /^(INPUT|SELECT|TEXTAREA)$/.test(el.tagName));
543
591
  }
544
592
  function emit(target, name, detail) {
545
- const event = new CustomEvent(`waveformsounds:${name}`, { bubbles: true, detail });
593
+ const event = new CustomEvent(`waveformsounds:${name}`, { bubbles: true, composed: true, detail });
546
594
  target.dispatchEvent(event);
547
595
  return event;
548
596
  }
@@ -552,7 +600,7 @@
552
600
  return hash;
553
601
  }
554
602
 
555
- // src/js/data/navigation.js
603
+ // src/js/data/navigation.ts
556
604
  var SEEK_STEP = 0.1;
557
605
  function rowTarget(key, at, count) {
558
606
  if (!count) return null;
@@ -571,7 +619,11 @@
571
619
  }
572
620
  function seekTarget(progress, key) {
573
621
  if (key !== "ArrowRight" && key !== "ArrowLeft") return null;
574
- return clamp(progress + (key === "ArrowRight" ? SEEK_STEP : -SEEK_STEP), 0, 0.999);
622
+ return clamp(progress + (key === "ArrowRight" ? SEEK_STEP : -SEEK_STEP), 0, SEEK_END);
623
+ }
624
+ var SEEK_END = 0.999;
625
+ function sliderEdgeTarget(key) {
626
+ return key === "Home" ? 0 : key === "End" ? SEEK_END : null;
575
627
  }
576
628
  function pageWindow(shown, limit) {
577
629
  const visible = new Set(shown.slice(0, limit));
@@ -581,7 +633,10 @@
581
633
  return pos >= limit ? pos + 1 : limit;
582
634
  }
583
635
 
584
- // src/js/data/bpm.js
636
+ // src/js/data/bpm.ts
637
+ function bpmExtent(range) {
638
+ return range ? { min: Math.floor(range.min), max: Math.ceil(range.max) } : null;
639
+ }
585
640
  function bpmFilterFromRange(lo, hi, extent) {
586
641
  const a = Math.min(lo, hi), b = Math.max(lo, hi);
587
642
  return {
@@ -606,7 +661,7 @@
606
661
  return filter.bpmMin != null && filter.bpmMin !== "" || filter.bpmMax != null && filter.bpmMax !== "";
607
662
  }
608
663
 
609
- // src/js/render/strings.js
664
+ // src/js/render/strings.ts
610
665
  var DEFAULT_STRINGS = {
611
666
  search: "Search sounds",
612
667
  searchPlaceholder: "Search sounds\u2026",
@@ -638,6 +693,7 @@
638
693
  play: "Play {title}",
639
694
  pause: "Pause {title}",
640
695
  seek: "Seek {title}",
696
+ seekValue: "{time} of {duration}",
641
697
  download: "Download {title}",
642
698
  count: "{count} sounds",
643
699
  countOne: "1 sound",
@@ -645,7 +701,10 @@
645
701
  showMore: "Show {count} more",
646
702
  empty: "No sounds match.",
647
703
  clear: "Clear filters",
648
- nowPlaying: "Playing {title}"
704
+ nowPlaying: "Playing {title}",
705
+ playError: "Could not play {title}",
706
+ loadError: "Could not load the sounds.",
707
+ noSounds: "No sounds."
649
708
  };
650
709
  var SORT_LABEL_KEYS = {
651
710
  default: "sortDefault",
@@ -667,7 +726,7 @@
667
726
  return total === 1 ? strings.countOne : fill(strings.count, { count: total });
668
727
  }
669
728
 
670
- // src/js/render/options.js
729
+ // src/js/render/options.ts
671
730
  var FILTERS = ["type", "key", "bpm", "loop"];
672
731
  var COLUMNS = ["type", "bpm", "key", "duration"];
673
732
  var RENDER_DEFAULTS = {
@@ -682,6 +741,15 @@
682
741
  columns: [...COLUMNS],
683
742
  maxTypeChips: 10
684
743
  };
744
+ var RENDER_OPTION_KEYS = [...Object.keys(RENDER_DEFAULTS), "idPrefix", "loop", "strings"];
745
+ function pickRenderOptions(options) {
746
+ const out = {};
747
+ for (const key of RENDER_OPTION_KEYS) {
748
+ const value = options?.[key];
749
+ if (value != null) out[key] = value;
750
+ }
751
+ return out;
752
+ }
685
753
  function defined(obj) {
686
754
  const out = {};
687
755
  for (const k in obj ?? {}) if (obj[k] !== void 0) out[k] = obj[k];
@@ -709,7 +777,7 @@
709
777
  };
710
778
  }
711
779
 
712
- // src/js/core/options.js
780
+ // src/js/core/options.ts
713
781
  var DEFAULT_OPTIONS = {
714
782
  ...RENDER_DEFAULTS,
715
783
  sounds: null,
@@ -722,6 +790,8 @@
722
790
  loop: null,
723
791
  autoAdvance: false,
724
792
  arrowAudition: true,
793
+ // null is "unset" (the container's id, else a hash); the public type,
794
+ // unchanged from 0.3.1, has no null, hence the cast (it emits nothing).
725
795
  idPrefix: null,
726
796
  urlState: false,
727
797
  playerOptions: null,
@@ -799,7 +869,7 @@
799
869
  return out;
800
870
  }
801
871
 
802
- // src/js/render/html.js
872
+ // src/js/render/html.ts
803
873
  var VOID = /* @__PURE__ */ new Set(["input", "br", "img"]);
804
874
  function text(value) {
805
875
  return escapeHtml(value ?? "");
@@ -818,7 +888,7 @@
818
888
  return open + children.flat(Infinity).filter((c) => c != null && c !== false && c !== "").join("") + `</${tag}>`;
819
889
  }
820
890
 
821
- // src/js/render/icons.js
891
+ // src/js/render/icons.ts
822
892
  function icon(path, extraClass = "") {
823
893
  const cls = extraClass ? `ws-icon ${extraClass}` : "ws-icon";
824
894
  return `<svg class="${cls}" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="${path}"/></svg>`;
@@ -833,7 +903,7 @@
833
903
  loop: icon("M17 4l3 3-3 3V8H8a3 3 0 0 0-3 3v1H3v-1a5 5 0 0 1 5-5h9V4zM7 20l-3-3 3-3v2h9a3 3 0 0 0 3-3v-1h2v1a5 5 0 0 1-5 5H7v2z")
834
904
  };
835
905
 
836
- // src/js/render/markup.js
906
+ // src/js/render/markup.ts
837
907
  function idBase(sounds) {
838
908
  const signature = [sounds.length, ...sounds.map((s) => s.url)].join("|");
839
909
  return `ws${hashString(signature).toString(36)}`;
@@ -990,7 +1060,7 @@
990
1060
  placeholder: s.findKey,
991
1061
  options: [{ value: "", label: s.anyKey }, ...f.keys.map((k) => ({ value: k, label: k }))]
992
1062
  }),
993
- plan.bpm && renderBpmMenu({ id, s, range: f.bpm }),
1063
+ plan.bpm && renderBpmMenu({ id, s, range: bpmExtent(f.bpm) }),
994
1064
  plan.loops && renderLoopFilter(s),
995
1065
  plan.sorts.length > 0 && menu("sort", {
996
1066
  label: s.sort,
@@ -1093,13 +1163,32 @@
1093
1163
  list.map((sound, i) => renderRow(sound, i, o, i >= page))
1094
1164
  ) + renderFooter(ctx);
1095
1165
  }
1166
+ function renderOptionAttributes(options = {}) {
1167
+ const set = pickRenderOptions(options);
1168
+ const o = resolveRenderOptions(options);
1169
+ const out = {};
1170
+ for (const key of RENDER_OPTION_KEYS) {
1171
+ if (key === "player" || !(key in set)) continue;
1172
+ const name = `data-${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`;
1173
+ if (key === "strings") {
1174
+ const strings = defined(set.strings);
1175
+ if (Object.keys(strings).length) out[name] = JSON.stringify(strings);
1176
+ } else if (key === "loop" || key === "idPrefix") {
1177
+ out[name] = String(set[key]);
1178
+ } else {
1179
+ const value = o[key];
1180
+ out[name] = Array.isArray(value) ? value.join(",") : String(value);
1181
+ }
1182
+ }
1183
+ return out;
1184
+ }
1096
1185
  function renderSoundsElement(sounds, options = {}, className = "") {
1097
1186
  const o = resolveRenderOptions(options);
1098
1187
  const cls = ["waveform-sounds", `waveform-sounds--${o.player}`, className].filter(Boolean).join(" ");
1099
- return h("div", { class: cls, "data-waveform-sounds": true, "data-player": o.player }, renderSounds(sounds, options));
1188
+ return h("div", { class: cls, "data-waveform-sounds": true, "data-player": o.player, ...renderOptionAttributes(options) }, renderSounds(sounds, options));
1100
1189
  }
1101
1190
 
1102
- // src/js/dom/rows.js
1191
+ // src/js/dom/rows.ts
1103
1192
  var ROW = ":scope > [data-ws-index]";
1104
1193
  function readRows(list) {
1105
1194
  const rows = [...list.querySelectorAll(ROW)].sort((a, b) => Number(a.dataset.wsIndex) - Number(b.dataset.wsIndex));
@@ -1145,7 +1234,7 @@
1145
1234
  list.appendChild(frag);
1146
1235
  }
1147
1236
 
1148
- // src/js/dom/colors.js
1237
+ // src/js/dom/colors.ts
1149
1238
  function parseAlpha(color) {
1150
1239
  const c = String(color ?? "").trim();
1151
1240
  if (!c || c === "transparent") return 0;
@@ -1162,9 +1251,21 @@
1162
1251
  }
1163
1252
  return "#fff";
1164
1253
  }
1254
+ function forcedColors() {
1255
+ try {
1256
+ return typeof matchMedia === "function" && matchMedia("(forced-colors: active)").matches;
1257
+ } catch {
1258
+ return false;
1259
+ }
1260
+ }
1261
+ function ancestorsOf(el) {
1262
+ const out = [];
1263
+ for (let node = el.parentElement || el.getRootNode?.()?.host; node; node = node.parentElement || node.getRootNode?.()?.host) out.push(node);
1264
+ return out;
1265
+ }
1165
1266
  function resolveCssColor(container, value) {
1166
1267
  const probe = document.createElement("span");
1167
- probe.style.cssText = "position:absolute;width:0;height:0;overflow:hidden;visibility:hidden";
1268
+ probe.style.cssText = "position:absolute;width:0;height:0;overflow:hidden;visibility:hidden;forced-color-adjust:none";
1168
1269
  probe.style.color = value;
1169
1270
  container.appendChild(probe);
1170
1271
  const color = getComputedStyle(probe).color;
@@ -1172,15 +1273,23 @@
1172
1273
  return color;
1173
1274
  }
1174
1275
 
1175
- // src/js/data/url-state.js
1276
+ // src/js/data/url-state.ts
1176
1277
  function urlKeys(urlState) {
1177
1278
  if (!urlState) return null;
1178
1279
  const p = typeof urlState === "string" ? `${urlState}-` : "";
1179
1280
  return { q: `${p}q`, type: `${p}type`, key: `${p}key`, bpm: `${p}bpm`, loop: `${p}loop`, sort: `${p}sort` };
1180
1281
  }
1181
1282
  function parseBpmRange(value) {
1182
- const m = String(value ?? "").match(/^(\d*)-(\d*)$/);
1183
- return m && (m[1] || m[2]) ? { bpmMin: m[1], bpmMax: m[2] } : null;
1283
+ const m = String(value ?? "").match(/^(\d+(?:\.\d+)?)?-(\d+(?:\.\d+)?)?$/);
1284
+ if (!m || !(m[1] || m[2])) return null;
1285
+ const lo = m[1] ?? "", hi = m[2] ?? "";
1286
+ return lo && hi && Number(lo) > Number(hi) ? { bpmMin: hi, bpmMax: lo } : { bpmMin: lo, bpmMax: hi };
1287
+ }
1288
+ function bpmRangeWithin(range, extent) {
1289
+ if (!extent) return null;
1290
+ const inside = (v) => v !== "" && Number(v) >= extent.min && Number(v) <= extent.max ? v : "";
1291
+ const out = { bpmMin: inside(range.bpmMin), bpmMax: inside(range.bpmMax) };
1292
+ return out.bpmMin || out.bpmMax ? out : null;
1184
1293
  }
1185
1294
  function formatBpmRange(min, max) {
1186
1295
  const lo = min ?? "", hi = max ?? "";
@@ -1196,7 +1305,8 @@
1196
1305
  if (type && available.types.some((t) => t.name === type)) out.filter.type = type;
1197
1306
  const key = normalizeKey(sp.get(keys.key));
1198
1307
  if (key && available.keys.includes(key)) out.filter.key = key;
1199
- const bpm = parseBpmRange(sp.get(keys.bpm));
1308
+ const parsed = parseBpmRange(sp.get(keys.bpm));
1309
+ const bpm = parsed && available.bpm !== void 0 ? bpmRangeWithin(parsed, available.bpm) : parsed;
1200
1310
  if (bpm) Object.assign(out.filter, bpm);
1201
1311
  const loop = sp.get(keys.loop);
1202
1312
  if (LOOP_FILTERS.includes(loop) && available.loops > 0 && available.oneShots > 0) out.filter.loop = loop;
@@ -1217,23 +1327,25 @@
1217
1327
  return url.href;
1218
1328
  }
1219
1329
 
1220
- // src/js/core/WaveformSounds.js
1330
+ // src/js/core/WaveformSounds.ts
1221
1331
  var NO_FILTER = Object.freeze({ query: "", type: "", key: "", bpmMin: "", bpmMax: "", loop: "" });
1222
1332
  var SEARCH_DELAY = 120;
1223
1333
  var BPM_DELAY = 200;
1224
1334
  var URL_DELAY = 250;
1225
- var WaveformSounds = class _WaveformSounds {
1226
- /** @type {Map<Element, WaveformSounds>} */
1335
+ var WaveformSounds = class _WaveformSounds extends EventTarget {
1336
+ /** Every live instance, by its element. */
1227
1337
  static instances = /* @__PURE__ */ new Map();
1228
1338
  /**
1229
1339
  * @param {HTMLElement|string} container - The element (or a selector).
1230
- * @param {import('../../../index').WaveformSoundsOptions} [options]
1340
+ * @param {WaveformSoundsOptions} [options]
1231
1341
  */
1232
1342
  constructor(container, options = {}) {
1343
+ super();
1233
1344
  const el = typeof container === "string" ? document.querySelector(container) : container;
1234
1345
  if (!el) throw new Error(`${LOG} Container not found: ${container}`);
1235
1346
  this.container = el;
1236
- this.options = mergeOptions(DEFAULT_OPTIONS, options, readDataOptions(el));
1347
+ const data = el._wsOptions?.() ?? readDataOptions(el);
1348
+ this.options = mergeOptions(DEFAULT_OPTIONS, options, data);
1237
1349
  this.options.waveformStyle = this.options.waveformStyle === "bars" ? "bars" : "mirror";
1238
1350
  this.strings = { ...DEFAULT_STRINGS, ...this.options.strings || {} };
1239
1351
  this.render = { ...resolveRenderOptions(this.options), strings: this.strings };
@@ -1256,7 +1368,9 @@
1256
1368
  _WaveformSounds.instances.set(el, this);
1257
1369
  el.dataset.wsInitialized = "true";
1258
1370
  this.ready = Promise.resolve().then(() => this._init()).catch((err) => {
1371
+ if (this.destroyed) return;
1259
1372
  console.error(`${LOG} Failed to initialise:`, err);
1373
+ this._showLoadError();
1260
1374
  this._emit("error", { error: err });
1261
1375
  this.options.onError?.(err, this);
1262
1376
  });
@@ -1265,12 +1379,13 @@
1265
1379
  /**
1266
1380
  * Adopt server-rendered markup or render it (from `sounds` or a fetched
1267
1381
  * manifest), then wire everything up.
1268
- * @private
1382
+ * @internal
1269
1383
  */
1270
1384
  async _init() {
1271
1385
  const el = this.container;
1272
1386
  const adopted = el.querySelector("[data-ws-list]");
1273
1387
  if (adopted) {
1388
+ this._adoptedHTML = el.innerHTML;
1274
1389
  this.sounds = readRows(adopted);
1275
1390
  } else {
1276
1391
  this._originalHTML = el.innerHTML;
@@ -1287,7 +1402,7 @@
1287
1402
  this._resolveColors();
1288
1403
  if (!this._loopSet) this.loop = loopsByDefault(this.options.loop, facets(this.sounds));
1289
1404
  this._setLoop(this.loop);
1290
- this._bpmExtent = facets(this.sounds).bpm;
1405
+ this._bpmExtent = bpmExtent(facets(this.sounds).bpm);
1291
1406
  this._sorts = availableSorts(this.render.sorts, facets(this.sounds));
1292
1407
  if (!this._sortSet) this.sortBy = this._sorts[0] || "default";
1293
1408
  this._readUrl();
@@ -1300,18 +1415,32 @@
1300
1415
  }
1301
1416
  /**
1302
1417
  * The sounds from the `sounds` option, else the `manifest` URL.
1303
- * @returns {Promise<import('../../../index').Sound[]>}
1304
- * @private
1418
+ * @internal
1305
1419
  */
1306
1420
  async _loadSounds() {
1307
1421
  if (this.options.sounds || !this.options.manifest) return normalizeSounds(this.options.sounds || []);
1308
- const res = await fetch(this.options.manifest);
1309
- if (!res.ok) throw new Error(`${LOG} Manifest ${this.options.manifest}: HTTP ${res.status}`);
1310
- return parseManifest(await res.json());
1422
+ const url = this.options.manifest;
1423
+ const res = await fetch(url, { signal: this._ctl.signal });
1424
+ if (!res.ok) throw new Error(`${LOG} Manifest ${url}: HTTP ${res.status}`);
1425
+ const manifest = await res.json();
1426
+ if (!Array.isArray(manifest) && !Array.isArray(manifest?.sounds)) throw new Error(`${LOG} Manifest ${url}: no "sounds" list`);
1427
+ return parseManifest(manifest);
1428
+ }
1429
+ /**
1430
+ * A build that failed (the manifest 404s, isn't JSON, isn't a manifest)
1431
+ * says so where the list would be — unless the container holds the
1432
+ * site's own fallback, which stays. destroy() restores what was there.
1433
+ * @internal
1434
+ */
1435
+ _showLoadError() {
1436
+ const el = this.container;
1437
+ if (this.$ || el.querySelector("*")) return;
1438
+ this._originalHTML ??= el.innerHTML;
1439
+ el.innerHTML = h("p", { class: "ws-empty ws-load-error", role: "alert", "data-ws-load-error": true }, text(this.strings.loadError));
1311
1440
  }
1312
1441
  /**
1313
1442
  * Look up the elements the runtime drives.
1314
- * @private
1443
+ * @internal
1315
1444
  */
1316
1445
  _cacheRefs() {
1317
1446
  const q = (sel) => this.container.querySelector(sel);
@@ -1334,11 +1463,36 @@
1334
1463
  loopFilter: [...this.container.querySelectorAll("[data-ws-loop-filter]")]
1335
1464
  };
1336
1465
  this.rows = indexRows(this.$.list);
1466
+ this._active = null;
1467
+ for (const row of this.rows) if (row) this._rowStops(row, false);
1468
+ }
1469
+ /**
1470
+ * Make a row's own controls (play, download, and the seek slider when it
1471
+ * is the current sound) Tab stops, or not.
1472
+ * @internal
1473
+ */
1474
+ _rowStops(row, on) {
1475
+ const play = row.querySelector(".ws-play");
1476
+ if (play) play.tabIndex = on ? 0 : -1;
1477
+ const dl = row.querySelector(".ws-download");
1478
+ if (dl) dl.tabIndex = on ? 0 : -1;
1479
+ const wave = row.querySelector(".ws-wave");
1480
+ if (wave) wave.tabIndex = on && Number(row.dataset.wsIndex) === this.currentIndex ? 0 : -1;
1481
+ }
1482
+ /**
1483
+ * Move the list's Tab stop to `row` (roving tabindex).
1484
+ * @internal
1485
+ */
1486
+ _rove(row) {
1487
+ if (!row || row === this._active) return;
1488
+ if (this._active) this._rowStops(this._active, false);
1489
+ this._active = row;
1490
+ this._rowStops(row, true);
1337
1491
  }
1338
1492
  /**
1339
1493
  * Every listener. All are removed by `destroy()` through one
1340
1494
  * AbortController.
1341
- * @private
1495
+ * @internal
1342
1496
  */
1343
1497
  _bind() {
1344
1498
  const sig = { signal: this._ctl.signal };
@@ -1347,6 +1501,7 @@
1347
1501
  root.addEventListener("click", (e) => this._onClick(e), sig);
1348
1502
  root.addEventListener("pointerdown", (e) => this._onPointerDown(e), sig);
1349
1503
  root.addEventListener("keydown", (e) => this._onKey(e), sig);
1504
+ $.list.addEventListener("focusin", (e) => this._rove(e.target.closest("[data-ws-index]")), sig);
1350
1505
  let searchTimer = 0, bpmTimer = 0;
1351
1506
  $.search?.addEventListener("input", () => {
1352
1507
  clearTimeout(searchTimer);
@@ -1390,7 +1545,7 @@
1390
1545
  /**
1391
1546
  * Clicks: type chips, loops or one-shots, Show more, Clear, Loop, a touch tap on a waveform
1392
1547
  * (seek), and anywhere else on a row (play/pause).
1393
- * @private
1548
+ * @internal
1394
1549
  */
1395
1550
  _onClick(e) {
1396
1551
  const t = e.target;
@@ -1405,11 +1560,13 @@
1405
1560
  return;
1406
1561
  }
1407
1562
  if (t.closest("[data-ws-more]")) {
1408
- this.showMore();
1563
+ this._showMoreFromButton();
1409
1564
  return;
1410
1565
  }
1411
1566
  if (t.closest("[data-ws-clear]")) {
1412
1567
  this.clearFilters();
1568
+ if (this.$.search) this.$.search.focus();
1569
+ else this._focusRow(visibleRows(this.$.list)[0]);
1413
1570
  return;
1414
1571
  }
1415
1572
  if (t.closest("[data-ws-loop]")) {
@@ -1426,10 +1583,21 @@
1426
1583
  this.toggle(Number(row.dataset.wsIndex));
1427
1584
  this._focusRowQuietly(row);
1428
1585
  }
1586
+ /**
1587
+ * "Show more", pressed: reveal the next page. When that was the last page
1588
+ * the button hides, so focus moves to the first row it revealed rather
1589
+ * than falling to <body>.
1590
+ * @internal
1591
+ */
1592
+ _showMoreFromButton() {
1593
+ const before = new Set(visibleRows(this.$.list));
1594
+ this.showMore();
1595
+ if (this.$.more?.hidden) this._focusRow(visibleRows(this.$.list).find((r) => !before.has(r)));
1596
+ }
1429
1597
  /**
1430
1598
  * Mouse and pen seek on PRESS, like every scrubber. Remembers the
1431
1599
  * pointer type for the click that follows.
1432
- * @private
1600
+ * @internal
1433
1601
  */
1434
1602
  _onPointerDown(e) {
1435
1603
  this._lastPointer = e.pointerType;
@@ -1440,7 +1608,7 @@
1440
1608
  }
1441
1609
  /**
1442
1610
  * Seek (or start) a row's sound where its waveform was pressed.
1443
- * @private
1611
+ * @internal
1444
1612
  */
1445
1613
  _seekAt(wave, clientX) {
1446
1614
  const row = wave.closest("[data-ws-index]");
@@ -1449,8 +1617,9 @@
1449
1617
  }
1450
1618
  /**
1451
1619
  * Keys on the list: `/` focuses search; ↑/↓/Home/End move between rows
1452
- * (auditioning while something plays); ←/→ seek the playing row.
1453
- * @private
1620
+ * (auditioning while something plays); ←/→ seek the playing row, and on
1621
+ * its seek slider Home/End seek to the start/end.
1622
+ * @internal
1454
1623
  */
1455
1624
  _onKey(e) {
1456
1625
  if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey) return;
@@ -1462,7 +1631,8 @@
1462
1631
  const row = e.target.closest?.("[data-ws-index]");
1463
1632
  if (!row) return;
1464
1633
  const index = Number(row.dataset.wsIndex);
1465
- const seek = seekTarget(this.progress, e.key);
1634
+ const edge = e.target.closest(".ws-wave") ? sliderEdgeTarget(e.key) : null;
1635
+ const seek = edge ?? seekTarget(this.progress, e.key);
1466
1636
  if (seek !== null) {
1467
1637
  if (index !== this.currentIndex || !this.engine) return;
1468
1638
  e.preventDefault();
@@ -1482,7 +1652,7 @@
1482
1652
  }
1483
1653
  /**
1484
1654
  * Focus a row's play button.
1485
- * @private
1655
+ * @internal
1486
1656
  */
1487
1657
  _focusRow(row) {
1488
1658
  row?.querySelector(".ws-play")?.focus();
@@ -1493,7 +1663,7 @@
1493
1663
  * on the title or waveform left focus on <body>, and Safari never
1494
1664
  * focuses a clicked button). No scroll jump, and no focus ring: the
1495
1665
  * browser shows none for a focus that follows a pointer.
1496
- * @private
1666
+ * @internal
1497
1667
  */
1498
1668
  _focusRowQuietly(row) {
1499
1669
  const btn = row?.querySelector(".ws-play");
@@ -1503,16 +1673,23 @@
1503
1673
  /**
1504
1674
  * Draw row canvases as they scroll into view; redraw on resize and on
1505
1675
  * theme flips (the canvas can't follow CSS by itself).
1506
- * @private
1676
+ * @internal
1507
1677
  */
1508
1678
  _observe() {
1509
1679
  if (this.render.player !== "inline" || typeof window === "undefined") return;
1510
1680
  this._drawn = /* @__PURE__ */ new Set();
1681
+ this._dirty = /* @__PURE__ */ new Set();
1511
1682
  if ("IntersectionObserver" in window) {
1683
+ this._onScreen = /* @__PURE__ */ new Set();
1512
1684
  this._io = new IntersectionObserver((entries) => {
1513
1685
  for (const entry of entries) {
1514
- if (!entry.isIntersecting) continue;
1515
1686
  const i = Number(entry.target.dataset.wsIndex);
1687
+ if (!entry.isIntersecting) {
1688
+ this._onScreen.delete(i);
1689
+ continue;
1690
+ }
1691
+ this._onScreen.add(i);
1692
+ if (this._drawn.has(i) && !this._dirty.has(i)) continue;
1516
1693
  this._drawn.add(i);
1517
1694
  this._drawRow(i);
1518
1695
  }
@@ -1531,44 +1708,61 @@
1531
1708
  });
1532
1709
  this._ro.observe(this.$.list);
1533
1710
  }
1534
- const refresh = () => requestAnimationFrame(() => {
1535
- this._resolveColors();
1536
- this._redrawAll();
1537
- });
1711
+ let queued = 0;
1712
+ const refresh = () => {
1713
+ if (queued) return;
1714
+ queued = requestAnimationFrame(() => {
1715
+ queued = 0;
1716
+ if (this._resolveColors()) this._redrawAll();
1717
+ });
1718
+ };
1538
1719
  this._mo = new MutationObserver(refresh);
1539
- const watch = { attributes: true, attributeFilter: ["class", "data-theme", "data-color-scheme", "style"] };
1540
- this._mo.observe(document.documentElement, watch);
1541
- if (document.body) this._mo.observe(document.body, watch);
1542
- try {
1543
- window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", refresh, { signal: this._ctl.signal });
1544
- } catch {
1720
+ this._mo.observe(this.container, { attributes: true, attributeFilter: ["class", "data-theme", "data-color-scheme"] });
1721
+ for (const node of ancestorsOf(this.container)) {
1722
+ this._mo.observe(node, { attributes: true, attributeFilter: ["class", "data-theme", "data-color-scheme", "style"] });
1723
+ }
1724
+ for (const query of ["(prefers-color-scheme: dark)", "(forced-colors: active)"]) {
1725
+ try {
1726
+ window.matchMedia(query).addEventListener("change", refresh, { signal: this._ctl.signal });
1727
+ } catch {
1728
+ }
1545
1729
  }
1546
1730
  }
1547
1731
  /**
1548
- * Resolve the canvas colours (options, else the CSS custom properties)
1549
- * and keep `--ws-surface` current unless the site set it.
1550
- * @private
1732
+ * Resolve the canvas colours (options, else the CSS custom properties;
1733
+ * system colours under forced colours) and keep `--ws-surface` current
1734
+ * unless the site set it.
1735
+ * @returns Whether the canvas colours changed.
1736
+ * @internal
1551
1737
  */
1552
1738
  _resolveColors() {
1739
+ const before = this.colors;
1553
1740
  if (this._autoSurface || !getComputedStyle(this.container).getPropertyValue("--ws-surface").trim()) {
1554
1741
  this._autoSurface = true;
1555
1742
  this.container.style.removeProperty("--ws-surface");
1556
1743
  this.container.style.setProperty("--ws-surface", pageSurface(this.container));
1557
1744
  }
1745
+ const forced = forcedColors();
1558
1746
  this.colors = {
1559
- wave: this.options.waveformColor || resolveCssColor(this.container, "var(--ws-wave-color)") || "rgba(128,128,128,.5)",
1560
- progress: this.options.progressColor || resolveCssColor(this.container, "var(--ws-progress-color)") || "currentColor"
1747
+ wave: (forced ? resolveCssColor(this.container, "CanvasText") : this.options.waveformColor || resolveCssColor(this.container, "var(--ws-wave-color)")) || "rgba(128,128,128,.5)",
1748
+ progress: (forced ? resolveCssColor(this.container, "Highlight") : this.options.progressColor || resolveCssColor(this.container, "var(--ws-progress-color)")) || "currentColor"
1561
1749
  };
1750
+ return !before || before.wave !== this.colors.wave || before.progress !== this.colors.progress;
1562
1751
  }
1563
1752
  /**
1564
1753
  * Draw one row's waveform (only once it has been on screen).
1565
- * @private
1754
+ * @internal
1566
1755
  */
1567
1756
  _drawRow(index) {
1568
1757
  if (this.render.player !== "inline" || index == null || !this._drawn?.has(index)) return;
1569
1758
  const row = this.rows[index];
1570
1759
  const canvas = row?.querySelector("canvas");
1571
- if (!canvas || row.hidden) return;
1760
+ if (!canvas) return;
1761
+ if (row.hidden) {
1762
+ this._dirty?.add(index);
1763
+ return;
1764
+ }
1765
+ this._dirty?.delete(index);
1572
1766
  const gap = Number(this.options.barGap);
1573
1767
  drawRowWaveform(canvas, this.sounds[index].peaks, index === this.currentIndex ? this.progress : 0, {
1574
1768
  style: this.options.waveformStyle,
@@ -1579,21 +1773,28 @@
1579
1773
  });
1580
1774
  }
1581
1775
  /**
1582
- * Redraw every row drawn so far.
1583
- * @private
1776
+ * After a resize or a theme flip: redraw the rows on screen now, and
1777
+ * mark the rest stale — each is redrawn when it scrolls back in. (With
1778
+ * 1000 rows drawn, redrawing them all took ~0.4s in Chrome and ~1.9s in
1779
+ * WebKit per resize step.)
1780
+ * @internal
1584
1781
  */
1585
1782
  _redrawAll() {
1586
- this._drawn?.forEach((i) => this._drawRow(i));
1783
+ this._drawn?.forEach((i) => {
1784
+ if (this._onScreen && !this._onScreen.has(i)) this._dirty.add(i);
1785
+ else this._drawRow(i);
1786
+ });
1587
1787
  }
1588
1788
  /* ── Filters in the address ───────────────────────────────────────── */
1589
1789
  /**
1590
1790
  * Apply the filter and sort from the address (`urlState`).
1591
- * @private
1791
+ * @internal
1592
1792
  */
1593
1793
  _readUrl() {
1594
1794
  const keys = urlKeys(this.options.urlState);
1595
1795
  if (!keys || typeof location === "undefined") return;
1596
- const { filter, sort } = readUrlState(location.search, keys, facets(this.sounds), this._sorts);
1796
+ const f = facets(this.sounds);
1797
+ const { filter, sort } = readUrlState(location.search, keys, { ...f, bpm: bpmExtent(f.bpm) }, this._sorts);
1597
1798
  this.filter = { ...this.filter, ...filter };
1598
1799
  if (sort) {
1599
1800
  this.sortBy = sort;
@@ -1603,7 +1804,7 @@
1603
1804
  /**
1604
1805
  * Rewrite the address shortly after a change (replaceState: no history
1605
1806
  * entries).
1606
- * @private
1807
+ * @internal
1607
1808
  */
1608
1809
  _queueUrl() {
1609
1810
  const keys = urlKeys(this.options.urlState);
@@ -1618,14 +1819,15 @@
1618
1819
  /* ── Filtering, sorting, paging ───────────────────────────────────── */
1619
1820
  /** The sounds that pass the filter, in the current sort order. */
1620
1821
  get visible() {
1621
- return sortSounds(this.sounds.filter((s) => matches(s, this.filter)), this.sortBy);
1822
+ return [...this._shown ?? this._match()];
1622
1823
  }
1623
1824
  /**
1624
- * Change the filter (merged into the current one) and re-apply. Back to
1625
- * the first page.
1626
- *
1627
- * @param {Partial<import('../../../index').SoundsFilter>} patch
1825
+ * Filter and sort the sounds now.
1826
+ * @internal
1628
1827
  */
1828
+ _match() {
1829
+ return sortSounds(this.sounds.filter((s) => matches(s, this.filter)), this.sortBy);
1830
+ }
1629
1831
  setFilter(patch = {}) {
1630
1832
  this.filter = { ...this.filter, ...patch };
1631
1833
  this.limit = this._pageSize();
@@ -1636,7 +1838,7 @@
1636
1838
  clearFilters() {
1637
1839
  this.setFilter(NO_FILTER);
1638
1840
  }
1639
- /** @param {import('../../../index').SoundsSort} by */
1841
+ /** @param by */
1640
1842
  setSort(by) {
1641
1843
  this._sortSet = true;
1642
1844
  this.sortBy = SORTS.includes(by) ? by : "default";
@@ -1651,7 +1853,7 @@
1651
1853
  }
1652
1854
  /**
1653
1855
  * Rows per page (Infinity when paging is off).
1654
- * @private
1856
+ * @internal
1655
1857
  */
1656
1858
  _pageSize() {
1657
1859
  return this.render.pageSize > 0 ? this.render.pageSize : Infinity;
@@ -1659,7 +1861,7 @@
1659
1861
  /**
1660
1862
  * Show the current filter and sort in the controls (they can be set from
1661
1863
  * code or the address, not only by the controls themselves).
1662
- * @private
1864
+ * @internal
1663
1865
  */
1664
1866
  _syncControls() {
1665
1867
  const $ = this.$, f = this.filter;
@@ -1681,7 +1883,7 @@
1681
1883
  * Show a BPM filter in its menu: the button label, the panel's readout,
1682
1884
  * the filled part of the track, and which handle sits on top (the one
1683
1885
  * that can still move, when they meet).
1684
- * @private
1886
+ * @internal
1685
1887
  */
1686
1888
  _showBpm(f) {
1687
1889
  const $ = this.$, extent = this._bpmExtent;
@@ -1698,18 +1900,20 @@
1698
1900
  * Lay the rows out for the current filter, sort and page: order, hide,
1699
1901
  * "Show more", the empty state and the count. Then report it.
1700
1902
  *
1701
- * @param {{resort: boolean}} opts - Reorder the rows even if the sort
1903
+ * @param opts - Reorder the rows even if the sort
1702
1904
  * hasn't changed.
1703
- * @private
1905
+ * @internal
1704
1906
  */
1705
1907
  _apply({ resort }) {
1706
1908
  const $ = this.$;
1707
1909
  if (!$) return;
1708
1910
  if (resort || this.sortBy !== this._lastSort) {
1709
- orderRows($.list, sortSounds(this.sounds, this.sortBy).map((s) => this.rows[this.sounds.indexOf(s)]));
1911
+ const index = new Map(this.sounds.map((s, i) => [s, i]));
1912
+ orderRows($.list, sortSounds(this.sounds, this.sortBy).map((s) => this.rows[index.get(s)]));
1710
1913
  this._lastSort = this.sortBy;
1711
1914
  }
1712
- const shown = this.visible;
1915
+ const shown = this._match();
1916
+ this._shown = shown;
1713
1917
  const { visible, remaining } = pageWindow(shown, this.limit);
1714
1918
  this.sounds.forEach((s, i) => {
1715
1919
  if (this.rows[i]) this.rows[i].hidden = !visible.has(s);
@@ -1718,8 +1922,22 @@
1718
1922
  $.more.hidden = remaining <= 0;
1719
1923
  $.more.textContent = fill(this.strings.showMore, { count: Math.min(remaining, this.render.pageSize || remaining) });
1720
1924
  }
1721
- if ($.empty) $.empty.hidden = shown.length > 0;
1925
+ if ($.empty) {
1926
+ $.empty.hidden = shown.length > 0;
1927
+ if (!this.sounds.length && $.empty.textContent !== this.strings.noSounds) $.empty.textContent = this.strings.noSounds;
1928
+ }
1722
1929
  if ($.count) $.count.textContent = countText(shown.length, this.sounds.length, this.strings);
1930
+ if (!this._active || this._active.hidden) {
1931
+ const lost = !!this._active?.contains(document.activeElement);
1932
+ const first = visibleRows($.list)[0];
1933
+ if (first) {
1934
+ this._rove(first);
1935
+ if (lost) this._focusRowQuietly(first);
1936
+ } else if (this._active) {
1937
+ this._rowStops(this._active, false);
1938
+ this._active = null;
1939
+ }
1940
+ }
1723
1941
  if (this._cued && !this.playing) this._cueFirst();
1724
1942
  this._queueUrl();
1725
1943
  this._emit("filter", { visible: shown.length, total: this.sounds.length, filter: { ...this.filter }, sort: this.sortBy });
@@ -1730,32 +1948,40 @@
1730
1948
  * Resolve an index, id or sound to an index in `this.sounds`. No
1731
1949
  * target means the current sound, else the first visible one.
1732
1950
  *
1733
- * @param {number|string|Object} [target]
1734
- * @returns {number|null}
1735
- * @private
1951
+ * @param target
1952
+ * @internal
1736
1953
  */
1737
1954
  _indexOf(target) {
1738
- if (target == null) return this.currentIndex ?? (this.visible[0] ? this.sounds.indexOf(this.visible[0]) : null);
1955
+ if (target == null) {
1956
+ if (this.currentIndex != null) return this.currentIndex;
1957
+ const first = (this._shown ?? this._match())[0];
1958
+ return first ? this.sounds.indexOf(first) : null;
1959
+ }
1739
1960
  if (typeof target === "number") return this.sounds[target] ? target : null;
1740
1961
  const i = typeof target === "object" ? this.sounds.indexOf(target) : this.sounds.findIndex((s) => s.id === String(target));
1741
1962
  return i >= 0 ? i : null;
1742
1963
  }
1743
1964
  /**
1744
1965
  * The WaveformPlayer class: `playerClass`, else the page's global.
1745
- * @returns {Function|null}
1746
- * @private
1966
+ * @internal
1747
1967
  */
1748
1968
  _playerClass() {
1749
1969
  return this.options.playerClass || (typeof window !== "undefined" ? window.WaveformPlayer : null) || null;
1750
1970
  }
1971
+ /**
1972
+ * The engine as the list drives it (fields the core keeps internal).
1973
+ * @internal
1974
+ */
1975
+ _eng() {
1976
+ return this.engine;
1977
+ }
1751
1978
  /**
1752
1979
  * The element the engine mounts into: a child of the engine slot, never
1753
1980
  * the slot itself. WaveformPlayer resets its container's `className`,
1754
1981
  * which would strip `ws-engine--strip` (and with it the docked styling).
1755
1982
  * Made here rather than in the markup so server-rendered HTML from any
1756
1983
  * version works.
1757
- * @returns {HTMLElement}
1758
- * @private
1984
+ * @internal
1759
1985
  */
1760
1986
  _engineMount() {
1761
1987
  const slot = this.$.engine;
@@ -1769,32 +1995,34 @@
1769
1995
  }
1770
1996
  /**
1771
1997
  * Build the engine once (it holds no audio until a play).
1772
- * @returns {Object|null} The engine, or null without a player class.
1773
- * @private
1998
+ * @returns The engine, or null without a player class.
1999
+ * @internal
1774
2000
  */
1775
2001
  _ensureEngine() {
1776
- if (this.engine) return this.engine;
2002
+ if (this.engine) return this._eng();
1777
2003
  const Player = this._playerClass();
1778
2004
  if (!Player) {
1779
2005
  console.error(`${LOG} @arraypress/waveform-player is required: load it before playing (or pass playerClass).`);
1780
2006
  return null;
1781
2007
  }
1782
- this.engine = new Player(this._engineMount(), engineOptions(this.options.playerOptions, this.render.player, {
2008
+ const options = engineOptions(this.options.playerOptions, this.render.player, {
1783
2009
  onLoad: () => this._onEngineLoad(),
1784
2010
  onPlay: () => this._setPlaying(true),
1785
2011
  onPause: () => this._setPlaying(false),
1786
2012
  onEnd: () => this._onEnd(),
1787
2013
  onTimeUpdate: (time, duration) => this._onTime(time, duration),
1788
2014
  onError: (err) => this._onEngineError(err)
1789
- }));
1790
- return this.engine;
2015
+ });
2016
+ this._preload = options.preload;
2017
+ this.engine = new Player(this._engineMount(), options);
2018
+ return this._eng();
1791
2019
  }
1792
2020
  /**
1793
2021
  * Play a sound (by index, id or sound object), or resume the current
1794
2022
  * one. Before the list is built the call waits for it.
1795
2023
  *
1796
- * @param {number|string|Object} [target]
1797
- * @param {{at?: number}} [opts] - `at`: start position 0..1.
2024
+ * @param target
2025
+ * @param opts - `at`: start position 0..1.
1798
2026
  */
1799
2027
  play(target, opts = {}) {
1800
2028
  if (!this.$) {
@@ -1820,34 +2048,44 @@
1820
2048
  if (previous != null) this._paintRow(previous);
1821
2049
  this._paintRow(index);
1822
2050
  const sound = this.sounds[index];
1823
- engine.loadTrack(sound.url, sound.title, sound.type || null, { waveform: enginePeaks(sound, this.render.player), autoplay: true });
2051
+ engine.loadTrack(sound.url, sound.title, sound.type || null, engineTrack(sound, this.render.player, true, this._preload));
1824
2052
  }
1825
2053
  /**
1826
2054
  * Strip layout: load the first sound the list shows into the docked
1827
2055
  * player WITHOUT playing it, so the player shows a title and waveform
1828
2056
  * (and its play button plays that sound) instead of an empty frame.
1829
- * Only metadata is fetched — the browser default for any `<audio>`.
2057
+ * Nothing is fetched (`preload: 'none'`): the player shows the title,
2058
+ * length and peaks from the data, and the audio loads on play — a filter
2059
+ * change re-cues, and each cue used to fetch a file's metadata.
1830
2060
  * The row isn't marked current until it plays.
1831
- * @private
2061
+ * @internal
1832
2062
  */
1833
2063
  _cueFirst() {
1834
- const engine = this.engine;
1835
- const first = this.visible[0];
2064
+ const engine = this._eng();
2065
+ const first = (this._shown ?? this._match())[0];
1836
2066
  if (!engine || !first) return;
1837
2067
  const index = this.sounds.indexOf(first);
1838
2068
  if (index === this.currentIndex) return;
1839
2069
  this.currentIndex = index;
1840
2070
  this.progress = 0;
1841
2071
  this._cued = true;
1842
- engine.loadTrack(first.url, first.title, first.type || null, { waveform: enginePeaks(first, "strip"), autoplay: false });
2072
+ const audio = engine.audio;
2073
+ const shim = audio && typeof audio.load === "function";
2074
+ if (shim) audio.load = () => {
2075
+ };
2076
+ try {
2077
+ engine.loadTrack(first.url, first.title, first.type || null, engineTrack(first, "strip", false, "none"));
2078
+ } finally {
2079
+ if (shim) delete audio.load;
2080
+ }
1843
2081
  }
1844
2082
  /** Pause the current sound. */
1845
2083
  pause() {
1846
- if (this.engine && this.playing) this.engine.pause();
2084
+ if (this.engine && this.playing) this._eng().pause();
1847
2085
  }
1848
2086
  /**
1849
2087
  * The current sound plays/pauses; another sound starts.
1850
- * @param {number|string|Object} [target]
2088
+ * @param target
1851
2089
  */
1852
2090
  toggle(target) {
1853
2091
  const index = this._indexOf(target);
@@ -1867,12 +2105,12 @@
1867
2105
  * Play the visible sound `dir` places away, revealing it if it's past
1868
2106
  * the current page.
1869
2107
  *
1870
- * @param {1|-1} dir
1871
- * @returns {boolean} Whether there was one.
1872
- * @private
2108
+ * @param dir
2109
+ * @returns Whether there was one.
2110
+ * @internal
1873
2111
  */
1874
2112
  _step(dir) {
1875
- const shown = this.visible;
2113
+ const shown = this._shown ?? this._match();
1876
2114
  const at = this.currentIndex == null || this._cued ? -1 : shown.indexOf(this.sounds[this.currentIndex]);
1877
2115
  const target = shown[at + dir];
1878
2116
  if (!target) return false;
@@ -1888,7 +2126,7 @@
1888
2126
  * Loop the current sound (auditioning a loop is the common case). When
1889
2127
  * the list marks its loops (`loop: true` on any sound), only those
1890
2128
  * repeat: a one-shot always plays once.
1891
- * @param {boolean} on
2129
+ * @param on
1892
2130
  */
1893
2131
  setLoop(on) {
1894
2132
  this._loopSet = true;
@@ -1897,16 +2135,16 @@
1897
2135
  }
1898
2136
  /**
1899
2137
  * Apply the loop state to the toggle and the engine.
1900
- * @private
2138
+ * @internal
1901
2139
  */
1902
2140
  _setLoop(on) {
1903
2141
  this.$?.loop?.setAttribute("aria-pressed", String(on));
1904
- if (this.engine?.audio) this.engine.audio.loop = this._repeats();
2142
+ if (this._eng()?.audio) this._eng().audio.loop = this._repeats();
1905
2143
  }
1906
2144
  /**
1907
2145
  * Should the current sound repeat? The Loop toggle is on, and either
1908
2146
  * the list doesn't say which sounds are loops or this one is.
1909
- * @private
2147
+ * @internal
1910
2148
  */
1911
2149
  _repeats() {
1912
2150
  if (!this.loop) return false;
@@ -1916,52 +2154,54 @@
1916
2154
  /**
1917
2155
  * Seek a row's sound to `fraction`; a row that isn't current starts
1918
2156
  * there. Before the duration is known the seek waits for it.
1919
- * @private
2157
+ * @internal
1920
2158
  */
1921
2159
  _seekRow(index, fraction) {
1922
2160
  if (index !== this.currentIndex || !this.engine) {
1923
2161
  this.play(index, { at: fraction });
1924
2162
  return;
1925
2163
  }
1926
- const duration = this.engine.audio?.duration;
2164
+ const duration = this._eng().audio?.duration;
1927
2165
  if (!Number.isFinite(duration) || duration <= 0) {
1928
2166
  this._pendingSeek = fraction;
1929
2167
  return;
1930
2168
  }
1931
- this.engine.seekTo(fraction * duration);
2169
+ this._eng().seekTo(fraction * duration);
1932
2170
  this.progress = fraction;
1933
2171
  this._paintRow(index);
1934
- if (!this.playing) this.engine.play();
2172
+ this._paintSlider();
2173
+ if (!this.playing) this._eng().play();
1935
2174
  }
1936
2175
  /**
1937
- * The engine loaded a sound: apply the loop, borrow decoded peaks for a
2176
+ * The engine loaded a sound: clear an earlier failure, apply the loop, borrow decoded peaks for a
1938
2177
  * row that had none, and land a pending seek.
1939
- * @private
2178
+ * @internal
1940
2179
  */
1941
2180
  _onEngineLoad() {
1942
- if (this.engine?.audio) this.engine.audio.loop = this._repeats();
2181
+ if (this.currentIndex != null) this.rows[this.currentIndex]?.classList.remove("is-error");
2182
+ if (this._eng()?.audio) this._eng().audio.loop = this._repeats();
1943
2183
  const sound = this.sounds[this.currentIndex];
1944
- if (sound && !sound.peaks && this.engine?.waveformData?.length) {
1945
- sound.peaks = resample(this.engine.waveformData, 96);
2184
+ if (sound && !sound.peaks && this._eng()?.waveformData?.length) {
2185
+ sound.peaks = resample(this._eng().waveformData, 96);
1946
2186
  this._drawRow(this.currentIndex);
1947
2187
  }
1948
- const duration = this.engine?.audio?.duration;
2188
+ const duration = this._eng()?.audio?.duration;
1949
2189
  if (this._pendingSeek != null && Number.isFinite(duration) && duration > 0) {
1950
- this.engine.seekTo(this._pendingSeek * duration);
2190
+ this._eng().seekTo(this._pendingSeek * duration);
1951
2191
  this.progress = this._pendingSeek;
1952
2192
  this._pendingSeek = null;
1953
2193
  }
1954
2194
  }
1955
2195
  /**
1956
2196
  * Playback progress: repaint the current row, once per frame.
1957
- * @private
2197
+ * @internal
1958
2198
  */
1959
2199
  _onTime(time, duration) {
1960
2200
  if (this.currentIndex == null || !duration) return;
1961
2201
  if (this._pendingSeek != null) {
1962
2202
  const fraction = this._pendingSeek;
1963
2203
  this._pendingSeek = null;
1964
- this.engine.seekTo(fraction * duration);
2204
+ this._eng().seekTo(fraction * duration);
1965
2205
  return;
1966
2206
  }
1967
2207
  this.progress = Math.min(Math.max(time / duration, 0), 1);
@@ -1969,12 +2209,12 @@
1969
2209
  this._raf = requestAnimationFrame(() => {
1970
2210
  this._raf = 0;
1971
2211
  this._drawRow(this.currentIndex);
1972
- this.rows[this.currentIndex]?.querySelector(".ws-wave")?.setAttribute("aria-valuenow", String(Math.round(this.progress * 100)));
2212
+ this._paintSlider();
1973
2213
  });
1974
2214
  }
1975
2215
  /**
1976
2216
  * A sound finished: report it, then auto-advance or settle.
1977
- * @private
2217
+ * @internal
1978
2218
  */
1979
2219
  _onEnd() {
1980
2220
  const sound = this.sounds[this.currentIndex];
@@ -1985,37 +2225,64 @@
1985
2225
  this._setPlaying(false);
1986
2226
  }
1987
2227
  /**
1988
- * A sound failed to load or play: mark its row and report it.
1989
- * @private
2228
+ * A sound failed to load or play: it isn't playing (no stale "Pause"),
2229
+ * its row is marked until it plays, and the live region says so.
2230
+ * @internal
1990
2231
  */
1991
2232
  _onEngineError(err) {
1992
- this.rows[this.currentIndex]?.classList.add("is-error");
1993
- this._emit("error", { error: err, sound: this.sounds[this.currentIndex], index: this.currentIndex });
2233
+ const index = this.currentIndex;
2234
+ const sound = index == null ? void 0 : this.sounds[index];
2235
+ if (index != null) this.rows[index]?.classList.add("is-error");
2236
+ this._setPlaying(false);
2237
+ if (sound && !this._cued && this.$?.status) this.$.status.textContent = fill(this.strings.playError, { title: sound.title });
2238
+ this._emit("error", { error: err, sound, index });
1994
2239
  this.options.onError?.(err, this);
1995
2240
  }
1996
2241
  /**
1997
- * Record play/pause and repaint. Events fire only on a real change: at a
1998
- * natural end the browser fires `pause` then `ended`, and `_onEnd()`
1999
- * also settles the state — one pause event, not two.
2000
- * @private
2242
+ * Record play/pause and repaint, and report what the listener hears.
2243
+ * Events follow the SOUND, not the flag: switching sounds while one plays
2244
+ * (↓ audition, `play(i)`, `next()`, auto-advance) never flips `playing`
2245
+ * in some engines (the media element swaps source without a `pause`),
2246
+ * so the last sound announced is tracked — a different one starting
2247
+ * reports `pause` for the outgoing sound, then `play` for the new one.
2248
+ * At a natural end the browser fires `pause` then `ended`, and `_onEnd()`
2249
+ * settles the state again: one pause event, not two.
2250
+ * @internal
2001
2251
  */
2002
2252
  _setPlaying(on) {
2003
- const changed = this.playing !== on;
2004
2253
  this.playing = on;
2005
2254
  if (on) this._cued = false;
2006
2255
  const index = this.currentIndex;
2007
2256
  if (index == null) return;
2257
+ if (on) this.rows[index]?.classList.remove("is-error");
2008
2258
  this._paintRow(index);
2009
- if (!changed) return;
2259
+ const was = this._announced ?? null;
2260
+ if (on) {
2261
+ if (was === index) return;
2262
+ if (was != null) this._announce("pause", was);
2263
+ this._announced = index;
2264
+ this._announce("play", index);
2265
+ } else if (was != null) {
2266
+ this._announced = null;
2267
+ this._announce("pause", was);
2268
+ }
2269
+ }
2270
+ /**
2271
+ * Report a sound starting or stopping: the live region (on play), the
2272
+ * `waveformsounds:play|pause` event and the `onPlay` / `onPause` callback.
2273
+ * @internal
2274
+ */
2275
+ _announce(type, index) {
2010
2276
  const sound = this.sounds[index];
2011
- if (on && this.$.status) this.$.status.textContent = fill(this.strings.nowPlaying, { title: sound.title });
2012
- this._emit(on ? "play" : "pause", { sound, index });
2013
- (on ? this.options.onPlay : this.options.onPause)?.(sound, this);
2277
+ if (!sound) return;
2278
+ if (type === "play" && this.$?.status) this.$.status.textContent = fill(this.strings.nowPlaying, { title: sound.title });
2279
+ this._emit(type, { sound, index });
2280
+ (type === "play" ? this.options.onPlay : this.options.onPause)?.(sound, this);
2014
2281
  }
2015
2282
  /* ── Row painting ─────────────────────────────────────────────────── */
2016
2283
  /**
2017
2284
  * A row's state classes, play-button label and waveform.
2018
- * @private
2285
+ * @internal
2019
2286
  */
2020
2287
  _paintRow(index) {
2021
2288
  const row = this.rows[index];
@@ -2031,18 +2298,38 @@
2031
2298
  }
2032
2299
  const wave = row.querySelector(".ws-wave");
2033
2300
  if (wave) {
2034
- wave.tabIndex = current ? 0 : -1;
2035
- if (!current) wave.setAttribute("aria-valuenow", "0");
2301
+ wave.tabIndex = current && row === this._active ? 0 : -1;
2302
+ if (!current) {
2303
+ wave.setAttribute("aria-valuenow", "0");
2304
+ wave.removeAttribute("aria-valuetext");
2305
+ }
2036
2306
  }
2037
2307
  this._drawRow(index);
2038
2308
  }
2309
+ /**
2310
+ * The current row's seek slider: its position (0–100) and, for a screen
2311
+ * reader, the time ("0:12 of 0:30").
2312
+ * @internal
2313
+ */
2314
+ _paintSlider() {
2315
+ const index = this.currentIndex;
2316
+ const wave = index == null ? null : this.rows[index]?.querySelector(".ws-wave");
2317
+ if (!wave) return;
2318
+ wave.setAttribute("aria-valuenow", String(Math.round(this.progress * 100)));
2319
+ const audio = this._eng()?.audio;
2320
+ const duration = Number.isFinite(audio?.duration) && audio.duration > 0 ? audio.duration : this.sounds[index].duration;
2321
+ if (duration) wave.setAttribute("aria-valuetext", fill(this.strings.seekValue, { time: formatClock(this.progress * duration), duration: formatDuration(duration) }));
2322
+ }
2039
2323
  /* ── Events & lifecycle ──────────────────────────────────────────── */
2040
2324
  /**
2041
- * Emit a `waveformsounds:<name>` event carrying this instance.
2042
- * @private
2325
+ * Announce a moment both ways: a `waveformsounds:<name>` event on the
2326
+ * container carrying the details and this instance, then a plain `<name>`
2327
+ * event on the instance.
2328
+ * @internal
2043
2329
  */
2044
2330
  _emit(name, detail = {}) {
2045
2331
  emit(this.container, name, { ...detail, instance: this });
2332
+ this.dispatchEvent(new Event(name));
2046
2333
  }
2047
2334
  /** The sound playing (or paused) now, or null. */
2048
2335
  get current() {
@@ -2052,10 +2339,15 @@
2052
2339
  * Tear down: listeners, observers, timers and the engine. Markup this
2053
2340
  * instance rendered is restored to what the container held before.
2054
2341
  * ADOPTED (server-rendered) markup is left as it is now — rows may be
2055
- * re-sorted, hidden or marked current — so to start again, re-render it
2056
- * rather than constructing a new instance over it.
2342
+ * re-sorted, hidden or marked current — unless `restore` is set: then it
2343
+ * is put back exactly as the server sent it, ready for a new instance
2344
+ * (what a framework re-mounting the same markup wants).
2345
+ *
2346
+ * @param options
2347
+ * @param options.restore - Put adopted server markup back as it was.
2348
+ * Default false. Since 2.1.0.
2057
2349
  */
2058
- destroy() {
2350
+ destroy(options = {}) {
2059
2351
  if (this.destroyed) return;
2060
2352
  this.destroyed = true;
2061
2353
  this._ctl.abort();
@@ -2065,12 +2357,13 @@
2065
2357
  if (this._raf) cancelAnimationFrame(this._raf);
2066
2358
  clearTimeout(this._urlTimer);
2067
2359
  try {
2068
- this.engine?.destroy();
2360
+ this._eng()?.destroy();
2069
2361
  } catch {
2070
2362
  }
2071
2363
  this.engine = null;
2072
2364
  this.$?.engine?.querySelector(":scope > [data-ws-engine-mount]")?.remove();
2073
2365
  if (this._originalHTML != null) this.container.innerHTML = this._originalHTML;
2366
+ else if (options.restore && this._adoptedHTML != null) this.container.innerHTML = this._adoptedHTML;
2074
2367
  if (this._addedClasses?.length) this.container.classList.remove(...this._addedClasses);
2075
2368
  if (this._autoSurface) this.container.style.removeProperty("--ws-surface");
2076
2369
  delete this.container.dataset.wsInitialized;
@@ -2079,8 +2372,8 @@
2079
2372
  /**
2080
2373
  * Initialise every `[data-waveform-sounds]` under `root` that isn't yet.
2081
2374
  *
2082
- * @param {ParentNode} [root=document]
2083
- * @returns {WaveformSounds[]} The new instances.
2375
+ * @param root
2376
+ * @returns The new instances.
2084
2377
  */
2085
2378
  static init(root = document) {
2086
2379
  if (typeof document === "undefined") return [];
@@ -2099,8 +2392,7 @@
2099
2392
  }
2100
2393
  /**
2101
2394
  * The instance on an element (or selector), if any.
2102
- * @param {Element|string} el
2103
- * @returns {WaveformSounds|null}
2395
+ * @param el
2104
2396
  */
2105
2397
  static getInstance(el) {
2106
2398
  const node = typeof el === "string" ? document.querySelector(el) : el;
@@ -2113,16 +2405,151 @@
2113
2405
  }
2114
2406
  };
2115
2407
 
2116
- // src/js/entry.js
2408
+ // src/js/core/element.ts
2409
+ var ELEMENT_OPTION_KEYS = [
2410
+ "player",
2411
+ "manifest",
2412
+ "search",
2413
+ "filters",
2414
+ "sorts",
2415
+ "showCount",
2416
+ "menuSearch",
2417
+ "idPrefix",
2418
+ "urlState",
2419
+ "loopToggle",
2420
+ "pageSize",
2421
+ "maxTypeChips",
2422
+ "columns",
2423
+ "waveformStyle",
2424
+ "waveformColor",
2425
+ "progressColor",
2426
+ "barWidth",
2427
+ "barGap",
2428
+ "loop",
2429
+ "autoAdvance",
2430
+ "arrowAudition",
2431
+ "strings",
2432
+ "playerOptions"
2433
+ ];
2434
+ var kebab = (key) => key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
2435
+ function readElementOptions(el) {
2436
+ const dataset = {};
2437
+ for (const key of ELEMENT_OPTION_KEYS) {
2438
+ const name = kebab(key);
2439
+ const value = el.getAttribute(name) ?? el.getAttribute(`data-${name}`);
2440
+ if (value != null) dataset[key] = value;
2441
+ }
2442
+ return readDataOptions({ dataset });
2443
+ }
2444
+ var Base = typeof HTMLElement === "undefined" ? class {
2445
+ } : HTMLElement;
2446
+ var WaveformSoundsElement = class extends Base {
2447
+ /** Every option attribute, plain and `data-` prefixed. */
2448
+ static get observedAttributes() {
2449
+ return ELEMENT_OPTION_KEYS.flatMap((key) => [kebab(key), `data-${kebab(key)}`]);
2450
+ }
2451
+ /** Build the list (or keep it, after a move). */
2452
+ connectedCallback() {
2453
+ if (this._leaving !== void 0) {
2454
+ clearTimeout(this._leaving);
2455
+ this._leaving = void 0;
2456
+ return;
2457
+ }
2458
+ if (!this.sounds) this._build();
2459
+ }
2460
+ /** Destroy the list, unless the element comes straight back (a move). */
2461
+ disconnectedCallback() {
2462
+ clearTimeout(this._leaving);
2463
+ this._leaving = setTimeout(() => {
2464
+ this._leaving = void 0;
2465
+ if (!this.isConnected) this._teardown();
2466
+ }, 0);
2467
+ }
2468
+ /**
2469
+ * An option attribute changed: rebuild once the task's changes are in.
2470
+ *
2471
+ * @param name
2472
+ * @param previous
2473
+ * @param value
2474
+ */
2475
+ attributeChangedCallback(name, previous, value) {
2476
+ if (!this.sounds || previous === value) return;
2477
+ const kind = name.replace(/^data-/, "") === "manifest" ? "manifest" : "rebuild";
2478
+ if (this._pending) {
2479
+ if (kind === "manifest") this._pending = kind;
2480
+ return;
2481
+ }
2482
+ this._pending = kind;
2483
+ queueMicrotask(() => {
2484
+ const pending = this._pending;
2485
+ this._pending = void 0;
2486
+ if (this.sounds) this._rebuild(pending === "manifest");
2487
+ });
2488
+ }
2489
+ /**
2490
+ * The options the list reads off this element (`WaveformSounds` calls it
2491
+ * in place of reading `data-*` alone).
2492
+ * @internal
2493
+ */
2494
+ _wsOptions() {
2495
+ return readElementOptions(this);
2496
+ }
2497
+ /**
2498
+ * Build the list into the element.
2499
+ * @internal
2500
+ */
2501
+ _build(options = {}) {
2502
+ WaveformSounds.getInstance(this)?.destroy({ restore: true });
2503
+ try {
2504
+ this.sounds = new WaveformSounds(this, options);
2505
+ } catch (error) {
2506
+ this.sounds = null;
2507
+ console.error(`${LOG} Failed to initialise:`, error, this);
2508
+ }
2509
+ }
2510
+ /**
2511
+ * Destroy the list, putting server-rendered markup back as it came.
2512
+ * @internal
2513
+ */
2514
+ _teardown() {
2515
+ this.sounds?.destroy({ restore: true });
2516
+ this.sounds = null;
2517
+ }
2518
+ /**
2519
+ * Rebuild for new options: re-rendered from the sounds the list holds
2520
+ * (the markup must follow the new options), or fetched afresh when the
2521
+ * manifest changed.
2522
+ * @internal
2523
+ */
2524
+ _rebuild(refetch) {
2525
+ const sounds = refetch || !this.sounds.$ ? void 0 : this.sounds.sounds.slice();
2526
+ this._teardown();
2527
+ this.innerHTML = "";
2528
+ this._build(sounds ? { sounds } : {});
2529
+ }
2530
+ };
2531
+ function defineWaveformSoundsElement(name = "waveform-sounds") {
2532
+ if (typeof customElements === "undefined") return void 0;
2533
+ const existing = customElements.get(name);
2534
+ if (existing) return existing;
2535
+ const element = class extends WaveformSoundsElement {
2536
+ };
2537
+ customElements.define(name, element);
2538
+ return element;
2539
+ }
2540
+
2541
+ // src/js/entry.ts
2117
2542
  WaveformSounds.utils = { encodePeaks, decodePeaks, normalizeKey, normalizeSounds, parseManifest, facets, matches, sortSounds, formatDuration, renderSounds };
2118
2543
  WaveformSounds.DEFAULT_OPTIONS = DEFAULT_OPTIONS;
2119
2544
  WaveformSounds.DEFAULT_STRINGS = DEFAULT_STRINGS;
2545
+ WaveformSounds.defineElement = defineWaveformSoundsElement;
2120
2546
  if (typeof window !== "undefined") window.WaveformSounds = WaveformSounds;
2121
2547
  var entry_default = WaveformSounds;
2122
2548
 
2123
- // src/js/index.js
2549
+ // src/js/index.ts
2124
2550
  var index_default = entry_default;
2125
2551
  if (typeof document !== "undefined" && document.documentElement?.dataset?.waveformAutoinit !== "false") {
2552
+ defineWaveformSoundsElement();
2126
2553
  if (document.readyState === "loading") {
2127
2554
  document.addEventListener("DOMContentLoaded", () => entry_default.init(), { once: true });
2128
2555
  } else {
@@ -2134,8 +2561,8 @@
2134
2561
  * @arraypress/waveform-sounds
2135
2562
  * A searchable, filterable list of sounds for WaveformPlayer.
2136
2563
  *
2137
- * Importing this entry initialises every `[data-waveform-sounds]` element
2138
- * once the DOM is ready. Opt out page-wide with
2564
+ * Importing this entry registers `<waveform-sounds>` and initialises every
2565
+ * `[data-waveform-sounds]` element once the DOM is ready. Opt out page-wide with
2139
2566
  * `<html data-waveform-autoinit="false">` (the family's switch), or import
2140
2567
  * `@arraypress/waveform-sounds/no-autoinit`.
2141
2568
  *