@arraypress/waveform-sounds 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +24 -2
  2. package/dist/waveform-sounds-no-autoinit.esm.js +495 -90
  3. package/dist/waveform-sounds-render.esm.js +55 -5
  4. package/dist/waveform-sounds.css +88 -17
  5. package/dist/waveform-sounds.esm.js +498 -92
  6. package/dist/waveform-sounds.js +494 -92
  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 +88 -17
  11. package/src/js/core/WaveformSounds.ts +350 -87
  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 +0 -5
  15. package/src/js/data/bpm.ts +14 -4
  16. package/src/js/data/navigation.ts +16 -3
  17. package/src/js/data/sounds.ts +44 -14
  18. package/src/js/data/url-state.ts +33 -10
  19. package/src/js/dom/colors.ts +28 -1
  20. package/src/js/dom/draw.ts +0 -1
  21. package/src/js/dom/menus.ts +0 -2
  22. package/src/js/dom/rows.ts +0 -3
  23. package/src/js/entry.ts +13 -3
  24. package/src/js/index.ts +7 -3
  25. package/src/js/render/html.ts +0 -2
  26. package/src/js/render/icons.ts +0 -1
  27. package/src/js/render/markup.ts +41 -13
  28. package/src/js/render/options.ts +26 -4
  29. package/src/js/render/strings.ts +4 -3
  30. package/src/js/render-entry.ts +1 -1
  31. package/src/js/shared/utils.ts +4 -4
  32. package/src/js/types.ts +30 -3
  33. package/types/core/WaveformSounds.d.ts +40 -10
  34. package/types/core/WaveformSounds.d.ts.map +1 -1
  35. package/types/core/element.d.ts +84 -0
  36. package/types/core/element.d.ts.map +1 -0
  37. package/types/core/engine.d.ts +8 -3
  38. package/types/core/engine.d.ts.map +1 -1
  39. package/types/core/options.d.ts +0 -5
  40. package/types/core/options.d.ts.map +1 -1
  41. package/types/data/bpm.d.ts +17 -4
  42. package/types/data/bpm.d.ts.map +1 -1
  43. package/types/data/navigation.d.ts +11 -2
  44. package/types/data/navigation.d.ts.map +1 -1
  45. package/types/data/sounds.d.ts +13 -12
  46. package/types/data/sounds.d.ts.map +1 -1
  47. package/types/data/url-state.d.ts +32 -6
  48. package/types/data/url-state.d.ts.map +1 -1
  49. package/types/dom/colors.d.ts +13 -0
  50. package/types/dom/colors.d.ts.map +1 -1
  51. package/types/dom/draw.d.ts +0 -1
  52. package/types/dom/draw.d.ts.map +1 -1
  53. package/types/dom/menus.d.ts +0 -2
  54. package/types/dom/menus.d.ts.map +1 -1
  55. package/types/dom/rows.d.ts +0 -3
  56. package/types/dom/rows.d.ts.map +1 -1
  57. package/types/entry.d.ts +10 -4
  58. package/types/entry.d.ts.map +1 -1
  59. package/types/index.d.ts +2 -2
  60. package/types/index.d.ts.map +1 -1
  61. package/types/render/html.d.ts +0 -2
  62. package/types/render/html.d.ts.map +1 -1
  63. package/types/render/icons.d.ts.map +1 -1
  64. package/types/render/markup.d.ts +17 -8
  65. package/types/render/markup.d.ts.map +1 -1
  66. package/types/render/options.d.ts +17 -4
  67. package/types/render/options.d.ts.map +1 -1
  68. package/types/render/strings.d.ts +0 -3
  69. package/types/render/strings.d.ts.map +1 -1
  70. package/types/render-entry.d.ts +1 -1
  71. package/types/render-entry.d.ts.map +1 -1
  72. package/types/shared/utils.d.ts +3 -3
  73. package/types/shared/utils.d.ts.map +1 -1
  74. package/types/types.d.ts +29 -3
  75. package/types/types.d.ts.map +1 -1
@@ -82,12 +82,25 @@
82
82
  }
83
83
  return out;
84
84
  }
