@arraypress/waveform-player 1.16.0 → 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();
@@ -849,6 +850,7 @@ var WaveformPlayer = class _WaveformPlayer {
849
850
  this.waveformData = [];
850
851
  this.progress = 0;
851
852
  this._activeMarkerIndex = -1;
853
+ this._markerLabelTimer = null;
852
854
  this.isPlaying = false;
853
855
  this.isLoading = false;
854
856
  this.hasError = false;
@@ -987,7 +989,7 @@ var WaveformPlayer = class _WaveformPlayer {
987
989
  ` : ""}
988
990
  ${this.options.showPlaybackSpeed ? `
989
991
  <div class="waveform-speed">
990
- <button class="speed-btn" aria-label="Playback speed">
992
+ <button class="speed-btn" aria-label="Playback speed" aria-haspopup="true" aria-expanded="false">
991
993
  <span class="speed-value">1x</span>
992
994
  </button>
993
995
  <div class="speed-menu" style="display: none;">
@@ -1086,8 +1088,9 @@ var WaveformPlayer = class _WaveformPlayer {
1086
1088
  }
1087
1089
  /**
1088
1090
  * Wire up the playback-speed menu: toggle it open on the speed button,
1089
- * close it on any outside click, and apply the chosen rate when a
1090
- * `.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
1091
1094
  * instance `AbortController` signal so {@link WaveformPlayer#destroy} tears
1092
1095
  * them down. No-op if the speed elements are absent.
1093
1096
  * @private
@@ -1096,19 +1099,27 @@ var WaveformPlayer = class _WaveformPlayer {
1096
1099
  const speedBtn = this.container.querySelector(".speed-btn");
1097
1100
  const speedMenu = this.container.querySelector(".speed-menu");
1098
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
+ };
1099
1106
  speedBtn.addEventListener("click", (e) => {
1100
1107
  e.stopPropagation();
1101
- speedMenu.style.display = speedMenu.style.display === "none" ? "block" : "none";
1102
- }, { signal: this._ac.signal });
1103
- document.addEventListener("click", () => {
1104
- speedMenu.style.display = "none";
1108
+ setSpeedMenu(speedMenu.style.display === "none");
1105
1109
  }, { signal: this._ac.signal });
1110
+ document.addEventListener("click", () => setSpeedMenu(false), { signal: this._ac.signal });
1106
1111
  speedMenu.addEventListener("click", (e) => {
1107
1112
  e.stopPropagation();
1108
1113
  if (e.target.classList.contains("speed-option")) {
1109
- const rate = parseFloat(e.target.dataset.rate);
1110
- this.setPlaybackRate(rate);
1111
- 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();
1112
1123
  }
1113
1124
  }, { signal: this._ac.signal });
1114
1125
  this.updateSpeedUI();
@@ -1126,7 +1137,8 @@ var WaveformPlayer = class _WaveformPlayer {
1126
1137
  */
1127
1138
  initKeyboardControls() {
1128
1139
  this.container.setAttribute("tabindex", "-1");
1129
- this.container.addEventListener("click", () => {
1140
+ this.container.addEventListener("click", (e) => {
1141
+ if (e.target.closest(INTERACTIVE_ELEMENTS)) return;
1130
1142
  _WaveformPlayer.getAllInstances().forEach((player) => {
1131
1143
  if (player !== this) {
1132
1144
  player.container.setAttribute("tabindex", "-1");
@@ -1338,7 +1350,56 @@ var WaveformPlayer = class _WaveformPlayer {
1338
1350
  this.audio.addEventListener("error", (e) => this.onError(e));
1339
1351
  }
1340
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);
1341
1401
  this.setupHoverTime();
1402
+ this.setupSeekHandle();
1342
1403
  this.resizeHandler = debounce(() => this.resizeCanvas(), 100);
1343
1404
  window.addEventListener("resize", this.resizeHandler);
1344
1405
  }
@@ -1547,7 +1608,8 @@ var WaveformPlayer = class _WaveformPlayer {
1547
1608
  ...this.options,
1548
1609
  waveformStyle: this.options.waveformStyle || "bars",
1549
1610
  color: this.options.waveformColor,
1550
- progressColor: this.options.progressColor
1611
+ progressColor: this.options.progressColor,
1612
+ seekActive: this._seekHover || this._dragging
1551
1613
  });
1552
1614
  }
1553
1615
  /**
@@ -1583,6 +1645,7 @@ var WaveformPlayer = class _WaveformPlayer {
1583
1645
  if (!this.markersContainer) return;
1584
1646
  this.markersContainer.innerHTML = "";
1585
1647
  this._activeMarkerIndex = -1;
1648
+ clearTimeout(this._markerLabelTimer);
1586
1649
  if (!this.options.showMarkers || !this.options.markers?.length) return;
1587
1650
  const duration = this.getSeekDuration();
1588
1651
  if (!duration) {
@@ -1652,6 +1715,13 @@ var WaveformPlayer = class _WaveformPlayer {
1652
1715
  if (active !== this._activeMarkerIndex) {
1653
1716
  this._activeMarkerIndex = active;
1654
1717
  this.setActiveMarker(active);
1718
+ clearTimeout(this._markerLabelTimer);
1719
+ els.forEach((el, i) => el.classList.toggle("show-label", i === active));
1720
+ if (active >= 0) {
1721
+ this._markerLabelTimer = setTimeout(() => {
1722
+ this.markersContainer?.querySelectorAll(".waveform-marker").forEach((el) => el.classList.remove("show-label"));
1723
+ }, 2500);
1724
+ }
1655
1725
  }
1656
1726
  }
1657
1727
  /**
@@ -1669,21 +1739,78 @@ var WaveformPlayer = class _WaveformPlayer {
1669
1739
  this.seekEl.appendChild(tip);
1670
1740
  this.hoverTimeEl = tip;
1671
1741
  this.seekEl.addEventListener("pointermove", (e) => {
1672
- const dur = this.getSeekDuration();
1673
- if (!dur) {
1674
- tip.style.opacity = "0";
1675
- return;
1676
- }
1677
- const rect = this.canvas.getBoundingClientRect();
1678
- const pct = clamp((e.clientX - rect.left) / rect.width);
1679
- tip.textContent = formatTime(pct * dur);
1680
- tip.style.left = pct * 100 + "%";
1681
- tip.style.opacity = "1";
1742
+ if (!this._dragging) this._updateHoverTip(e.clientX);
1682
1743
  });
1683
1744
  this.seekEl.addEventListener("pointerleave", () => {
1684
- tip.style.opacity = "0";
1745
+ if (!this._dragging) this._hideHoverTip();
1685
1746
  });
1686
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
+ }
1687
1814
  // ============================================
1688
1815
  // Event Handlers
1689
1816
  // ============================================
@@ -1700,9 +1827,23 @@ var WaveformPlayer = class _WaveformPlayer {
1700
1827
  * @fires WaveformPlayer#waveformplayer:request-seek
1701
1828
  */
1702
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) {
1703
1844
  const rect = this.canvas.getBoundingClientRect();
1704
- const x = event.clientX - rect.left;
1705
- const targetPercent = clamp(x / rect.width);
1845
+ if (!rect.width) return;
1846
+ const targetPercent = clamp((clientX - rect.left) / rect.width);
1706
1847
  if (this.options.audioMode === "external") {
1707
1848
  this._requestSeek(targetPercent);
1708
1849
  return;
@@ -1884,10 +2025,12 @@ var WaveformPlayer = class _WaveformPlayer {
1884
2025
  */
1885
2026
  updateProgress() {
1886
2027
  if (!this.audio || !this.audio.duration) return;
2028
+ if (this._dragging) return;
1887
2029
  const newProgress = this.audio.currentTime / this.audio.duration;
1888
2030
  if (Math.abs(newProgress - this.progress) > 1e-3) {
1889
2031
  this.progress = newProgress;
1890
2032
  this.drawWaveform();
2033
+ this._updateSeekHandle();
1891
2034
  }
1892
2035
  if (this.currentTimeEl) {
1893
2036
  this.currentTimeEl.textContent = formatTime(this.audio.currentTime);
@@ -2230,6 +2373,7 @@ var WaveformPlayer = class _WaveformPlayer {
2230
2373
  this._emit("waveformplayer:destroy", { player: this, url: this.options.url });
2231
2374
  this.pause();
2232
2375
  this.stopSmoothUpdate();
2376
+ clearTimeout(this._markerLabelTimer);
2233
2377
  this._ac?.abort();
2234
2378
  if (this.resizeObserver) {
2235
2379
  this.resizeObserver.disconnect();
@@ -2298,7 +2442,7 @@ var WaveformPlayer = class _WaveformPlayer {
2298
2442
  * @param {number} samples - Number of samples
2299
2443
  * @returns {Promise<number[]>} Waveform peak data
2300
2444
  */
2301
- static async generateWaveformData(url, samples = 200) {
2445
+ static async generateWaveformData(url, samples = DEFAULT_SAMPLES) {
2302
2446
  try {
2303
2447
  const result = await generateWaveform(url, samples);
2304
2448
  return result.peaks;