@arraypress/waveform-sounds 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +44 -2
  2. package/dist/waveform-sounds-no-autoinit.esm.js +914 -208
  3. package/dist/waveform-sounds-render.esm.js +274 -82
  4. package/dist/waveform-sounds.css +92 -17
  5. package/dist/waveform-sounds.esm.js +917 -210
  6. package/dist/waveform-sounds.js +913 -210
  7. package/dist/waveform-sounds.min.css +1 -1
  8. package/dist/waveform-sounds.min.js +3 -3
  9. package/package.json +1 -1
  10. package/src/css/waveform-sounds.css +92 -17
  11. package/src/js/core/WaveformSounds.ts +540 -120
  12. package/src/js/core/element.ts +208 -0
  13. package/src/js/core/engine.ts +9 -3
  14. package/src/js/core/options.ts +1 -5
  15. package/src/js/data/bpm.ts +14 -4
  16. package/src/js/data/keys.ts +156 -0
  17. package/src/js/data/navigation.ts +51 -11
  18. package/src/js/data/sounds.ts +73 -36
  19. package/src/js/data/url-state.ts +39 -12
  20. package/src/js/dom/colors.ts +28 -1
  21. package/src/js/dom/draw.ts +16 -3
  22. package/src/js/dom/menus.ts +2 -3
  23. package/src/js/dom/rows.ts +38 -15
  24. package/src/js/entry.ts +13 -3
  25. package/src/js/index.ts +7 -3
  26. package/src/js/render/html.ts +0 -2
  27. package/src/js/render/icons.ts +59 -17
  28. package/src/js/render/markup.ts +156 -62
  29. package/src/js/render/options.ts +29 -5
  30. package/src/js/render/strings.ts +57 -4
  31. package/src/js/render-entry.ts +1 -1
  32. package/src/js/shared/utils.ts +4 -4
  33. package/src/js/types.ts +54 -3
  34. package/types/core/WaveformSounds.d.ts +41 -11
  35. package/types/core/WaveformSounds.d.ts.map +1 -1
  36. package/types/core/element.d.ts +84 -0
  37. package/types/core/element.d.ts.map +1 -0
  38. package/types/core/engine.d.ts +8 -3
  39. package/types/core/engine.d.ts.map +1 -1
  40. package/types/core/options.d.ts +0 -5
  41. package/types/core/options.d.ts.map +1 -1
  42. package/types/data/bpm.d.ts +17 -4
  43. package/types/data/bpm.d.ts.map +1 -1
  44. package/types/data/keys.d.ts +88 -0
  45. package/types/data/keys.d.ts.map +1 -0
  46. package/types/data/navigation.d.ts +38 -11
  47. package/types/data/navigation.d.ts.map +1 -1
  48. package/types/data/sounds.d.ts +33 -17
  49. package/types/data/sounds.d.ts.map +1 -1
  50. package/types/data/url-state.d.ts +38 -7
  51. package/types/data/url-state.d.ts.map +1 -1
  52. package/types/dom/colors.d.ts +13 -0
  53. package/types/dom/colors.d.ts.map +1 -1
  54. package/types/dom/draw.d.ts +5 -3
  55. package/types/dom/draw.d.ts.map +1 -1
  56. package/types/dom/menus.d.ts +0 -2
  57. package/types/dom/menus.d.ts.map +1 -1
  58. package/types/dom/rows.d.ts +19 -11
  59. package/types/dom/rows.d.ts.map +1 -1
  60. package/types/entry.d.ts +10 -4
  61. package/types/entry.d.ts.map +1 -1
  62. package/types/index.d.ts +2 -2
  63. package/types/index.d.ts.map +1 -1
  64. package/types/render/html.d.ts +0 -2
  65. package/types/render/html.d.ts.map +1 -1
  66. package/types/render/icons.d.ts +41 -3
  67. package/types/render/icons.d.ts.map +1 -1
  68. package/types/render/markup.d.ts +44 -12
  69. package/types/render/markup.d.ts.map +1 -1
  70. package/types/render/options.d.ts +18 -5
  71. package/types/render/options.d.ts.map +1 -1
  72. package/types/render/strings.d.ts +22 -4
  73. package/types/render/strings.d.ts.map +1 -1
  74. package/types/render-entry.d.ts +1 -1
  75. package/types/render-entry.d.ts.map +1 -1
  76. package/types/shared/utils.d.ts +3 -3
  77. package/types/shared/utils.d.ts.map +1 -1
  78. package/types/types.d.ts +53 -3
  79. package/types/types.d.ts.map +1 -1
@@ -70,6 +70,94 @@ function matchesAll(name, query, options = {}) {
70
70
  });
71
71
  }
72
72
 
