@arraypress/waveform-player 1.28.1 → 1.29.1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arraypress/waveform-player",
3
- "version": "1.28.1",
3
+ "version": "1.29.1",
4
4
  "description": "Lightweight, customizable audio player with waveform visualization",
5
5
  "type": "module",
6
6
  "types": "./index.d.ts",
package/src/js/core.js CHANGED
@@ -18,7 +18,9 @@ import {
18
18
  formatCssLength,
19
19
  toFiniteNumber,
20
20
  toNumberArray,
21
- DEFAULT_SAMPLES
21
+ DEFAULT_SAMPLES,
22
+ inTimeRanges,
23
+ coversDuration,
22
24
  } from './utils.js';
23
25
 
24
26
  import {
@@ -64,6 +66,9 @@ export class WaveformPlayer {
64
66
  /** @type {WaveformPlayer|null} */
65
67
  static currentlyPlaying = null;
66
68
 
69
+ /** Audio URLs already warned about lacking byte-range support. @private */
70
+ static _noRangeWarned = new Set();
71
+
67
72
  /**
68
73
  * Create a new WaveformPlayer instance.
69
74
  *
@@ -185,6 +190,7 @@ export class WaveformPlayer {
185
190
  this.init();
186
191
  } catch (error) {
187
192
  WaveformPlayer.instances.delete(this.id);
193
+ WaveformPlayer._releaseThemeWatch();
188
194
  this._ac.abort();
189
195
  throw error;
190
196
  }
@@ -716,9 +722,10 @@ export class WaveformPlayer {
716
722
  // trigger opens and focuses the first/checked option.
717
723
  speedBtn.closest('.waveform-speed')?.addEventListener('keydown', (e) => {
718
724
  const opts = options();
719
- const i = opts.indexOf(document.activeElement);
725
+ const focused = this._activeElement();
726
+ const i = opts.indexOf(focused);
720
727
  if (!isOpen()) {
721
- if ((e.key === 'ArrowDown' || e.key === 'ArrowUp') && document.activeElement === speedBtn) {
728
+ if ((e.key === 'ArrowDown' || e.key === 'ArrowUp') && focused === speedBtn) {
722
729
  e.preventDefault();
723
730
  setSpeedMenu(true);
724
731
  }
@@ -749,6 +756,18 @@ export class WaveformPlayer {
749
756
  * ±0.1) and `m`/`M` (mute). Listeners use the instance abort signal.
750
757
  * @private
751
758
  */
759
+ /**
760
+ * The focused element as seen from this player's own tree. Inside a shadow
761
+ * root `document.activeElement` is the shadow *host*, so comparing it with
762
+ * the container (or a control) never matches and every keyboard shortcut
763
+ * silently stops; the root node's `activeElement` is the real one.
764
+ * @returns {Element|null}
765
+ * @private
766
+ */
767
+ _activeElement() {
768
+ return this.container.getRootNode().activeElement ?? document.activeElement;
769
+ }
770
+
752
771
  initKeyboardControls() {
753
772
  // Make container focusable but not in tab order by default
754
773
  this.container.setAttribute('tabindex', '-1');
@@ -775,7 +794,7 @@ export class WaveformPlayer {
775
794
  // owns those). Space (togglePlay) still works because togglePlay
776
795
  // routes through the request-play/pause events.
777
796
  this.container.addEventListener('keydown', (e) => {
778
- if (document.activeElement !== this.container) return;
797
+ if (this._activeElement() !== this.container) return;
779
798
 
780
799
  const key = e.key;
781
800
  const hasAudio = !!this.audio;
@@ -1108,7 +1127,8 @@ export class WaveformPlayer {
1108
1127
  this.audio.addEventListener('seeked', () => this._updatePositionState());
1109
1128
  this.audio.addEventListener('ratechange', () => this._updatePositionState());
1110
1129
  this.audio.addEventListener('timeupdate', () => {
1111
- if (this.isPlaying && Date.now() - this._frameAt > 500) this.updateProgress();
1130
+ // Not mid cache-reload: currentTime reads 0 until the seek lands.
1131
+ if (this.isPlaying && !this._seekReload && Date.now() - this._frameAt > 500) this.updateProgress();
1112
1132
  });
1113
1133
  }
1114
1134
 
@@ -1324,7 +1344,9 @@ export class WaveformPlayer {
1324
1344
  try {
1325
1345
  const result = await generateWaveform(url, this.options.samples, this.options.showBPM);
1326
1346
  if (id !== this._loadId) return;
1327
- this.waveformData = result.peaks;
1347
+ // Peaks the caller supplied while we decoded (setWaveformData)
1348
+ // describe this track too, and were asked for explicitly.
1349
+ if (this.options.waveform === inlinePeaks) this.waveformData = result.peaks;
1328
1350
 
1329
1351
  // Store BPM if detected
1330
1352
  if (result.bpm) {
@@ -1333,9 +1355,11 @@ export class WaveformPlayer {
1333
1355
  }
1334
1356
  } catch (error) {
1335
1357
  if (id !== this._loadId) return;
1336
- console.warn('[WaveformPlayer] Using placeholder waveform:', error);
1337
- this.waveformData = generatePlaceholderWaveform(this.options.samples);
1338
- this.container.classList.add('waveform-is-placeholder');
1358
+ if (this.options.waveform === inlinePeaks) {
1359
+ console.warn('[WaveformPlayer] Using placeholder waveform:', error);
1360
+ this.waveformData = generatePlaceholderWaveform(this.options.samples);
1361
+ this.container.classList.add('waveform-is-placeholder');
1362
+ }
1339
1363
  }
1340
1364
  }
1341
1365
 
@@ -1370,6 +1394,9 @@ export class WaveformPlayer {
1370
1394
  * @private
1371
1395
  */
1372
1396
  _resetTrack() {
1397
+ // A seek waiting on / reloading the previous file no longer applies.
1398
+ this._cancelCacheSeek?.();
1399
+ this._seekReload = null;
1373
1400
  this.progress = 0;
1374
1401
  this.waveformData = [];
1375
1402
  this._extDuration = 0;
@@ -1537,6 +1564,13 @@ export class WaveformPlayer {
1537
1564
  * carries no peaks resolves `false` and leaves the canvas as it was —
1538
1565
  * {@link WaveformPlayer#load} then decodes the audio instead. One that
1539
1566
  * resolves after a newer load has started is discarded.
1567
+ *
1568
+ * The data also becomes the current track's `waveform` option, so it
1569
+ * outlives the load already in flight: the first load() runs a frame after
1570
+ * construction (see init()) and draws `options.waveform`, which used to
1571
+ * paint over peaks set before that frame — an easy race to lose with a
1572
+ * cached or fast fetch. A later reload of the same track reuses them too.
1573
+ * {@link WaveformPlayer#loadTrack} still replaces them for a new track.
1540
1574
  * @param {string|number[]} data - Peaks as an array, a JSON/CSV string, or
1541
1575
  * a URL to a `.json` peaks file.
1542
1576
  * @returns {Promise<boolean>|undefined} For a `.json` URL, a promise of
@@ -1544,6 +1578,8 @@ export class WaveformPlayer {
1544
1578
  * synchronously).
1545
1579
  */
1546
1580
  setWaveformData(data) {
1581
+ this.options.waveform = data;
1582
+
1547
1583
  // URL to JSON file — fetch peaks and maybe markers / bpm
1548
1584
  if (typeof data === 'string' && /\.json(?:[?#]|$)/i.test(data.trim())) {
1549
1585
  const id = this._loadId;
@@ -1557,6 +1593,7 @@ export class WaveformPlayer {
1557
1593
  const peaks = toNumberArray(Array.isArray(json) ? json : json?.peaks, {fallback: []});
1558
1594
  if (!peaks.length) throw new Error('no peaks');
1559
1595
  this.waveformData = peaks;
1596
+ this.container.classList.remove('waveform-is-placeholder');
1560
1597
  // A peaks sidecar is a third source of markers, and a remote
1561
1598
  // one — normalize it on the same terms as the option paths.
1562
1599
  if (json.markers && !this.options.markers?.length) {
@@ -1583,6 +1620,7 @@ export class WaveformPlayer {
1583
1620
  // also drops non-numeric members (the old comma path mapped them to
1584
1621
  // NaN, and a NaN peak draws as a gap rather than an error).
1585
1622
  this.waveformData = toNumberArray(data, {fallback: []});
1623
+ this.container.classList.remove('waveform-is-placeholder');
1586
1624
  this.drawWaveform();
1587
1625
  }
1588
1626
 
@@ -1976,8 +2014,9 @@ export class WaveformPlayer {
1976
2014
  * @fires WaveformPlayer#waveformplayer:play
1977
2015
  */
1978
2016
  onPlay() {
1979
- // Ignore during destruction
1980
- if (this.isDestroying) return;
2017
+ // Ignore during destruction, and during a seek's cache reload (an
2018
+ // internal pause/play pair consumers shouldn't see; see _reloadForSeek).
2019
+ if (this.isDestroying || this._seekReload) return;
1981
2020
 
1982
2021
  this.isPlaying = true;
1983
2022
 
@@ -2006,8 +2045,8 @@ export class WaveformPlayer {
2006
2045
  * @fires WaveformPlayer#waveformplayer:pause
2007
2046
  */
2008
2047
  onPause() {
2009
- // Ignore during destruction
2010
- if (this.isDestroying) return;
2048
+ // Ignore during destruction, and during a seek's cache reload.
2049
+ if (this.isDestroying || this._seekReload) return;
2011
2050
 
2012
2051
  this.isPlaying = false;
2013
2052
 
@@ -2248,6 +2287,24 @@ export class WaveformPlayer {
2248
2287
  WaveformPlayer._themeWatch = {obs, mq, refresh};
2249
2288
  }
2250
2289
 
2290
+ /**
2291
+ * Disconnect the shared theme watcher once no player is registered. The
2292
+ * watcher only ever refreshes registered instances, so with none left it
2293
+ * has nothing to do; the next constructor re-installs it lazily via
2294
+ * {@link WaveformPlayer._watchTheme}. Pages that swap players in and out
2295
+ * (SPAs, block editors) no longer keep a document observer alive forever.
2296
+ * @private
2297
+ */
2298
+ static _releaseThemeWatch() {
2299
+ const watch = WaveformPlayer._themeWatch;
2300
+ if (!watch || WaveformPlayer.instances.size > 0) return;
2301
+ watch.obs.disconnect();
2302
+ try {
2303
+ watch.mq?.removeEventListener('change', watch.refresh);
2304
+ } catch (e) { /* no matchMedia listeners */ }
2305
+ WaveformPlayer._themeWatch = null;
2306
+ }
2307
+
2251
2308
  /**
2252
2309
  * Sync the speed control's label and the menu's active-option highlight to
2253
2310
  * the audio element's current `playbackRate`. No-op in external mode (no
@@ -2465,6 +2522,126 @@ export class WaveformPlayer {
2465
2522
  }
2466
2523
  }
2467
2524
 
2525
+ /**
2526
+ * Move the owned `<audio>` to `time`. The single path every self-mode seek
2527
+ * takes ({@link WaveformPlayer#seekTo}, {@link WaveformPlayer#seekToPercent},
2528
+ * so clicks, drags, keys and the slider too).
2529
+ *
2530
+ * Some hosts ignore HTTP byte ranges: they answer a `Range` request with
2531
+ * `200` and the whole file (Cloudflare Pages and Workers static assets, and
2532
+ * plenty of plain servers). Chromium then can't seek the media at all —
2533
+ * `seekable` stays `0–0` even once every byte has arrived — which is the
2534
+ * "long tracks snap back to 0" symptom. The copy in the browser's HTTP
2535
+ * cache *is* seekable (why a page refresh "fixes" it), so when the target
2536
+ * isn't seekable this reloads the element from cache and seeks there; see
2537
+ * {@link WaveformPlayer#_seekViaCache}. Detection is by the element's own
2538
+ * `seekable`, not the browser, so engines that can already seek (WebKit,
2539
+ * Firefox) never take that path; it runs at most once per file.
2540
+ * @param {number} time - Target position in seconds.
2541
+ * @private
2542
+ */
2543
+ _seekAudio(time) {
2544
+ const audio = this.audio;
2545
+ // Only divert when the element positively reports ranges that exclude
2546
+ // the target (Chromium's `0–0` on these hosts). No ranges at all means
2547
+ // "unknown" (no metadata yet, some engines, test DOMs): seek as always.
2548
+ const seekable = audio.seekable;
2549
+ if (!Number.isFinite(audio.duration)
2550
+ || !seekable || seekable.length === 0
2551
+ || inTimeRanges(seekable, time)
2552
+ || this._seekReloadedUrl === this.options.url) {
2553
+ audio.currentTime = time;
2554
+ return;
2555
+ }
2556
+ this._seekViaCache(time);
2557
+ }
2558
+
2559
+ /**
2560
+ * Seek on a host without byte-range support: once the whole file is
2561
+ * downloaded (raising `preload` to `auto` until it is, then restoring it),
2562
+ * reload the element from the browser cache and seek there. Repeated seeks
2563
+ * while waiting just update the target. Warns once per URL, since the
2564
+ * real fix is serving audio from a range-capable host.
2565
+ * @param {number} time - Target position in seconds.
2566
+ * @private
2567
+ */
2568
+ _seekViaCache(time) {
2569
+ const audio = this.audio;
2570
+ const url = this.options.url;
2571
+ this._cacheSeekTime = time;
2572
+
2573
+ if (!WaveformPlayer._noRangeWarned.has(url)) {
2574
+ WaveformPlayer._noRangeWarned.add(url);
2575
+ console.warn(`[WaveformPlayer] ${url}: the host ignores HTTP Range requests, so seeking waits for the download and reloads from cache. Serve audio with Range support for instant seeks.`);
2576
+ }
2577
+
2578
+ if (this._cancelCacheSeek) return; // Already waiting; the target is updated.
2579
+ if (coversDuration(audio.buffered, audio.duration)) {
2580
+ this._reloadForSeek(url);
2581
+ return;
2582
+ }
2583
+
2584
+ const preload = audio.preload;
2585
+ audio.preload = 'auto';
2586
+ this.setLoading(true);
2587
+ const stop = () => {
2588
+ audio.removeEventListener('progress', check);
2589
+ audio.removeEventListener('canplaythrough', check);
2590
+ audio.preload = preload;
2591
+ this._cancelCacheSeek = null;
2592
+ };
2593
+ const check = () => {
2594
+ if (this.audio !== audio || this.options.url !== url) return stop();
2595
+ if (!coversDuration(audio.buffered, audio.duration)) return;
2596
+ stop();
2597
+ this._reloadForSeek(url);
2598
+ };
2599
+ this._cancelCacheSeek = stop;
2600
+ audio.addEventListener('progress', check, {signal: this._ac.signal});
2601
+ audio.addEventListener('canplaythrough', check, {signal: this._ac.signal});
2602
+ }
2603
+
2604
+ /**
2605
+ * Reload the fully-downloaded file from cache, seek to the pending target
2606
+ * and resume. The element's own pause/play events during the reload are
2607
+ * internal plumbing, so onPause/onPlay ignore them while `_seekReload` is
2608
+ * set: consumers (the bar, waveform-tracker) see a seek, not a pause and a
2609
+ * new play, and the button doesn't flicker.
2610
+ * @param {string} url - The file being reloaded.
2611
+ * @private
2612
+ */
2613
+ _reloadForSeek(url) {
2614
+ const audio = this.audio;
2615
+ const wasPlaying = !audio.paused && !audio.ended;
2616
+ const rate = audio.playbackRate;
2617
+ this._seekReloadedUrl = url;
2618
+ this._seekReload = {wasPlaying};
2619
+
2620
+ const finish = () => {
2621
+ this._seekReload = null;
2622
+ this.setLoading(false);
2623
+ this.updateProgress();
2624
+ };
2625
+ audio.addEventListener('loadedmetadata', () => {
2626
+ if (this.audio !== audio || this.options.url !== url) return;
2627
+ audio.playbackRate = rate; // load() resets it to the default
2628
+ audio.currentTime = this._cacheSeekTime;
2629
+ if (!wasPlaying) {
2630
+ finish();
2631
+ return;
2632
+ }
2633
+ audio.play().then(() => {
2634
+ finish();
2635
+ this.startSmoothUpdate();
2636
+ }, () => {
2637
+ // Playback refused after the reload: show the true state.
2638
+ finish();
2639
+ this.onPause();
2640
+ });
2641
+ }, {once: true, signal: this._ac.signal});
2642
+ audio.load();
2643
+ }
2644
+
2468
2645
  /**
2469
2646
  * Seek the owned `<audio>` element to an absolute time, clamped to
2470
2647
  * `[0, duration]`, and refresh progress. Self mode only — a no-op when
@@ -2477,7 +2654,7 @@ export class WaveformPlayer {
2477
2654
  // Coerce + guard like setVolume(): `audio.currentTime = NaN` throws.
2478
2655
  const s = Number(seconds);
2479
2656
  if (this.audio && this.audio.duration && Number.isFinite(s)) {
2480
- this.audio.currentTime = clamp(s, 0, this.audio.duration);
2657
+ this._seekAudio(clamp(s, 0, this.audio.duration));
2481
2658
  this.updateProgress();
2482
2659
  }
2483
2660
  }
@@ -2491,7 +2668,7 @@ export class WaveformPlayer {
2491
2668
  seekToPercent(percent) {
2492
2669
  const p = Number(percent);
2493
2670
  if (this.audio && this.audio.duration && Number.isFinite(p)) {
2494
- this.audio.currentTime = this.audio.duration * clamp(p);
2671
+ this._seekAudio(this.audio.duration * clamp(p));
2495
2672
  this.updateProgress();
2496
2673
  }
2497
2674
  }
@@ -2580,8 +2757,10 @@ export class WaveformPlayer {
2580
2757
  this.resizeHandler = null;
2581
2758
  }
2582
2759
 
2583
- // Remove from instances map
2760
+ // Remove from instances map (and drop the shared theme watcher if
2761
+ // this was the last player)
2584
2762
  WaveformPlayer.instances.delete(this.id);
2763
+ WaveformPlayer._releaseThemeWatch();
2585
2764
 
2586
2765
  // Clear current playing / Media Session references to this instance
2587
2766
  if (WaveformPlayer.currentlyPlaying === this) {
@@ -2660,6 +2839,7 @@ export class WaveformPlayer {
2660
2839
  static destroyAll() {
2661
2840
  this.instances.forEach(player => player.destroy());
2662
2841
  this.instances.clear();
2842
+ this._releaseThemeWatch();
2663
2843
  }
2664
2844
 
2665
2845
  /**
package/src/js/entry.js CHANGED
@@ -29,6 +29,7 @@ import {
29
29
  isBrowser,
30
30
  } from './utils.js';
31
31
  import {detectColorScheme} from './themes.js';
32
+ import {extractPeaks} from './audio.js';
32
33
 
33
34
  // Expose a small set of pure helpers as a single source of truth so consumers
34
35
  // (e.g. @arraypress/waveform-bar, @arraypress/waveform-playlist) can reuse them
@@ -40,7 +41,10 @@ import {detectColorScheme} from './themes.js';
40
41
  // independently). Attached to the class so it's reachable from the IIFE global
41
42
  // too — which is how the bar reaches it, since it depends on this package as a
42
43
  // runtime peer rather than importing the module.
43
- WaveformPlayer.utils = {formatTime, extractTitleFromUrl, escapeHtml, isSafeHref, parseDataAttributes, detectColorScheme};
44
+ // `extractPeaks` is here so code that decodes audio itself (a worker, a
45
+ // browser extension's offscreen document) draws exactly what the player would,
46
+ // instead of keeping a copy of the algorithm.
47
+ WaveformPlayer.utils = {formatTime, extractTitleFromUrl, escapeHtml, isSafeHref, parseDataAttributes, detectColorScheme, extractPeaks};
44
48
 
45
49
  /**
46
50
  * Construct a player for one declarative element, unless it already has one.
package/src/js/themes.js CHANGED
@@ -47,7 +47,8 @@ function hasThemeHint(scheme) {
47
47
  /**
48
48
  * Collect what the page paints behind `el`.
49
49
  *
50
- * Walks `el` and its ancestors up to `<html>`, alpha-compositing each element's
50
+ * Walks `el` and its ancestors up to `<html>` (through shadow-root hosts),
51
+ * alpha-compositing each element's
51
52
  * background *colour* front-to-back. Walking the chain (rather than reading
52
53
  * `<body>` alone) is what makes real layouts work: plenty of pages paint their
53
54
  * background on a wrapper `<div>` or on `<html>` instead of `<body>`, and a
@@ -72,7 +73,11 @@ function collectBackdrop(el) {
72
73
  let sum = 0;
73
74
  let alpha = 0;
74
75
 
75
- for (let node = el; node && node.nodeType === 1 && alpha < 0.995; node = node.parentElement) {
76
+ // At a shadow root parentElement is null; continue from the shadow host,
77
+ // or a player inside a web component / extension UI stops reading the
78
+ // page at its own boundary and misses the card it sits on.
79
+ const up = (node) => node.parentElement || node.getRootNode?.().host || null;
80
+ for (let node = el; node && node.nodeType === 1 && alpha < 0.995; node = up(node)) {
76
81
  const c = parseColor(getComputedStyle(node).backgroundColor);
77
82
  if (!c || c.a <= 0) continue;
78
83
 
package/src/js/utils.js CHANGED
@@ -680,4 +680,36 @@ export function resampleData(data, targetLength) {
680
680
  }
681
681
 
682
682
  return result;
683
- }
683
+ }
684
+
685
+ /**
686
+ * Whether a time falls inside a `TimeRanges` (e.g. `audio.seekable`), with a
687
+ * little slack for float rounding at the edges.
688
+ *
689
+ * @param {Pick<TimeRanges, 'length'|'start'|'end'>} ranges - The ranges.
690
+ * @param {number} time - Seconds.
691
+ * @returns {boolean}
692
+ */
693
+ export function inTimeRanges(ranges, time) {
694
+ for (let i = 0; i < ranges.length; i++) {
695
+ if (ranges.start(i) - 0.05 <= time && time <= ranges.end(i) + 0.05) return true;
696
+ }
697
+ return false;
698
+ }
699
+
700
+ /**
701
+ * Whether one range of a `TimeRanges` (e.g. `audio.buffered`) spans the whole
702
+ * track: the file is fully downloaded, and so in the browser's HTTP cache.
703
+ *
704
+ * @param {Pick<TimeRanges, 'length'|'start'|'end'>} ranges - The ranges.
705
+ * @param {number} duration - Track length in seconds.
706
+ * @returns {boolean}
707
+ */
708
+ export function coversDuration(ranges, duration) {
709
+ if (!Number.isFinite(duration) || duration <= 0) return false;
710
+ for (let i = 0; i < ranges.length; i++) {
711
+ if (ranges.start(i) <= 0.05 && ranges.end(i) >= duration - 0.1) return true;
712
+ }
713
+ return false;
714
+ }
715
+