85
+ var COMPACT_PREFIX = "wp1:";
86
+ function decodeCompact(body) {
87
+ if (!body || !/^[\w-]+$/.test(body) || body.length % 4 === 1) return null;
88
+ try {
89
+ const bytes = atob(body.replace(/-/g, "+").replace(/_/g, "/"));
90
+ const out = new Array(bytes.length);
91
+ for (let i = 0; i < bytes.length; i++) out[i] = bytes.charCodeAt(i) / 255;
92
+ return out;
93
+ } catch {
94
+ return null;
95
+ }
96
+ }
85
97
  function decodePeaks(value, scale = 1) {
86
98
  if (value == null || value === "") return null;
87
99
  if (typeof value === "string") {
100
+ if (value.startsWith(COMPACT_PREFIX)) return decodeCompact(value.slice(COMPACT_PREFIX.length));
88
101
  if (!/^[0-9a-f]+$/i.test(value) || value.length % 2) return null;
89
102
  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;
103
+ for (let i = 0; i < out2.length; i++) out2[i] = parseInt(value.slice(i * 2, i * 2 + 2), 16) / 255;
91
104
  return out2;
92
105
  }
93
106
  if (!Array.isArray(value)) return null;
@@ -121,13 +134,18 @@
121
134
  const total = s < 1 ? Math.ceil(s) : Math.floor(s);
122
135
  return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`;
123
136
  }
137
+ function formatClock(seconds) {
138
+ const total = Number.isFinite(seconds) && seconds > 0 ? Math.floor(seconds) : 0;
139
+ const h2 = Math.floor(total / 3600), m = Math.floor(total % 3600 / 60), sec = String(total % 60).padStart(2, "0");
140
+ return h2 ? `${h2}:${String(m).padStart(2, "0")}:${sec}` : `${m}:${sec}`;
141
+ }
124
142
  function parseDuration(value) {
125
143
  if (value == null || value === "") return null;
126
144
  if (typeof value === "number") return Number.isFinite(value) && value >= 0 ? value : null;
127
145
  const str = String(value).trim();
128
146
  if (/^\d+(\.\d+)?$/.test(str)) return Number(str);
147
+ if (!/^\d+(\.\d+)?(:\d+(\.\d+)?)+$/.test(str)) return null;
129
148
  const parts = str.split(":").map(Number);
130
- if (parts.length < 2 || parts.some((n) => !Number.isFinite(n))) return null;
131
149
  return parts.reduce((acc, n) => acc * 60 + n, 0);
132
150
  }
133
151
  function titleFromUrl(url) {
@@ -343,8 +361,9 @@
343
361
  function enginePeaks(sound, layout) {
344
362
  return layout === "strip" && sound.waveform || sound.peaks || null;
345
363
  }
346
- function engineTrack(sound, layout, autoplay) {
364
+ function engineTrack(sound, layout, autoplay, preload) {
347
365
  const track = { waveform: enginePeaks(sound, layout), autoplay };
366
+ if (preload) track.preload = preload;
348
367
  if (sound.duration != null && sound.duration > 0) track.duration = sound.duration;
349
368
  if (sound.download) track.downloadUrl = sound.download;
350
369
  return track;
@@ -571,7 +590,7 @@
571
590
  return !!el && (el.isContentEditable || /^(INPUT|SELECT|TEXTAREA)$/.test(el.tagName));
572
591
  }
573
592
  function emit(target, name, detail) {
574
- const event = new CustomEvent(`waveformsounds:${name}`, { bubbles: true, detail });
593
+ const event = new CustomEvent(`waveformsounds:${name}`, { bubbles: true, composed: true, detail });
575
594
  target.dispatchEvent(event);
576
595
  return event;
577
596
  }
@@ -600,7 +619,11 @@
600
619
  }
601
620
  function seekTarget(progress, key) {
602
621
  if (key !== "ArrowRight" && key !== "ArrowLeft") return null;
603
- return clamp(progress + (key === "ArrowRight" ? SEEK_STEP : -SEEK_STEP), 0, 0.999);
622
+ return clamp(progress + (key === "ArrowRight" ? SEEK_STEP : -SEEK_STEP), 0, SEEK_END);
623
+ }
624
+ var SEEK_END = 0.999;
625
+ function sliderEdgeTarget(key) {
626
+ return key === "Home" ? 0 : key === "End" ? SEEK_END : null;
604
627
  }
605
628
  function pageWindow(shown, limit) {
606
629
  const visible = new Set(shown.slice(0, limit));
@@ -611,6 +634,9 @@
611
634
  }
612
635
 
613
636
  // src/js/data/bpm.ts
637
+ function bpmExtent(range) {
638
+ return range ? { min: Math.floor(range.min), max: Math.ceil(range.max) } : null;
639
+ }
614
640
  function bpmFilterFromRange(lo, hi, extent) {
615
641
  const a = Math.min(lo, hi), b = Math.max(lo, hi);
616
642
  return {
@@ -667,6 +693,7 @@
667
693
  play: "Play {title}",
668
694
  pause: "Pause {title}",
669
695
  seek: "Seek {title}",
696
+ seekValue: "{time} of {duration}",
670
697
  download: "Download {title}",
671
698
  count: "{count} sounds",
672
699
  countOne: "1 sound",
@@ -674,7 +701,10 @@
674
701
  showMore: "Show {count} more",
675
702
  empty: "No sounds match.",
676
703
  clear: "Clear filters",
677
- nowPlaying: "Playing {title}"
704
+ nowPlaying: "Playing {title}",
705
+ playError: "Could not play {title}",
706
+ loadError: "Could not load the sounds.",
707
+ noSounds: "No sounds."
678
708
  };
679
709
  var SORT_LABEL_KEYS = {
680
710
  default: "sortDefault",
@@ -711,6 +741,15 @@
711
741
  columns: [...COLUMNS],
712
742
  maxTypeChips: 10
713
743
  };
744
+ var RENDER_OPTION_KEYS = [...Object.keys(RENDER_DEFAULTS), "idPrefix", "loop", "strings"];
745
+ function pickRenderOptions(options) {
746
+ const out = {};
747
+ for (const key of RENDER_OPTION_KEYS) {
748
+ const value = options?.[key];
749
+ if (value != null) out[key] = value;
750
+ }
751
+ return out;
752
+ }
714
753
  function defined(obj) {
715
754
  const out = {};
716
755
  for (const k in obj ?? {}) if (obj[k] !== void 0) out[k] = obj[k];
@@ -1021,7 +1060,7 @@
1021
1060
  placeholder: s.findKey,
1022
1061
  options: [{ value: "", label: s.anyKey }, ...f.keys.map((k) => ({ value: k, label: k }))]
1023
1062
  }),
1024
- plan.bpm && renderBpmMenu({ id, s, range: f.bpm }),
1063
+ plan.bpm && renderBpmMenu({ id, s, range: bpmExtent(f.bpm) }),
1025
1064
  plan.loops && renderLoopFilter(s),
1026
1065
  plan.sorts.length > 0 && menu("sort", {
1027
1066
  label: s.sort,
@@ -1124,10 +1163,29 @@
1124
1163
  list.map((sound, i) => renderRow(sound, i, o, i >= page))
1125
1164
  ) + renderFooter(ctx);
1126
1165
  }
1166
+ function renderOptionAttributes(options = {}) {
1167
+ const set = pickRenderOptions(options);
1168
+ const o = resolveRenderOptions(options);
1169
+ const out = {};
1170
+ for (const key of RENDER_OPTION_KEYS) {
1171
+ if (key === "player" || !(key in set)) continue;
1172
+ const name = `data-${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`;
1173
+ if (key === "strings") {
1174
+ const strings = defined(set.strings);
1175
+ if (Object.keys(strings).length) out[name] = JSON.stringify(strings);
1176
+ } else if (key === "loop" || key === "idPrefix") {
1177
+ out[name] = String(set[key]);
1178
+ } else {
1179
+ const value = o[key];
1180
+ out[name] = Array.isArray(value) ? value.join(",") : String(value);
1181
+ }
1182
+ }
1183
+ return out;
1184
+ }
1127
1185
  function renderSoundsElement(sounds, options = {}, className = "") {
1128
1186
  const o = resolveRenderOptions(options);
1129
1187
  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));
1188
+ return h("div", { class: cls, "data-waveform-sounds": true, "data-player": o.player, ...renderOptionAttributes(options) }, renderSounds(sounds, options));
1131
1189
  }
1132
1190
 
1133
1191
  // src/js/dom/rows.ts
@@ -1193,9 +1251,21 @@
1193
1251
  }
1194
1252
  return "#fff";
1195
1253
  }
1254
+ function forcedColors() {
1255
+ try {
1256
+ return typeof matchMedia === "function" && matchMedia("(forced-colors: active)").matches;
1257
+ } catch {
1258
+ return false;
1259
+ }
1260
+ }
1261
+ function ancestorsOf(el) {
1262
+ const out = [];
1263
+ for (let node = el.parentElement || el.getRootNode?.()?.host; node; node = node.parentElement || node.getRootNode?.()?.host) out.push(node);
1264
+ return out;
1265
+ }
1196
1266
  function resolveCssColor(container, value) {
1197
1267
  const probe = document.createElement("span");
1198
- probe.style.cssText = "position:absolute;width:0;height:0;overflow:hidden;visibility:hidden";
1268
+ probe.style.cssText = "position:absolute;width:0;height:0;overflow:hidden;visibility:hidden;forced-color-adjust:none";
1199
1269
  probe.style.color = value;
1200
1270
  container.appendChild(probe);
1201
1271
  const color = getComputedStyle(probe).color;
@@ -1210,8 +1280,16 @@
1210
1280
  return { q: `${p}q`, type: `${p}type`, key: `${p}key`, bpm: `${p}bpm`, loop: `${p}loop`, sort: `${p}sort` };
1211
1281
  }
1212
1282
  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;
1283
+ const m = String(value ?? "").match(/^(\d+(?:\.\d+)?)?-(\d+(?:\.\d+)?)?$/);
1284
+ if (!m || !(m[1] || m[2])) return null;
1285
+ const lo = m[1] ?? "", hi = m[2] ?? "";
1286
+ return lo && hi && Number(lo) > Number(hi) ? { bpmMin: hi, bpmMax: lo } : { bpmMin: lo, bpmMax: hi };
1287
+ }
1288
+ function bpmRangeWithin(range, extent) {
1289
+ if (!extent) return null;
1290
+ const inside = (v) => v !== "" && Number(v) >= extent.min && Number(v) <= extent.max ? v : "";
1291
+ const out = { bpmMin: inside(range.bpmMin), bpmMax: inside(range.bpmMax) };
1292
+ return out.bpmMin || out.bpmMax ? out : null;
1215
1293
  }
1216
1294
  function formatBpmRange(min, max) {
1217
1295
  const lo = min ?? "", hi = max ?? "";
@@ -1227,7 +1305,8 @@
1227
1305
  if (type && available.types.some((t) => t.name === type)) out.filter.type = type;
1228
1306
  const key = normalizeKey(sp.get(keys.key));
1229
1307
  if (key && available.keys.includes(key)) out.filter.key = key;
1230
- const bpm = parseBpmRange(sp.get(keys.bpm));
1308
+ const parsed = parseBpmRange(sp.get(keys.bpm));
1309
+ const bpm = parsed && available.bpm !== void 0 ? bpmRangeWithin(parsed, available.bpm) : parsed;
1231
1310
  if (bpm) Object.assign(out.filter, bpm);
1232
1311
  const loop = sp.get(keys.loop);
1233
1312
  if (LOOP_FILTERS.includes(loop) && available.loops > 0 && available.oneShots > 0) out.filter.loop = loop;
@@ -1253,7 +1332,7 @@
1253
1332
  var SEARCH_DELAY = 120;
1254
1333
  var BPM_DELAY = 200;
1255
1334
  var URL_DELAY = 250;
1256
- var WaveformSounds = class _WaveformSounds {
1335
+ var WaveformSounds = class _WaveformSounds extends EventTarget {
1257
1336
  /** Every live instance, by its element. */
1258
1337
  static instances = /* @__PURE__ */ new Map();
1259
1338
  /**
@@ -1261,10 +1340,12 @@
1261
1340
  * @param {WaveformSoundsOptions} [options]
1262
1341
  */
1263
1342
  constructor(container, options = {}) {
1343
+ super();
1264
1344
  const el = typeof container === "string" ? document.querySelector(container) : container;
1265
1345
  if (!el) throw new Error(`${LOG} Container not found: ${container}`);
1266
1346
  this.container = el;
1267
- this.options = mergeOptions(DEFAULT_OPTIONS, options, readDataOptions(el));
1347
+ const data = el._wsOptions?.() ?? readDataOptions(el);
1348
+ this.options = mergeOptions(DEFAULT_OPTIONS, options, data);
1268
1349
  this.options.waveformStyle = this.options.waveformStyle === "bars" ? "bars" : "mirror";
1269
1350
  this.strings = { ...DEFAULT_STRINGS, ...this.options.strings || {} };
1270
1351
  this.render = { ...resolveRenderOptions(this.options), strings: this.strings };
@@ -1287,7 +1368,9 @@
1287
1368
  _WaveformSounds.instances.set(el, this);
1288
1369
  el.dataset.wsInitialized = "true";
1289
1370
  this.ready = Promise.resolve().then(() => this._init()).catch((err) => {
1371
+ if (this.destroyed) return;
1290
1372
  console.error(`${LOG} Failed to initialise:`, err);
1373
+ this._showLoadError();
1291
1374
  this._emit("error", { error: err });
1292
1375
  this.options.onError?.(err, this);
1293
1376
  });
@@ -1302,6 +1385,7 @@
1302
1385
  const el = this.container;
1303
1386
  const adopted = el.querySelector("[data-ws-list]");
1304
1387
  if (adopted) {
1388
+ this._adoptedHTML = el.innerHTML;
1305
1389
  this.sounds = readRows(adopted);
1306
1390
  } else {
1307
1391
  this._originalHTML = el.innerHTML;
@@ -1318,7 +1402,7 @@
1318
1402
  this._resolveColors();
1319
1403
  if (!this._loopSet) this.loop = loopsByDefault(this.options.loop, facets(this.sounds));
1320
1404
  this._setLoop(this.loop);
1321
- this._bpmExtent = facets(this.sounds).bpm;
1405
+ this._bpmExtent = bpmExtent(facets(this.sounds).bpm);
1322
1406
  this._sorts = availableSorts(this.render.sorts, facets(this.sounds));
1323
1407
  if (!this._sortSet) this.sortBy = this._sorts[0] || "default";
1324
1408
  this._readUrl();
@@ -1331,14 +1415,28 @@
1331
1415
  }
1332
1416
  /**
1333
1417
  * The sounds from the `sounds` option, else the `manifest` URL.
1334
- * @returns
1335
1418
  * @internal
1336
1419
  */
1337
1420
  async _loadSounds() {
1338
1421
  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());
1422
+ const url = this.options.manifest;
1423
+ const res = await fetch(url, { signal: this._ctl.signal });
1424
+ if (!res.ok) throw new Error(`${LOG} Manifest ${url}: HTTP ${res.status}`);
1425
+ const manifest = await res.json();
1426
+ if (!Array.isArray(manifest) && !Array.isArray(manifest?.sounds)) throw new Error(`${LOG} Manifest ${url}: no "sounds" list`);
1427
+ return parseManifest(manifest);
1428
+ }
1429
+ /**
1430
+ * A build that failed (the manifest 404s, isn't JSON, isn't a manifest)
1431
+ * says so where the list would be — unless the container holds the
1432
+ * site's own fallback, which stays. destroy() restores what was there.
1433
+ * @internal
1434
+ */
1435
+ _showLoadError() {
1436
+ const el = this.container;
1437
+ if (this.$ || el.querySelector("*")) return;
1438
+ this._originalHTML ??= el.innerHTML;
1439
+ el.innerHTML = h("p", { class: "ws-empty ws-load-error", role: "alert", "data-ws-load-error": true }, text(this.strings.loadError));
1342
1440
  }
1343
1441
  /**
1344
1442
  * Look up the elements the runtime drives.
@@ -1365,6 +1463,31 @@
1365
1463
  loopFilter: [...this.container.querySelectorAll("[data-ws-loop-filter]")]
1366
1464
  };
1367
1465
  this.rows = indexRows(this.$.list);
1466
+ this._active = null;
1467
+ for (const row of this.rows) if (row) this._rowStops(row, false);
1468
+ }
1469
+ /**
1470
+ * Make a row's own controls (play, download, and the seek slider when it
1471
+ * is the current sound) Tab stops, or not.
1472
+ * @internal
1473
+ */
1474
+ _rowStops(row, on) {
1475
+ const play = row.querySelector(".ws-play");
1476
+ if (play) play.tabIndex = on ? 0 : -1;
1477
+ const dl = row.querySelector(".ws-download");
1478
+ if (dl) dl.tabIndex = on ? 0 : -1;
1479
+ const wave = row.querySelector(".ws-wave");
1480
+ if (wave) wave.tabIndex = on && Number(row.dataset.wsIndex) === this.currentIndex ? 0 : -1;
1481
+ }
1482
+ /**
1483
+ * Move the list's Tab stop to `row` (roving tabindex).
1484
+ * @internal
1485
+ */
1486
+ _rove(row) {
1487
+ if (!row || row === this._active) return;
1488
+ if (this._active) this._rowStops(this._active, false);
1489
+ this._active = row;
1490
+ this._rowStops(row, true);
1368
1491
  }
1369
1492
  /**
1370
1493
  * Every listener. All are removed by `destroy()` through one
@@ -1378,6 +1501,7 @@
1378
1501
  root.addEventListener("click", (e) => this._onClick(e), sig);
1379
1502
  root.addEventListener("pointerdown", (e) => this._onPointerDown(e), sig);
1380
1503
  root.addEventListener("keydown", (e) => this._onKey(e), sig);
1504
+ $.list.addEventListener("focusin", (e) => this._rove(e.target.closest("[data-ws-index]")), sig);
1381
1505
  let searchTimer = 0, bpmTimer = 0;
1382
1506
  $.search?.addEventListener("input", () => {
1383
1507
  clearTimeout(searchTimer);
@@ -1436,11 +1560,13 @@
1436
1560
  return;
1437
1561
  }
1438
1562
  if (t.closest("[data-ws-more]")) {
1439
- this.showMore();
1563
+ this._showMoreFromButton();
1440
1564
  return;
1441
1565
  }
1442
1566
  if (t.closest("[data-ws-clear]")) {
1443
1567
  this.clearFilters();
1568
+ if (this.$.search) this.$.search.focus();
1569
+ else this._focusRow(visibleRows(this.$.list)[0]);
1444
1570
  return;
1445
1571
  }
1446
1572
  if (t.closest("[data-ws-loop]")) {
@@ -1457,6 +1583,17 @@
1457
1583
  this.toggle(Number(row.dataset.wsIndex));
1458
1584
  this._focusRowQuietly(row);
1459
1585
  }
1586
+ /**
1587
+ * "Show more", pressed: reveal the next page. When that was the last page
1588
+ * the button hides, so focus moves to the first row it revealed rather
1589
+ * than falling to <body>.
1590
+ * @internal
1591
+ */
1592
+ _showMoreFromButton() {
1593
+ const before = new Set(visibleRows(this.$.list));
1594
+ this.showMore();
1595
+ if (this.$.more?.hidden) this._focusRow(visibleRows(this.$.list).find((r) => !before.has(r)));
1596
+ }
1460
1597
  /**
1461
1598
  * Mouse and pen seek on PRESS, like every scrubber. Remembers the
1462
1599
  * pointer type for the click that follows.
@@ -1480,7 +1617,8 @@
1480
1617
  }
1481
1618
  /**
1482
1619
  * Keys on the list: `/` focuses search; ↑/↓/Home/End move between rows
1483
- * (auditioning while something plays); ←/→ seek the playing row.
1620
+ * (auditioning while something plays); ←/→ seek the playing row, and on
1621
+ * its seek slider Home/End seek to the start/end.
1484
1622
  * @internal
1485
1623
  */
1486
1624
  _onKey(e) {
@@ -1493,7 +1631,8 @@
1493
1631
  const row = e.target.closest?.("[data-ws-index]");
1494
1632
  if (!row) return;
1495
1633
  const index = Number(row.dataset.wsIndex);
1496
- const seek = seekTarget(this.progress, e.key);
1634
+ const edge = e.target.closest(".ws-wave") ? sliderEdgeTarget(e.key) : null;
1635
+ const seek = edge ?? seekTarget(this.progress, e.key);
1497
1636
  if (seek !== null) {
1498
1637
  if (index !== this.currentIndex || !this.engine) return;
1499
1638
  e.preventDefault();
@@ -1539,11 +1678,18 @@
1539
1678
  _observe() {
1540
1679
  if (this.render.player !== "inline" || typeof window === "undefined") return;
1541
1680
  this._drawn = /* @__PURE__ */ new Set();
1681
+ this._dirty = /* @__PURE__ */ new Set();
1542
1682
  if ("IntersectionObserver" in window) {
1683
+ this._onScreen = /* @__PURE__ */ new Set();
1543
1684
  this._io = new IntersectionObserver((entries) => {
1544
1685
  for (const entry of entries) {
1545
- if (!entry.isIntersecting) continue;
1546
1686
  const i = Number(entry.target.dataset.wsIndex);
1687
+ if (!entry.isIntersecting) {
1688
+ this._onScreen.delete(i);
1689
+ continue;
1690
+ }
1691
+ this._onScreen.add(i);
1692
+ if (this._drawn.has(i) && !this._dirty.has(i)) continue;
1547
1693
  this._drawn.add(i);
1548
1694
  this._drawRow(i);
1549
1695
  }
@@ -1562,34 +1708,46 @@
1562
1708
  });
1563
1709
  this._ro.observe(this.$.list);
1564
1710
  }
1565
- const refresh = () => requestAnimationFrame(() => {
1566
- this._resolveColors();
1567
- this._redrawAll();
1568
- });
1711
+ let queued = 0;
1712
+ const refresh = () => {
1713
+ if (queued) return;
1714
+ queued = requestAnimationFrame(() => {
1715
+ queued = 0;
1716
+ if (this._resolveColors()) this._redrawAll();
1717
+ });
1718
+ };
1569
1719
  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 {
1720
+ this._mo.observe(this.container, { attributes: true, attributeFilter: ["class", "data-theme", "data-color-scheme"] });
1721
+ for (const node of ancestorsOf(this.container)) {
1722
+ this._mo.observe(node, { attributes: true, attributeFilter: ["class", "data-theme", "data-color-scheme", "style"] });
1723
+ }
1724
+ for (const query of ["(prefers-color-scheme: dark)", "(forced-colors: active)"]) {
1725
+ try {
1726
+ window.matchMedia(query).addEventListener("change", refresh, { signal: this._ctl.signal });
1727
+ } catch {
1728
+ }
1576
1729
  }
1577
1730
  }
1578
1731
  /**
1579
- * Resolve the canvas colours (options, else the CSS custom properties)
1580
- * and keep `--ws-surface` current unless the site set it.
1732
+ * Resolve the canvas colours (options, else the CSS custom properties;
1733
+ * system colours under forced colours) and keep `--ws-surface` current
1734
+ * unless the site set it.
1735
+ * @returns Whether the canvas colours changed.
1581
1736
  * @internal
1582
1737
  */
1583
1738
  _resolveColors() {
1739
+ const before = this.colors;
1584
1740
  if (this._autoSurface || !getComputedStyle(this.container).getPropertyValue("--ws-surface").trim()) {
1585
1741
  this._autoSurface = true;
1586
1742
  this.container.style.removeProperty("--ws-surface");
1587
1743
  this.container.style.setProperty("--ws-surface", pageSurface(this.container));
1588
1744
  }
1745
+ const forced = forcedColors();
1589
1746
  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"
1747
+ wave: (forced ? resolveCssColor(this.container, "CanvasText") : this.options.waveformColor || resolveCssColor(this.container, "var(--ws-wave-color)")) || "rgba(128,128,128,.5)",
1748
+ progress: (forced ? resolveCssColor(this.container, "Highlight") : this.options.progressColor || resolveCssColor(this.container, "var(--ws-progress-color)")) || "currentColor"
1592
1749
  };
1750
+ return !before || before.wave !== this.colors.wave || before.progress !== this.colors.progress;
1593
1751
  }
1594
1752
  /**
1595
1753
  * Draw one row's waveform (only once it has been on screen).
@@ -1599,7 +1757,12 @@
1599
1757
  if (this.render.player !== "inline" || index == null || !this._drawn?.has(index)) return;
1600
1758
  const row = this.rows[index];
1601
1759
  const canvas = row?.querySelector("canvas");
1602
- if (!canvas || row.hidden) return;
1760
+ if (!canvas) return;
1761
+ if (row.hidden) {
1762
+ this._dirty?.add(index);
1763
+ return;
1764
+ }
1765
+ this._dirty?.delete(index);
1603
1766
  const gap = Number(this.options.barGap);
1604
1767
  drawRowWaveform(canvas, this.sounds[index].peaks, index === this.currentIndex ? this.progress : 0, {
1605
1768
  style: this.options.waveformStyle,
@@ -1610,11 +1773,17 @@
1610
1773
  });
1611
1774
  }
1612
1775
  /**
1613
- * Redraw every row drawn so far.
1776
+ * After a resize or a theme flip: redraw the rows on screen now, and
1777
+ * mark the rest stale — each is redrawn when it scrolls back in. (With
1778
+ * 1000 rows drawn, redrawing them all took ~0.4s in Chrome and ~1.9s in
1779
+ * WebKit per resize step.)
1614
1780
  * @internal
1615
1781
  */
1616
1782
  _redrawAll() {
1617
- this._drawn?.forEach((i) => this._drawRow(i));
1783
+ this._drawn?.forEach((i) => {
1784
+ if (this._onScreen && !this._onScreen.has(i)) this._dirty.add(i);
1785
+ else this._drawRow(i);
1786
+ });
1618
1787
  }
1619
1788
  /* ── Filters in the address ───────────────────────────────────────── */
1620
1789
  /**
@@ -1624,7 +1793,8 @@
1624
1793
  _readUrl() {
1625
1794
  const keys = urlKeys(this.options.urlState);
1626
1795
  if (!keys || typeof location === "undefined") return;
1627
- const { filter, sort } = readUrlState(location.search, keys, facets(this.sounds), this._sorts);
1796
+ const f = facets(this.sounds);
1797
+ const { filter, sort } = readUrlState(location.search, keys, { ...f, bpm: bpmExtent(f.bpm) }, this._sorts);
1628
1798
  this.filter = { ...this.filter, ...filter };
1629
1799
  if (sort) {
1630
1800
  this.sortBy = sort;
@@ -1649,6 +1819,13 @@
1649
1819
  /* ── Filtering, sorting, paging ───────────────────────────────────── */
1650
1820
  /** The sounds that pass the filter, in the current sort order. */
1651
1821
  get visible() {
1822
+ return [...this._shown ?? this._match()];
1823
+ }
1824
+ /**
1825
+ * Filter and sort the sounds now.
1826
+ * @internal
1827
+ */
1828
+ _match() {
1652
1829
  return sortSounds(this.sounds.filter((s) => matches(s, this.filter)), this.sortBy);
1653
1830
  }
1654
1831
  setFilter(patch = {}) {
@@ -1731,10 +1908,12 @@
1731
1908
  const $ = this.$;
1732
1909
  if (!$) return;
1733
1910
  if (resort || this.sortBy !== this._lastSort) {
1734
- orderRows($.list, sortSounds(this.sounds, this.sortBy).map((s) => this.rows[this.sounds.indexOf(s)]));
1911
+ const index = new Map(this.sounds.map((s, i) => [s, i]));
1912
+ orderRows($.list, sortSounds(this.sounds, this.sortBy).map((s) => this.rows[index.get(s)]));
1735
1913
  this._lastSort = this.sortBy;
1736
1914
  }
1737
- const shown = this.visible;
1915
+ const shown = this._match();
1916
+ this._shown = shown;
1738
1917
  const { visible, remaining } = pageWindow(shown, this.limit);
1739
1918
  this.sounds.forEach((s, i) => {
1740
1919
  if (this.rows[i]) this.rows[i].hidden = !visible.has(s);
@@ -1743,8 +1922,22 @@
1743
1922
  $.more.hidden = remaining <= 0;
1744
1923
  $.more.textContent = fill(this.strings.showMore, { count: Math.min(remaining, this.render.pageSize || remaining) });
1745
1924
  }
1746
- if ($.empty) $.empty.hidden = shown.length > 0;
1925
+ if ($.empty) {
1926
+ $.empty.hidden = shown.length > 0;
1927
+ if (!this.sounds.length && $.empty.textContent !== this.strings.noSounds) $.empty.textContent = this.strings.noSounds;
1928
+ }
1747
1929
  if ($.count) $.count.textContent = countText(shown.length, this.sounds.length, this.strings);
1930
+ if (!this._active || this._active.hidden) {
1931
+ const lost = !!this._active?.contains(document.activeElement);
1932
+ const first = visibleRows($.list)[0];
1933
+ if (first) {
1934
+ this._rove(first);
1935
+ if (lost) this._focusRowQuietly(first);
1936
+ } else if (this._active) {
1937
+ this._rowStops(this._active, false);
1938
+ this._active = null;
1939
+ }
1940
+ }
1748
1941
  if (this._cued && !this.playing) this._cueFirst();
1749
1942
  this._queueUrl();
1750
1943
  this._emit("filter", { visible: shown.length, total: this.sounds.length, filter: { ...this.filter }, sort: this.sortBy });
@@ -1756,30 +1949,38 @@
1756
1949
  * target means the current sound, else the first visible one.
1757
1950
  *
1758
1951
  * @param target
1759
- * @returns
1760
1952
  * @internal
1761
1953
  */
1762
1954
  _indexOf(target) {
1763
- if (target == null) return this.currentIndex ?? (this.visible[0] ? this.sounds.indexOf(this.visible[0]) : null);
1955
+ if (target == null) {
1956
+ if (this.currentIndex != null) return this.currentIndex;
1957
+ const first = (this._shown ?? this._match())[0];
1958
+ return first ? this.sounds.indexOf(first) : null;
1959
+ }
1764
1960
  if (typeof target === "number") return this.sounds[target] ? target : null;
1765
1961
  const i = typeof target === "object" ? this.sounds.indexOf(target) : this.sounds.findIndex((s) => s.id === String(target));
1766
1962
  return i >= 0 ? i : null;
1767
1963
  }
1768
1964
  /**
1769
1965
  * The WaveformPlayer class: `playerClass`, else the page's global.
1770
- * @returns
1771
1966
  * @internal
1772
1967
  */
1773
1968
  _playerClass() {
1774
1969
  return this.options.playerClass || (typeof window !== "undefined" ? window.WaveformPlayer : null) || null;
1775
1970
  }
1971
+ /**
1972
+ * The engine as the list drives it (fields the core keeps internal).
1973
+ * @internal
1974
+ */
1975
+ _eng() {
1976
+ return this.engine;
1977
+ }
1776
1978
  /**
1777
1979
  * The element the engine mounts into: a child of the engine slot, never
1778
1980
  * the slot itself. WaveformPlayer resets its container's `className`,
1779
1981
  * which would strip `ws-engine--strip` (and with it the docked styling).
1780
1982
  * Made here rather than in the markup so server-rendered HTML from any
1781
1983
  * version works.
1782
- * @returns
1783
1984
  * @internal
1784
1985
  */
1785
1986
  _engineMount() {
@@ -1798,21 +1999,23 @@
1798
1999
  * @internal
1799
2000
  */
1800
2001
  _ensureEngine() {
1801
- if (this.engine) return this.engine;
2002
+ if (this.engine) return this._eng();
1802
2003
  const Player = this._playerClass();
1803
2004
  if (!Player) {
1804
2005
  console.error(`${LOG} @arraypress/waveform-player is required: load it before playing (or pass playerClass).`);
1805
2006
  return null;
1806
2007
  }
1807
- this.engine = new Player(this._engineMount(), engineOptions(this.options.playerOptions, this.render.player, {
2008
+ const options = engineOptions(this.options.playerOptions, this.render.player, {
1808
2009
  onLoad: () => this._onEngineLoad(),
1809
2010
  onPlay: () => this._setPlaying(true),
1810
2011
  onPause: () => this._setPlaying(false),
1811
2012
  onEnd: () => this._onEnd(),
1812
2013
  onTimeUpdate: (time, duration) => this._onTime(time, duration),
1813
2014
  onError: (err) => this._onEngineError(err)
1814
- }));
1815
- return this.engine;
2015
+ });
2016
+ this._preload = options.preload;
2017
+ this.engine = new Player(this._engineMount(), options);
2018
+ return this._eng();
1816
2019
  }
1817
2020
  /**
1818
2021
  * Play a sound (by index, id or sound object), or resume the current
@@ -1845,30 +2048,40 @@
1845
2048
  if (previous != null) this._paintRow(previous);
1846
2049
  this._paintRow(index);
1847
2050
  const sound = this.sounds[index];
1848
- engine.loadTrack(sound.url, sound.title, sound.type || null, engineTrack(sound, this.render.player, true));
2051
+ engine.loadTrack(sound.url, sound.title, sound.type || null, engineTrack(sound, this.render.player, true, this._preload));
1849
2052
  }
1850
2053
  /**
1851
2054
  * Strip layout: load the first sound the list shows into the docked
1852
2055
  * player WITHOUT playing it, so the player shows a title and waveform
1853
2056
  * (and its play button plays that sound) instead of an empty frame.
1854
- * Only metadata is fetched — the browser default for any `<audio>`.
2057
+ * Nothing is fetched (`preload: 'none'`): the player shows the title,
2058
+ * length and peaks from the data, and the audio loads on play — a filter
2059
+ * change re-cues, and each cue used to fetch a file's metadata.
1855
2060
  * The row isn't marked current until it plays.
1856
2061
  * @internal
1857
2062
  */
1858
2063
  _cueFirst() {
1859
- const engine = this.engine;
1860
- const first = this.visible[0];
2064
+ const engine = this._eng();
2065
+ const first = (this._shown ?? this._match())[0];
1861
2066
  if (!engine || !first) return;
1862
2067
  const index = this.sounds.indexOf(first);
1863
2068
  if (index === this.currentIndex) return;
1864
2069
  this.currentIndex = index;
1865
2070
  this.progress = 0;
1866
2071
  this._cued = true;
1867
- engine.loadTrack(first.url, first.title, first.type || null, engineTrack(first, "strip", false));
2072
+ const audio = engine.audio;
2073
+ const shim = audio && typeof audio.load === "function";
2074
+ if (shim) audio.load = () => {
2075
+ };
2076
+ try {
2077
+ engine.loadTrack(first.url, first.title, first.type || null, engineTrack(first, "strip", false, "none"));
2078
+ } finally {
2079
+ if (shim) delete audio.load;
2080
+ }
1868
2081
  }
1869
2082
  /** Pause the current sound. */
1870
2083
  pause() {
1871
- if (this.engine && this.playing) this.engine.pause();
2084
+ if (this.engine && this.playing) this._eng().pause();
1872
2085
  }
1873
2086
  /**
1874
2087
  * The current sound plays/pauses; another sound starts.
@@ -1897,7 +2110,7 @@
1897
2110
  * @internal
1898
2111
  */
1899
2112
  _step(dir) {
1900
- const shown = this.visible;
2113
+ const shown = this._shown ?? this._match();
1901
2114
  const at = this.currentIndex == null || this._cued ? -1 : shown.indexOf(this.sounds[this.currentIndex]);
1902
2115
  const target = shown[at + dir];
1903
2116
  if (!target) return false;
@@ -1926,7 +2139,7 @@
1926
2139
  */
1927
2140
  _setLoop(on) {
1928
2141
  this.$?.loop?.setAttribute("aria-pressed", String(on));
1929
- if (this.engine?.audio) this.engine.audio.loop = this._repeats();
2142
+ if (this._eng()?.audio) this._eng().audio.loop = this._repeats();
1930
2143
  }
1931
2144
  /**
1932
2145
  * Should the current sound repeat? The Loop toggle is on, and either
@@ -1948,31 +2161,33 @@
1948
2161
  this.play(index, { at: fraction });
1949
2162
  return;
1950
2163
  }
1951
- const duration = this.engine.audio?.duration;
2164
+ const duration = this._eng().audio?.duration;
1952
2165
  if (!Number.isFinite(duration) || duration <= 0) {
1953
2166
  this._pendingSeek = fraction;
1954
2167
  return;
1955
2168
  }
1956
- this.engine.seekTo(fraction * duration);
2169
+ this._eng().seekTo(fraction * duration);
1957
2170
  this.progress = fraction;
1958
2171
  this._paintRow(index);
1959
- if (!this.playing) this.engine.play();
2172
+ this._paintSlider();
2173
+ if (!this.playing) this._eng().play();
1960
2174
  }
1961
2175
  /**
1962
- * The engine loaded a sound: apply the loop, borrow decoded peaks for a
2176
+ * The engine loaded a sound: clear an earlier failure, apply the loop, borrow decoded peaks for a
1963
2177
  * row that had none, and land a pending seek.
1964
2178
  * @internal
1965
2179
  */
1966
2180
  _onEngineLoad() {
1967
- if (this.engine?.audio) this.engine.audio.loop = this._repeats();
2181
+ if (this.currentIndex != null) this.rows[this.currentIndex]?.classList.remove("is-error");
2182
+ if (this._eng()?.audio) this._eng().audio.loop = this._repeats();
1968
2183
  const sound = this.sounds[this.currentIndex];
1969
- if (sound && !sound.peaks && this.engine?.waveformData?.length) {
1970
- sound.peaks = resample(this.engine.waveformData, 96);
2184
+ if (sound && !sound.peaks && this._eng()?.waveformData?.length) {
2185
+ sound.peaks = resample(this._eng().waveformData, 96);
1971
2186
  this._drawRow(this.currentIndex);
1972
2187
  }
1973
- const duration = this.engine?.audio?.duration;
2188
+ const duration = this._eng()?.audio?.duration;
1974
2189
  if (this._pendingSeek != null && Number.isFinite(duration) && duration > 0) {
1975
- this.engine.seekTo(this._pendingSeek * duration);
2190
+ this._eng().seekTo(this._pendingSeek * duration);
1976
2191
  this.progress = this._pendingSeek;
1977
2192
  this._pendingSeek = null;
1978
2193
  }
@@ -1986,7 +2201,7 @@
1986
2201
  if (this._pendingSeek != null) {
1987
2202
  const fraction = this._pendingSeek;
1988
2203
  this._pendingSeek = null;
1989
- this.engine.seekTo(fraction * duration);
2204
+ this._eng().seekTo(fraction * duration);
1990
2205
  return;
1991
2206
  }
1992
2207
  this.progress = Math.min(Math.max(time / duration, 0), 1);
@@ -1994,7 +2209,7 @@
1994
2209
  this._raf = requestAnimationFrame(() => {
1995
2210
  this._raf = 0;
1996
2211
  this._drawRow(this.currentIndex);
1997
- this.rows[this.currentIndex]?.querySelector(".ws-wave")?.setAttribute("aria-valuenow", String(Math.round(this.progress * 100)));
2212
+ this._paintSlider();
1998
2213
  });
1999
2214
  }
2000
2215
  /**
@@ -2010,32 +2225,59 @@
2010
2225
  this._setPlaying(false);
2011
2226
  }
2012
2227
  /**
2013
- * A sound failed to load or play: mark its row and report it.
2228
+ * A sound failed to load or play: it isn't playing (no stale "Pause"),
2229
+ * its row is marked until it plays, and the live region says so.
2014
2230
  * @internal
2015
2231
  */
2016
2232
  _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 });
2233
+ const index = this.currentIndex;
2234
+ const sound = index == null ? void 0 : this.sounds[index];
2235
+ if (index != null) this.rows[index]?.classList.add("is-error");
2236
+ this._setPlaying(false);
2237
+ if (sound && !this._cued && this.$?.status) this.$.status.textContent = fill(this.strings.playError, { title: sound.title });
2238
+ this._emit("error", { error: err, sound, index });
2019
2239
  this.options.onError?.(err, this);
2020
2240
  }
2021
2241
  /**
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.
2242
+ * Record play/pause and repaint, and report what the listener hears.
2243
+ * Events follow the SOUND, not the flag: switching sounds while one plays
2244
+ * (↓ audition, `play(i)`, `next()`, auto-advance) never flips `playing`
2245
+ * in some engines (the media element swaps source without a `pause`),
2246
+ * so the last sound announced is tracked — a different one starting
2247
+ * reports `pause` for the outgoing sound, then `play` for the new one.
2248
+ * At a natural end the browser fires `pause` then `ended`, and `_onEnd()`
2249
+ * settles the state again: one pause event, not two.
2025
2250
  * @internal
2026
2251
  */
2027
2252
  _setPlaying(on) {
2028
- const changed = this.playing !== on;
2029
2253
  this.playing = on;
2030
2254
  if (on) this._cued = false;
2031
2255
  const index = this.currentIndex;
2032
2256
  if (index == null) return;
2257
+ if (on) this.rows[index]?.classList.remove("is-error");
2033
2258
  this._paintRow(index);
2034
- if (!changed) return;
2259
+ const was = this._announced ?? null;
2260
+ if (on) {
2261
+ if (was === index) return;
2262
+ if (was != null) this._announce("pause", was);
2263
+ this._announced = index;
2264
+ this._announce("play", index);
2265
+ } else if (was != null) {
2266
+ this._announced = null;
2267
+ this._announce("pause", was);
2268
+ }
2269
+ }
2270
+ /**
2271
+ * Report a sound starting or stopping: the live region (on play), the
2272
+ * `waveformsounds:play|pause` event and the `onPlay` / `onPause` callback.
2273
+ * @internal
2274
+ */
2275
+ _announce(type, index) {
2035
2276
  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);
2277
+ if (!sound) return;
2278
+ if (type === "play" && this.$?.status) this.$.status.textContent = fill(this.strings.nowPlaying, { title: sound.title });
2279
+ this._emit(type, { sound, index });
2280
+ (type === "play" ? this.options.onPlay : this.options.onPause)?.(sound, this);
2039
2281
  }
2040
2282
  /* ── Row painting ─────────────────────────────────────────────────── */
2041
2283
  /**
@@ -2056,18 +2298,38 @@
2056
2298
  }
2057
2299
  const wave = row.querySelector(".ws-wave");
2058
2300
  if (wave) {
2059
- wave.tabIndex = current ? 0 : -1;
2060
- if (!current) wave.setAttribute("aria-valuenow", "0");
2301
+ wave.tabIndex = current && row === this._active ? 0 : -1;
2302
+ if (!current) {
2303
+ wave.setAttribute("aria-valuenow", "0");
2304
+ wave.removeAttribute("aria-valuetext");
2305
+ }
2061
2306
  }
2062
2307
  this._drawRow(index);
2063
2308
  }
2309
+ /**
2310
+ * The current row's seek slider: its position (0–100) and, for a screen
2311
+ * reader, the time ("0:12 of 0:30").
2312
+ * @internal
2313
+ */
2314
+ _paintSlider() {
2315
+ const index = this.currentIndex;
2316
+ const wave = index == null ? null : this.rows[index]?.querySelector(".ws-wave");
2317
+ if (!wave) return;
2318
+ wave.setAttribute("aria-valuenow", String(Math.round(this.progress * 100)));
2319
+ const audio = this._eng()?.audio;
2320
+ const duration = Number.isFinite(audio?.duration) && audio.duration > 0 ? audio.duration : this.sounds[index].duration;
2321
+ if (duration) wave.setAttribute("aria-valuetext", fill(this.strings.seekValue, { time: formatClock(this.progress * duration), duration: formatDuration(duration) }));
2322
+ }
2064
2323
  /* ── Events & lifecycle ──────────────────────────────────────────── */
2065
2324
  /**
2066
- * Emit a `waveformsounds:<name>` event carrying this instance.
2325
+ * Announce a moment both ways: a `waveformsounds:<name>` event on the
2326
+ * container carrying the details and this instance, then a plain `<name>`
2327
+ * event on the instance.
2067
2328
  * @internal
2068
2329
  */
2069
2330
  _emit(name, detail = {}) {
2070
2331
  emit(this.container, name, { ...detail, instance: this });
2332
+ this.dispatchEvent(new Event(name));
2071
2333
  }
2072
2334
  /** The sound playing (or paused) now, or null. */
2073
2335
  get current() {
@@ -2077,10 +2339,15 @@
2077
2339
  * Tear down: listeners, observers, timers and the engine. Markup this
2078
2340
  * instance rendered is restored to what the container held before.
2079
2341
  * 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.
2342
+ * re-sorted, hidden or marked current — unless `restore` is set: then it
2343
+ * is put back exactly as the server sent it, ready for a new instance
2344
+ * (what a framework re-mounting the same markup wants).
2345
+ *
2346
+ * @param options
2347
+ * @param options.restore - Put adopted server markup back as it was.
2348
+ * Default false. Since 2.1.0.
2082
2349
  */
2083
- destroy() {
2350
+ destroy(options = {}) {
2084
2351
  if (this.destroyed) return;
2085
2352
  this.destroyed = true;
2086
2353
  this._ctl.abort();
@@ -2090,12 +2357,13 @@
2090
2357
  if (this._raf) cancelAnimationFrame(this._raf);
2091
2358
  clearTimeout(this._urlTimer);
2092
2359
  try {
2093
- this.engine?.destroy();
2360
+ this._eng()?.destroy();
2094
2361
  } catch {
2095
2362
  }
2096
2363
  this.engine = null;
2097
2364
  this.$?.engine?.querySelector(":scope > [data-ws-engine-mount]")?.remove();
2098
2365
  if (this._originalHTML != null) this.container.innerHTML = this._originalHTML;
2366
+ else if (options.restore && this._adoptedHTML != null) this.container.innerHTML = this._adoptedHTML;
2099
2367
  if (this._addedClasses?.length) this.container.classList.remove(...this._addedClasses);
2100
2368
  if (this._autoSurface) this.container.style.removeProperty("--ws-surface");
2101
2369
  delete this.container.dataset.wsInitialized;
@@ -2125,7 +2393,6 @@
2125
2393
  /**
2126
2394
  * The instance on an element (or selector), if any.
2127
2395
  * @param el
2128
- * @returns
2129
2396
  */
2130
2397
  static getInstance(el) {
2131
2398
  const node = typeof el === "string" ? document.querySelector(el) : el;
@@ -2138,16 +2405,151 @@
2138
2405
  }
2139
2406
  };
2140
2407
 
2408
+ // src/js/core/element.ts
2409
+ var ELEMENT_OPTION_KEYS = [
2410
+ "player",
2411
+ "manifest",
2412
+ "search",
2413
+ "filters",
2414
+ "sorts",
2415
+ "showCount",
2416
+ "menuSearch",
2417
+ "idPrefix",
2418
+ "urlState",
2419
+ "loopToggle",
2420
+ "pageSize",
2421
+ "maxTypeChips",
2422
+ "columns",
2423
+ "waveformStyle",
2424
+ "waveformColor",
2425
+ "progressColor",
2426
+ "barWidth",
2427
+ "barGap",
2428
+ "loop",
2429
+ "autoAdvance",
2430
+ "arrowAudition",
2431
+ "strings",
2432
+ "playerOptions"
2433
+ ];
2434
+ var kebab = (key) => key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
2435
+ function readElementOptions(el) {
2436
+ const dataset = {};
2437
+ for (const key of ELEMENT_OPTION_KEYS) {
2438
+ const name = kebab(key);
2439
+ const value = el.getAttribute(name) ?? el.getAttribute(`data-${name}`);
2440
+ if (value != null) dataset[key] = value;
2441
+ }
2442
+ return readDataOptions({ dataset });
2443
+ }
2444
+ var Base = typeof HTMLElement === "undefined" ? class {
2445
+ } : HTMLElement;
2446
+ var WaveformSoundsElement = class extends Base {
2447
+ /** Every option attribute, plain and `data-` prefixed. */
2448
+ static get observedAttributes() {
2449
+ return ELEMENT_OPTION_KEYS.flatMap((key) => [kebab(key), `data-${kebab(key)}`]);
2450
+ }
2451
+ /** Build the list (or keep it, after a move). */
2452
+ connectedCallback() {
2453
+ if (this._leaving !== void 0) {
2454
+ clearTimeout(this._leaving);
2455
+ this._leaving = void 0;
2456
+ return;
2457
+ }
2458
+ if (!this.sounds) this._build();
2459
+ }
2460
+ /** Destroy the list, unless the element comes straight back (a move). */
2461
+ disconnectedCallback() {
2462
+ clearTimeout(this._leaving);
2463
+ this._leaving = setTimeout(() => {
2464
+ this._leaving = void 0;
2465
+ if (!this.isConnected) this._teardown();
2466
+ }, 0);
2467
+ }
2468
+ /**
2469
+ * An option attribute changed: rebuild once the task's changes are in.
2470
+ *
2471
+ * @param name
2472
+ * @param previous
2473
+ * @param value
2474
+ */
2475
+ attributeChangedCallback(name, previous, value) {
2476
+ if (!this.sounds || previous === value) return;
2477
+ const kind = name.replace(/^data-/, "") === "manifest" ? "manifest" : "rebuild";
2478
+ if (this._pending) {
2479
+ if (kind === "manifest") this._pending = kind;
2480
+ return;
2481
+ }
2482
+ this._pending = kind;
2483
+ queueMicrotask(() => {
2484
+ const pending = this._pending;
2485
+ this._pending = void 0;
2486
+ if (this.sounds) this._rebuild(pending === "manifest");
2487
+ });
2488
+ }
2489
+ /**
2490
+ * The options the list reads off this element (`WaveformSounds` calls it
2491
+ * in place of reading `data-*` alone).
2492
+ * @internal
2493
+ */
2494
+ _wsOptions() {
2495
+ return readElementOptions(this);
2496
+ }
2497
+ /**
2498
+ * Build the list into the element.
2499
+ * @internal
2500
+ */
2501
+ _build(options = {}) {
2502
+ WaveformSounds.getInstance(this)?.destroy({ restore: true });
2503
+ try {
2504
+ this.sounds = new WaveformSounds(this, options);
2505
+ } catch (error) {
2506
+ this.sounds = null;
2507
+ console.error(`${LOG} Failed to initialise:`, error, this);
2508
+ }
2509
+ }
2510
+ /**
2511
+ * Destroy the list, putting server-rendered markup back as it came.
2512
+ * @internal
2513
+ */
2514
+ _teardown() {
2515
+ this.sounds?.destroy({ restore: true });
2516
+ this.sounds = null;
2517
+ }
2518
+ /**
2519
+ * Rebuild for new options: re-rendered from the sounds the list holds
2520
+ * (the markup must follow the new options), or fetched afresh when the
2521
+ * manifest changed.
2522
+ * @internal
2523
+ */
2524
+ _rebuild(refetch) {
2525
+ const sounds = refetch || !this.sounds.$ ? void 0 : this.sounds.sounds.slice();
2526
+ this._teardown();
2527
+ this.innerHTML = "";
2528
+ this._build(sounds ? { sounds } : {});
2529
+ }
2530
+ };
2531
+ function defineWaveformSoundsElement(name = "waveform-sounds") {
2532
+ if (typeof customElements === "undefined") return void 0;
2533
+ const existing = customElements.get(name);
2534
+ if (existing) return existing;
2535
+ const element = class extends WaveformSoundsElement {
2536
+ };
2537
+ customElements.define(name, element);
2538
+ return element;
2539
+ }
2540
+
2141
2541
  // src/js/entry.ts
2142
2542
  WaveformSounds.utils = { encodePeaks, decodePeaks, normalizeKey, normalizeSounds, parseManifest, facets, matches, sortSounds, formatDuration, renderSounds };
2143
2543
  WaveformSounds.DEFAULT_OPTIONS = DEFAULT_OPTIONS;
2144
2544
  WaveformSounds.DEFAULT_STRINGS = DEFAULT_STRINGS;
2545
+ WaveformSounds.defineElement = defineWaveformSoundsElement;
2145
2546
  if (typeof window !== "undefined") window.WaveformSounds = WaveformSounds;
2146
2547
  var entry_default = WaveformSounds;
2147
2548
 
2148
2549
  // src/js/index.ts
2149
2550
  var index_default = entry_default;
2150
2551
  if (typeof document !== "undefined" && document.documentElement?.dataset?.waveformAutoinit !== "false") {
2552
+ defineWaveformSoundsElement();
2151
2553
  if (document.readyState === "loading") {
2152
2554
  document.addEventListener("DOMContentLoaded", () => entry_default.init(), { once: true });
2153
2555
  } else {
@@ -2159,8 +2561,8 @@
2159
2561
  * @arraypress/waveform-sounds
2160
2562
  * A searchable, filterable list of sounds for WaveformPlayer.
2161
2563
  *
2162
- * Importing this entry initialises every `[data-waveform-sounds]` element
2163
- * once the DOM is ready. Opt out page-wide with
2564
+ * Importing this entry registers `<waveform-sounds>` and initialises every
2565
+ * `[data-waveform-sounds]` element once the DOM is ready. Opt out page-wide with
2164
2566
  * `<html data-waveform-autoinit="false">` (the family's switch), or import
2165
2567
  * `@arraypress/waveform-sounds/no-autoinit`.
2166
2568
  *