@arraypress/waveform-player 1.16.1 → 1.17.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.
@@ -25,6 +25,14 @@ __export(index_exports, {
25
25
  module.exports = __toCommonJS(index_exports);
26
26
 
27
27
  // src/js/utils.js
28
+ var DEFAULT_SAMPLES = 1800;
29
+ function maxOf(values) {
30
+ let max = -Infinity;
31
+ for (let i = 0; i < values.length; i++) {
32
+ if (values[i] > max) max = values[i];
33
+ }
34
+ return max;
35
+ }
28
36
  function escapeHtml(str) {
29
37
  return String(str == null ? "" : str).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
30
38
  }
@@ -107,6 +115,7 @@ function parseDataAttributes(element) {
107
115
  setBool("showInfo");
108
116
  setBool("showTime");
109
117
  setBool("showHoverTime");
118
+ setBool("seekHandle");
110
119
  setBool("showBPM", "showBpm");
111
120
  setNum("bpm");
112
121
  setBool("singlePlay");
@@ -451,33 +460,19 @@ function drawSeekbar(ctx, canvas, peaks, progress, options) {
451
460
  const centerY = height / 2;
452
461
  const barHeight = 4;
453
462
  const borderRadius = barHeight / 2;
463
+ const active = !!options.seekActive;
454
464
  ctx.clearRect(0, 0, width, height);
455
465
  ctx.fillStyle = options.color || "rgba(255, 255, 255, 0.2)";
456
466
  capsulePath(ctx, borderRadius, width, centerY, barHeight);
457
467
  ctx.fill();
458
468
  if (progress > 0) {
459
469
  const progressWidth = Math.max(borderRadius * 2, progress * width);
460
- ctx.shadowBlur = 8;
461
- ctx.shadowColor = options.progressColor;
470
+ ctx.save();
471
+ ctx.globalAlpha = options.seekHandle && !active ? 0.7 : 1;
462
472
  ctx.fillStyle = options.progressColor || "rgba(255, 255, 255, 0.9)";
463
473
  capsulePath(ctx, borderRadius, progressWidth, centerY, barHeight);
464
474
  ctx.fill();
465
- ctx.shadowBlur = 0;
466
- const handleRadius = 8;
467
- const handleX = progressWidth;
468
- ctx.shadowBlur = 4;
469
- ctx.shadowColor = "rgba(0, 0, 0, 0.3)";
470
- ctx.shadowOffsetY = 2;
471
- ctx.fillStyle = "#ffffff";
472
- ctx.beginPath();
473
- ctx.arc(handleX, centerY, handleRadius, 0, Math.PI * 2);
474
- ctx.fill();
475
- ctx.shadowBlur = 0;
476
- ctx.shadowOffsetY = 0;
477
- ctx.fillStyle = options.progressColor || "rgba(255, 255, 255, 0.9)";
478
- ctx.beginPath();
479
- ctx.arc(handleX, centerY, handleRadius * 0.4, 0, Math.PI * 2);
480
- ctx.fill();
475
+ ctx.restore();
481
476
  }
482
477
  }
483
478
  var DRAWING_STYLES = {
@@ -566,7 +561,7 @@ function detectOnsets(channelData, sampleRate) {
566
561
  }
567
562
 
568
563
  // src/js/audio.js
569
- function extractPeaks(buffer, samples = 200) {
564
+ function extractPeaks(buffer, samples = DEFAULT_SAMPLES) {
570
565
  const sampleSize = buffer.length / samples;
571
566
  const channels = buffer.numberOfChannels;
572
567
  const peaks = [];
@@ -588,10 +583,10 @@ function extractPeaks(buffer, samples = 200) {
588
583
  }
589
584
  }
590
585
  }
591
- const maxPeak = Math.max(...peaks);
586
+ const maxPeak = maxOf(peaks);
592
587
  return maxPeak > 0 ? peaks.map((peak) => peak / maxPeak) : peaks;
593
588
  }
594
- async function generateWaveform(url, samples = 200, shouldDetectBPM = false) {
589
+ async function generateWaveform(url, samples = DEFAULT_SAMPLES, shouldDetectBPM = false) {
595
590
  let audioContext;
596
591
  try {
597
592
  const AudioCtx = window.AudioContext || /** @type {any} */
@@ -611,7 +606,7 @@ async function generateWaveform(url, samples = 200, shouldDetectBPM = false) {
611
606
  if (audioContext) audioContext.close();
612
607
  }
613
608
  }
614
- function generatePlaceholderWaveform(samples = 200) {
609
+ function generatePlaceholderWaveform(samples = DEFAULT_SAMPLES) {
615
610
  const data = [];
616
611
  for (let i = 0; i < samples; i++) {
617
612
  const base = Math.random() * 0.5 + 0.3;
@@ -621,7 +616,7 @@ function generatePlaceholderWaveform(samples = 200) {
621
616
  return data;
622
617
  }
623
618
  function normalizePeaks(peaks, targetMax = 0.95) {
624
- const maxPeak = Math.max(...peaks);
619
+ const maxPeak = maxOf(peaks);
625
620
  if (maxPeak === 0 || maxPeak > targetMax) return peaks;
626
621
  const scaleFactor = targetMax / maxPeak;
627
622
  return peaks.map((peak) => peak * scaleFactor);
@@ -693,7 +688,7 @@ var DEFAULT_OPTIONS = {
693
688
  // bars, so this is fidelity headroom, not the visible bar count. 1800 (the
694
689
  // SoundCloud/WaveformGen figure) keeps wide / high-DPI waveforms crisp; the
695
690
  // every-frame scan means a higher value costs no extra extraction time.
696
- samples: 1800,
691
+ samples: DEFAULT_SAMPLES,
697
692
  preload: "metadata",
698
693
  // Audio mode — 'self' = player owns the <audio> element (default, current
699
694
  // behavior). 'external' = player is a visualization-only surface; no audio
@@ -744,6 +739,11 @@ var DEFAULT_OPTIONS = {
744
739
  showInfo: true,
745
740
  showTime: true,
746
741
  showHoverTime: false,
742
+ // Show a draggable circle handle + hover brightness-lift on the SEEKBAR
743
+ // style only (it's meaningless on a waveform, where the fill-edge is the
744
+ // playhead). Off by default; the bar turns it on. Drag-to-scrub works
745
+ // regardless of this.
746
+ seekHandle: false,
747
747
  showBPM: false,
748
748
  // Known BPM to display in the badge (with showBPM). Wins over auto-detection
749
749
  // — set it when peaks are pre-generated so the tempo still shows. null = auto.
@@ -793,6 +793,7 @@ var ARTWORK_FALLBACK = "data:image/svg+xml," + encodeURIComponent(
793
793
  );
794
794
  var SEEK_STEP_SECONDS = 5;
795
795
  var SEEK_PAGE_SECONDS = 10;
796
+ var INTERACTIVE_ELEMENTS = 'button, a[href], input, [role="slider"]';
796
797
  var WaveformPlayer = class _WaveformPlayer {
797
798
  /** @type {Map<string, WaveformPlayer>} */
798
799
  static instances = /* @__PURE__ */ new Map();
@@ -988,7 +989,7 @@ var WaveformPlayer = class _WaveformPlayer {
988
989
  ` : ""}
989
990
  ${this.options.showPlaybackSpeed ? `
990
991
  <div class="waveform-speed">
991
- <button class="speed-btn" aria-label="Playback speed">
992
+ <button class="speed-btn" aria-label="Playback speed" aria-haspopup="true" aria-expanded="false">
992
993
  <span class="speed-value">1x</span>
993
994
  </button>
994
995
  <div class="speed-menu" style="display: none;">
@@ -1087,8 +1088,9 @@ var WaveformPlayer = class _WaveformPlayer {
1087
1088
  }
1088
1089
  /**
1089
1090
  * Wire up the playback-speed menu: toggle it open on the speed button,
1090
- * close it on any outside click, and apply the chosen rate when a
1091
- * `.speed-option` is clicked. All listeners are registered against the
1091
+ * close it on outside click or Escape (keeping `aria-expanded` on the
1092
+ * trigger in sync), and apply the chosen rate when a `.speed-option` is
1093
+ * clicked, returning focus to the trigger. All listeners are registered against the
1092
1094
  * instance `AbortController` signal so {@link WaveformPlayer#destroy} tears
1093
1095
  * them down. No-op if the speed elements are absent.
1094
1096
  * @private
@@ -1097,19 +1099,27 @@ var WaveformPlayer = class _WaveformPlayer {
1097
1099
  const speedBtn = this.container.querySelector(".speed-btn");
1098
1100
  const speedMenu = this.container.querySelector(".speed-menu");
1099
1101
  if (!speedBtn || !speedMenu) return;
1102
+ const setSpeedMenu = (open) => {
1103
+ speedMenu.style.display = open ? "block" : "none";
1104
+ speedBtn.setAttribute("aria-expanded", open ? "true" : "false");
1105
+ };
1100
1106
  speedBtn.addEventListener("click", (e) => {
1101
1107
  e.stopPropagation();
1102
- speedMenu.style.display = speedMenu.style.display === "none" ? "block" : "none";
1103
- }, { signal: this._ac.signal });
1104
- document.addEventListener("click", () => {
1105
- speedMenu.style.display = "none";
1108
+ setSpeedMenu(speedMenu.style.display === "none");
1106
1109
  }, { signal: this._ac.signal });
1110
+ document.addEventListener("click", () => setSpeedMenu(false), { signal: this._ac.signal });
1107
1111
  speedMenu.addEventListener("click", (e) => {
1108
1112
  e.stopPropagation();
1109
1113
  if (e.target.classList.contains("speed-option")) {
1110
- const rate = parseFloat(e.target.dataset.rate);
1111
- this.setPlaybackRate(rate);
1112
- speedMenu.style.display = "none";
1114
+ this.setPlaybackRate(parseFloat(e.target.dataset.rate));
1115
+ setSpeedMenu(false);
1116
+ speedBtn.focus();
1117
+ }
1118
+ }, { signal: this._ac.signal });
1119
+ speedBtn.closest(".waveform-speed")?.addEventListener("keydown", (e) => {
1120
+ if (e.key === "Escape" && speedMenu.style.display !== "none") {
1121
+ setSpeedMenu(false);
1122
+ speedBtn.focus();
1113
1123
  }
1114
1124
  }, { signal: this._ac.signal });
1115
1125
  this.updateSpeedUI();
@@ -1127,7 +1137,8 @@ var WaveformPlayer = class _WaveformPlayer {
1127
1137
  */
1128
1138
  initKeyboardControls() {
1129
1139
  this.container.setAttribute("tabindex", "-1");
1130
- this.container.addEventListener("click", () => {
1140
+ this.container.addEventListener("click", (e) => {
1141
+ if (e.target.closest(INTERACTIVE_ELEMENTS)) return;
1131
1142
  _WaveformPlayer.getAllInstances().forEach((player) => {
1132
1143
  if (player !== this) {
1133
1144
  player.container.setAttribute("tabindex", "-1");
@@ -1339,7 +1350,56 @@ var WaveformPlayer = class _WaveformPlayer {
1339
1350
  this.audio.addEventListener("error", (e) => this.onError(e));
1340
1351
  }
1341
1352
  this.canvas.addEventListener("click", (e) => this.handleCanvasClick(e));
1353
+ this._dragging = false;
1354
+ this._seekHover = false;
1355
+ this._handleNear = false;
1356
+ this.canvas.addEventListener("pointerenter", () => {
1357
+ this._seekHover = true;
1358
+ this.drawWaveform();
1359
+ this._updateSeekHandle();
1360
+ });
1361
+ this.canvas.addEventListener("pointerleave", () => {
1362
+ this._seekHover = false;
1363
+ this._handleNear = false;
1364
+ if (!this._dragging) this._hideHoverTip();
1365
+ this.drawWaveform();
1366
+ this._updateSeekHandle();
1367
+ });
1368
+ this.canvas.addEventListener("pointerdown", (e) => {
1369
+ if (e.pointerType === "mouse" && e.button !== 0) return;
1370
+ this._dragging = true;
1371
+ try {
1372
+ this.canvas.setPointerCapture(e.pointerId);
1373
+ } catch (err) {
1374
+ }
1375
+ this._scrubTo(e.clientX);
1376
+ });
1377
+ this.canvas.addEventListener("pointermove", (e) => {
1378
+ if (this._dragging) {
1379
+ this._scrubTo(e.clientX);
1380
+ return;
1381
+ }
1382
+ const rect = this.canvas.getBoundingClientRect();
1383
+ if (rect.width) {
1384
+ this._handleNear = Math.abs(e.clientX - rect.left - this.progress * rect.width) <= 10;
1385
+ this._updateSeekHandle();
1386
+ }
1387
+ });
1388
+ const endDrag = (e) => {
1389
+ if (!this._dragging) return;
1390
+ this._dragging = false;
1391
+ try {
1392
+ this.canvas.releasePointerCapture(e.pointerId);
1393
+ } catch (err) {
1394
+ }
1395
+ this._seekFromPointer(e.clientX);
1396
+ if (!this._seekHover) this._hideHoverTip();
1397
+ this._updateSeekHandle();
1398
+ };
1399
+ this.canvas.addEventListener("pointerup", endDrag);
1400
+ this.canvas.addEventListener("pointercancel", endDrag);
1342
1401
  this.setupHoverTime();
1402
+ this.setupSeekHandle();
1343
1403
  this.resizeHandler = debounce(() => this.resizeCanvas(), 100);
1344
1404
  window.addEventListener("resize", this.resizeHandler);
1345
1405
  }
@@ -1548,7 +1608,8 @@ var WaveformPlayer = class _WaveformPlayer {
1548
1608
  ...this.options,
1549
1609
  waveformStyle: this.options.waveformStyle || "bars",
1550
1610
  color: this.options.waveformColor,
1551
- progressColor: this.options.progressColor
1611
+ progressColor: this.options.progressColor,
1612
+ seekActive: this._seekHover || this._dragging
1552
1613
  });
1553
1614
  }
1554
1615
  /**
@@ -1678,21 +1739,78 @@ var WaveformPlayer = class _WaveformPlayer {
1678
1739
  this.seekEl.appendChild(tip);
1679
1740
  this.hoverTimeEl = tip;
1680
1741
  this.seekEl.addEventListener("pointermove", (e) => {
1681
- const dur = this.getSeekDuration();
1682
- if (!dur) {
1683
- tip.style.opacity = "0";
1684
- return;
1685
- }
1686
- const rect = this.canvas.getBoundingClientRect();
1687
- const pct = clamp((e.clientX - rect.left) / rect.width);
1688
- tip.textContent = formatTime(pct * dur);
1689
- tip.style.left = pct * 100 + "%";
1690
- tip.style.opacity = "1";
1742
+ if (!this._dragging) this._updateHoverTip(e.clientX);
1691
1743
  });
1692
1744
  this.seekEl.addEventListener("pointerleave", () => {
1693
- tip.style.opacity = "0";
1745
+ if (!this._dragging) this._hideHoverTip();
1694
1746
  });
1695
1747
  }
1748
+ /**
1749
+ * Position + fill the hover-time tooltip for a given client-X. Shared by
1750
+ * hover and drag-scrub. No-op when the tooltip isn't enabled
1751
+ * (`showHoverTime` off).
1752
+ * @param {number} clientX - Pointer client-X coordinate.
1753
+ * @private
1754
+ */
1755
+ _updateHoverTip(clientX) {
1756
+ const tip = this.hoverTimeEl;
1757
+ if (!tip) return;
1758
+ const dur = this.getSeekDuration();
1759
+ if (!dur) {
1760
+ tip.style.opacity = "0";
1761
+ return;
1762
+ }
1763
+ const rect = this.canvas.getBoundingClientRect();
1764
+ const pct = clamp((clientX - rect.left) / rect.width);
1765
+ tip.textContent = formatTime(pct * dur);
1766
+ tip.style.left = pct * 100 + "%";
1767
+ tip.style.opacity = "1";
1768
+ }
1769
+ /** Hide the hover-time tooltip. @private */
1770
+ _hideHoverTip() {
1771
+ if (this.hoverTimeEl) this.hoverTimeEl.style.opacity = "0";
1772
+ }
1773
+ /**
1774
+ * Visually preview a seek during a drag — moves the playhead + handle +
1775
+ * tooltip to the cursor WITHOUT touching the audio (playback continues; the
1776
+ * real seek is committed on release).
1777
+ * @param {number} clientX - Pointer client-X coordinate.
1778
+ * @private
1779
+ */
1780
+ _scrubTo(clientX) {
1781
+ const rect = this.canvas.getBoundingClientRect();
1782
+ if (!rect.width) return;
1783
+ this.progress = clamp((clientX - rect.left) / rect.width);
1784
+ this.drawWaveform();
1785
+ this._updateSeekHandle();
1786
+ this._updateHoverTip(clientX);
1787
+ }
1788
+ /**
1789
+ * Create the draggable seek handle — a DOM circle over the playhead, shown
1790
+ * only on hover / drag (Spotify-style). Pointer-events are off so it never
1791
+ * blocks the canvas scrub; size + visibility are CSS.
1792
+ * @private
1793
+ */
1794
+ setupSeekHandle() {
1795
+ if (!this.options.seekHandle || this.options.waveformStyle !== "seekbar" || !this.seekEl) return;
1796
+ const h = document.createElement("div");
1797
+ h.className = "waveform-seek-handle";
1798
+ h.setAttribute("aria-hidden", "true");
1799
+ this.seekEl.appendChild(h);
1800
+ this.seekHandleEl = h;
1801
+ }
1802
+ /**
1803
+ * Position the seek handle at the current progress and toggle its
1804
+ * visibility (hover / drag) + expanded (drag / direct-hover) classes.
1805
+ * @private
1806
+ */
1807
+ _updateSeekHandle() {
1808
+ const h = this.seekHandleEl;
1809
+ if (!h) return;
1810
+ h.style.left = this.progress * 100 + "%";
1811
+ h.classList.toggle("is-visible", this._seekHover || this._dragging);
1812
+ h.classList.toggle("is-active", this._dragging || this._handleNear);
1813
+ }
1696
1814
  // ============================================
1697
1815
  // Event Handlers
1698
1816
  // ============================================
@@ -1709,9 +1827,23 @@ var WaveformPlayer = class _WaveformPlayer {
1709
1827
  * @fires WaveformPlayer#waveformplayer:request-seek
1710
1828
  */
1711
1829
  handleCanvasClick(event) {
1830
+ this._seekFromPointer(event.clientX);
1831
+ }
1832
+ /**
1833
+ * Seek to a horizontal client-X position over the canvas — shared by
1834
+ * click and drag. In external mode the player has no audio of its own,
1835
+ * so it dispatches a cancelable `waveformplayer:request-seek` with the
1836
+ * target percentage (updating the local visual optimistically); in self
1837
+ * mode it seeks the owned `<audio>` via
1838
+ * {@link WaveformPlayer#seekToPercent}.
1839
+ * @param {number} clientX - Pointer client-X coordinate.
1840
+ * @private
1841
+ * @fires WaveformPlayer#waveformplayer:request-seek
1842
+ */
1843
+ _seekFromPointer(clientX) {
1712
1844
  const rect = this.canvas.getBoundingClientRect();
1713
- const x = event.clientX - rect.left;
1714
- const targetPercent = clamp(x / rect.width);
1845
+ if (!rect.width) return;
1846
+ const targetPercent = clamp((clientX - rect.left) / rect.width);
1715
1847
  if (this.options.audioMode === "external") {
1716
1848
  this._requestSeek(targetPercent);
1717
1849
  return;
@@ -1893,10 +2025,12 @@ var WaveformPlayer = class _WaveformPlayer {
1893
2025
  */
1894
2026
  updateProgress() {
1895
2027
  if (!this.audio || !this.audio.duration) return;
2028
+ if (this._dragging) return;
1896
2029
  const newProgress = this.audio.currentTime / this.audio.duration;
1897
2030
  if (Math.abs(newProgress - this.progress) > 1e-3) {
1898
2031
  this.progress = newProgress;
1899
2032
  this.drawWaveform();
2033
+ this._updateSeekHandle();
1900
2034
  }
1901
2035
  if (this.currentTimeEl) {
1902
2036
  this.currentTimeEl.textContent = formatTime(this.audio.currentTime);
@@ -2308,7 +2442,7 @@ var WaveformPlayer = class _WaveformPlayer {
2308
2442
  * @param {number} samples - Number of samples
2309
2443
  * @returns {Promise<number[]>} Waveform peak data
2310
2444
  */
2311
- static async generateWaveformData(url, samples = 200) {
2445
+ static async generateWaveformData(url, samples = DEFAULT_SAMPLES) {
2312
2446
  try {
2313
2447
  const result = await generateWaveform(url, samples);
2314
2448
  return result.peaks;