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