@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.
@@ -1,5 +1,13 @@
1
1
  (() => {
2
2
  // src/js/utils.js
3
+ var DEFAULT_SAMPLES = 1800;
4
+ function maxOf(values) {
5
+ let max = -Infinity;
6
+ for (let i = 0; i < values.length; i++) {
7
+ if (values[i] > max) max = values[i];
8
+ }
9
+ return max;
10
+ }
3
11
  function escapeHtml(str) {
4
12
  return String(str == null ? "" : str).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
5
13
  }
@@ -82,6 +90,7 @@
82
90
  setBool("showInfo");
83
91
  setBool("showTime");
84
92
  setBool("showHoverTime");
93
+ setBool("seekHandle");
85
94
  setBool("showBPM", "showBpm");
86
95
  setNum("bpm");
87
96
  setBool("singlePlay");
@@ -426,33 +435,19 @@
426
435
  const centerY = height / 2;
427
436
  const barHeight = 4;
428
437
  const borderRadius = barHeight / 2;
438
+ const active = !!options.seekActive;
429
439
  ctx.clearRect(0, 0, width, height);
430
440
  ctx.fillStyle = options.color || "rgba(255, 255, 255, 0.2)";
431
441
  capsulePath(ctx, borderRadius, width, centerY, barHeight);
432
442
  ctx.fill();
433
443
  if (progress > 0) {
434
444
  const progressWidth = Math.max(borderRadius * 2, progress * width);
435
- ctx.shadowBlur = 8;
436
- ctx.shadowColor = options.progressColor;
445
+ ctx.save();
446
+ ctx.globalAlpha = options.seekHandle && !active ? 0.7 : 1;
437
447
  ctx.fillStyle = options.progressColor || "rgba(255, 255, 255, 0.9)";
438
448
  capsulePath(ctx, borderRadius, progressWidth, centerY, barHeight);
439
449
  ctx.fill();
440
- ctx.shadowBlur = 0;
441
- const handleRadius = 8;
442
- const handleX = progressWidth;
443
- ctx.shadowBlur = 4;
444
- ctx.shadowColor = "rgba(0, 0, 0, 0.3)";
445
- ctx.shadowOffsetY = 2;
446
- ctx.fillStyle = "#ffffff";
447
- ctx.beginPath();
448
- ctx.arc(handleX, centerY, handleRadius, 0, Math.PI * 2);
449
- ctx.fill();
450
- ctx.shadowBlur = 0;
451
- ctx.shadowOffsetY = 0;
452
- ctx.fillStyle = options.progressColor || "rgba(255, 255, 255, 0.9)";
453
- ctx.beginPath();
454
- ctx.arc(handleX, centerY, handleRadius * 0.4, 0, Math.PI * 2);
455
- ctx.fill();
450
+ ctx.restore();
456
451
  }
457
452
  }
458
453
  var DRAWING_STYLES = {
@@ -541,7 +536,7 @@
541
536
  }
542
537
 
543
538
  // src/js/audio.js
544
- function extractPeaks(buffer, samples = 200) {
539
+ function extractPeaks(buffer, samples = DEFAULT_SAMPLES) {
545
540
  const sampleSize = buffer.length / samples;
546
541
  const channels = buffer.numberOfChannels;
547
542
  const peaks = [];
@@ -563,10 +558,10 @@
563
558
  }
564
559
  }
565
560
  }
566
- const maxPeak = Math.max(...peaks);
561
+ const maxPeak = maxOf(peaks);
567
562
  return maxPeak > 0 ? peaks.map((peak) => peak / maxPeak) : peaks;
568
563
  }
