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