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