569
- async function generateWaveform(url, samples = 200, shouldDetectBPM = false) {
564
+ async function generateWaveform(url, samples = DEFAULT_SAMPLES, shouldDetectBPM = false) {
570
565
  let audioContext;
571
566
  try {
572
567
  const AudioCtx = window.AudioContext || /** @type {any} */
@@ -586,7 +581,7 @@
586
581
  if (audioContext) audioContext.close();
587
582
  }
588
583
  }
589
- function generatePlaceholderWaveform(samples = 200) {
584
+ function generatePlaceholderWaveform(samples = DEFAULT_SAMPLES) {
590
585
  const data = [];
591
586
  for (let i = 0; i < samples; i++) {
592
587
  const base = Math.random() * 0.5 + 0.3;
@@ -596,7 +591,7 @@
596
591
  return data;
597
592
  }
598
593
  function normalizePeaks(peaks, targetMax = 0.95) {
599
- const maxPeak = Math.max(...peaks);
594
+ const maxPeak = maxOf(peaks);
600
595
  if (maxPeak === 0 || maxPeak > targetMax) return peaks;
601
596
  const scaleFactor = targetMax / maxPeak;
602
597
  return peaks.map((peak) => peak * scaleFactor);
@@ -668,7 +663,7 @@
668
663
  // bars, so this is fidelity headroom, not the visible bar count. 1800 (the
669
664
  // SoundCloud/WaveformGen figure) keeps wide / high-DPI waveforms crisp; the
670
665
  // every-frame scan means a higher value costs no extra extraction time.
671
- samples: 1800,
666
+ samples: DEFAULT_SAMPLES,
672
667
  preload: "metadata",
673
668
  // Audio mode — 'self' = player owns the <audio> element (default, current
674
669
  // behavior). 'external' = player is a visualization-only surface; no audio
@@ -719,6 +714,11 @@
719
714
  showInfo: true,
720
715
  showTime: true,
721
716
  showHoverTime: false,
717
+ // Show a draggable circle handle + hover brightness-lift on the SEEKBAR
718
+ // style only (it's meaningless on a waveform, where the fill-edge is the
719
+ // playhead). Off by default; the bar turns it on. Drag-to-scrub works
720
+ // regardless of this.
721
+ seekHandle: false,
722
722
  showBPM: false,
723
723
  // Known BPM to display in the badge (with showBPM). Wins over auto-detection
724
724
  // — set it when peaks are pre-generated so the tempo still shows. null = auto.
@@ -768,6 +768,7 @@
768
768
  );
769
769
  var SEEK_STEP_SECONDS = 5;
770
770
  var SEEK_PAGE_SECONDS = 10;
771
+ var INTERACTIVE_ELEMENTS = 'button, a[href], input, [role="slider"]';
771
772
  var WaveformPlayer = class _WaveformPlayer {
772
773
  /** @type {Map<string, WaveformPlayer>} */
773
774
  static instances = /* @__PURE__ */ new Map();
@@ -824,6 +825,7 @@
824
825
  this.waveformData = [];
825
826
  this.progress = 0;
826
827
  this._activeMarkerIndex = -1;
828
+ this._markerLabelTimer = null;
827
829
  this.isPlaying = false;
828
830
  this.isLoading = false;
829
831
  this.hasError = false;
@@ -962,7 +964,7 @@
962
964
  ` : ""}
963
965
  ${this.options.showPlaybackSpeed ? `
964
966
  <div class="waveform-speed">
965
- <button class="speed-btn" aria-label="Playback speed">
967
+ <button class="speed-btn" aria-label="Playback speed" aria-haspopup="true" aria-expanded="false">
966
968
  <span class="speed-value">1x</span>
967
969
  </button>
968
970
  <div class="speed-menu" style="display: none;">
@@ -1061,8 +1063,9 @@
1061
1063
  }
1062
1064
  /**
1063
1065
  * Wire up the playback-speed menu: toggle it open on the speed button,
1064
- * close it on any outside click, and apply the chosen rate when a
1065
- * `.speed-option` is clicked. All listeners are registered against the
1066
+ * close it on outside click or Escape (keeping `aria-expanded` on the
1067
+ * trigger in sync), and apply the chosen rate when a `.speed-option` is
1068
+ * clicked, returning focus to the trigger. All listeners are registered against the
1066
1069
  * instance `AbortController` signal so {@link WaveformPlayer#destroy} tears
1067
1070
  * them down. No-op if the speed elements are absent.
1068
1071
  * @private
@@ -1071,19 +1074,27 @@
1071
1074
  const speedBtn = this.container.querySelector(".speed-btn");
1072
1075
  const speedMenu = this.container.querySelector(".speed-menu");
1073
1076
  if (!speedBtn || !speedMenu) return;
1077
+ const setSpeedMenu = (open) => {
1078
+ speedMenu.style.display = open ? "block" : "none";
1079
+ speedBtn.setAttribute("aria-expanded", open ? "true" : "false");
1080
+ };
1074
1081
  speedBtn.addEventListener("click", (e) => {
1075
1082
  e.stopPropagation();
1076
- speedMenu.style.display = speedMenu.style.display === "none" ? "block" : "none";
1077
- }, { signal: this._ac.signal });
1078
- document.addEventListener("click", () => {
1079
- speedMenu.style.display = "none";
1083
+ setSpeedMenu(speedMenu.style.display === "none");
1080
1084
  }, { signal: this._ac.signal });
1085
+ document.addEventListener("click", () => setSpeedMenu(false), { signal: this._ac.signal });
1081
1086
  speedMenu.addEventListener("click", (e) => {
1082
1087
  e.stopPropagation();
1083
1088
  if (e.target.classList.contains("speed-option")) {
1084
- const rate = parseFloat(e.target.dataset.rate);
1085
- this.setPlaybackRate(rate);
1086
- speedMenu.style.display = "none";
1089
+ this.setPlaybackRate(parseFloat(e.target.dataset.rate));
1090
+ setSpeedMenu(false);
1091
+ speedBtn.focus();
1092
+ }
1093
+ }, { signal: this._ac.signal });
1094
+ speedBtn.closest(".waveform-speed")?.addEventListener("keydown", (e) => {
1095
+ if (e.key === "Escape" && speedMenu.style.display !== "none") {
1096
+ setSpeedMenu(false);
1097
+ speedBtn.focus();
1087
1098
  }
1088
1099
  }, { signal: this._ac.signal });
1089
1100
  this.updateSpeedUI();
@@ -1101,7 +1112,8 @@
1101
1112
  */
1102
1113
  initKeyboardControls() {
1103
1114
  this.container.setAttribute("tabindex", "-1");
1104
- this.container.addEventListener("click", () => {
1115
+ this.container.addEventListener("click", (e) => {
1116
+ if (e.target.closest(INTERACTIVE_ELEMENTS)) return;
1105
1117
  _WaveformPlayer.getAllInstances().forEach((player) => {
1106
1118
  if (player !== this) {
1107
1119
  player.container.setAttribute("tabindex", "-1");
@@ -1313,7 +1325,56 @@
1313
1325
  this.audio.addEventListener("error", (e) => this.onError(e));
1314
1326
  }
1315
1327
  this.canvas.addEventListener("click", (e) => this.handleCanvasClick(e));
1328
+ this._dragging = false;
1329
+ this._seekHover = false;
1330
+ this._handleNear = false;
1331
+ this.canvas.addEventListener("pointerenter", () => {
1332
+ this._seekHover = true;
1333
+ this.drawWaveform();
1334
+ this._updateSeekHandle();
1335
+ });
1336
+ this.canvas.addEventListener("pointerleave", () => {
1337
+ this._seekHover = false;
1338
+ this._handleNear = false;
1339
+ if (!this._dragging) this._hideHoverTip();
1340
+ this.drawWaveform();
1341
+ this._updateSeekHandle();
1342
+ });
1343
+ this.canvas.addEventListener("pointerdown", (e) => {
1344
+ if (e.pointerType === "mouse" && e.button !== 0) return;
1345
+ this._dragging = true;
1346
+ try {
1347
+ this.canvas.setPointerCapture(e.pointerId);
1348
+ } catch (err) {
1349
+ }
1350
+ this._scrubTo(e.clientX);
1351
+ });
1352
+ this.canvas.addEventListener("pointermove", (e) => {
1353
+ if (this._dragging) {
1354
+ this._scrubTo(e.clientX);
1355
+ return;
1356
+ }
1357
+ const rect = this.canvas.getBoundingClientRect();
1358
+ if (rect.width) {
1359
+ this._handleNear = Math.abs(e.clientX - rect.left - this.progress * rect.width) <= 10;
1360
+ this._updateSeekHandle();
1361
+ }
1362
+ });
1363
+ const endDrag = (e) => {
1364
+ if (!this._dragging) return;
1365
+ this._dragging = false;
1366
+ try {
1367
+ this.canvas.releasePointerCapture(e.pointerId);
1368
+ } catch (err) {
1369
+ }
1370
+ this._seekFromPointer(e.clientX);
1371
+ if (!this._seekHover) this._hideHoverTip();
1372
+ this._updateSeekHandle();
1373
+ };
1374
+ this.canvas.addEventListener("pointerup", endDrag);
1375
+ this.canvas.addEventListener("pointercancel", endDrag);
1316
1376
  this.setupHoverTime();
1377
+ this.setupSeekHandle();
1317
1378
  this.resizeHandler = debounce(() => this.resizeCanvas(), 100);
1318
1379
  window.addEventListener("resize", this.resizeHandler);
1319
1380
  }
@@ -1522,7 +1583,8 @@
1522
1583
  ...this.options,
1523
1584
  waveformStyle: this.options.waveformStyle || "bars",
1524
1585
  color: this.options.waveformColor,
1525
- progressColor: this.options.progressColor
1586
+ progressColor: this.options.progressColor,
1587
+ seekActive: this._seekHover || this._dragging
1526
1588
  });
1527
1589
  }
1528
1590
  /**
@@ -1558,6 +1620,7 @@
1558
1620
  if (!this.markersContainer) return;
1559
1621
  this.markersContainer.innerHTML = "";
1560
1622
  this._activeMarkerIndex = -1;
1623
+ clearTimeout(this._markerLabelTimer);
1561
1624
  if (!this.options.showMarkers || !this.options.markers?.length) return;
1562
1625
  const duration = this.getSeekDuration();
1563
1626
  if (!duration) {
@@ -1627,6 +1690,13 @@
1627
1690
  if (active !== this._activeMarkerIndex) {
1628
1691
  this._activeMarkerIndex = active;
1629
1692
  this.setActiveMarker(active);
1693
+ clearTimeout(this._markerLabelTimer);
1694
+ els.forEach((el, i) => el.classList.toggle("show-label", i === active));
1695
+ if (active >= 0) {
1696
+ this._markerLabelTimer = setTimeout(() => {
1697
+ this.markersContainer?.querySelectorAll(".waveform-marker").forEach((el) => el.classList.remove("show-label"));
1698
+ }, 2500);
1699
+ }
1630
1700
  }
1631
1701
  }
1632
1702
  /**
@@ -1644,21 +1714,78 @@
1644
1714
  this.seekEl.appendChild(tip);
1645
1715
  this.hoverTimeEl = tip;
1646
1716
  this.seekEl.addEventListener("pointermove", (e) => {
1647
- const dur = this.getSeekDuration();
1648
- if (!dur) {
1649
- tip.style.opacity = "0";
1650
- return;
1651
- }
1652
- const rect = this.canvas.getBoundingClientRect();
1653
- const pct = clamp((e.clientX - rect.left) / rect.width);
1654
- tip.textContent = formatTime(pct * dur);
1655
- tip.style.left = pct * 100 + "%";
1656
- tip.style.opacity = "1";
1717
+ if (!this._dragging) this._updateHoverTip(e.clientX);
1657
1718
  });
1658
1719
  this.seekEl.addEventListener("pointerleave", () => {
1659
- tip.style.opacity = "0";
1720
+ if (!this._dragging) this._hideHoverTip();
1660
1721
  });
1661
1722
  }
1723
+ /**
1724
+ * Position + fill the hover-time tooltip for a given client-X. Shared by
1725
+ * hover and drag-scrub. No-op when the tooltip isn't enabled
1726
+ * (`showHoverTime` off).
1727
+ * @param {number} clientX - Pointer client-X coordinate.
1728
+ * @private
1729
+ */
1730
+ _updateHoverTip(clientX) {
1731
+ const tip = this.hoverTimeEl;
1732
+ if (!tip) return;
1733
+ const dur = this.getSeekDuration();
1734
+ if (!dur) {
1735
+ tip.style.opacity = "0";
1736
+ return;
1737
+ }
1738
+ const rect = this.canvas.getBoundingClientRect();
1739
+ const pct = clamp((clientX - rect.left) / rect.width);
1740
+ tip.textContent = formatTime(pct * dur);
1741
+ tip.style.left = pct * 100 + "%";
1742
+ tip.style.opacity = "1";
1743
+ }
1744
+ /** Hide the hover-time tooltip. @private */
1745
+ _hideHoverTip() {
1746
+ if (this.hoverTimeEl) this.hoverTimeEl.style.opacity = "0";
1747
+ }
1748
+ /**
1749
+ * Visually preview a seek during a drag — moves the playhead + handle +
1750
+ * tooltip to the cursor WITHOUT touching the audio (playback continues; the
1751
+ * real seek is committed on release).
1752
+ * @param {number} clientX - Pointer client-X coordinate.
1753
+ * @private
1754
+ */
1755
+ _scrubTo(clientX) {
1756
+ const rect = this.canvas.getBoundingClientRect();
1757
+ if (!rect.width) return;
1758
+ this.progress = clamp((clientX - rect.left) / rect.width);
1759
+ this.drawWaveform();
1760
+ this._updateSeekHandle();
1761
+ this._updateHoverTip(clientX);
1762
+ }
1763
+ /**
1764
+ * Create the draggable seek handle — a DOM circle over the playhead, shown
1765
+ * only on hover / drag (Spotify-style). Pointer-events are off so it never
1766
+ * blocks the canvas scrub; size + visibility are CSS.
1767
+ * @private
1768
+ */
1769
+ setupSeekHandle() {
1770
+ if (!this.options.seekHandle || this.options.waveformStyle !== "seekbar" || !this.seekEl) return;
1771
+ const h = document.createElement("div");
1772
+ h.className = "waveform-seek-handle";
1773
+ h.setAttribute("aria-hidden", "true");
1774
+ this.seekEl.appendChild(h);
1775
+ this.seekHandleEl = h;
1776
+ }
1777
+ /**
1778
+ * Position the seek handle at the current progress and toggle its
1779
+ * visibility (hover / drag) + expanded (drag / direct-hover) classes.
1780
+ * @private
1781
+ */
1782
+ _updateSeekHandle() {
1783
+ const h = this.seekHandleEl;
1784
+ if (!h) return;
1785
+ h.style.left = this.progress * 100 + "%";
1786
+ h.classList.toggle("is-visible", this._seekHover || this._dragging);
1787
+ h.classList.toggle("is-active", this._dragging || this._handleNear);
1788
+ }
1662
1789
  // ============================================
1663
1790
  // Event Handlers
1664
1791
  // ============================================
@@ -1675,9 +1802,23 @@
1675
1802
  * @fires WaveformPlayer#waveformplayer:request-seek
1676
1803
  */
1677
1804
  handleCanvasClick(event) {
1805
+ this._seekFromPointer(event.clientX);
1806
+ }
1807
+ /**
1808
+ * Seek to a horizontal client-X position over the canvas — shared by
1809
+ * click and drag. In external mode the player has no audio of its own,
1810
+ * so it dispatches a cancelable `waveformplayer:request-seek` with the
1811
+ * target percentage (updating the local visual optimistically); in self
1812
+ * mode it seeks the owned `<audio>` via
1813
+ * {@link WaveformPlayer#seekToPercent}.
1814
+ * @param {number} clientX - Pointer client-X coordinate.
1815
+ * @private
1816
+ * @fires WaveformPlayer#waveformplayer:request-seek
1817
+ */
1818
+ _seekFromPointer(clientX) {
1678
1819
  const rect = this.canvas.getBoundingClientRect();
1679
- const x = event.clientX - rect.left;
1680
- const targetPercent = clamp(x / rect.width);
1820
+ if (!rect.width) return;
1821
+ const targetPercent = clamp((clientX - rect.left) / rect.width);
1681
1822
  if (this.options.audioMode === "external") {
1682
1823
  this._requestSeek(targetPercent);
1683
1824
  return;
@@ -1859,10 +2000,12 @@
1859
2000
  */
1860
2001
  updateProgress() {
1861
2002
  if (!this.audio || !this.audio.duration) return;
2003
+ if (this._dragging) return;
1862
2004
  const newProgress = this.audio.currentTime / this.audio.duration;
1863
2005
  if (Math.abs(newProgress - this.progress) > 1e-3) {
1864
2006
  this.progress = newProgress;
1865
2007
  this.drawWaveform();
2008
+ this._updateSeekHandle();
1866
2009
  }
1867
2010
  if (this.currentTimeEl) {
1868
2011
  this.currentTimeEl.textContent = formatTime(this.audio.currentTime);
@@ -2205,6 +2348,7 @@
2205
2348
  this._emit("waveformplayer:destroy", { player: this, url: this.options.url });
2206
2349
  this.pause();
2207
2350
  this.stopSmoothUpdate();
2351
+ clearTimeout(this._markerLabelTimer);
2208
2352
  this._ac?.abort();
2209
2353
  if (this.resizeObserver) {
2210
2354
  this.resizeObserver.disconnect();
@@ -2273,7 +2417,7 @@
2273
2417
  * @param {number} samples - Number of samples
2274
2418
  * @returns {Promise<number[]>} Waveform peak data
2275
2419
  */
2276
- static async generateWaveformData(url, samples = 200) {
2420
+ static async generateWaveformData(url, samples = DEFAULT_SAMPLES) {
2277
2421
  try {
2278
2422
  const result = await generateWaveform(url, samples);
2279
2423
  return result.peaks;