73
+ // src/js/data/keys.ts
74
+ var KEY_PITCH = {
75
+ C: 0,
76
+ "B#": 0,
77
+ "C#": 1,
78
+ Db: 1,
79
+ D: 2,
80
+ "D#": 3,
81
+ Eb: 3,
82
+ E: 4,
83
+ Fb: 4,
84
+ "E#": 5,
85
+ F: 5,
86
+ "F#": 6,
87
+ Gb: 6,
88
+ G: 7,
89
+ "G#": 8,
90
+ Ab: 8,
91
+ A: 9,
92
+ "A#": 10,
93
+ Bb: 10,
94
+ B: 11,
95
+ Cb: 11
96
+ };
97
+ var CONVENTIONAL_MAJOR = ["C", "Db", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B"];
98
+ var CONVENTIONAL_MINOR = ["Cm", "C#m", "Dm", "Ebm", "Em", "Fm", "F#m", "Gm", "G#m", "Am", "Bbm", "Bm"];
99
+ var SHARPS = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
100
+ var FLATS = ["C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"];
101
+ function parseKey(key) {
102
+ const m = /^([A-G][#b]?)(m?)$/.exec(String(key ?? ""));
103
+ if (!m || KEY_PITCH[m[1]] === void 0) return null;
104
+ return { root: m[1], pitch: KEY_PITCH[m[1]], minor: m[2] === "m" };
105
+ }
106
+ function keyClass(key) {
107
+ const k = parseKey(key);
108
+ return k ? `${k.pitch}${k.minor ? "m" : ""}` : key;
109
+ }
110
+ function sameKey(a, b, merge = true) {
111
+ return a === b || merge && !!a && keyClass(a) === keyClass(b);
112
+ }
113
+ function keyRank(key) {
114
+ if (!key) return Infinity;
115
+ const k = parseKey(key);
116
+ return k ? k.pitch * 2 + (k.minor ? 1 : 0) : 1e3;
117
+ }
118
+ function enharmonics(key) {
119
+ const k = parseKey(key);
120
+ if (!k) return key ? [key] : [];
121
+ const mode = k.minor ? "m" : "";
122
+ return [.../* @__PURE__ */ new Set([key, SHARPS[k.pitch] + mode, FLATS[k.pitch] + mode])];
123
+ }
124
+ function canonicalSpelling(counts) {
125
+ let best = 0;
126
+ for (const n of counts.values()) if (n > best) best = n;
127
+ const tied = [...counts].filter(([, n]) => n === best).map(([k2]) => k2).sort();
128
+ if (tied.length === 1) return tied[0];
129
+ const k = parseKey(tied[0]);
130
+ const conventional = k ? (k.minor ? CONVENTIONAL_MINOR : CONVENTIONAL_MAJOR)[k.pitch] : "";
131
+ return tied.includes(conventional) ? conventional : tied[0];
132
+ }
133
+ function keyEntries(keys, merge = true) {
134
+ const groups = /* @__PURE__ */ new Map();
135
+ for (const key of keys) {
136
+ if (!key) continue;
137
+ const cls = merge ? keyClass(key) : key;
138
+ const g = groups.get(cls) ?? /* @__PURE__ */ new Map();
139
+ groups.set(cls, g);
140
+ g.set(key, (g.get(key) || 0) + 1);
141
+ }
142
+ const out = [];
143
+ const aliases = {};
144
+ for (const g of groups.values()) {
145
+ const entry = canonicalSpelling(g);
146
+ out.push(entry);
147
+ const others = [...g.keys()].filter((k) => k !== entry).sort();
148
+ if (others.length) aliases[entry] = others;
149
+ }
150
+ out.sort((a, b) => keyRank(a) - keyRank(b) || a.localeCompare(b));
151
+ return { keys: out, aliases };
152
+ }
153
+ function keyEntry(key, entries, merge = true) {
154
+ if (!key) return "";
155
+ if (entries.includes(key)) return key;
156
+ if (!merge) return "";
157
+ const cls = keyClass(key);
158
+ return entries.find((e) => keyClass(e) === cls) ?? "";
159
+ }
160
+
73
161
  // src/js/data/sounds.ts
74
162
  function encodePeaks(peaks) {
75
163
  if (!Array.isArray(peaks)) return "";
@@ -80,12 +168,25 @@ function encodePeaks(peaks) {
80
168
  }
81
169
  return out;
82
170
  }
171
+ var COMPACT_PREFIX = "wp1:";
172
+ function decodeCompact(body) {
173
+ if (!body || !/^[\w-]+$/.test(body) || body.length % 4 === 1) return null;
174
+ try {
175
+ const bytes = atob(body.replace(/-/g, "+").replace(/_/g, "/"));
176
+ const out = new Array(bytes.length);
177
+ for (let i = 0; i < bytes.length; i++) out[i] = bytes.charCodeAt(i) / 255;
178
+ return out;
179
+ } catch {
180
+ return null;
181
+ }
182
+ }
83
183
  function decodePeaks(value, scale = 1) {
84
184
  if (value == null || value === "") return null;
85
185
  if (typeof value === "string") {
186
+ if (value.startsWith(COMPACT_PREFIX)) return decodeCompact(value.slice(COMPACT_PREFIX.length));
86
187
  if (!/^[0-9a-f]+$/i.test(value) || value.length % 2) return null;
87
188
  const out2 = new Array(value.length / 2);
88
- for (let i = 0; i < out2.length; i++) out2[i] = parseInt(value.substr(i * 2, 2), 16) / 255;
189
+ for (let i = 0; i < out2.length; i++) out2[i] = parseInt(value.slice(i * 2, i * 2 + 2), 16) / 255;
89
190
  return out2;
90
191
  }
91
192
  if (!Array.isArray(value)) return null;
@@ -103,14 +204,6 @@ function normalizeKey(key) {
103
204
  const minor = m[3] && /^m(in(or)?)?$/i.test(m[3]) && m[3] !== "M";
104
205
  return root + acc + (minor ? "m" : "");
105
206
  }
106
- var KEY_PITCH = { C: 0, "C#": 1, Db: 1, D: 2, "D#": 3, Eb: 3, E: 4, F: 5, "F#": 6, Gb: 6, G: 7, "G#": 8, Ab: 8, A: 9, "A#": 10, Bb: 10, B: 11 };
107
- function keyRank(key) {
108
- if (!key) return Infinity;
109
- const minor = key.endsWith("m");
110
- const root = minor ? key.slice(0, -1) : key;
111
- const p = KEY_PITCH[root];
112
- return p === void 0 ? 1e3 : p * 2 + (minor ? 1 : 0);
113
- }
114
207
  function formatDuration(seconds) {
115
208
  if (seconds == null || seconds === "") return "";
116
209
  const s = Number(seconds);
@@ -119,13 +212,18 @@ function formatDuration(seconds) {
119
212
  const total = s < 1 ? Math.ceil(s) : Math.floor(s);
120
213
  return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`;
121
214
  }
215
+ function formatClock(seconds) {
216
+ const total = Number.isFinite(seconds) && seconds > 0 ? Math.floor(seconds) : 0;
217
+ const h2 = Math.floor(total / 3600), m = Math.floor(total % 3600 / 60), sec = String(total % 60).padStart(2, "0");
218
+ return h2 ? `${h2}:${String(m).padStart(2, "0")}:${sec}` : `${m}:${sec}`;
219
+ }
122
220
  function parseDuration(value) {
123
221
  if (value == null || value === "") return null;
124
222
  if (typeof value === "number") return Number.isFinite(value) && value >= 0 ? value : null;
125
223
  const str = String(value).trim();
126
224
  if (/^\d+(\.\d+)?$/.test(str)) return Number(str);
225
+ if (!/^\d+(\.\d+)?(:\d+(\.\d+)?)+$/.test(str)) return null;
127
226
  const parts = str.split(":").map(Number);
128
- if (parts.length < 2 || parts.some((n) => !Number.isFinite(n))) return null;
129
227
  return parts.reduce((acc, n) => acc * 60 + n, 0);
130
228
  }
131
229
  function titleFromUrl(url) {
@@ -179,13 +277,13 @@ function normalizeSounds(list, peakScale = 1) {
179
277
  });
180
278
  return out;
181
279
  }
182
- function facets(sounds) {
280
+ function facets(sounds, options = {}) {
183
281
  const types = /* @__PURE__ */ new Map();
184
- const keys = /* @__PURE__ */ new Set();
282
+ const keys = [];
185
283
  let min = Infinity, max = -Infinity, hasDuration = false, loops = 0;
186
284
  for (const s of sounds) {
187
285
  if (s.type) types.set(s.type, (types.get(s.type) || 0) + 1);
188
- if (s.key) keys.add(s.key);
286
+ if (s.key) keys.push(s.key);
189
287
  if (s.bpm != null) {
190
288
  min = Math.min(min, s.bpm);
191
289
  max = Math.max(max, s.bpm);
@@ -193,18 +291,21 @@ function facets(sounds) {
193
291
  if (s.duration != null) hasDuration = true;
194
292
  if (s.loop) loops++;
195
293
  }
294
+ const entries = keyEntries(keys, options.mergeEnharmonicKeys !== false);
196
295
  return {
197
296
  types: [...types].map(([name, count]) => ({ name, count })),
198
- keys: [...keys].sort((a, b) => keyRank(a) - keyRank(b) || a.localeCompare(b)),
297
+ keys: entries.keys,
298
+ keyAliases: entries.aliases,
199
299
  bpm: min === Infinity ? null : { min, max },
200
300
  hasDuration,
201
301
  loops,
202
302
  oneShots: sounds.length - loops
203
303
  };
204
304
  }
205
- function matches(sound, filter = {}) {
305
+ function matches(sound, filter = {}, options = {}) {
306
+ const merge = options.mergeEnharmonicKeys !== false;
206
307
  if (filter.type && sound.type !== filter.type) return false;
207
- if (filter.key && sound.key !== normalizeKey(filter.key)) return false;
308
+ if (filter.key && !sameKey(sound.key, normalizeKey(filter.key), merge)) return false;
208
309
  if (filter.loop === "loop" && !sound.loop) return false;
209
310
  if (filter.loop === "one-shot" && sound.loop) return false;
210
311
  const lo = Number(filter.bpmMin), hi = Number(filter.bpmMax);
@@ -215,7 +316,7 @@ function matches(sound, filter = {}) {
215
316
  }
216
317
  const terms = words(filter.query || "");
217
318
  if (terms.length) {
218
- const hay = [sound.title, sound.type, sound.key, ...sound.tags || []].join(" ");
319
+ const hay = [sound.title, sound.type, ...merge ? enharmonics(sound.key) : [sound.key], ...sound.tags || []].join(" ");
219
320
  const folded = fold(hay);
220
321
  const rest = terms.filter((w) => !(/^\d+$/.test(w) && !folded.includes(w) && sound.bpm != null && Math.round(sound.bpm) === Number(w)));
221
322
  if (rest.length && !matchesAll(hay, rest.join(" "))) return false;
@@ -260,6 +361,16 @@ function resample(peaks, count) {
260
361
  if (!peaks?.length || count <= 0) return [];
261
362
  if (peaks.length === count) return peaks;
262
363
  const out = new Array(count);
364
+ if (count > peaks.length) {
365
+ const last = peaks.length - 1;
366
+ const ratio = peaks.length / count;
367
+ for (let i = 0; i < count; i++) {
368
+ const x = Math.min(Math.max((i + 0.5) * ratio - 0.5, 0), last);
369
+ const j = Math.floor(x), t = x - j;
370
+ out[i] = j >= last ? peaks[last] : peaks[j] + (peaks[j + 1] - peaks[j]) * t;
371
+ }
372
+ return out;
373
+ }
263
374
  const step = peaks.length / count;
264
375
  for (let i = 0; i < count; i++) {
265
376
  const start = Math.floor(i * step);
@@ -341,8 +452,9 @@ function engineOptions(user, layout, handlers) {
341
452
  function enginePeaks(sound, layout) {
342
453
  return layout === "strip" && sound.waveform || sound.peaks || null;
343
454
  }
344
- function engineTrack(sound, layout, autoplay) {
455
+ function engineTrack(sound, layout, autoplay, preload) {
345
456
  const track = { waveform: enginePeaks(sound, layout), autoplay };
457
+ if (preload) track.preload = preload;
346
458
  if (sound.duration != null && sound.duration > 0) track.duration = sound.duration;
347
459
  if (sound.download) track.downloadUrl = sound.download;
348
460
  return track;
@@ -488,7 +600,7 @@ var Menus = class {
488
600
  const p = partsOf(menu);
489
601
  let first = null;
490
602
  for (const opt of optionsOf(p)) {
491
- opt.hidden = !optionMatches(opt.textContent, query);
603
+ opt.hidden = !optionMatches(`${opt.textContent} ${opt.dataset.alt ?? ""}`, query);
492
604
  if (!opt.hidden) first ??= opt;
493
605
  }
494
606
  p.none.hidden = first !== null;
@@ -569,7 +681,7 @@ function isTyping(el) {
569
681
  return !!el && (el.isContentEditable || /^(INPUT|SELECT|TEXTAREA)$/.test(el.tagName));
570
682
  }
571
683
  function emit(target, name, detail) {
572
- const event = new CustomEvent(`waveformsounds:${name}`, { bubbles: true, detail });
684
+ const event = new CustomEvent(`waveformsounds:${name}`, { bubbles: true, composed: true, detail });
573
685
  target.dispatchEvent(event);
574
686
  return event;
575
687
  }
@@ -598,17 +710,30 @@ function rowTarget(key, at, count) {
598
710
  }
599
711
  function seekTarget(progress, key) {
600
712
  if (key !== "ArrowRight" && key !== "ArrowLeft") return null;
601
- return clamp(progress + (key === "ArrowRight" ? SEEK_STEP : -SEEK_STEP), 0, 0.999);
713
+ return clamp(progress + (key === "ArrowRight" ? SEEK_STEP : -SEEK_STEP), 0, SEEK_END);
714
+ }
715
+ var SEEK_END = 0.999;
716
+ function sliderEdgeTarget(key) {
717
+ return key === "Home" ? 0 : key === "End" ? SEEK_END : null;
718
+ }
719
+ var RENDER_CHUNK = 50;
720
+ function renderedCount(matching, limit, budget) {
721
+ return Math.min(matching, limit === Infinity ? budget : limit);
722
+ }
723
+ function firstRender(pageSize) {
724
+ return pageSize > 0 ? pageSize : RENDER_CHUNK;
602
725
  }
603
- function pageWindow(shown, limit) {
604
- const visible = new Set(shown.slice(0, limit));
605
- return { visible, remaining: shown.length - visible.size };
726
+ function budgetToReveal(budget, pos) {
727
+ return pos < budget ? budget : Math.ceil((pos + 1) / RENDER_CHUNK) * RENDER_CHUNK;
606
728
  }
607
729
  function limitToReveal(limit, pos) {
608
730
  return pos >= limit ? pos + 1 : limit;
609
731
  }
610
732
 
611
733
  // src/js/data/bpm.ts
734
+ function bpmExtent(range) {
735
+ return range ? { min: Math.floor(range.min), max: Math.ceil(range.max) } : null;
736
+ }
612
737
  function bpmFilterFromRange(lo, hi, extent) {
613
738
  const a = Math.min(lo, hi), b = Math.max(lo, hi);
614
739
  return {
@@ -665,6 +790,7 @@ var DEFAULT_STRINGS = {
665
790
  play: "Play {title}",
666
791
  pause: "Pause {title}",
667
792
  seek: "Seek {title}",
793
+ seekValue: "{time} of {duration}",
668
794
  download: "Download {title}",
669
795
  count: "{count} sounds",
670
796
  countOne: "1 sound",
@@ -672,7 +798,18 @@ var DEFAULT_STRINGS = {
672
798
  showMore: "Show {count} more",
673
799
  empty: "No sounds match.",
674
800
  clear: "Clear filters",
675
- nowPlaying: "Playing {title}"
801
+ nowPlaying: "Playing {title}",
802
+ playError: "Could not play {title}",
803
+ loadError: "Could not load the sounds.",
804
+ noSounds: "No sounds.",
805
+ rowBpm: "{bpm} BPM",
806
+ rowKey: "key {key}",
807
+ rowDuration: "{duration}",
808
+ keyMajor: "{note} major",
809
+ keyMinor: "{note} minor",
810
+ noteSharp: "{note} sharp",
811
+ noteFlat: "{note} flat",
812
+ listSeparator: ", "
676
813
  };
677
814
  var SORT_LABEL_KEYS = {
678
815
  default: "sortDefault",
@@ -693,6 +830,27 @@ function countText(shown, total, strings = DEFAULT_STRINGS) {
693
830
  if (shown !== total) return fill(strings.countFiltered, { count: shown, total });
694
831
  return total === 1 ? strings.countOne : fill(strings.count, { count: total });
695
832
  }
833
+ function spokenKey(key, strings = DEFAULT_STRINGS) {
834
+ const k = parseKey(key);
835
+ if (!k) return key;
836
+ const letter = k.root[0], acc = k.root.slice(1);
837
+ const note = acc === "#" ? fill(strings.noteSharp, { note: letter }) : acc === "b" ? fill(strings.noteFlat, { note: letter }) : letter;
838
+ return fill(k.minor ? strings.keyMinor : strings.keyMajor, { note });
839
+ }
840
+ function rowSummary(sound, columns, strings = DEFAULT_STRINGS) {
841
+ const parts = [];
842
+ for (const c of columns) {
843
+ if (c === "type" && sound.type) parts.push(sound.type);
844
+ else if (c === "bpm" && sound.bpm != null) parts.push(fill(strings.rowBpm, { bpm: sound.bpm }));
845
+ else if (c === "key" && sound.key) parts.push(fill(strings.rowKey, { key: spokenKey(sound.key, strings) }));
846
+ else if (c === "duration") {
847
+ const d = formatDuration(sound.duration);
848
+ if (d) parts.push(fill(strings.rowDuration, { duration: d }));
849
+ }
850
+ }
851
+ if (sound.loop) parts.push(strings.isLoop);
852
+ return parts.join(strings.listSeparator);
853
+ }
696
854
 
697
855
  // src/js/render/options.ts
698
856
  var FILTERS = ["type", "key", "bpm", "loop"];
@@ -707,8 +865,18 @@ var RENDER_DEFAULTS = {
707
865
  menuSearch: 8,
708
866
  pageSize: 50,
709
867
  columns: [...COLUMNS],
710
- maxTypeChips: 10
868
+ maxTypeChips: 10,
869
+ mergeEnharmonicKeys: true
711
870
  };
871
+ var RENDER_OPTION_KEYS = [...Object.keys(RENDER_DEFAULTS), "idPrefix", "loop", "strings"];
872
+ function pickRenderOptions(options) {
873
+ const out = {};
874
+ for (const key of RENDER_OPTION_KEYS) {
875
+ const value = options?.[key];
876
+ if (value != null) out[key] = value;
877
+ }
878
+ return out;
879
+ }
712
880
  function defined(obj) {
713
881
  const out = {};
714
882
  for (const k in obj ?? {}) if (obj[k] !== void 0) out[k] = obj[k];
@@ -732,6 +900,7 @@ function resolveRenderOptions(options = {}) {
732
900
  menuSearch: wholeNumber(o.menuSearch, RENDER_DEFAULTS.menuSearch),
733
901
  maxTypeChips: wholeNumber(o.maxTypeChips, RENDER_DEFAULTS.maxTypeChips),
734
902
  pageSize: wholeNumber(o.pageSize, RENDER_DEFAULTS.pageSize),
903
+ mergeEnharmonicKeys: o.mergeEnharmonicKeys !== false,
735
904
  strings: { ...DEFAULT_STRINGS, ...defined(options.strings) }
736
905
  };
737
906
  }
@@ -805,6 +974,7 @@ function readDataOptions(el) {
805
974
  pageSize: parseNumber(d.pageSize),
806
975
  maxTypeChips: parseNumber(d.maxTypeChips),
807
976
  columns: parseList(d.columns),
977
+ mergeEnharmonicKeys: parseBool(d.mergeEnharmonicKeys),
808
978
  waveformStyle: d.waveformStyle || void 0,
809
979
  waveformColor: d.waveformColor || void 0,
810
980
  progressColor: d.progressColor || void 0,
@@ -848,19 +1018,27 @@ function h(tag, attributes = {}, ...children) {
848
1018
  }
849
1019
 
850
1020
  // src/js/render/icons.ts
851
- function icon(path, extraClass = "") {
852
- const cls = extraClass ? `ws-icon ${extraClass}` : "ws-icon";
853
- return `<svg class="${cls}" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="${path}"/></svg>`;
854
- }
855
- var ICONS = {
856
- play: icon("M8 5.5v13l11-6.5z", "ws-icon-play"),
857
- pause: icon("M7 5h3.5v14H7zM13.5 5H17v14h-3.5z", "ws-icon-pause"),
858
- search: icon("M10.5 4a6.5 6.5 0 1 0 4.03 11.6l4.43 4.43 1.41-1.41-4.43-4.43A6.5 6.5 0 0 0 10.5 4zm0 2a4.5 4.5 0 1 1 0 9 4.5 4.5 0 0 1 0-9z"),
859
- chevron: icon("M6.4 8.6 12 14.2l5.6-5.6L19 10l-7 7-7-7z", "ws-menu-chevron"),
860
- check: icon("M9.5 16.2 5.3 12l-1.4 1.4 5.6 5.6 11-11-1.4-1.4z", "ws-menu-check"),
861
- download: icon("M11 4h2v8.6l3.3-3.3 1.4 1.4L12 16.4l-5.7-5.7 1.4-1.4 3.3 3.3zM5 18h14v2H5z"),
862
- 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")
1021
+ var ICON_PATHS = {
1022
+ play: "M8 5.5v13l11-6.5z",
1023
+ pause: "M7 5h3.5v14H7zM13.5 5H17v14h-3.5z",
1024
+ search: "M10.5 4a6.5 6.5 0 1 0 4.03 11.6l4.43 4.43 1.41-1.41-4.43-4.43A6.5 6.5 0 0 0 10.5 4zm0 2a4.5 4.5 0 1 1 0 9 4.5 4.5 0 0 1 0-9z",
1025
+ chevron: "M6.4 8.6 12 14.2l5.6-5.6L19 10l-7 7-7-7z",
1026
+ check: "M9.5 16.2 5.3 12l-1.4 1.4 5.6 5.6 11-11-1.4-1.4z",
1027
+ download: "M11 4h2v8.6l3.3-3.3 1.4 1.4L12 16.4l-5.7-5.7 1.4-1.4 3.3 3.3zM5 18h14v2H5z",
1028
+ loop: "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"
863
1029
  };
1030
+ var ICON_NAMES = Object.keys(ICON_PATHS);
1031
+ function iconId(id, name) {
1032
+ return `${id}-i-${name}`;
1033
+ }
1034
+ function iconSprite(id, names) {
1035
+ const symbols = ICON_NAMES.filter((n) => names.includes(n)).map((n) => `<symbol id="${escapeHtml(iconId(id, n))}" viewBox="0 0 24 24"><path d="${ICON_PATHS[n]}"/></symbol>`).join("");
1036
+ return `<svg class="ws-sprite" data-ws-sprite="${escapeHtml(id)}" width="0" height="0" aria-hidden="true" focusable="false">${symbols}</svg>`;
1037
+ }
1038
+ function icon(id, name, extraClass = "") {
1039
+ const cls = extraClass ? `ws-icon ${extraClass}` : "ws-icon";
1040
+ return `<svg class="${cls}" aria-hidden="true" focusable="false"><use href="#${escapeHtml(iconId(id, name))}"/></svg>`;
1041
+ }
864
1042
 
865
1043
  // src/js/render/markup.ts
866
1044
  function idBase(sounds) {
@@ -884,11 +1062,11 @@ function toolbarPlan(f, o) {
884
1062
  function loopsByDefault(loop, f) {
885
1063
  return loop == null ? f.loops > 0 : !!loop;
886
1064
  }
887
- function renderSearch(s) {
1065
+ function renderSearch(s, id) {
888
1066
  return h(
889
1067
  "label",
890
1068
  { class: "ws-search" },
891
- ICONS.search,
1069
+ icon(id, "search"),
892
1070
  h("span", { class: "ws-sr" }, text(s.search)),
893
1071
  h("input", { type: "search", class: "ws-search-input", "data-ws-search": true, placeholder: s.searchPlaceholder, autocomplete: "off", spellcheck: "false" })
894
1072
  );
@@ -902,7 +1080,7 @@ function renderMenu(name, m) {
902
1080
  { type: "button", class: "ws-menu-btn", "data-ws-menu-btn": true, "aria-haspopup": "listbox", "aria-expanded": "false", "aria-controls": listId },
903
1081
  m.prefix ? h("span", { class: "ws-menu-prefix" }, text(m.prefix)) : h("span", { class: "ws-sr" }, text(`${m.label}: `)),
904
1082
  h("span", { class: "ws-menu-value", "data-ws-menu-value": true }, text(current.label)),
905
- ICONS.chevron
1083
+ icon(m.id, "chevron", "ws-menu-chevron")
906
1084
  );
907
1085
  const search = searchable && h("input", {
908
1086
  type: "search",
@@ -919,8 +1097,8 @@ function renderMenu(name, m) {
919
1097
  });
920
1098
  const options = m.options.map((o, i) => h(
921
1099
  "li",
922
- { role: "option", id: `${m.id}-${name}-${i}`, class: "ws-menu-option", "data-value": o.value, "aria-selected": String(o === current) },
923
- ICONS.check,
1100
+ { role: "option", id: `${m.id}-${name}-${i}`, class: "ws-menu-option", "data-value": o.value, "data-alt": o.alt, "aria-selected": String(o === current) },
1101
+ icon(m.id, "check", "ws-menu-check"),
924
1102
  h("span", { class: "ws-menu-text" }, text(o.label)),
925
1103
  o.count != null && h("span", { class: "ws-menu-count" }, text(o.count))
926
1104
  ));
@@ -957,7 +1135,7 @@ function renderBpmMenu({ id, s, range }) {
957
1135
  { type: "button", class: "ws-menu-btn", "data-ws-menu-btn": true, "aria-haspopup": "dialog", "aria-expanded": "false", "aria-controls": popId },
958
1136
  h("span", { class: "ws-sr" }, text(`${s.bpm}: `)),
959
1137
  h("span", { class: "ws-menu-value", "data-ws-menu-value": true }, text(bpmLabel({}, range, s))),
960
- ICONS.chevron
1138
+ icon(id, "chevron", "ws-menu-chevron")
961
1139
  ),
962
1140
  h(
963
1141
  "div",
@@ -992,8 +1170,8 @@ function renderLoopFilter(s) {
992
1170
  button("one-shot", s.oneShots)
993
1171
  );
994
1172
  }
995
- function renderLoopToggle(s, pressed) {
996
- return h("button", { type: "button", class: "ws-loop", "data-ws-loop": true, "aria-pressed": String(pressed) }, ICONS.loop, h("span", {}, text(s.loop)));
1173
+ function renderLoopToggle(s, pressed, id) {
1174
+ return h("button", { type: "button", class: "ws-loop", "data-ws-loop": true, "aria-pressed": String(pressed) }, icon(id, "loop"), h("span", {}, text(s.loop)));
997
1175
  }
998
1176
  function renderChip(value, label, count, pressed) {
999
1177
  return h(
@@ -1017,9 +1195,9 @@ function renderToolbar(plan, { o, s, f, total, id }) {
1017
1195
  label: s.key,
1018
1196
  value: "",
1019
1197
  placeholder: s.findKey,
1020
- options: [{ value: "", label: s.anyKey }, ...f.keys.map((k) => ({ value: k, label: k }))]
1198
+ options: [{ value: "", label: s.anyKey }, ...f.keys.map((k) => ({ value: k, label: k, alt: f.keyAliases[k]?.join(" ") }))]
1021
1199
  }),
1022
- plan.bpm && renderBpmMenu({ id, s, range: f.bpm }),
1200
+ plan.bpm && renderBpmMenu({ id, s, range: bpmExtent(f.bpm) }),
1023
1201
  plan.loops && renderLoopFilter(s),
1024
1202
  plan.sorts.length > 0 && menu("sort", {
1025
1203
  label: s.sort,
@@ -1027,7 +1205,7 @@ function renderToolbar(plan, { o, s, f, total, id }) {
1027
1205
  value: plan.sorts[0],
1028
1206
  options: plan.sorts.map((k) => ({ value: k, label: s[SORT_LABEL_KEYS[k]] }))
1029
1207
  }),
1030
- plan.loop && renderLoopToggle(s, loopsByDefault(o.loop, f))
1208
+ plan.loop && renderLoopToggle(s, loopsByDefault(o.loop, f), id)
1031
1209
  ].filter(Boolean);
1032
1210
  const chips = plan.types === "chips" && h(
1033
1211
  "div",
@@ -1039,7 +1217,7 @@ function renderToolbar(plan, { o, s, f, total, id }) {
1039
1217
  return h(
1040
1218
  "div",
1041
1219
  { class: "ws-toolbar" },
1042
- plan.search && renderSearch(s),
1220
+ plan.search && renderSearch(s, id),
1043
1221
  controls.length > 0 && h("div", { class: "ws-controls" }, controls),
1044
1222
  // The chips and the count share a row (the count alone without chips).
1045
1223
  (chips || count) && h("div", { class: "ws-meta" }, chips, count)
@@ -1051,49 +1229,66 @@ var CELLS = {
1051
1229
  key: (sound) => text(sound.key),
1052
1230
  duration: (sound) => text(formatDuration(sound.duration))
1053
1231
  };
1054
- function renderRow(sound, index, o, hidden = false) {
1232
+ function renderRow(sound, index, o, id) {
1055
1233
  const s = o.strings;
1056
1234
  const vars = { title: sound.title };
1057
1235
  const cells = o.columns.map((c) => h("span", { class: `ws-cell ws-${c}` }, CELLS[c](sound)));
1236
+ const summary = rowSummary(sound, o.columns, s);
1237
+ const described = summary ? `${id}-d${index}` : null;
1058
1238
  return h(
1059
1239
  "li",
1060
- {
1061
- class: "ws-row",
1062
- "data-ws-index": index,
1063
- "data-ws-id": sound.id,
1064
- "data-url": sound.url,
1065
- "data-title": sound.title,
1066
- "data-type": sound.type || null,
1067
- "data-bpm": sound.bpm,
1068
- "data-key": sound.key || null,
1069
- "data-duration": sound.duration,
1070
- "data-tags": sound.tags?.length ? sound.tags.join(",") : null,
1071
- "data-peaks": sound.peaks ? encodePeaks(sound.peaks) : null,
1072
- "data-waveform": sound.waveform,
1073
- "data-download": sound.download,
1074
- "data-loop": sound.loop ? "true" : null,
1075
- hidden
1076
- },
1077
- h("button", { type: "button", class: "ws-play", "aria-pressed": "false", "aria-label": fill(s.play, vars) }, ICONS.play, ICONS.pause),
1240
+ { class: "ws-row", "data-ws-index": index },
1241
+ h(
1242
+ "button",
1243
+ { type: "button", class: "ws-play", "aria-pressed": "false", "aria-label": fill(s.play, vars), "aria-describedby": described },
1244
+ icon(id, "play", "ws-icon-play"),
1245
+ icon(id, "pause", "ws-icon-pause")
1246
+ ),
1078
1247
  h(
1079
1248
  "span",
1080
1249
  { class: "ws-cell ws-title" },
1081
1250
  h("span", { class: "ws-title-text" }, text(sound.title)),
1082
- // A loop says so beside its name; a one-shot carries nothing.
1083
- sound.loop && h("span", { class: "ws-loop-mark", title: s.isLoop }, ICONS.loop, h("span", { class: "ws-sr" }, text(s.isLoop)))
1251
+ // A loop says so beside its name (and in the read-out); a one-shot carries nothing.
1252
+ sound.loop && h("span", { class: "ws-loop-mark", title: s.isLoop, "aria-hidden": "true" }, icon(id, "loop"))
1084
1253
  ),
1085
1254
  // Wide rows: `display: contents` makes each cell a column. Narrow
1086
1255
  // rows: one line under the title.
1087
- cells.length > 0 && h("span", { class: "ws-cells" }, cells),
1088
- o.player === "inline" && h(
1089
- "span",
1090
- { class: "ws-wave", role: "slider", "aria-label": fill(s.seek, vars), "aria-valuemin": "0", "aria-valuemax": "100", "aria-valuenow": "0", tabindex: "-1" },
1091
- h("canvas", { class: "ws-canvas", "aria-hidden": "true" })
1092
- ),
1256
+ cells.length > 0 && h("span", { class: "ws-cells", "aria-hidden": "true" }, cells),
1257
+ summary && h("span", { class: "ws-sr", id: described }, text(summary)),
1258
+ o.player === "inline" && h("span", { class: "ws-wave", "aria-hidden": "true" }, h("canvas", { class: "ws-canvas" })),
1093
1259
  // Optional, per sound: a plain link. Rows without one carry nothing.
1094
- sound.download && h("a", { class: "ws-download", href: sound.download, download: true, "aria-label": fill(s.download, vars) }, ICONS.download)
1260
+ sound.download && h("a", { class: "ws-download", href: sound.download, download: true, "aria-label": fill(s.download, vars) }, icon(id, "download"))
1095
1261
  );
1096
1262
  }
1263
+ function renderSoundsData(list) {
1264
+ const data = list.map((s, i) => {
1265
+ const d = {};
1266
+ if (s.id !== `sound-${i + 1}`) d.id = s.id;
1267
+ d.url = s.url;
1268
+ d.title = s.title;
1269
+ if (s.type) d.type = s.type;
1270
+ if (s.bpm != null) d.bpm = s.bpm;
1271
+ if (s.key) d.key = s.key;
1272
+ if (s.duration != null) d.duration = s.duration;
1273
+ if (s.tags.length) d.tags = s.tags;
1274
+ if (s.peaks) d.peaks = encodePeaks(s.peaks);
1275
+ if (s.waveform) d.waveform = s.waveform;
1276
+ if (s.download) d.download = s.download;
1277
+ if (s.loop) d.loop = true;
1278
+ return d;
1279
+ });
1280
+ return `<script type="application/json" data-ws-sounds>${JSON.stringify(data).replace(/</g, "\\u003c")}<\/script>`;
1281
+ }
1282
+ function iconsUsed(plan, list) {
1283
+ const names = [];
1284
+ if (list.length) names.push("play", "pause");
1285
+ if (plan.search) names.push("search");
1286
+ if (plan.types === "menu" || plan.key || plan.sorts.length) names.push("chevron", "check");
1287
+ else if (plan.bpm) names.push("chevron");
1288
+ if (plan.loop || list.some((s) => s.loop)) names.push("loop");
1289
+ if (list.some((s) => s.download)) names.push("download");
1290
+ return names;
1291
+ }
1097
1292
  function renderFooter({ o, s, total }) {
1098
1293
  const page = o.pageSize > 0 ? o.pageSize : total;
1099
1294
  const more = Math.max(0, total - page);
@@ -1112,24 +1307,58 @@ function renderFooter({ o, s, total }) {
1112
1307
  ].join("");
1113
1308
  }
1114
1309
  function renderSounds(sounds, options = {}) {
1310
+ return renderList(normalizeSounds(sounds), options, true);
1311
+ }
1312
+ function renderList(list, options, withData) {
1115
1313
  const o = resolveRenderOptions(options);
1116
- const list = normalizeSounds(sounds);
1117
- const ctx = { o, s: o.strings, f: facets(list), total: list.length, id: o.idPrefix || idBase(list) };
1118
- const page = o.pageSize > 0 ? o.pageSize : Infinity;
1119
- return renderToolbar(toolbarPlan(ctx.f, o), ctx) + h(
1314
+ const ctx = { o, s: o.strings, f: facets(list, o), total: list.length, id: o.idPrefix || idBase(list) };
1315
+ const plan = toolbarPlan(ctx.f, o);
1316
+ const index = new Map(list.map((sound, i) => [sound, i]));
1317
+ const first = sortSounds(list, availableSorts(o.sorts, ctx.f)[0] || "default").slice(0, firstRender(o.pageSize));
1318
+ return iconSprite(ctx.id, iconsUsed(plan, list)) + renderToolbar(plan, ctx) + h(
1120
1319
  "ul",
1121
1320
  { class: `ws-list ws-list--${o.player}`, role: "list", "data-ws-list": true },
1122
- list.map((sound, i) => renderRow(sound, i, o, i >= page))
1123
- ) + renderFooter(ctx);
1321
+ first.map((sound) => renderRow(sound, index.get(sound), o, ctx.id))
1322
+ ) + renderFooter(ctx) + (withData ? renderSoundsData(list) : "");
1323
+ }
1324
+ function renderOptionAttributes(options = {}) {
1325
+ const set = pickRenderOptions(options);
1326
+ const o = resolveRenderOptions(options);
1327
+ const out = {};
1328
+ for (const key of RENDER_OPTION_KEYS) {
1329
+ if (key === "player" || !(key in set)) continue;
1330
+ const name = `data-${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`;
1331
+ if (key === "strings") {
1332
+ const strings = defined(set.strings);
1333
+ if (Object.keys(strings).length) out[name] = JSON.stringify(strings);
1334
+ } else if (key === "loop" || key === "idPrefix") {
1335
+ out[name] = String(set[key]);
1336
+ } else {
1337
+ const value = o[key];
1338
+ out[name] = Array.isArray(value) ? value.join(",") : String(value);
1339
+ }
1340
+ }
1341
+ return out;
1124
1342
  }
1125
1343
  function renderSoundsElement(sounds, options = {}, className = "") {
1126
1344
  const o = resolveRenderOptions(options);
1127
1345
  const cls = ["waveform-sounds", `waveform-sounds--${o.player}`, className].filter(Boolean).join(" ");
1128
- return h("div", { class: cls, "data-waveform-sounds": true, "data-player": o.player }, renderSounds(sounds, options));
1346
+ return h("div", { class: cls, "data-waveform-sounds": true, "data-player": o.player, ...renderOptionAttributes(options) }, renderSounds(sounds, options));
1129
1347
  }
1130
1348
 
1131
1349
  // src/js/dom/rows.ts
1132
1350
  var ROW = ":scope > [data-ws-index]";
1351
+ function readSoundsData(root) {
1352
+ const script = root.querySelector(":scope > script[data-ws-sounds]");
1353
+ if (!script) return null;
1354
+ try {
1355
+ const list = JSON.parse(script.textContent || "");
1356
+ if (Array.isArray(list)) return normalizeSounds(list);
1357
+ } catch {
1358
+ }
1359
+ console.warn(`${LOG} Ignoring unreadable sounds JSON (data-ws-sounds)`);
1360
+ return null;
1361
+ }
1133
1362
  function readRows(list) {
1134
1363
  const rows = [...list.querySelectorAll(ROW)].sort((a, b) => Number(a.dataset.wsIndex) - Number(b.dataset.wsIndex));
1135
1364
  const sounds = [];
@@ -1168,10 +1397,14 @@ function indexRows(list) {
1168
1397
  function visibleRows(list) {
1169
1398
  return [...list.querySelectorAll(ROW)].filter((r) => !r.hidden);
1170
1399
  }
1171
- function orderRows(list, rows) {
1172
- const frag = document.createDocumentFragment();
1173
- for (const row of rows) if (row) frag.appendChild(row);
1174
- list.appendChild(frag);
1400
+ function layoutRows(list, rows) {
1401
+ const keep = new Set(rows);
1402
+ for (const el of [...list.children]) if (!keep.has(el)) el.remove();
1403
+ let cursor = list.firstElementChild;
1404
+ for (const row of rows) {
1405
+ if (row === cursor) cursor = cursor.nextElementSibling;
1406
+ else list.insertBefore(row, cursor);
1407
+ }
1175
1408
  }
1176
1409
 
1177
1410
  // src/js/dom/colors.ts
@@ -1191,9 +1424,21 @@ function pageSurface(el, minAlpha = 0.95) {
1191
1424
  }
1192
1425
  return "#fff";
1193
1426
  }
1427
+ function forcedColors() {
1428
+ try {
1429
+ return typeof matchMedia === "function" && matchMedia("(forced-colors: active)").matches;
1430
+ } catch {
1431
+ return false;
1432
+ }
1433
+ }
1434
+ function ancestorsOf(el) {
1435
+ const out = [];
1436
+ for (let node = el.parentElement || el.getRootNode?.()?.host; node; node = node.parentElement || node.getRootNode?.()?.host) out.push(node);
1437
+ return out;
1438
+ }
1194
1439
  function resolveCssColor(container, value) {
1195
1440
  const probe = document.createElement("span");
1196
- probe.style.cssText = "position:absolute;width:0;height:0;overflow:hidden;visibility:hidden";
1441
+ probe.style.cssText = "position:absolute;width:0;height:0;overflow:hidden;visibility:hidden;forced-color-adjust:none";
1197
1442
  probe.style.color = value;
1198
1443
  container.appendChild(probe);
1199
1444
  const color = getComputedStyle(probe).color;
@@ -1208,14 +1453,22 @@ function urlKeys(urlState) {
1208
1453
  return { q: `${p}q`, type: `${p}type`, key: `${p}key`, bpm: `${p}bpm`, loop: `${p}loop`, sort: `${p}sort` };
1209
1454
  }
1210
1455
  function parseBpmRange(value) {
1211
- const m = String(value ?? "").match(/^(\d*)-(\d*)$/);
1212
- return m && (m[1] || m[2]) ? { bpmMin: m[1], bpmMax: m[2] } : null;
1456
+ const m = String(value ?? "").match(/^(\d+(?:\.\d+)?)?-(\d+(?:\.\d+)?)?$/);
1457
+ if (!m || !(m[1] || m[2])) return null;
1458
+ const lo = m[1] ?? "", hi = m[2] ?? "";
1459
+ return lo && hi && Number(lo) > Number(hi) ? { bpmMin: hi, bpmMax: lo } : { bpmMin: lo, bpmMax: hi };
1460
+ }
1461
+ function bpmRangeWithin(range, extent) {
1462
+ if (!extent) return null;
1463
+ const inside = (v) => v !== "" && Number(v) >= extent.min && Number(v) <= extent.max ? v : "";
1464
+ const out = { bpmMin: inside(range.bpmMin), bpmMax: inside(range.bpmMax) };
1465
+ return out.bpmMin || out.bpmMax ? out : null;
1213
1466
  }
1214
1467
  function formatBpmRange(min, max) {
1215
1468
  const lo = min ?? "", hi = max ?? "";
1216
1469
  return lo !== "" || hi !== "" ? `${lo}-${hi}` : "";
1217
1470
  }
1218
- function readUrlState(search, keys, available, sorts) {
1471
+ function readUrlState(search, keys, available, sorts, options = {}) {
1219
1472
  const out = { filter: {}, sort: null };
1220
1473
  if (!keys) return out;
1221
1474
  const sp = new URLSearchParams(search);
@@ -1223,9 +1476,10 @@ function readUrlState(search, keys, available, sorts) {
1223
1476
  if (q) out.filter.query = q;
1224
1477
  const type = sp.get(keys.type);
1225
1478
  if (type && available.types.some((t) => t.name === type)) out.filter.type = type;
1226
- const key = normalizeKey(sp.get(keys.key));
1227
- if (key && available.keys.includes(key)) out.filter.key = key;
1228
- const bpm = parseBpmRange(sp.get(keys.bpm));
1479
+ const key = keyEntry(normalizeKey(sp.get(keys.key)), available.keys, options.mergeEnharmonicKeys !== false);
1480
+ if (key) out.filter.key = key;
1481
+ const parsed = parseBpmRange(sp.get(keys.bpm));
1482
+ const bpm = parsed && available.bpm !== void 0 ? bpmRangeWithin(parsed, available.bpm) : parsed;
1229
1483
  if (bpm) Object.assign(out.filter, bpm);
1230
1484
  const loop = sp.get(keys.loop);
1231
1485
  if (LOOP_FILTERS.includes(loop) && available.loops > 0 && available.oneShots > 0) out.filter.loop = loop;
@@ -1251,7 +1505,7 @@ var NO_FILTER = Object.freeze({ query: "", type: "", key: "", bpmMin: "", bpmMax
1251
1505
  var SEARCH_DELAY = 120;
1252
1506
  var BPM_DELAY = 200;
1253
1507
  var URL_DELAY = 250;
1254
- var WaveformSounds = class _WaveformSounds {
1508
+ var WaveformSounds = class _WaveformSounds extends EventTarget {
1255
1509
  /** Every live instance, by its element. */
1256
1510
  static instances = /* @__PURE__ */ new Map();
1257
1511
  /**
@@ -1259,10 +1513,12 @@ var WaveformSounds = class _WaveformSounds {
1259
1513
  * @param {WaveformSoundsOptions} [options]
1260
1514
  */
1261
1515
  constructor(container, options = {}) {
1516
+ super();
1262
1517
  const el = typeof container === "string" ? document.querySelector(container) : container;
1263
1518
  if (!el) throw new Error(`${LOG} Container not found: ${container}`);
1264
1519
  this.container = el;
1265
- this.options = mergeOptions(DEFAULT_OPTIONS, options, readDataOptions(el));
1520
+ const data = el._wsOptions?.() ?? readDataOptions(el);
1521
+ this.options = mergeOptions(DEFAULT_OPTIONS, options, data);
1266
1522
  this.options.waveformStyle = this.options.waveformStyle === "bars" ? "bars" : "mirror";
1267
1523
  this.strings = { ...DEFAULT_STRINGS, ...this.options.strings || {} };
1268
1524
  this.render = { ...resolveRenderOptions(this.options), strings: this.strings };
@@ -1271,6 +1527,9 @@ var WaveformSounds = class _WaveformSounds {
1271
1527
  this.filter = { ...NO_FILTER };
1272
1528
  this.sortBy = "default";
1273
1529
  this.limit = this._pageSize();
1530
+ this._budget = this._firstBudget();
1531
+ this._index = /* @__PURE__ */ new Map();
1532
+ this._failed = /* @__PURE__ */ new Set();
1274
1533
  this.currentIndex = null;
1275
1534
  this.playing = false;
1276
1535
  this.progress = 0;
@@ -1285,7 +1544,9 @@ var WaveformSounds = class _WaveformSounds {
1285
1544
  _WaveformSounds.instances.set(el, this);
1286
1545
  el.dataset.wsInitialized = "true";
1287
1546
  this.ready = Promise.resolve().then(() => this._init()).catch((err) => {
1547
+ if (this.destroyed) return;
1288
1548
  console.error(`${LOG} Failed to initialise:`, err);
1549
+ this._showLoadError();
1289
1550
  this._emit("error", { error: err });
1290
1551
  this.options.onError?.(err, this);
1291
1552
  });
@@ -1300,28 +1561,32 @@ var WaveformSounds = class _WaveformSounds {
1300
1561
  const el = this.container;
1301
1562
  const adopted = el.querySelector("[data-ws-list]");
1302
1563
  if (adopted) {
1303
- this.sounds = readRows(adopted);
1564
+ this._adoptedHTML = el.innerHTML;
1565
+ this.sounds = readSoundsData(el) ?? readRows(adopted);
1304
1566
  } else {
1305
1567
  this._originalHTML = el.innerHTML;
1306
1568
  this.sounds = await this._loadSounds();
1307
1569
  if (this.destroyed) return;
1308
- el.innerHTML = renderSounds(this.sounds, { ...this.render, idPrefix: this.options.idPrefix || el.id || void 0 });
1570
+ el.innerHTML = renderList(this.sounds, { ...this.render, idPrefix: this.options.idPrefix || el.id || void 0 }, false);
1309
1571
  }
1310
1572
  if (this.destroyed) return;
1573
+ this._index = new Map(this.sounds.map((sound, i) => [sound, i]));
1311
1574
  this._addedClasses = ["waveform-sounds", `waveform-sounds--${this.render.player}`].filter((c) => !el.classList.contains(c));
1312
1575
  el.classList.add(...this._addedClasses);
1576
+ this._facets = facets(this.sounds, this.render);
1313
1577
  this._cacheRefs();
1314
1578
  this._bind();
1315
1579
  this._observe();
1316
1580
  this._resolveColors();
1317
- if (!this._loopSet) this.loop = loopsByDefault(this.options.loop, facets(this.sounds));
1581
+ if (!this._loopSet) this.loop = loopsByDefault(this.options.loop, this._facets);
1318
1582
  this._setLoop(this.loop);
1319
- this._bpmExtent = facets(this.sounds).bpm;
1320
- this._sorts = availableSorts(this.render.sorts, facets(this.sounds));
1583
+ this._bpmExtent = bpmExtent(this._facets.bpm);
1584
+ this._sorts = availableSorts(this.render.sorts, this._facets);
1321
1585
  if (!this._sortSet) this.sortBy = this._sorts[0] || "default";
1322
1586
  this._readUrl();
1587
+ this.filter = { ...this.filter, key: this._keyEntry(this.filter.key) };
1323
1588
  this._syncControls();
1324
- this._apply({ resort: this.sortBy !== "default" });
1589
+ this._apply();
1325
1590
  if (this._playerClass()) this._ensureEngine();
1326
1591
  if (this.render.player === "strip" && this.engine && this.currentIndex == null) this._cueFirst();
1327
1592
  this._emit("ready", { sounds: this.sounds.length });
@@ -1329,14 +1594,28 @@ var WaveformSounds = class _WaveformSounds {
1329
1594
  }
1330
1595
  /**
1331
1596
  * The sounds from the `sounds` option, else the `manifest` URL.
1332
- * @returns
1333
1597
  * @internal
1334
1598
  */
1335
1599
  async _loadSounds() {
1336
1600
  if (this.options.sounds || !this.options.manifest) return normalizeSounds(this.options.sounds || []);
1337
- const res = await fetch(this.options.manifest);
1338
- if (!res.ok) throw new Error(`${LOG} Manifest ${this.options.manifest}: HTTP ${res.status}`);
1339
- return parseManifest(await res.json());
1601
+ const url = this.options.manifest;
1602
+ const res = await fetch(url, { signal: this._ctl.signal });
1603
+ if (!res.ok) throw new Error(`${LOG} Manifest ${url}: HTTP ${res.status}`);
1604
+ const manifest = await res.json();
1605
+ if (!Array.isArray(manifest) && !Array.isArray(manifest?.sounds)) throw new Error(`${LOG} Manifest ${url}: no "sounds" list`);
1606
+ return parseManifest(manifest);
1607
+ }
1608
+ /**
1609
+ * A build that failed (the manifest 404s, isn't JSON, isn't a manifest)
1610
+ * says so where the list would be — unless the container holds the
1611
+ * site's own fallback, which stays. destroy() restores what was there.
1612
+ * @internal
1613
+ */
1614
+ _showLoadError() {
1615
+ const el = this.container;
1616
+ if (this.$ || el.querySelector("*")) return;
1617
+ this._originalHTML ??= el.innerHTML;
1618
+ el.innerHTML = h("p", { class: "ws-empty ws-load-error", role: "alert", "data-ws-load-error": true }, text(this.strings.loadError));
1340
1619
  }
1341
1620
  /**
1342
1621
  * Look up the elements the runtime drives.
@@ -1362,7 +1641,65 @@ var WaveformSounds = class _WaveformSounds {
1362
1641
  chips: [...this.container.querySelectorAll("[data-ws-type]")],
1363
1642
  loopFilter: [...this.container.querySelectorAll("[data-ws-loop-filter]")]
1364
1643
  };
1365
- this.rows = indexRows(this.$.list);
1644
+ const sprite = q("[data-ws-sprite]");
1645
+ this._iconId = sprite?.dataset.wsSprite ?? (this.options.idPrefix || this.container.id || idBase(this.sounds));
1646
+ if (!sprite) this.$.list.insertAdjacentHTML("beforebegin", iconSprite(this._iconId, ICON_NAMES));
1647
+ this.rows = [];
1648
+ this._active = null;
1649
+ for (const row of indexRows(this.$.list)) if (row) this._adoptRow(row);
1650
+ }
1651
+ /**
1652
+ * Take a row (server-rendered, or just rendered) into the list's
1653
+ * keeping: its index, its Tab stops off, the state of its sound (current,
1654
+ * failed), and the observer that draws it.
1655
+ * @internal
1656
+ */
1657
+ _adoptRow(row) {
1658
+ const i = Number(row.dataset.wsIndex);
1659
+ this.rows[i] = row;
1660
+ this._rowStops(row, false);
1661
+ const wave = row.querySelector(".ws-wave");
1662
+ if (i === this.currentIndex || this._failed.has(i) || wave?.hasAttribute("role")) this._paintRow(i);
1663
+ if (i === this.currentIndex) this._paintSlider();
1664
+ if (this._io) this._io.observe(row);
1665
+ else this._drawn?.add(i);
1666
+ }
1667
+ /**
1668
+ * Rows for these sounds, rendered (in one pass) where they have none.
1669
+ * @returns The rows, in the order given.
1670
+ * @internal
1671
+ */
1672
+ _rowsFor(indices) {
1673
+ const missing = indices.filter((i) => !this.rows[i]);
1674
+ if (missing.length) {
1675
+ const tpl = document.createElement("template");
1676
+ tpl.innerHTML = missing.map((i) => renderRow(this.sounds[i], i, this.render, this._iconId)).join("");
1677
+ for (const row of [...tpl.content.children]) this._adoptRow(row);
1678
+ }
1679
+ return indices.map((i) => this.rows[i]);
1680
+ }
1681
+ /**
1682
+ * Make a row's own controls (play, download, and the seek slider when it
1683
+ * is the current sound) Tab stops, or not.
1684
+ * @internal
1685
+ */
1686
+ _rowStops(row, on) {
1687
+ const play = row.querySelector(".ws-play");
1688
+ if (play) play.tabIndex = on ? 0 : -1;
1689
+ const dl = row.querySelector(".ws-download");
1690
+ if (dl) dl.tabIndex = on ? 0 : -1;
1691
+ const wave = row.querySelector(".ws-wave");
1692
+ if (wave && Number(row.dataset.wsIndex) === this.currentIndex) wave.tabIndex = on ? 0 : -1;
1693
+ }
1694
+ /**
1695
+ * Move the list's Tab stop to `row` (roving tabindex).
1696
+ * @internal
1697
+ */
1698
+ _rove(row) {
1699
+ if (!row || row === this._active) return;
1700
+ if (this._active) this._rowStops(this._active, false);
1701
+ this._active = row;
1702
+ this._rowStops(row, true);
1366
1703
  }
1367
1704
  /**
1368
1705
  * Every listener. All are removed by `destroy()` through one
@@ -1376,6 +1713,7 @@ var WaveformSounds = class _WaveformSounds {
1376
1713
  root.addEventListener("click", (e) => this._onClick(e), sig);
1377
1714
  root.addEventListener("pointerdown", (e) => this._onPointerDown(e), sig);
1378
1715
  root.addEventListener("keydown", (e) => this._onKey(e), sig);
1716
+ $.list.addEventListener("focusin", (e) => this._rove(e.target.closest("[data-ws-index]")), sig);
1379
1717
  let searchTimer = 0, bpmTimer = 0;
1380
1718
  $.search?.addEventListener("input", () => {
1381
1719
  clearTimeout(searchTimer);
@@ -1434,11 +1772,13 @@ var WaveformSounds = class _WaveformSounds {
1434
1772
  return;
1435
1773
  }
1436
1774
  if (t.closest("[data-ws-more]")) {
1437
- this.showMore();
1775
+ this._showMoreFromButton();
1438
1776
  return;
1439
1777
  }
1440
1778
  if (t.closest("[data-ws-clear]")) {
1441
1779
  this.clearFilters();
1780
+ if (this.$.search) this.$.search.focus();
1781
+ else this._focusRow(visibleRows(this.$.list)[0]);
1442
1782
  return;
1443
1783
  }
1444
1784
  if (t.closest("[data-ws-loop]")) {
@@ -1455,6 +1795,17 @@ var WaveformSounds = class _WaveformSounds {
1455
1795
  this.toggle(Number(row.dataset.wsIndex));
1456
1796
  this._focusRowQuietly(row);
1457
1797
  }
1798
+ /**
1799
+ * "Show more", pressed: reveal the next page. When that was the last page
1800
+ * the button hides, so focus moves to the first row it revealed rather
1801
+ * than falling to <body>.
1802
+ * @internal
1803
+ */
1804
+ _showMoreFromButton() {
1805
+ const before = new Set(visibleRows(this.$.list));
1806
+ this.showMore();
1807
+ if (this.$.more?.hidden) this._focusRow(visibleRows(this.$.list).find((r) => !before.has(r)));
1808
+ }
1458
1809
  /**
1459
1810
  * Mouse and pen seek on PRESS, like every scrubber. Remembers the
1460
1811
  * pointer type for the click that follows.
@@ -1478,7 +1829,8 @@ var WaveformSounds = class _WaveformSounds {
1478
1829
  }
1479
1830
  /**
1480
1831
  * Keys on the list: `/` focuses search; ↑/↓/Home/End move between rows
1481
- * (auditioning while something plays); ←/→ seek the playing row.
1832
+ * (auditioning while something plays); ←/→ seek the playing row, and on
1833
+ * its seek slider Home/End seek to the start/end.
1482
1834
  * @internal
1483
1835
  */
1484
1836
  _onKey(e) {
@@ -1491,23 +1843,43 @@ var WaveformSounds = class _WaveformSounds {
1491
1843
  const row = e.target.closest?.("[data-ws-index]");
1492
1844
  if (!row) return;
1493
1845
  const index = Number(row.dataset.wsIndex);
1494
- const seek = seekTarget(this.progress, e.key);
1846
+ const edge = e.target.closest(".ws-wave") ? sliderEdgeTarget(e.key) : null;
1847
+ const seek = edge ?? seekTarget(this.progress, e.key);
1495
1848
  if (seek !== null) {
1496
1849
  if (index !== this.currentIndex || !this.engine) return;
1497
1850
  e.preventDefault();
1498
1851
  this._seekRow(index, seek);
1499
1852
  return;
1500
1853
  }
1501
- const rows = visibleRows(this.$.list);
1502
- const target = rowTarget(e.key, rows.indexOf(row), rows.length);
1854
+ const shown = this._shown ?? [];
1855
+ const target = rowTarget(e.key, shown.indexOf(this.sounds[index]), Math.min(shown.length, this.limit));
1503
1856
  if (target === null) return;
1504
1857
  e.preventDefault();
1505
1858
  if (target === "search") {
1506
1859
  this.$.search?.focus();
1507
1860
  return;
1508
1861
  }
1509
- this._focusRow(rows[target]);
1510
- if (this.options.arrowAudition && this.playing) this.play(Number(rows[target].dataset.wsIndex));
1862
+ this._focusRow(this._reveal(target));
1863
+ if (this.options.arrowAudition && this.playing) this.play(this._index.get(shown[target]));
1864
+ }
1865
+ /**
1866
+ * The row at position `pos` of the matching sounds, revealing it first:
1867
+ * past the page, the page grows to it (as `next()` always did); with
1868
+ * paging off, rows are rendered up to it.
1869
+ * @internal
1870
+ */
1871
+ _reveal(pos) {
1872
+ const sound = this._shown?.[pos];
1873
+ if (!sound) return void 0;
1874
+ const limit = limitToReveal(this.limit, pos);
1875
+ if (limit !== this.limit) {
1876
+ this.limit = limit;
1877
+ this._apply();
1878
+ } else if (this.limit === Infinity && pos >= this._budget) {
1879
+ this._budget = budgetToReveal(this._budget, pos);
1880
+ this._layout();
1881
+ }
1882
+ return this.rows[this._index.get(sound)];
1511
1883
  }
1512
1884
  /**
1513
1885
  * Focus a row's play button.
@@ -1537,11 +1909,18 @@ var WaveformSounds = class _WaveformSounds {
1537
1909
  _observe() {
1538
1910
  if (this.render.player !== "inline" || typeof window === "undefined") return;
1539
1911
  this._drawn = /* @__PURE__ */ new Set();
1912
+ this._dirty = /* @__PURE__ */ new Set();
1540
1913
  if ("IntersectionObserver" in window) {
1914
+ this._onScreen = /* @__PURE__ */ new Set();
1541
1915
  this._io = new IntersectionObserver((entries) => {
1542
1916
  for (const entry of entries) {
1543
- if (!entry.isIntersecting) continue;
1544
1917
  const i = Number(entry.target.dataset.wsIndex);
1918
+ if (!entry.isIntersecting) {
1919
+ this._onScreen.delete(i);
1920
+ continue;
1921
+ }
1922
+ this._onScreen.add(i);
1923
+ if (this._drawn.has(i) && !this._dirty.has(i)) continue;
1545
1924
  this._drawn.add(i);
1546
1925
  this._drawRow(i);
1547
1926
  }
@@ -1560,34 +1939,46 @@ var WaveformSounds = class _WaveformSounds {
1560
1939
  });
1561
1940
  this._ro.observe(this.$.list);
1562
1941
  }
1563
- const refresh = () => requestAnimationFrame(() => {
1564
- this._resolveColors();
1565
- this._redrawAll();
1566
- });
1942
+ let queued = 0;
1943
+ const refresh = () => {
1944
+ if (queued) return;
1945
+ queued = requestAnimationFrame(() => {
1946
+ queued = 0;
1947
+ if (this._resolveColors()) this._redrawAll();
1948
+ });
1949
+ };
1567
1950
  this._mo = new MutationObserver(refresh);
1568
- const watch = { attributes: true, attributeFilter: ["class", "data-theme", "data-color-scheme", "style"] };
1569
- this._mo.observe(document.documentElement, watch);
1570
- if (document.body) this._mo.observe(document.body, watch);
1571
- try {
1572
- window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", refresh, { signal: this._ctl.signal });
1573
- } catch {
1951
+ this._mo.observe(this.container, { attributes: true, attributeFilter: ["class", "data-theme", "data-color-scheme"] });
1952
+ for (const node of ancestorsOf(this.container)) {
1953
+ this._mo.observe(node, { attributes: true, attributeFilter: ["class", "data-theme", "data-color-scheme", "style"] });
1954
+ }
1955
+ for (const query of ["(prefers-color-scheme: dark)", "(forced-colors: active)"]) {
1956
+ try {
1957
+ window.matchMedia(query).addEventListener("change", refresh, { signal: this._ctl.signal });
1958
+ } catch {
1959
+ }
1574
1960
  }
1575
1961
  }
1576
1962
  /**
1577
- * Resolve the canvas colours (options, else the CSS custom properties)
1578
- * and keep `--ws-surface` current unless the site set it.
1963
+ * Resolve the canvas colours (options, else the CSS custom properties;
1964
+ * system colours under forced colours) and keep `--ws-surface` current
1965
+ * unless the site set it.
1966
+ * @returns Whether the canvas colours changed.
1579
1967
  * @internal
1580
1968
  */
1581
1969
  _resolveColors() {
1970
+ const before = this.colors;
1582
1971
  if (this._autoSurface || !getComputedStyle(this.container).getPropertyValue("--ws-surface").trim()) {
1583
1972
  this._autoSurface = true;
1584
1973
  this.container.style.removeProperty("--ws-surface");
1585
1974
  this.container.style.setProperty("--ws-surface", pageSurface(this.container));
1586
1975
  }
1976
+ const forced = forcedColors();
1587
1977
  this.colors = {
1588
- wave: this.options.waveformColor || resolveCssColor(this.container, "var(--ws-wave-color)") || "rgba(128,128,128,.5)",
1589
- progress: this.options.progressColor || resolveCssColor(this.container, "var(--ws-progress-color)") || "currentColor"
1978
+ wave: (forced ? resolveCssColor(this.container, "CanvasText") : this.options.waveformColor || resolveCssColor(this.container, "var(--ws-wave-color)")) || "rgba(128,128,128,.5)",
1979
+ progress: (forced ? resolveCssColor(this.container, "Highlight") : this.options.progressColor || resolveCssColor(this.container, "var(--ws-progress-color)")) || "currentColor"
1590
1980
  };
1981
+ return !before || before.wave !== this.colors.wave || before.progress !== this.colors.progress;
1591
1982
  }
1592
1983
  /**
1593
1984
  * Draw one row's waveform (only once it has been on screen).
@@ -1597,7 +1988,12 @@ var WaveformSounds = class _WaveformSounds {
1597
1988
  if (this.render.player !== "inline" || index == null || !this._drawn?.has(index)) return;
1598
1989
  const row = this.rows[index];
1599
1990
  const canvas = row?.querySelector("canvas");
1600
- if (!canvas || row.hidden) return;
1991
+ if (!canvas) return;
1992
+ if (!row.isConnected) {
1993
+ this._dirty?.add(index);
1994
+ return;
1995
+ }
1996
+ this._dirty?.delete(index);
1601
1997
  const gap = Number(this.options.barGap);
1602
1998
  drawRowWaveform(canvas, this.sounds[index].peaks, index === this.currentIndex ? this.progress : 0, {
1603
1999
  style: this.options.waveformStyle,
@@ -1608,11 +2004,17 @@ var WaveformSounds = class _WaveformSounds {
1608
2004
  });
1609
2005
  }
1610
2006
  /**
1611
- * Redraw every row drawn so far.
2007
+ * After a resize or a theme flip: redraw the rows on screen now, and
2008
+ * mark the rest stale — each is redrawn when it scrolls back in. (With
2009
+ * 1000 rows drawn, redrawing them all took ~0.4s in Chrome and ~1.9s in
2010
+ * WebKit per resize step.)
1612
2011
  * @internal
1613
2012
  */
1614
2013
  _redrawAll() {
1615
- this._drawn?.forEach((i) => this._drawRow(i));
2014
+ this._drawn?.forEach((i) => {
2015
+ if (this._onScreen && !this._onScreen.has(i)) this._dirty.add(i);
2016
+ else this._drawRow(i);
2017
+ });
1616
2018
  }
1617
2019
  /* ── Filters in the address ───────────────────────────────────────── */
1618
2020
  /**
@@ -1622,7 +2024,8 @@ var WaveformSounds = class _WaveformSounds {
1622
2024
  _readUrl() {
1623
2025
  const keys = urlKeys(this.options.urlState);
1624
2026
  if (!keys || typeof location === "undefined") return;
1625
- const { filter, sort } = readUrlState(location.search, keys, facets(this.sounds), this._sorts);
2027
+ const f = this._facets;
2028
+ const { filter, sort } = readUrlState(location.search, keys, { ...f, bpm: bpmExtent(f.bpm) }, this._sorts, this.render);
1626
2029
  this.filter = { ...this.filter, ...filter };
1627
2030
  if (sort) {
1628
2031
  this.sortBy = sort;
@@ -1647,13 +2050,33 @@ var WaveformSounds = class _WaveformSounds {
1647
2050
  /* ── Filtering, sorting, paging ───────────────────────────────────── */
1648
2051
  /** The sounds that pass the filter, in the current sort order. */
1649
2052
  get visible() {
1650
- return sortSounds(this.sounds.filter((s) => matches(s, this.filter)), this.sortBy);
2053
+ return [...this._shown ?? this._match()];
2054
+ }
2055
+ /**
2056
+ * Filter and sort the sounds now.
2057
+ * @internal
2058
+ */
2059
+ _match() {
2060
+ return sortSounds(this.sounds.filter((s) => matches(s, this.filter, this.render)), this.sortBy);
2061
+ }
2062
+ /**
2063
+ * A key filter in the list's own spelling: with enharmonic keys merged,
2064
+ * `A#m` on a list whose entry is `Bbm` becomes `Bbm` (so the menu and
2065
+ * the address show the entry). A key the list doesn't have stays as
2066
+ * given (it matches nothing, as before).
2067
+ * @internal
2068
+ */
2069
+ _keyEntry(key) {
2070
+ const k = normalizeKey(key);
2071
+ return this._facets && keyEntry(k, this._facets.keys, this.render.mergeEnharmonicKeys) || k;
1651
2072
  }
1652
2073
  setFilter(patch = {}) {
1653
2074
  this.filter = { ...this.filter, ...patch };
2075
+ if (patch.key) this.filter.key = this._keyEntry(patch.key);
1654
2076
  this.limit = this._pageSize();
2077
+ this._budget = this._firstBudget();
1655
2078
  this._syncControls();
1656
- this._apply({ resort: false });
2079
+ this._apply();
1657
2080
  }
1658
2081
  /** Reset every filter (the sort stays). */
1659
2082
  clearFilters() {
@@ -1664,13 +2087,13 @@ var WaveformSounds = class _WaveformSounds {
1664
2087
  this._sortSet = true;
1665
2088
  this.sortBy = SORTS.includes(by) ? by : "default";
1666
2089
  this.menus?.setValue("sort", this.sortBy);
1667
- this._apply({ resort: true });
2090
+ this._apply();
1668
2091
  }
1669
2092
  /** Reveal the next page of results. */
1670
2093
  showMore() {
1671
2094
  if (this.limit === Infinity) return;
1672
2095
  this.limit += this.render.pageSize;
1673
- this._apply({ resort: false });
2096
+ this._apply();
1674
2097
  }
1675
2098
  /**
1676
2099
  * Rows per page (Infinity when paging is off).
@@ -1679,6 +2102,15 @@ var WaveformSounds = class _WaveformSounds {
1679
2102
  _pageSize() {
1680
2103
  return this.render.pageSize > 0 ? this.render.pageSize : Infinity;
1681
2104
  }
2105
+ /**
2106
+ * Paging off: the rows a list (or a new filter) starts with — a chunk,
2107
+ * more as the list scrolls (see `_watchEnd`); all of them where nothing
2108
+ * can tell it scrolled (no IntersectionObserver).
2109
+ * @internal
2110
+ */
2111
+ _firstBudget() {
2112
+ return typeof IntersectionObserver === "undefined" ? Infinity : RENDER_CHUNK;
2113
+ }
1682
2114
  /**
1683
2115
  * Show the current filter and sort in the controls (they can be set from
1684
2116
  * code or the address, not only by the controls themselves).
@@ -1718,66 +2150,111 @@ var WaveformSounds = class _WaveformSounds {
1718
2150
  $.bpmRange.classList.toggle("is-active", lo > extent.min || hi < extent.max);
1719
2151
  }
1720
2152
  /**
1721
- * Lay the rows out for the current filter, sort and page: order, hide,
2153
+ * Lay the list out for the current filter, sort and page: its rows,
1722
2154
  * "Show more", the empty state and the count. Then report it.
1723
- *
1724
- * @param opts - Reorder the rows even if the sort
1725
- * hasn't changed.
1726
2155
  * @internal
1727
2156
  */
1728
- _apply({ resort }) {
2157
+ _apply() {
1729
2158
  const $ = this.$;
1730
2159
  if (!$) return;
1731
- if (resort || this.sortBy !== this._lastSort) {
1732
- orderRows($.list, sortSounds(this.sounds, this.sortBy).map((s) => this.rows[this.sounds.indexOf(s)]));
1733
- this._lastSort = this.sortBy;
1734
- }
1735
- const shown = this.visible;
1736
- const { visible, remaining } = pageWindow(shown, this.limit);
1737
- this.sounds.forEach((s, i) => {
1738
- if (this.rows[i]) this.rows[i].hidden = !visible.has(s);
1739
- });
2160
+ const shown = this._match();
2161
+ this._shown = shown;
2162
+ this._layout();
2163
+ const remaining = shown.length - Math.min(shown.length, this.limit);
1740
2164
  if ($.more) {
1741
2165
  $.more.hidden = remaining <= 0;
1742
2166
  $.more.textContent = fill(this.strings.showMore, { count: Math.min(remaining, this.render.pageSize || remaining) });
1743
2167
  }
1744
- if ($.empty) $.empty.hidden = shown.length > 0;
2168
+ if ($.empty) {
2169
+ $.empty.hidden = shown.length > 0;
2170
+ if (!this.sounds.length && $.empty.textContent !== this.strings.noSounds) $.empty.textContent = this.strings.noSounds;
2171
+ }
1745
2172
  if ($.count) $.count.textContent = countText(shown.length, this.sounds.length, this.strings);
1746
2173
  if (this._cued && !this.playing) this._cueFirst();
1747
2174
  this._queueUrl();
1748
2175
  this._emit("filter", { visible: shown.length, total: this.sounds.length, filter: { ...this.filter }, sort: this.sortBy });
1749
2176
  this.options.onFilter?.(shown, this);
1750
2177
  }
2178
+ /**
2179
+ * Put exactly the rows shown in the list, in order: the page (or with
2180
+ * paging off the rows rendered so far) of the matching sounds. Rows are
2181
+ * rendered the first time they are shown; rows that stop being shown
2182
+ * leave the DOM (kept, with their drawing, for when they come back).
2183
+ * @internal
2184
+ */
2185
+ _layout() {
2186
+ const $ = this.$, shown = this._shown;
2187
+ const count = renderedCount(shown.length, this.limit, this._budget);
2188
+ const focused = $.list.contains(document.activeElement) ? document.activeElement : null;
2189
+ const rows = this._rowsFor(shown.slice(0, count).map((sound) => this._index.get(sound)));
2190
+ layoutRows($.list, rows);
2191
+ if (focused?.isConnected && document.activeElement !== focused) focused.focus({ preventScroll: true });
2192
+ if (!this._io && this._drawn) for (const row of rows) this._drawRow(Number(row.dataset.wsIndex));
2193
+ if (!this._active || !this._active.isConnected) {
2194
+ const first = rows[0];
2195
+ if (first) {
2196
+ this._rove(first);
2197
+ if (focused && !focused.isConnected) this._focusRowQuietly(first);
2198
+ } else if (this._active) {
2199
+ this._rowStops(this._active, false);
2200
+ this._active = null;
2201
+ }
2202
+ }
2203
+ this._watchEnd(count < Math.min(shown.length, this.limit) ? rows[rows.length - 1] : null);
2204
+ }
2205
+ /**
2206
+ * Render the next chunk of rows once `row` (the last one rendered) comes
2207
+ * within ~1200px of the viewport; nothing to watch for `null`.
2208
+ * @internal
2209
+ */
2210
+ _watchEnd(row) {
2211
+ this._endIo?.disconnect();
2212
+ if (!row || typeof IntersectionObserver === "undefined") return;
2213
+ this._endIo ??= new IntersectionObserver((entries) => {
2214
+ if (this.destroyed || !entries.some((entry) => entry.isIntersecting)) return;
2215
+ this._budget += RENDER_CHUNK;
2216
+ this._layout();
2217
+ }, { rootMargin: "0px 0px 1200px 0px" });
2218
+ this._endIo.observe(row);
2219
+ }
1751
2220
  /* ── Playback ─────────────────────────────────────────────────────── */
1752
2221
  /**
1753
2222
  * Resolve an index, id or sound to an index in `this.sounds`. No
1754
2223
  * target means the current sound, else the first visible one.
1755
2224
  *
1756
2225
  * @param target
1757
- * @returns
1758
2226
  * @internal
1759
2227
  */
1760
2228
  _indexOf(target) {
1761
- if (target == null) return this.currentIndex ?? (this.visible[0] ? this.sounds.indexOf(this.visible[0]) : null);
2229
+ if (target == null) {
2230
+ if (this.currentIndex != null) return this.currentIndex;
2231
+ const first = (this._shown ?? this._match())[0];
2232
+ return first ? this.sounds.indexOf(first) : null;
2233
+ }
1762
2234
  if (typeof target === "number") return this.sounds[target] ? target : null;
1763
- const i = typeof target === "object" ? this.sounds.indexOf(target) : this.sounds.findIndex((s) => s.id === String(target));
2235
+ const i = typeof target === "object" ? this._index.get(target) ?? this.sounds.indexOf(target) : this.sounds.findIndex((s) => s.id === String(target));
1764
2236
  return i >= 0 ? i : null;
1765
2237
  }
1766
2238
  /**
1767
2239
  * The WaveformPlayer class: `playerClass`, else the page's global.
1768
- * @returns
1769
2240
  * @internal
1770
2241
  */
1771
2242
  _playerClass() {
1772
2243
  return this.options.playerClass || (typeof window !== "undefined" ? window.WaveformPlayer : null) || null;
1773
2244
  }
2245
+ /**
2246
+ * The engine as the list drives it (fields the core keeps internal).
2247
+ * @internal
2248
+ */
2249
+ _eng() {
2250
+ return this.engine;
2251
+ }
1774
2252
  /**
1775
2253
  * The element the engine mounts into: a child of the engine slot, never
1776
2254
  * the slot itself. WaveformPlayer resets its container's `className`,
1777
2255
  * which would strip `ws-engine--strip` (and with it the docked styling).
1778
2256
  * Made here rather than in the markup so server-rendered HTML from any
1779
2257
  * version works.
1780
- * @returns
1781
2258
  * @internal
1782
2259
  */
1783
2260
  _engineMount() {
@@ -1796,21 +2273,23 @@ var WaveformSounds = class _WaveformSounds {
1796
2273
  * @internal
1797
2274
  */
1798
2275
  _ensureEngine() {
1799
- if (this.engine) return this.engine;
2276
+ if (this.engine) return this._eng();
1800
2277
  const Player = this._playerClass();
1801
2278
  if (!Player) {
1802
2279
  console.error(`${LOG} @arraypress/waveform-player is required: load it before playing (or pass playerClass).`);
1803
2280
  return null;
1804
2281
  }
1805
- this.engine = new Player(this._engineMount(), engineOptions(this.options.playerOptions, this.render.player, {
2282
+ const options = engineOptions(this.options.playerOptions, this.render.player, {
1806
2283
  onLoad: () => this._onEngineLoad(),
1807
2284
  onPlay: () => this._setPlaying(true),
1808
2285
  onPause: () => this._setPlaying(false),
1809
2286
  onEnd: () => this._onEnd(),
1810
2287
  onTimeUpdate: (time, duration) => this._onTime(time, duration),
1811
2288
  onError: (err) => this._onEngineError(err)
1812
- }));
1813
- return this.engine;
2289
+ });
2290
+ this._preload = options.preload;
2291
+ this.engine = new Player(this._engineMount(), options);
2292
+ return this._eng();
1814
2293
  }
1815
2294
  /**
1816
2295
  * Play a sound (by index, id or sound object), or resume the current
@@ -1843,30 +2322,40 @@ var WaveformSounds = class _WaveformSounds {
1843
2322
  if (previous != null) this._paintRow(previous);
1844
2323
  this._paintRow(index);
1845
2324
  const sound = this.sounds[index];
1846
- engine.loadTrack(sound.url, sound.title, sound.type || null, engineTrack(sound, this.render.player, true));
2325
+ engine.loadTrack(sound.url, sound.title, sound.type || null, engineTrack(sound, this.render.player, true, this._preload));
1847
2326
  }
1848
2327
  /**
1849
2328
  * Strip layout: load the first sound the list shows into the docked
1850
2329
  * player WITHOUT playing it, so the player shows a title and waveform
1851
2330
  * (and its play button plays that sound) instead of an empty frame.
1852
- * Only metadata is fetched — the browser default for any `<audio>`.
2331
+ * Nothing is fetched (`preload: 'none'`): the player shows the title,
2332
+ * length and peaks from the data, and the audio loads on play — a filter
2333
+ * change re-cues, and each cue used to fetch a file's metadata.
1853
2334
  * The row isn't marked current until it plays.
1854
2335
  * @internal
1855
2336
  */
1856
2337
  _cueFirst() {
1857
- const engine = this.engine;
1858
- const first = this.visible[0];
2338
+ const engine = this._eng();
2339
+ const first = (this._shown ?? this._match())[0];
1859
2340
  if (!engine || !first) return;
1860
2341
  const index = this.sounds.indexOf(first);
1861
2342
  if (index === this.currentIndex) return;
1862
2343
  this.currentIndex = index;
1863
2344
  this.progress = 0;
1864
2345
  this._cued = true;
1865
- engine.loadTrack(first.url, first.title, first.type || null, engineTrack(first, "strip", false));
2346
+ const audio = engine.audio;
2347
+ const shim = audio && typeof audio.load === "function";
2348
+ if (shim) audio.load = () => {
2349
+ };
2350
+ try {
2351
+ engine.loadTrack(first.url, first.title, first.type || null, engineTrack(first, "strip", false, "none"));
2352
+ } finally {
2353
+ if (shim) delete audio.load;
2354
+ }
1866
2355
  }
1867
2356
  /** Pause the current sound. */
1868
2357
  pause() {
1869
- if (this.engine && this.playing) this.engine.pause();
2358
+ if (this.engine && this.playing) this._eng().pause();
1870
2359
  }
1871
2360
  /**
1872
2361
  * The current sound plays/pauses; another sound starts.
@@ -1895,15 +2384,11 @@ var WaveformSounds = class _WaveformSounds {
1895
2384
  * @internal
1896
2385
  */
1897
2386
  _step(dir) {
1898
- const shown = this.visible;
2387
+ const shown = this._shown ?? this._match();
1899
2388
  const at = this.currentIndex == null || this._cued ? -1 : shown.indexOf(this.sounds[this.currentIndex]);
1900
2389
  const target = shown[at + dir];
1901
2390
  if (!target) return false;
1902
- const limit = limitToReveal(this.limit, at + dir);
1903
- if (limit !== this.limit) {
1904
- this.limit = limit;
1905
- this._apply({ resort: false });
1906
- }
2391
+ if (this.$) this._reveal(at + dir);
1907
2392
  this.play(this.sounds.indexOf(target));
1908
2393
  return true;
1909
2394
  }
@@ -1924,7 +2409,7 @@ var WaveformSounds = class _WaveformSounds {
1924
2409
  */
1925
2410
  _setLoop(on) {
1926
2411
  this.$?.loop?.setAttribute("aria-pressed", String(on));
1927
- if (this.engine?.audio) this.engine.audio.loop = this._repeats();
2412
+ if (this._eng()?.audio) this._eng().audio.loop = this._repeats();
1928
2413
  }
1929
2414
  /**
1930
2415
  * Should the current sound repeat? The Loop toggle is on, and either
@@ -1946,31 +2431,33 @@ var WaveformSounds = class _WaveformSounds {
1946
2431
  this.play(index, { at: fraction });
1947
2432
  return;
1948
2433
  }
1949
- const duration = this.engine.audio?.duration;
2434
+ const duration = this._eng().audio?.duration;
1950
2435
  if (!Number.isFinite(duration) || duration <= 0) {
1951
2436
  this._pendingSeek = fraction;
1952
2437
  return;
1953
2438
  }
1954
- this.engine.seekTo(fraction * duration);
2439
+ this._eng().seekTo(fraction * duration);
1955
2440
  this.progress = fraction;
1956
2441
  this._paintRow(index);
1957
- if (!this.playing) this.engine.play();
2442
+ this._paintSlider();
2443
+ if (!this.playing) this._eng().play();
1958
2444
  }
1959
2445
  /**
1960
- * The engine loaded a sound: apply the loop, borrow decoded peaks for a
2446
+ * The engine loaded a sound: clear an earlier failure, apply the loop, borrow decoded peaks for a
1961
2447
  * row that had none, and land a pending seek.
1962
2448
  * @internal
1963
2449
  */
1964
2450
  _onEngineLoad() {
1965
- if (this.engine?.audio) this.engine.audio.loop = this._repeats();
2451
+ if (this.currentIndex != null) this._markFailed(this.currentIndex, false);
2452
+ if (this._eng()?.audio) this._eng().audio.loop = this._repeats();
1966
2453
  const sound = this.sounds[this.currentIndex];
1967
- if (sound && !sound.peaks && this.engine?.waveformData?.length) {
1968
- sound.peaks = resample(this.engine.waveformData, 96);
2454
+ if (sound && !sound.peaks && this._eng()?.waveformData?.length) {
2455
+ sound.peaks = resample(this._eng().waveformData, 96);
1969
2456
  this._drawRow(this.currentIndex);
1970
2457
  }
1971
- const duration = this.engine?.audio?.duration;
2458
+ const duration = this._eng()?.audio?.duration;
1972
2459
  if (this._pendingSeek != null && Number.isFinite(duration) && duration > 0) {
1973
- this.engine.seekTo(this._pendingSeek * duration);
2460
+ this._eng().seekTo(this._pendingSeek * duration);
1974
2461
  this.progress = this._pendingSeek;
1975
2462
  this._pendingSeek = null;
1976
2463
  }
@@ -1984,7 +2471,7 @@ var WaveformSounds = class _WaveformSounds {
1984
2471
  if (this._pendingSeek != null) {
1985
2472
  const fraction = this._pendingSeek;
1986
2473
  this._pendingSeek = null;
1987
- this.engine.seekTo(fraction * duration);
2474
+ this._eng().seekTo(fraction * duration);
1988
2475
  return;
1989
2476
  }
1990
2477
  this.progress = Math.min(Math.max(time / duration, 0), 1);
@@ -1992,7 +2479,7 @@ var WaveformSounds = class _WaveformSounds {
1992
2479
  this._raf = requestAnimationFrame(() => {
1993
2480
  this._raf = 0;
1994
2481
  this._drawRow(this.currentIndex);
1995
- this.rows[this.currentIndex]?.querySelector(".ws-wave")?.setAttribute("aria-valuenow", String(Math.round(this.progress * 100)));
2482
+ this._paintSlider();
1996
2483
  });
1997
2484
  }
1998
2485
  /**
@@ -2008,32 +2495,59 @@ var WaveformSounds = class _WaveformSounds {
2008
2495
  this._setPlaying(false);
2009
2496
  }
2010
2497
  /**
2011
- * A sound failed to load or play: mark its row and report it.
2498
+ * A sound failed to load or play: it isn't playing (no stale "Pause"),
2499
+ * its row is marked until it plays, and the live region says so.
2012
2500
  * @internal
2013
2501
  */
2014
2502
  _onEngineError(err) {
2015
- this.rows[this.currentIndex]?.classList.add("is-error");
2016
- this._emit("error", { error: err, sound: this.sounds[this.currentIndex], index: this.currentIndex });
2503
+ const index = this.currentIndex;
2504
+ const sound = index == null ? void 0 : this.sounds[index];
2505
+ if (index != null) this._markFailed(index, true);
2506
+ this._setPlaying(false);
2507
+ if (sound && !this._cued && this.$?.status) this.$.status.textContent = fill(this.strings.playError, { title: sound.title });
2508
+ this._emit("error", { error: err, sound, index });
2017
2509
  this.options.onError?.(err, this);
2018
2510
  }
2019
2511
  /**
2020
- * Record play/pause and repaint. Events fire only on a real change: at a
2021
- * natural end the browser fires `pause` then `ended`, and `_onEnd()`
2022
- * also settles the state — one pause event, not two.
2512
+ * Record play/pause and repaint, and report what the listener hears.
2513
+ * Events follow the SOUND, not the flag: switching sounds while one plays
2514
+ * (↓ audition, `play(i)`, `next()`, auto-advance) never flips `playing`
2515
+ * in some engines (the media element swaps source without a `pause`),
2516
+ * so the last sound announced is tracked — a different one starting
2517
+ * reports `pause` for the outgoing sound, then `play` for the new one.
2518
+ * At a natural end the browser fires `pause` then `ended`, and `_onEnd()`
2519
+ * settles the state again: one pause event, not two.
2023
2520
  * @internal
2024
2521
  */
2025
2522
  _setPlaying(on) {
2026
- const changed = this.playing !== on;
2027
2523
  this.playing = on;
2028
2524
  if (on) this._cued = false;
2029
2525
  const index = this.currentIndex;
2030
2526
  if (index == null) return;
2527
+ if (on) this._markFailed(index, false);
2031
2528
  this._paintRow(index);
2032
- if (!changed) return;
2529
+ const was = this._announced ?? null;
2530
+ if (on) {
2531
+ if (was === index) return;
2532
+ if (was != null) this._announce("pause", was);
2533
+ this._announced = index;
2534
+ this._announce("play", index);
2535
+ } else if (was != null) {
2536
+ this._announced = null;
2537
+ this._announce("pause", was);
2538
+ }
2539
+ }
2540
+ /**
2541
+ * Report a sound starting or stopping: the live region (on play), the
2542
+ * `waveformsounds:play|pause` event and the `onPlay` / `onPause` callback.
2543
+ * @internal
2544
+ */
2545
+ _announce(type, index) {
2033
2546
  const sound = this.sounds[index];
2034
- if (on && this.$.status) this.$.status.textContent = fill(this.strings.nowPlaying, { title: sound.title });
2035
- this._emit(on ? "play" : "pause", { sound, index });
2036
- (on ? this.options.onPlay : this.options.onPause)?.(sound, this);
2547
+ if (!sound) return;
2548
+ if (type === "play" && this.$?.status) this.$.status.textContent = fill(this.strings.nowPlaying, { title: sound.title });
2549
+ this._emit(type, { sound, index });
2550
+ (type === "play" ? this.options.onPlay : this.options.onPause)?.(sound, this);
2037
2551
  }
2038
2552
  /* ── Row painting ─────────────────────────────────────────────────── */
2039
2553
  /**
@@ -2052,20 +2566,67 @@ var WaveformSounds = class _WaveformSounds {
2052
2566
  btn.setAttribute("aria-pressed", String(on));
2053
2567
  btn.setAttribute("aria-label", fill(on ? this.strings.pause : this.strings.play, { title: this.sounds[index].title }));
2054
2568
  }
2569
+ row.classList.toggle("is-error", this._failed.has(index));
2055
2570
  const wave = row.querySelector(".ws-wave");
2056
- if (wave) {
2057
- wave.tabIndex = current ? 0 : -1;
2058
- if (!current) wave.setAttribute("aria-valuenow", "0");
2059
- }
2571
+ if (wave) this._paintWave(wave, current, row === this._active, this.sounds[index].title);
2060
2572
  this._drawRow(index);
2061
2573
  }
2574
+ /**
2575
+ * A row's waveform: the current sound's is THE seek slider (focusable,
2576
+ * labelled, with a value); every other one is a picture, hidden from
2577
+ * assistive tech and out of the Tab order (a pointer still seeks on it).
2578
+ * So a screen reader meets one slider, not one per row. Since 2.2.0.
2579
+ * @internal
2580
+ */
2581
+ _paintWave(wave, current, active, title) {
2582
+ if (!current) {
2583
+ if (wave.getAttribute("aria-hidden") === "true" && !wave.hasAttribute("role")) return;
2584
+ for (const name of ["role", "aria-label", "aria-valuemin", "aria-valuemax", "aria-valuenow", "aria-valuetext", "tabindex"]) wave.removeAttribute(name);
2585
+ wave.setAttribute("aria-hidden", "true");
2586
+ return;
2587
+ }
2588
+ wave.removeAttribute("aria-hidden");
2589
+ wave.setAttribute("role", "slider");
2590
+ wave.setAttribute("aria-label", fill(this.strings.seek, { title }));
2591
+ wave.setAttribute("aria-valuemin", "0");
2592
+ wave.setAttribute("aria-valuemax", "100");
2593
+ if (!wave.hasAttribute("aria-valuenow")) wave.setAttribute("aria-valuenow", String(Math.round(this.progress * 100)));
2594
+ wave.tabIndex = active ? 0 : -1;
2595
+ }
2596
+ /**
2597
+ * Record that a sound failed (or played after all), on its row if it
2598
+ * has one; a row rendered later picks it up from `_failed`.
2599
+ * @internal
2600
+ */
2601
+ _markFailed(index, failed) {
2602
+ if (failed) this._failed.add(index);
2603
+ else this._failed.delete(index);
2604
+ this.rows[index]?.classList.toggle("is-error", failed);
2605
+ }
2606
+ /**
2607
+ * The current row's seek slider: its position (0–100) and, for a screen
2608
+ * reader, the time ("0:12 of 0:30").
2609
+ * @internal
2610
+ */
2611
+ _paintSlider() {
2612
+ const index = this.currentIndex;
2613
+ const wave = index == null ? null : this.rows[index]?.querySelector(".ws-wave");
2614
+ if (!wave) return;
2615
+ wave.setAttribute("aria-valuenow", String(Math.round(this.progress * 100)));
2616
+ const audio = this._eng()?.audio;
2617
+ const duration = Number.isFinite(audio?.duration) && audio.duration > 0 ? audio.duration : this.sounds[index].duration;
2618
+ if (duration) wave.setAttribute("aria-valuetext", fill(this.strings.seekValue, { time: formatClock(this.progress * duration), duration: formatDuration(duration) }));
2619
+ }
2062
2620
  /* ── Events & lifecycle ──────────────────────────────────────────── */
2063
2621
  /**
2064
- * Emit a `waveformsounds:<name>` event carrying this instance.
2622
+ * Announce a moment both ways: a `waveformsounds:<name>` event on the
2623
+ * container carrying the details and this instance, then a plain `<name>`
2624
+ * event on the instance.
2065
2625
  * @internal
2066
2626
  */
2067
2627
  _emit(name, detail = {}) {
2068
2628
  emit(this.container, name, { ...detail, instance: this });
2629
+ this.dispatchEvent(new Event(name));
2069
2630
  }
2070
2631
  /** The sound playing (or paused) now, or null. */
2071
2632
  get current() {
@@ -2075,25 +2636,32 @@ var WaveformSounds = class _WaveformSounds {
2075
2636
  * Tear down: listeners, observers, timers and the engine. Markup this
2076
2637
  * instance rendered is restored to what the container held before.
2077
2638
  * ADOPTED (server-rendered) markup is left as it is now — rows may be
2078
- * re-sorted, hidden or marked current — so to start again, re-render it
2079
- * rather than constructing a new instance over it.
2639
+ * re-sorted, hidden or marked current — unless `restore` is set: then it
2640
+ * is put back exactly as the server sent it, ready for a new instance
2641
+ * (what a framework re-mounting the same markup wants).
2642
+ *
2643
+ * @param options
2644
+ * @param options.restore - Put adopted server markup back as it was.
2645
+ * Default false. Since 2.1.0.
2080
2646
  */
2081
- destroy() {
2647
+ destroy(options = {}) {
2082
2648
  if (this.destroyed) return;
2083
2649
  this.destroyed = true;
2084
2650
  this._ctl.abort();
2085
2651
  this._io?.disconnect();
2652
+ this._endIo?.disconnect();
2086
2653
  this._ro?.disconnect();
2087
2654
  this._mo?.disconnect();
2088
2655
  if (this._raf) cancelAnimationFrame(this._raf);
2089
2656
  clearTimeout(this._urlTimer);
2090
2657
  try {
2091
- this.engine?.destroy();
2658
+ this._eng()?.destroy();
2092
2659
  } catch {
2093
2660
  }
2094
2661
  this.engine = null;
2095
2662
  this.$?.engine?.querySelector(":scope > [data-ws-engine-mount]")?.remove();
2096
2663
  if (this._originalHTML != null) this.container.innerHTML = this._originalHTML;
2664
+ else if (options.restore && this._adoptedHTML != null) this.container.innerHTML = this._adoptedHTML;
2097
2665
  if (this._addedClasses?.length) this.container.classList.remove(...this._addedClasses);
2098
2666
  if (this._autoSurface) this.container.style.removeProperty("--ws-surface");
2099
2667
  delete this.container.dataset.wsInitialized;
@@ -2123,7 +2691,6 @@ var WaveformSounds = class _WaveformSounds {
2123
2691
  /**
2124
2692
  * The instance on an element (or selector), if any.
2125
2693
  * @param el
2126
- * @returns
2127
2694
  */
2128
2695
  static getInstance(el) {
2129
2696
  const node = typeof el === "string" ? document.querySelector(el) : el;
@@ -2136,16 +2703,152 @@ var WaveformSounds = class _WaveformSounds {
2136
2703
  }
2137
2704
  };
2138
2705
 
2706
+ // src/js/core/element.ts
2707
+ var ELEMENT_OPTION_KEYS = [
2708
+ "player",
2709
+ "manifest",
2710
+ "search",
2711
+ "filters",
2712
+ "sorts",
2713
+ "showCount",
2714
+ "menuSearch",
2715
+ "idPrefix",
2716
+ "urlState",
2717
+ "loopToggle",
2718
+ "pageSize",
2719
+ "maxTypeChips",
2720
+ "columns",
2721
+ "waveformStyle",
2722
+ "waveformColor",
2723
+ "progressColor",
2724
+ "barWidth",
2725
+ "barGap",
2726
+ "loop",
2727
+ "autoAdvance",
2728
+ "arrowAudition",
2729
+ "strings",
2730
+ "playerOptions",
2731
+ "mergeEnharmonicKeys"
2732
+ ];
2733
+ var kebab = (key) => key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
2734
+ function readElementOptions(el) {
2735
+ const dataset = {};
2736
+ for (const key of ELEMENT_OPTION_KEYS) {
2737
+ const name = kebab(key);
2738
+ const value = el.getAttribute(name) ?? el.getAttribute(`data-${name}`);
2739
+ if (value != null) dataset[key] = value;
2740
+ }
2741
+ return readDataOptions({ dataset });
2742
+ }
2743
+ var Base = typeof HTMLElement === "undefined" ? class {
2744
+ } : HTMLElement;
2745
+ var WaveformSoundsElement = class extends Base {
2746
+ /** Every option attribute, plain and `data-` prefixed. */
2747
+ static get observedAttributes() {
2748
+ return ELEMENT_OPTION_KEYS.flatMap((key) => [kebab(key), `data-${kebab(key)}`]);
2749
+ }
2750
+ /** Build the list (or keep it, after a move). */
2751
+ connectedCallback() {
2752
+ if (this._leaving !== void 0) {
2753
+ clearTimeout(this._leaving);
2754
+ this._leaving = void 0;
2755
+ return;
2756
+ }
2757
+ if (!this.sounds) this._build();
2758
+ }
2759
+ /** Destroy the list, unless the element comes straight back (a move). */
2760
+ disconnectedCallback() {
2761
+ clearTimeout(this._leaving);
2762
+ this._leaving = setTimeout(() => {
2763
+ this._leaving = void 0;
2764
+ if (!this.isConnected) this._teardown();
2765
+ }, 0);
2766
+ }
2767
+ /**
2768
+ * An option attribute changed: rebuild once the task's changes are in.
2769
+ *
2770
+ * @param name
2771
+ * @param previous
2772
+ * @param value
2773
+ */
2774
+ attributeChangedCallback(name, previous, value) {
2775
+ if (!this.sounds || previous === value) return;
2776
+ const kind = name.replace(/^data-/, "") === "manifest" ? "manifest" : "rebuild";
2777
+ if (this._pending) {
2778
+ if (kind === "manifest") this._pending = kind;
2779
+ return;
2780
+ }
2781
+ this._pending = kind;
2782
+ queueMicrotask(() => {
2783
+ const pending = this._pending;
2784
+ this._pending = void 0;
2785
+ if (this.sounds) this._rebuild(pending === "manifest");
2786
+ });
2787
+ }
2788
+ /**
2789
+ * The options the list reads off this element (`WaveformSounds` calls it
2790
+ * in place of reading `data-*` alone).
2791
+ * @internal
2792
+ */
2793
+ _wsOptions() {
2794
+ return readElementOptions(this);
2795
+ }
2796
+ /**
2797
+ * Build the list into the element.
2798
+ * @internal
2799
+ */
2800
+ _build(options = {}) {
2801
+ WaveformSounds.getInstance(this)?.destroy({ restore: true });
2802
+ try {
2803
+ this.sounds = new WaveformSounds(this, options);
2804
+ } catch (error) {
2805
+ this.sounds = null;
2806
+ console.error(`${LOG} Failed to initialise:`, error, this);
2807
+ }
2808
+ }
2809
+ /**
2810
+ * Destroy the list, putting server-rendered markup back as it came.
2811
+ * @internal
2812
+ */
2813
+ _teardown() {
2814
+ this.sounds?.destroy({ restore: true });
2815
+ this.sounds = null;
2816
+ }
2817
+ /**
2818
+ * Rebuild for new options: re-rendered from the sounds the list holds
2819
+ * (the markup must follow the new options), or fetched afresh when the
2820
+ * manifest changed.
2821
+ * @internal
2822
+ */
2823
+ _rebuild(refetch) {
2824
+ const sounds = refetch || !this.sounds.$ ? void 0 : this.sounds.sounds.slice();
2825
+ this._teardown();
2826
+ this.innerHTML = "";
2827
+ this._build(sounds ? { sounds } : {});
2828
+ }
2829
+ };
2830
+ function defineWaveformSoundsElement(name = "waveform-sounds") {
2831
+ if (typeof customElements === "undefined") return void 0;
2832
+ const existing = customElements.get(name);
2833
+ if (existing) return existing;
2834
+ const element = class extends WaveformSoundsElement {
2835
+ };
2836
+ customElements.define(name, element);
2837
+ return element;
2838
+ }
2839
+
2139
2840
  // src/js/entry.ts
2140
2841
  WaveformSounds.utils = { encodePeaks, decodePeaks, normalizeKey, normalizeSounds, parseManifest, facets, matches, sortSounds, formatDuration, renderSounds };
2141
2842
  WaveformSounds.DEFAULT_OPTIONS = DEFAULT_OPTIONS;
2142
2843
  WaveformSounds.DEFAULT_STRINGS = DEFAULT_STRINGS;
2844
+ WaveformSounds.defineElement = defineWaveformSoundsElement;
2143
2845
  if (typeof window !== "undefined") window.WaveformSounds = WaveformSounds;
2144
2846
  var entry_default = WaveformSounds;
2145
2847
 
2146
2848
  // src/js/index.ts
2147
2849
  var index_default = entry_default;
2148
2850
  if (typeof document !== "undefined" && document.documentElement?.dataset?.waveformAutoinit !== "false") {
2851
+ defineWaveformSoundsElement();
2149
2852
  if (document.readyState === "loading") {
2150
2853
  document.addEventListener("DOMContentLoaded", () => entry_default.init(), { once: true });
2151
2854
  } else {
@@ -2155,9 +2858,12 @@ if (typeof document !== "undefined" && document.documentElement?.dataset?.wavefo
2155
2858
  export {
2156
2859
  DEFAULT_OPTIONS,
2157
2860
  DEFAULT_STRINGS,
2861
+ RENDER_OPTION_KEYS,
2158
2862
  WaveformSounds,
2863
+ WaveformSoundsElement,
2159
2864
  decodePeaks,
2160
2865
  index_default as default,
2866
+ defineWaveformSoundsElement,
2161
2867
  encodePeaks,
2162
2868
  facets,
2163
2869
  formatDuration,
@@ -2165,6 +2871,7 @@ export {
2165
2871
  normalizeKey,
2166
2872
  normalizeSounds,
2167
2873
  parseManifest,
2874
+ pickRenderOptions,
2168
2875
  renderSounds,
2169
2876
  renderSoundsElement,
2170
2877
  sortSounds
@@ -2173,8 +2880,8 @@ export {
2173
2880
  * @arraypress/waveform-sounds
2174
2881
  * A searchable, filterable list of sounds for WaveformPlayer.
2175
2882
  *
2176
- * Importing this entry initialises every `[data-waveform-sounds]` element
2177
- * once the DOM is ready. Opt out page-wide with
2883
+ * Importing this entry registers `<waveform-sounds>` and initialises every
2884
+ * `[data-waveform-sounds]` element once the DOM is ready. Opt out page-wide with
2178
2885
  * `<html data-waveform-autoinit="false">` (the family's switch), or import
2179
2886
  * `@arraypress/waveform-sounds/no-autoinit`.
2180
2887
  *