@arraypress/waveform-player 1.26.0 → 1.27.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.
@@ -0,0 +1,3042 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/js/entry.js
20
+ var entry_exports = {};
21
+ __export(entry_exports, {
22
+ WaveformPlayer: () => WaveformPlayer,
23
+ default: () => entry_default
24
+ });
25
+ module.exports = __toCommonJS(entry_exports);
26
+
27
+ // src/js/utils.js
28
+ var DEFAULT_SAMPLES = 1800;
29
+ function isBrowser() {
30
+ return typeof window !== "undefined" && typeof document !== "undefined";
31
+ }
32
+ function maxOf(values) {
33
+ let max = -Infinity;
34
+ for (let i = 0; i < values.length; i++) {
35
+ if (values[i] > max) max = values[i];
36
+ }
37
+ return max;
38
+ }
39
+ function escapeHtml(str) {
40
+ return String(str == null ? "" : str).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
41
+ }
42
+ function formatCssLength(value) {
43
+ return escapeHtml(typeof value === "number" ? `${value}px` : value);
44
+ }
45
+ function isSafeHref(url) {
46
+ if (typeof url !== "string" || url === "") return false;
47
+ try {
48
+ const u = new URL(url, "http://localhost/");
49
+ return u.protocol === "http:" || u.protocol === "https:";
50
+ } catch (e) {
51
+ return false;
52
+ }
53
+ }
54
+ function clamp(value, min = 0, max = 1) {
55
+ return Math.max(min, Math.min(value, max));
56
+ }
57
+ function toFiniteNumber(value, fallback = null, opts = {}) {
58
+ const { min = -Infinity, max = Infinity, integer = false } = opts;
59
+ const n = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Number(value) : NaN;
60
+ if (!Number.isFinite(n)) return fallback;
61
+ const bounded = clamp(n, min, max);
62
+ return integer ? Math.round(bounded) : bounded;
63
+ }
64
+ function toArray(value, fallback = null) {
65
+ if (Array.isArray(value)) return value;
66
+ if (typeof value === "string" && value.trim().startsWith("[")) {
67
+ try {
68
+ const parsed = JSON.parse(value);
69
+ if (Array.isArray(parsed)) return parsed;
70
+ } catch (e) {
71
+ }
72
+ }
73
+ return fallback;
74
+ }
75
+ function toNumberArray(value, opts = {}) {
76
+ const { min = -Infinity, max = Infinity, fallback = null } = opts;
77
+ let list = toArray(value);
78
+ if (!list && typeof value === "string" && value.trim() !== "") {
79
+ list = value.split(/[,\s]+/);
80
+ }
81
+ if (!list) return fallback;
82
+ const numbers = list.map((v) => toFiniteNumber(v)).filter((n) => n !== null && n >= min && n <= max);
83
+ return numbers.length ? numbers : fallback;
84
+ }
85
+ function toEnum(value, allowed, fallback = null) {
86
+ return allowed.includes(value) ? value : fallback;
87
+ }
88
+ function toBool(value) {
89
+ if (typeof value === "string") {
90
+ const v = value.trim().toLowerCase();
91
+ return v !== "" && v !== "false" && v !== "0";
92
+ }
93
+ return !!value;
94
+ }
95
+ function parseBoolAttr(value) {
96
+ return value === void 0 ? void 0 : value === "true";
97
+ }
98
+ function parseColorValue(value) {
99
+ if (typeof value === "string" && value.trim().startsWith("[")) {
100
+ try {
101
+ return JSON.parse(value);
102
+ } catch (e) {
103
+ }
104
+ }
105
+ return value;
106
+ }
107
+ function parseDataAttributes(element) {
108
+ const options = {};
109
+ const setBool = (optKey, dataKey = optKey) => {
110
+ const v = parseBoolAttr(element.dataset[dataKey]);
111
+ if (v !== void 0) options[optKey] = v;
112
+ };
113
+ const setNum = (optKey, dataKey = optKey, float = false) => {
114
+ const raw = element.dataset[dataKey];
115
+ if (raw) options[optKey] = float ? parseFloat(raw) : parseInt(raw, 10);
116
+ };
117
+ const setLength = (optKey, dataKey = optKey) => {
118
+ const raw = element.dataset[dataKey];
119
+ if (!raw) return;
120
+ options[optKey] = /^\d+(\.\d+)?$/.test(raw.trim()) ? parseFloat(raw) : raw;
121
+ };
122
+ const setJsonArray = (optKey, dataKey = optKey) => {
123
+ const raw = element.dataset[dataKey];
124
+ if (!raw) return;
125
+ const parsed = toArray(raw);
126
+ if (parsed) options[optKey] = parsed;
127
+ else console.warn(`[WaveformPlayer] Invalid ${dataKey} attribute, expected a JSON array:`, raw);
128
+ };
129
+ if (element.dataset.src) options.url = element.dataset.src;
130
+ if (element.dataset.url) options.url = element.dataset.url;
131
+ setNum("height");
132
+ setNum("samples");
133
+ if (element.dataset.preload) {
134
+ options.preload = element.dataset.preload;
135
+ }
136
+ if (element.dataset.crossOrigin) {
137
+ options.crossOrigin = element.dataset.crossOrigin;
138
+ }
139
+ if (element.dataset.audioMode) options.audioMode = element.dataset.audioMode;
140
+ if (element.dataset.style) options.waveformStyle = element.dataset.style;
141
+ if (element.dataset.waveformStyle) options.waveformStyle = element.dataset.waveformStyle;
142
+ if (element.dataset.waveformGradient) options.waveformGradient = element.dataset.waveformGradient;
143
+ setNum("barWidth");
144
+ setNum("barSpacing");
145
+ setNum("barRadius");
146
+ if (element.dataset.buttonAlign) options.buttonAlign = element.dataset.buttonAlign;
147
+ if (element.dataset.layout) options.layout = element.dataset.layout;
148
+ if (element.dataset.buttonStyle) options.buttonStyle = element.dataset.buttonStyle;
149
+ setLength("buttonSize");
150
+ setLength("buttonRadius");
151
+ if (element.dataset.colorPreset) options.colorPreset = element.dataset.colorPreset;
152
+ if (element.dataset.waveformColor) options.waveformColor = parseColorValue(element.dataset.waveformColor);
153
+ if (element.dataset.progressColor) options.progressColor = parseColorValue(element.dataset.progressColor);
154
+ if (element.dataset.color) options.waveformColor = element.dataset.color;
155
+ if (element.dataset.theme) options.colorPreset = element.dataset.theme;
156
+ setBool("autoplay");
157
+ setBool("showControls");
158
+ setBool("showInfo");
159
+ setBool("showTime");
160
+ setBool("showHoverTime");
161
+ setBool("seekHandle");
162
+ setBool("showBPM", "showBpm");
163
+ setNum("bpm");
164
+ setBool("singlePlay");
165
+ setBool("playOnSeek");
166
+ if (element.dataset.title) options.title = element.dataset.title;
167
+ if (element.dataset.artist) options.artist = element.dataset.artist;
168
+ if (element.dataset.album) options.album = element.dataset.album;
169
+ if (element.dataset.artwork) options.artwork = element.dataset.artwork;
170
+ if (element.dataset.artworkPosition) options.artworkPosition = element.dataset.artworkPosition;
171
+ if (element.dataset.waveform) options.waveform = element.dataset.waveform;
172
+ setJsonArray("markers");
173
+ setNum("playbackRate", "playbackRate", true);
174
+ setBool("showPlaybackSpeed");
175
+ if (element.dataset.playbackRates) {
176
+ const rates = toNumberArray(element.dataset.playbackRates);
177
+ if (rates) options.playbackRates = rates;
178
+ else console.warn("[WaveformPlayer] Invalid playbackRates attribute:", element.dataset.playbackRates);
179
+ }
180
+ setBool("enableMediaSession");
181
+ setBool("showMarkers");
182
+ setBool("accessibleSeek");
183
+ if (element.dataset.seekLabel) options.seekLabel = element.dataset.seekLabel;
184
+ if (element.dataset.seekValueText) options.seekValueText = element.dataset.seekValueText;
185
+ if (element.dataset.errorText) options.errorText = element.dataset.errorText;
186
+ if (element.dataset.playPauseLabel) options.playPauseLabel = element.dataset.playPauseLabel;
187
+ if (element.dataset.speedLabel) options.speedLabel = element.dataset.speedLabel;
188
+ if (element.dataset.artworkAlt) options.artworkAlt = element.dataset.artworkAlt;
189
+ if (element.dataset.unknownTrackText) options.unknownTrackText = element.dataset.unknownTrackText;
190
+ if (element.dataset.playIcon) options.playIcon = element.dataset.playIcon;
191
+ if (element.dataset.pauseIcon) options.pauseIcon = element.dataset.pauseIcon;
192
+ return options;
193
+ }
194
+ function formatSeekValueText(template, ...args) {
195
+ let sequentialIndex = 0;
196
+ return template.replace(/%(?:(\d+)\$)?s/g, (match, position) => {
197
+ const index = position ? Number(position) - 1 : sequentialIndex++;
198
+ return args[index] ?? match;
199
+ });
200
+ }
201
+ function formatTime(seconds) {
202
+ const total = Number(seconds);
203
+ if (!total || !Number.isFinite(total) || total < 0) return "0:00";
204
+ const hrs = Math.floor(total / 3600);
205
+ const mins = Math.floor(total % 3600 / 60);
206
+ const secs = Math.floor(total % 60);
207
+ if (hrs > 0) {
208
+ return `${hrs}:${mins.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
209
+ }
210
+ return `${mins}:${secs.toString().padStart(2, "0")}`;
211
+ }
212
+ var idCounter = 0;
213
+ function generateId(url) {
214
+ const str = url || "audio";
215
+ let hash = 5381;
216
+ for (let i = 0; i < str.length; i++) {
217
+ hash = (hash << 5) + hash + str.charCodeAt(i) | 0;
218
+ }
219
+ return `wp_${(hash >>> 0).toString(36)}_${(idCounter++).toString(36)}`;
220
+ }
221
+ function extractTitleFromUrl(url) {
222
+ if (!url) return "Audio";
223
+ const parts = url.split("/");
224
+ const filename = parts[parts.length - 1];
225
+ const name = filename.split(".")[0];
226
+ return name.replace(/[-_]/g, " ").replace(/\b\w/g, (l) => l.toUpperCase());
227
+ }
228
+ function parseColor(color) {
229
+ if (typeof color !== "string") return null;
230
+ const m = color.match(/rgba?\(\s*([\d.]+)\s*[,\s]\s*([\d.]+)\s*[,\s]\s*([\d.]+)\s*(?:[,/]\s*([\d.]+)(%?))?/i);
231
+ if (!m) return null;
232
+ const r = Number(m[1]), g = Number(m[2]), b = Number(m[3]);
233
+ if (!Number.isFinite(r) || !Number.isFinite(g) || !Number.isFinite(b)) return null;
234
+ let a = m[4] === void 0 ? 1 : Number(m[4]);
235
+ if (!Number.isFinite(a)) return null;
236
+ if (m[5] === "%") a /= 100;
237
+ return { r, g, b, a: clamp(a, 0, 1) };
238
+ }
239
+ function perceivedBrightness(color) {
240
+ const c = parseColor(color);
241
+ if (!c || c.a <= 0) return null;
242
+ return (c.r * 299 + c.g * 587 + c.b * 114) / 1e3;
243
+ }
244
+ function mergeOptions(...sources) {
245
+ const result = {};
246
+ for (const source of sources) {
247
+ for (const key in source) {
248
+ if (source[key] !== null && source[key] !== void 0) {
249
+ result[key] = source[key];
250
+ }
251
+ }
252
+ }
253
+ return result;
254
+ }
255
+ function debounce(func, wait) {
256
+ let timeout;
257
+ return function executedFunction(...args) {
258
+ const later = () => {
259
+ clearTimeout(timeout);
260
+ func(...args);
261
+ };
262
+ clearTimeout(timeout);
263
+ timeout = setTimeout(later, wait);
264
+ };
265
+ }
266
+ function resampleData(data, targetLength) {
267
+ if (data.length === targetLength) return data;
268
+ if (data.length === 0 || targetLength === 0) return [];
269
+ const result = [];
270
+ if (targetLength > data.length) {
271
+ const ratio = (data.length - 1) / (targetLength - 1);
272
+ for (let i = 0; i < targetLength; i++) {
273
+ const index = i * ratio;
274
+ const lower = Math.floor(index);
275
+ const upper = Math.ceil(index);
276
+ const fraction = index - lower;
277
+ if (upper >= data.length) {
278
+ result.push(data[data.length - 1]);
279
+ } else if (lower === upper) {
280
+ result.push(data[lower]);
281
+ } else {
282
+ const value = data[lower] * (1 - fraction) + data[upper] * fraction;
283
+ result.push(value);
284
+ }
285
+ }
286
+ } else {
287
+ const bucketSize = data.length / targetLength;
288
+ for (let i = 0; i < targetLength; i++) {
289
+ const start = Math.floor(i * bucketSize);
290
+ const end = Math.floor((i + 1) * bucketSize);
291
+ let max = 0;
292
+ let count = 0;
293
+ for (let j = start; j <= end && j < data.length; j++) {
294
+ if (data[j] > max) {
295
+ max = data[j];
296
+ }
297
+ count++;
298
+ }
299
+ if (count === 0) {
300
+ const nearestIndex = Math.min(Math.round(i * bucketSize), data.length - 1);
301
+ max = data[nearestIndex];
302
+ }
303
+ result.push(max);
304
+ }
305
+ }
306
+ return result;
307
+ }
308
+
309
+ // src/js/drawing.js
310
+ function makeFill(ctx, value, canvas, options) {
311
+ if (!Array.isArray(value)) return value;
312
+ if (value.length < 2) return value[0];
313
+ const w = canvas.width;
314
+ const h = canvas.height;
315
+ const dir = options && options.waveformGradient;
316
+ const [x0, y0, x1, y1] = dir === "horizontal" ? [0, 0, w, 0] : dir === "diagonal" ? [0, 0, w, h] : [0, 0, 0, h];
317
+ try {
318
+ const grad = ctx.createLinearGradient(x0, y0, x1, y1);
319
+ value.forEach((c, i) => grad.addColorStop(i / (value.length - 1), c));
320
+ return grad;
321
+ } catch (e) {
322
+ return value[0];
323
+ }
324
+ }
325
+ function fillBar(ctx, x, y, w, h, radii) {
326
+ const any = Array.isArray(radii) ? radii.some((r) => r > 0) : radii > 0;
327
+ if (any && typeof ctx.roundRect === "function") {
328
+ const max = Math.min(w / 2, Math.abs(h) / 2);
329
+ const clampR = (r) => clamp(r, 0, max);
330
+ ctx.beginPath();
331
+ ctx.roundRect(x, y, w, h, Array.isArray(radii) ? radii.map(clampR) : clampR(radii));
332
+ ctx.fill();
333
+ } else {
334
+ ctx.fillRect(x, y, w, h);
335
+ }
336
+ }
337
+ function barRadiusPx(options, dpr) {
338
+ return (options.barRadius || 0) * dpr;
339
+ }
340
+ function barRadii(options, dpr) {
341
+ const r = barRadiusPx(options, dpr);
342
+ return [r, r, 0, 0];
343
+ }
344
+ function capsulePath(ctx, startX, endX, centerY, barHeight) {
345
+ const r = barHeight / 2;
346
+ ctx.beginPath();
347
+ ctx.moveTo(startX, centerY - r);
348
+ ctx.lineTo(endX - r, centerY - r);
349
+ ctx.arc(endX - r, centerY, r, -Math.PI / 2, Math.PI / 2);
350
+ ctx.lineTo(startX, centerY + r);
351
+ ctx.arc(startX, centerY, r, Math.PI / 2, -Math.PI / 2);
352
+ ctx.closePath();
353
+ }
354
+ function drawBars(ctx, canvas, peaks, progress, options) {
355
+ const dpr = window.devicePixelRatio || 1;
356
+ const barWidth = options.barWidth * dpr;
357
+ const barSpacing = options.barSpacing * dpr;
358
+ const barCount = Math.floor(canvas.width / (barWidth + barSpacing));
359
+ const resampledPeaks = resampleData(peaks, barCount);
360
+ const height = canvas.height;
361
+ const progressWidth = progress * canvas.width;
362
+ const radii = barRadii(options, dpr);
363
+ const baseFill = makeFill(ctx, options.color, canvas, options);
364
+ const progFill = makeFill(ctx, options.progressColor, canvas, options);
365
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
366
+ ctx.fillStyle = baseFill;
367
+ for (let i = 0; i < resampledPeaks.length; i++) {
368
+ const x = i * (barWidth + barSpacing);
369
+ if (x + barWidth > canvas.width) break;
370
+ const peakHeight = resampledPeaks[i] * height * 0.9;
371
+ const y = height - peakHeight;
372
+ fillBar(ctx, x, y, barWidth, peakHeight, radii);
373
+ }
374
+ ctx.save();
375
+ ctx.beginPath();
376
+ ctx.rect(0, 0, progressWidth, height);
377
+ ctx.clip();
378
+ ctx.fillStyle = progFill;
379
+ for (let i = 0; i < resampledPeaks.length; i++) {
380
+ const x = i * (barWidth + barSpacing);
381
+ if (x > progressWidth) break;
382
+ const peakHeight = resampledPeaks[i] * height * 0.9;
383
+ const y = height - peakHeight;
384
+ fillBar(ctx, x, y, barWidth, peakHeight, radii);
385
+ }
386
+ ctx.restore();
387
+ }
388
+ function drawMirror(ctx, canvas, peaks, progress, options) {
389
+ const dpr = window.devicePixelRatio || 1;
390
+ const barWidth = options.barWidth * dpr;
391
+ const barSpacing = options.barSpacing * dpr;
392
+ const barCount = Math.floor(canvas.width / (barWidth + barSpacing));
393
+ const resampledPeaks = resampleData(peaks, barCount);
394
+ const height = canvas.height;
395
+ const centerY = height / 2;
396
+ const progressWidth = progress * canvas.width;
397
+ const r = barRadiusPx(options, dpr);
398
+ const topRadii = [r, r, 0, 0];
399
+ const botRadii = [0, 0, r, r];
400
+ const baseFill = makeFill(ctx, options.color, canvas, options);
401
+ const progFill = makeFill(ctx, options.progressColor, canvas, options);
402
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
403
+ ctx.fillStyle = baseFill;
404
+ for (let i = 0; i < resampledPeaks.length; i++) {
405
+ const x = i * (barWidth + barSpacing);
406
+ if (x + barWidth > canvas.width) break;
407
+ const peakHeight = resampledPeaks[i] * height * 0.45;
408
+ fillBar(ctx, x, centerY - peakHeight, barWidth, peakHeight, topRadii);
409
+ fillBar(ctx, x, centerY, barWidth, peakHeight, botRadii);
410
+ }
411
+ ctx.save();
412
+ ctx.beginPath();
413
+ ctx.rect(0, 0, progressWidth, height);
414
+ ctx.clip();
415
+ ctx.fillStyle = progFill;
416
+ for (let i = 0; i < resampledPeaks.length; i++) {
417
+ const x = i * (barWidth + barSpacing);
418
+ if (x > progressWidth) break;
419
+ const peakHeight = resampledPeaks[i] * height * 0.45;
420
+ fillBar(ctx, x, centerY - peakHeight, barWidth, peakHeight, topRadii);
421
+ fillBar(ctx, x, centerY, barWidth, peakHeight, botRadii);
422
+ }
423
+ ctx.restore();
424
+ }
425
+ function drawLine(ctx, canvas, peaks, progress, options) {
426
+ const width = canvas.width;
427
+ const height = canvas.height;
428
+ const centerY = height / 2;
429
+ const amplitude = height * 0.35;
430
+ ctx.clearRect(0, 0, width, height);
431
+ const drawCurve = (color, lineWidth, endProgress = 1, addGlow = false) => {
432
+ const stroke = makeFill(ctx, color, canvas, options);
433
+ const solid = Array.isArray(color) ? color[color.length - 1] : color;
434
+ if (addGlow) {
435
+ ctx.shadowBlur = 12;
436
+ ctx.shadowColor = solid;
437
+ }
438
+ ctx.strokeStyle = stroke;
439
+ ctx.lineWidth = lineWidth;
440
+ ctx.lineCap = "round";
441
+ ctx.lineJoin = "round";
442
+ ctx.beginPath();
443
+ ctx.moveTo(0, centerY);
444
+ const points = [];
445
+ const samples = Math.floor(peaks.length * endProgress);
446
+ for (let i = 0; i < samples; i++) {
447
+ const x = i / (peaks.length - 1) * width;
448
+ const peakValue = peaks[i];
449
+ const waveOffset = Math.sin(i * 0.1) * peakValue;
450
+ const y = centerY + waveOffset * amplitude;
451
+ points.push({ x, y });
452
+ }
453
+ for (let i = 0; i < points.length - 1; i++) {
454
+ const cp1x = points[i].x + (points[i + 1].x - points[i].x) * 0.5;
455
+ const cp1y = points[i].y;
456
+ const cp2x = points[i + 1].x - (points[i + 1].x - points[i].x) * 0.5;
457
+ const cp2y = points[i + 1].y;
458
+ ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, points[i + 1].x, points[i + 1].y);
459
+ }
460
+ ctx.stroke();
461
+ if (addGlow) {
462
+ ctx.shadowBlur = 0;
463
+ }
464
+ };
465
+ ctx.strokeStyle = "rgba(255, 255, 255, 0.03)";
466
+ ctx.lineWidth = 0.5;
467
+ ctx.beginPath();
468
+ ctx.moveTo(0, centerY);
469
+ ctx.lineTo(width, centerY);
470
+ ctx.stroke();
471
+ for (let i = 0; i <= 10; i++) {
472
+ const x = width / 10 * i;
473
+ ctx.beginPath();
474
+ ctx.moveTo(x, 0);
475
+ ctx.lineTo(x, height);
476
+ ctx.stroke();
477
+ }
478
+ drawCurve(options.color, 2, 1, false);
479
+ if (progress > 0) {
480
+ drawCurve(options.progressColor, 3, progress, true);
481
+ }
482
+ }
483
+ function drawBlocks(ctx, canvas, peaks, progress, options) {
484
+ const dpr = window.devicePixelRatio || 1;
485
+ const barWidth = (options.barWidth || 3) * dpr;
486
+ const barSpacing = (options.barSpacing || 1) * dpr;
487
+ const barCount = Math.floor(canvas.width / (barWidth + barSpacing));
488
+ const resampledPeaks = resampleData(peaks, barCount);
489
+ const height = canvas.height;
490
+ const blockSize = 4 * dpr;
491
+ const blockGap = 2 * dpr;
492
+ const progressWidth = progress * canvas.width;
493
+ const centerY = height / 2;
494
+ const baseFill = makeFill(ctx, options.color, canvas, options);
495
+ const progFill = makeFill(ctx, options.progressColor, canvas, options);
496
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
497
+ for (let i = 0; i < resampledPeaks.length; i++) {
498
+ const x = i * (barWidth + barSpacing);
499
+ if (x + barWidth > canvas.width) break;
500
+ const peakHeight = resampledPeaks[i] * height * 0.9;
501
+ const blockCount = Math.floor(peakHeight / (blockSize + blockGap));
502
+ ctx.fillStyle = x < progressWidth ? progFill : baseFill;
503
+ for (let j = 0; j < blockCount; j++) {
504
+ const blockOffset = j * (blockSize + blockGap);
505
+ ctx.fillRect(x, centerY - blockOffset - blockSize, barWidth, blockSize);
506
+ if (j > 0) {
507
+ ctx.fillRect(x, centerY + blockOffset, barWidth, blockSize);
508
+ }
509
+ }
510
+ }
511
+ }
512
+ function drawDots(ctx, canvas, peaks, progress, options) {
513
+ const dpr = window.devicePixelRatio || 1;
514
+ const barWidth = (options.barWidth || 2) * dpr;
515
+ const barSpacing = (options.barSpacing || 3) * dpr;
516
+ const barCount = Math.floor(canvas.width / (barWidth + barSpacing));
517
+ const resampledPeaks = resampleData(peaks, barCount);
518
+ const height = canvas.height;
519
+ const dotRadius = Math.max(1.5 * dpr, barWidth / 2);
520
+ const progressWidth = progress * canvas.width;
521
+ const centerY = height / 2;
522
+ const baseFill = makeFill(ctx, options.color, canvas, options);
523
+ const progFill = makeFill(ctx, options.progressColor, canvas, options);
524
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
525
+ for (let i = 0; i < resampledPeaks.length; i++) {
526
+ const x = i * (barWidth + barSpacing) + barWidth / 2;
527
+ if (x > canvas.width) break;
528
+ const peakHeight = resampledPeaks[i] * height * 0.9;
529
+ ctx.fillStyle = x < progressWidth ? progFill : baseFill;
530
+ ctx.beginPath();
531
+ ctx.arc(x, centerY - peakHeight / 2, dotRadius, 0, Math.PI * 2);
532
+ ctx.fill();
533
+ ctx.beginPath();
534
+ ctx.arc(x, centerY + peakHeight / 2, dotRadius, 0, Math.PI * 2);
535
+ ctx.fill();
536
+ }
537
+ }
538
+ function drawSeekbar(ctx, canvas, peaks, progress, options) {
539
+ const width = canvas.width;
540
+ const height = canvas.height;
541
+ const centerY = height / 2;
542
+ const barHeight = 4;
543
+ const borderRadius = barHeight / 2;
544
+ const active = !!options.seekActive;
545
+ ctx.clearRect(0, 0, width, height);
546
+ ctx.fillStyle = makeFill(ctx, options.color, canvas, options) || "rgba(255, 255, 255, 0.2)";
547
+ capsulePath(ctx, borderRadius, width, centerY, barHeight);
548
+ ctx.fill();
549
+ if (progress > 0) {
550
+ const progressWidth = Math.max(borderRadius * 2, progress * width);
551
+ ctx.save();
552
+ ctx.globalAlpha = options.seekHandle && !active ? 0.7 : 1;
553
+ ctx.fillStyle = makeFill(ctx, options.progressColor, canvas, options) || "rgba(255, 255, 255, 0.9)";
554
+ capsulePath(ctx, borderRadius, progressWidth, centerY, barHeight);
555
+ ctx.fill();
556
+ ctx.restore();
557
+ }
558
+ }
559
+ var DRAWING_STYLES = {
560
+ "bars": drawBars,
561
+ // Classic vertical bars
562
+ "bar": drawBars,
563
+ "mirror": drawMirror,
564
+ // SoundCloud-style symmetrical
565
+ "line": drawLine,
566
+ // Smooth oscilloscope wave
567
+ "blocks": drawBlocks,
568
+ // LED meter segmented
569
+ "block": drawBlocks,
570
+ "dots": drawDots,
571
+ // Circular points
572
+ "dot": drawDots,
573
+ "seekbar": drawSeekbar
574
+ // Simple progress bar (no waveform)
575
+ };
576
+ function draw(ctx, canvas, peaks, progress, options) {
577
+ const drawFunc = DRAWING_STYLES[options.waveformStyle] || drawBars;
578
+ drawFunc(ctx, canvas, peaks, progress, options);
579
+ }
580
+
581
+ // src/js/bpm.js
582
+ function detectBPM(buffer) {
583
+ try {
584
+ const channelData = buffer.getChannelData(0);
585
+ const sampleRate = buffer.sampleRate;
586
+ const onsets = detectOnsets(channelData, sampleRate);
587
+ if (onsets.length < 2) return 120;
588
+ const intervals = [];
589
+ for (let i = 1; i < onsets.length; i++) {
590
+ intervals.push((onsets[i] - onsets[i - 1]) / sampleRate);
591
+ }
592
+ const tempoGroups = {};
593
+ intervals.forEach((interval) => {
594
+ const tempo = 60 / interval;
595
+ const bucket = Math.round(tempo / 3) * 3;
596
+ if (bucket > 60 && bucket < 200) {
597
+ tempoGroups[bucket] = (tempoGroups[bucket] || 0) + 1;
598
+ }
599
+ });
600
+ let maxCount = 0;
601
+ let detectedBPM = 120;
602
+ for (const [tempo, count] of Object.entries(tempoGroups)) {
603
+ if (count > maxCount) {
604
+ maxCount = count;
605
+ detectedBPM = parseInt(tempo);
606
+ }
607
+ }
608
+ if (detectedBPM < 70 && tempoGroups[detectedBPM * 2]) {
609
+ detectedBPM *= 2;
610
+ } else if (detectedBPM > 160 && tempoGroups[Math.round(detectedBPM / 2)]) {
611
+ detectedBPM = Math.round(detectedBPM / 2);
612
+ }
613
+ return detectedBPM - 1;
614
+ } catch (e) {
615
+ console.warn("[WaveformPlayer] BPM detection failed:", e);
616
+ return null;
617
+ }
618
+ }
619
+ function detectOnsets(channelData, sampleRate) {
620
+ const windowSize = 2048;
621
+ const hopSize = windowSize / 2;
622
+ const onsets = [];
623
+ let previousEnergy = 0;
624
+ for (let i = 0; i < channelData.length - windowSize; i += hopSize) {
625
+ let energy = 0;
626
+ for (let j = i; j < i + windowSize; j++) {
627
+ energy += channelData[j] * channelData[j];
628
+ }
629
+ energy = energy / windowSize;
630
+ const energyDiff = energy - previousEnergy;
631
+ const threshold = previousEnergy * 1.8 + 0.01;
632
+ if (energyDiff > threshold && energy > 0.01) {
633
+ const lastOnset = onsets[onsets.length - 1] || 0;
634
+ const minDistance = sampleRate * 0.15;
635
+ if (i - lastOnset > minDistance) {
636
+ onsets.push(i);
637
+ }
638
+ }
639
+ previousEnergy = energy * 0.8 + previousEnergy * 0.2;
640
+ }
641
+ return onsets;
642
+ }
643
+
644
+ // src/js/audio.js
645
+ function extractPeaks(buffer, samples = DEFAULT_SAMPLES) {
646
+ const sampleSize = buffer.length / samples;
647
+ const channels = buffer.numberOfChannels;
648
+ const peaks = [];
649
+ for (let c = 0; c < channels; c++) {
650
+ const chan = buffer.getChannelData(c);
651
+ for (let i = 0; i < samples; i++) {
652
+ const start = ~~(i * sampleSize);
653
+ const end = ~~(start + sampleSize);
654
+ let min = 0;
655
+ let max = 0;
656
+ for (let j = start; j < end; j++) {
657
+ const value = chan[j];
658
+ if (value > max) max = value;
659
+ if (value < min) min = value;
660
+ }
661
+ const peak = Math.max(Math.abs(max), Math.abs(min));
662
+ if (c === 0 || peak > peaks[i]) {
663
+ peaks[i] = peak;
664
+ }
665
+ }
666
+ }
667
+ const maxPeak = maxOf(peaks);
668
+ return maxPeak > 0 ? peaks.map((peak) => peak / maxPeak) : peaks;
669
+ }
670
+ async function generateWaveform(url, samples = DEFAULT_SAMPLES, shouldDetectBPM = false) {
671
+ let audioContext;
672
+ try {
673
+ const AudioCtx = window.AudioContext || /** @type {any} */
674
+ window.webkitAudioContext;
675
+ audioContext = new AudioCtx();
676
+ const response = await fetch(url);
677
+ const arrayBuffer = await response.arrayBuffer();
678
+ const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
679
+ let peaks = extractPeaks(audioBuffer, samples);
680
+ peaks = normalizePeaks(peaks);
681
+ let bpm = null;
682
+ if (shouldDetectBPM) {
683
+ bpm = detectBPM(audioBuffer);
684
+ }
685
+ return { peaks, bpm };
686
+ } finally {
687
+ if (audioContext) audioContext.close();
688
+ }
689
+ }
690
+ function generatePlaceholderWaveform(samples = DEFAULT_SAMPLES) {
691
+ const data = [];
692
+ for (let i = 0; i < samples; i++) {
693
+ const base = Math.random() * 0.5 + 0.3;
694
+ const variation = Math.sin(i / samples * Math.PI * 4) * 0.2;
695
+ data.push(clamp(base + variation, 0.1, 1));
696
+ }
697
+ return data;
698
+ }
699
+ function normalizePeaks(peaks, targetMax = 0.95) {
700
+ const maxPeak = maxOf(peaks);
701
+ if (maxPeak === 0 || maxPeak > targetMax) return peaks;
702
+ const scaleFactor = targetMax / maxPeak;
703
+ return peaks.map((peak) => peak * scaleFactor);
704
+ }
705
+
706
+ // src/js/themes.js
707
+ var LIGHT_THRESHOLD = 128;
708
+ function hasThemeHint(scheme) {
709
+ const root = document.documentElement;
710
+ const body = document.body;
711
+ return root.classList.contains(scheme) || root.classList.contains(`${scheme}-mode`) || root.classList.contains(`theme-${scheme}`) || root.getAttribute("data-theme") === scheme || root.getAttribute("data-color-scheme") === scheme || body.classList.contains(scheme) || body.classList.contains(`${scheme}-mode`) || body.getAttribute("data-theme") === scheme;
712
+ }
713
+ function collectBackdrop(el) {
714
+ let sum = 0;
715
+ let alpha = 0;
716
+ for (let node = el; node && node.nodeType === 1 && alpha < 0.995; node = node.parentElement) {
717
+ const c = parseColor(getComputedStyle(node).backgroundColor);
718
+ if (!c || c.a <= 0) continue;
719
+ const weight = c.a * (1 - alpha);
720
+ sum += (c.r * 299 + c.g * 587 + c.b * 114) / 1e3 * weight;
721
+ alpha += weight;
722
+ }
723
+ return { sum, alpha };
724
+ }
725
+ function detectCanvasScheme() {
726
+ const text = perceivedBrightness(getComputedStyle(document.body).color);
727
+ if (text !== null) return text > LIGHT_THRESHOLD ? "dark" : "light";
728
+ if (window.matchMedia) {
729
+ if (window.matchMedia("(prefers-color-scheme: dark)").matches) return "dark";
730
+ if (window.matchMedia("(prefers-color-scheme: light)").matches) return "light";
731
+ }
732
+ return "dark";
733
+ }
734
+ function detectColorScheme(el) {
735
+ if (hasThemeHint("dark")) return "dark";
736
+ if (hasThemeHint("light")) return "light";
737
+ try {
738
+ const start = el && el.nodeType === 1 ? el : document.body;
739
+ const { sum, alpha } = collectBackdrop(start);
740
+ const canvas = detectCanvasScheme();
741
+ const brightness = sum + (canvas === "dark" ? 0 : 255) * (1 - alpha);
742
+ if (brightness > LIGHT_THRESHOLD) return "light";
743
+ if (brightness < LIGHT_THRESHOLD) return "dark";
744
+ return canvas;
745
+ } catch (e) {
746
+ return "dark";
747
+ }
748
+ }
749
+ var COLOR_PRESETS = {
750
+ dark: {
751
+ waveformColor: "rgba(255, 255, 255, 0.3)",
752
+ progressColor: "rgba(255, 255, 255, 0.9)"
753
+ },
754
+ light: {
755
+ waveformColor: "rgba(0, 0, 0, 0.2)",
756
+ progressColor: "rgba(0, 0, 0, 0.8)"
757
+ }
758
+ };
759
+ function getColorPreset(presetName, el) {
760
+ if (presetName && COLOR_PRESETS[presetName]) {
761
+ return COLOR_PRESETS[presetName];
762
+ }
763
+ const detected = detectColorScheme(el);
764
+ return COLOR_PRESETS[detected];
765
+ }
766
+ var DEFAULT_OPTIONS = {
767
+ // Core settings
768
+ url: "",
769
+ height: 64,
770
+ // Source peak resolution for LIVE decode (ignored when peaks are supplied).
771
+ // The drawer resamples these to fit canvasWidth / (barWidth + barSpacing)
772
+ // bars, so this is fidelity headroom, not the visible bar count. 1800 (the
773
+ // SoundCloud/WaveformGen figure) keeps wide / high-DPI waveforms crisp; the
774
+ // every-frame scan means a higher value costs no extra extraction time.
775
+ samples: DEFAULT_SAMPLES,
776
+ preload: "metadata",
777
+ // CORS mode for the underlying <audio> element. Left null by default so the
778
+ // player behaves like a plain <audio> and never forces a CORS request —
779
+ // setting 'anonymous' here would break playback of media hosted on origins
780
+ // that don't send Access-Control-Allow-Origin (default-config S3/CDN). The
781
+ // playback element is never fed to createMediaElementSource, so it never
782
+ // needs CORS-clean media; peak analysis uses a separate fetch() path with
783
+ // its own placeholder fallback. Set 'anonymous' / 'use-credentials' only if
784
+ // you specifically need it. See issue #18.
785
+ crossOrigin: null,
786
+ // Audio mode — 'self' = player owns the <audio> element (default, current
787
+ // behavior). 'external' = player is a visualization-only surface; no audio
788
+ // element is created, play() dispatches `waveformplayer:request-play`
789
+ // instead of calling audio.play(), and setPlayingState/setProgress are
790
+ // expected to be driven by an external controller (e.g. WaveformBar).
791
+ audioMode: "self",
792
+ // Playback
793
+ playbackRate: 1,
794
+ showPlaybackSpeed: false,
795
+ playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2],
796
+ // Layout Options
797
+ buttonAlign: "auto",
798
+ // Player layout. 'default' = play button + waveform with a left-aligned
799
+ // info row below. 'preview' = compact: the title is centered under the
800
+ // waveform and the meta row (time / speed / BPM) is trimmed — ideal for
801
+ // sample-pack sample previews and dense grids.
802
+ layout: "default",
803
+ // Play/pause button style. 'circle' = bordered circle (default).
804
+ // 'minimal' = a bare play/pause glyph with no circle — the look sample-pack
805
+ // and beat stores use in their preview grids.
806
+ buttonStyle: "circle",
807
+ // Play/pause button size. null = the stylesheet default (36px circle /
808
+ // proportional minimal). A number is treated as px; a string (e.g. '4rem')
809
+ // is used verbatim. Sets the `--wfp-btn-size` CSS var, which scales BOTH
810
+ // styles — box and glyph — proportionally.
811
+ buttonSize: null,
812
+ // Play/pause button corner radius. null = the stylesheet default (50%, a
813
+ // circle). A number is treated as px; a string (e.g. '8px') is used
814
+ // verbatim. Set 0 for a square button. Sets the `--wfp-btn-radius` CSS var,
815
+ // which shapes the 'circle' style's box — the bare 'minimal' glyph has no
816
+ // box to round, so this is a no-op there.
817
+ buttonRadius: null,
818
+ // Default waveform style
819
+ waveformStyle: "mirror",
820
+ barWidth: 2,
821
+ barSpacing: 0,
822
+ // Rounded bar caps (px). 0 = square; 1 = soft caps (default). Applies to bars/mirror.
823
+ barRadius: 1,
824
+ // Gradient axis when waveformColor/progressColor is an array of stops:
825
+ // 'vertical' (top->bottom canvas gradient), 'horizontal' (hue sweep across the
826
+ // waveform) or 'diagonal'. Ignored for single colours.
827
+ waveformGradient: "vertical",
828
+ // Color preset: null = auto-detect, 'dark' = force dark, 'light' = force light
829
+ colorPreset: null,
830
+ // Canvas colours (null = inherit the resolved preset; arrays = gradient
831
+ // stops, see waveformGradient). The DOM chrome (button, title, meta) is
832
+ // themed via CSS variables (--wfp-button-color / --wfp-text-color /
833
+ // --wfp-text-secondary-color), not JS options.
834
+ waveformColor: null,
835
+ progressColor: null,
836
+ // Features
837
+ autoplay: false,
838
+ showControls: true,
839
+ showInfo: true,
840
+ showTime: true,
841
+ showHoverTime: false,
842
+ // Show a draggable circle handle + hover brightness-lift on the SEEKBAR
843
+ // style only (it's meaningless on a waveform, where the fill-edge is the
844
+ // playhead). Off by default; the bar turns it on. Drag-to-scrub works
845
+ // regardless of this.
846
+ seekHandle: false,
847
+ showBPM: false,
848
+ // Known BPM to display in the badge (with showBPM). Wins over auto-detection
849
+ // — set it when peaks are pre-generated so the tempo still shows. null = auto.
850
+ bpm: null,
851
+ singlePlay: true,
852
+ playOnSeek: true,
853
+ enableMediaSession: true,
854
+ // Markers
855
+ markers: [],
856
+ showMarkers: true,
857
+ // Accessibility — expose the waveform as a keyboard-operable slider
858
+ // (role="slider" + ARIA value attributes + arrow/page/home/end seeking).
859
+ // seekLabel sets the slider's accessible name; when null it falls back
860
+ // to the track title, then 'Seek'.
861
+ // seekValueText templates the slider's spoken aria-valuetext: %1$s is the
862
+ // current time and %2$s the total duration (both formatted M:SS). When null
863
+ // it falls back to '%1$s of %2$s'. Lets consumers localize the connective
864
+ // text without reformatting the times.
865
+ accessibleSeek: true,
866
+ seekLabel: null,
867
+ seekValueText: null,
868
+ // Content
869
+ title: null,
870
+ artist: null,
871
+ artwork: null,
872
+ // Where the `artwork` image renders. 'info' = the info row beside the title
873
+ // (needs showInfo). 'button' = the cover becomes the play/pause button,
874
+ // which still works with the info row hidden. Only ONE placement ever
875
+ // renders, so the same cover can't appear twice.
876
+ //
877
+ // 'button' is self-contained: the stylesheet drops the button's ring and
878
+ // swaps its defaults for cover-sized ones (64px, 8px rounding), because the
879
+ // transport defaults are wrong for artwork in both directions — 36px
880
+ // smudges a cover, and 50% crops square art into a circle. buttonSize /
881
+ // buttonRadius still override it if you want a different tile.
882
+ artworkPosition: "info",
883
+ album: "",
884
+ // Message shown in the error state when audio fails to load.
885
+ errorText: "Unable to load audio",
886
+ // Localizable UI strings (alongside seekLabel / seekValueText / errorText).
887
+ // These are screen-reader / assistive-tech facing, so translate them for
888
+ // non-English UIs. playPauseLabel/speedLabel are aria-labels; artworkAlt is
889
+ // the cover image alt text; unknownTrackText is the Media Session (lock-
890
+ // screen) title fallback used when no track title is set.
891
+ playPauseLabel: "Play/Pause",
892
+ speedLabel: "Playback speed",
893
+ artworkAlt: "Album artwork",
894
+ unknownTrackText: "Unknown Track",
895
+ // Icons (SVG)
896
+ playIcon: '<svg viewBox="0 0 24 24" width="16" height="16"><path d="M8 5v14l11-7z"/></svg>',
897
+ pauseIcon: '<svg viewBox="0 0 24 24" width="16" height="16"><path d="M6 4h4v16H6zM14 4h4v16h-4z"/></svg>',
898
+ // Callbacks
899
+ onLoad: null,
900
+ onPlay: null,
901
+ onPause: null,
902
+ onEnd: null,
903
+ onError: null,
904
+ onTimeUpdate: null,
905
+ // Optional queue navigation — when set, the player registers Media Session
906
+ // nexttrack/previoustrack handlers (lock-screen skip buttons). Called with
907
+ // the player instance; wired by waveform-bar / -playlist.
908
+ onNextTrack: null,
909
+ onPreviousTrack: null
910
+ };
911
+ var STYLE_DEFAULTS = {
912
+ bars: { barWidth: 3, barSpacing: 1 },
913
+ mirror: { barWidth: 2, barSpacing: 2 },
914
+ line: { barWidth: 2, barSpacing: 0 },
915
+ blocks: { barWidth: 4, barSpacing: 2 },
916
+ dots: { barWidth: 3, barSpacing: 3 },
917
+ seekbar: { barWidth: 1, barSpacing: 0 }
918
+ };
919
+ var BUTTON_ALIGNMENTS = ["auto", "top", "center", "bottom"];
920
+ var PLAYBACK_RATE_MIN = 0.25;
921
+ var PLAYBACK_RATE_MAX = 4;
922
+ var ENUMS = {
923
+ buttonAlign: BUTTON_ALIGNMENTS,
924
+ layout: ["default", "preview"],
925
+ buttonStyle: ["circle", "minimal"],
926
+ artworkPosition: ["info", "button"],
927
+ waveformStyle: Object.keys(STYLE_DEFAULTS),
928
+ waveformGradient: ["vertical", "horizontal", "diagonal"],
929
+ audioMode: ["self", "external"],
930
+ preload: ["none", "metadata", "auto"],
931
+ colorPreset: Object.keys(COLOR_PRESETS),
932
+ // Anything other than these two makes the browser fall back to 'anonymous',
933
+ // which forces a CORS request the caller never asked for — so a bad value
934
+ // has to resolve to null (no crossorigin attribute), not pass through.
935
+ crossOrigin: ["anonymous", "use-credentials"]
936
+ };
937
+ var NUMBERS = {
938
+ height: { min: 1, integer: true },
939
+ samples: { min: 1, integer: true },
940
+ barWidth: { min: 0 },
941
+ barSpacing: { min: 0 },
942
+ barRadius: { min: 0 },
943
+ bpm: { min: 1 },
944
+ // Matches the clamp in setPlaybackRate() — the menu must not offer a rate
945
+ // the setter would then silently refuse.
946
+ playbackRate: { min: PLAYBACK_RATE_MIN, max: PLAYBACK_RATE_MAX }
947
+ };
948
+ var BOOLEANS = [
949
+ "autoplay",
950
+ "showControls",
951
+ "showInfo",
952
+ "showTime",
953
+ "showHoverTime",
954
+ "seekHandle",
955
+ "showBPM",
956
+ "singlePlay",
957
+ "playOnSeek",
958
+ "enableMediaSession",
959
+ "showMarkers",
960
+ "accessibleSeek",
961
+ "showPlaybackSpeed"
962
+ ];
963
+ var CALLBACKS = [
964
+ "onLoad",
965
+ "onPlay",
966
+ "onPause",
967
+ "onEnd",
968
+ "onError",
969
+ "onTimeUpdate",
970
+ "onNextTrack",
971
+ "onPreviousTrack"
972
+ ];
973
+ function warnInvalid(key, value) {
974
+ console.warn(`[WaveformPlayer] Invalid ${key} option, using default:`, value);
975
+ }
976
+ function normalizeMarkers(value) {
977
+ const list = toArray(value);
978
+ if (!list) {
979
+ if (value != null) warnInvalid("markers", value);
980
+ return [];
981
+ }
982
+ return list.reduce((markers, marker) => {
983
+ const time = marker && typeof marker === "object" ? toFiniteNumber(marker.time, null, { min: 0 }) : null;
984
+ if (time === null) {
985
+ warnInvalid("marker", marker);
986
+ return markers;
987
+ }
988
+ markers.push({ ...marker, time, label: marker.label == null ? "" : marker.label });
989
+ return markers;
990
+ }, []);
991
+ }
992
+ function normalizeOptions(options) {
993
+ const supplied = (key) => options[key] != null;
994
+ const reject = (key) => {
995
+ warnInvalid(key, options[key]);
996
+ options[key] = DEFAULT_OPTIONS[key];
997
+ };
998
+ for (const [key, range] of Object.entries(NUMBERS)) {
999
+ if (!supplied(key)) continue;
1000
+ const n = toFiniteNumber(options[key], null, range);
1001
+ if (n === null) reject(key);
1002
+ else options[key] = n;
1003
+ }
1004
+ for (const [key, allowed] of Object.entries(ENUMS)) {
1005
+ if (supplied(key) && toEnum(options[key], allowed) === null) reject(key);
1006
+ }
1007
+ for (const key of BOOLEANS) {
1008
+ options[key] = toBool(options[key]);
1009
+ }
1010
+ for (const key of CALLBACKS) {
1011
+ if (supplied(key) && typeof options[key] !== "function") reject(key);
1012
+ }
1013
+ if (supplied("playbackRates")) {
1014
+ const rates = toNumberArray(options.playbackRates, {
1015
+ min: PLAYBACK_RATE_MIN,
1016
+ max: PLAYBACK_RATE_MAX,
1017
+ fallback: null
1018
+ });
1019
+ if (rates === null) reject("playbackRates");
1020
+ else options.playbackRates = rates;
1021
+ }
1022
+ options.markers = normalizeMarkers(options.markers);
1023
+ for (const key of ["buttonSize", "buttonRadius"]) {
1024
+ if (!supplied(key)) continue;
1025
+ const value = options[key];
1026
+ const ok = typeof value === "number" ? Number.isFinite(value) : typeof value === "string" && value.trim() !== "";
1027
+ if (!ok) reject(key);
1028
+ }
1029
+ for (const key of ["waveformColor", "progressColor"]) {
1030
+ if (!supplied(key)) continue;
1031
+ const value = options[key];
1032
+ if (!(typeof value === "string" && value.trim() !== "") && !Array.isArray(value)) reject(key);
1033
+ }
1034
+ return options;
1035
+ }
1036
+
1037
+ // src/js/core.js
1038
+ var ARTWORK_FALLBACK = "data:image/svg+xml," + encodeURIComponent(
1039
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><rect width="24" height="24" rx="4" fill="#71717a" fill-opacity="0.15"/><g fill="none" stroke="#a1a1aa" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><circle cx="8" cy="17" r="2.2"/><circle cx="17" cy="15" r="2.2"/><path d="M10.2 17V7l9-1.6v9"/></g></svg>'
1040
+ );
1041
+ var SEEK_STEP_SECONDS = 5;
1042
+ var SEEK_PAGE_SECONDS = 10;
1043
+ var INTERACTIVE_ELEMENTS = 'button, a[href], input, [role="slider"]';
1044
+ var WaveformPlayer = class _WaveformPlayer {
1045
+ /** @type {Map<string, WaveformPlayer>} */
1046
+ static instances = /* @__PURE__ */ new Map();
1047
+ /** @type {WaveformPlayer|null} */
1048
+ static currentlyPlaying = null;
1049
+ /**
1050
+ * Create a new WaveformPlayer instance.
1051
+ *
1052
+ * Resolves the container, merges options (defaults < `data-*` attributes <
1053
+ * constructor options), applies the colour preset and style-specific
1054
+ * defaults, registers the instance in the static map, and kicks off
1055
+ * {@link WaveformPlayer#init}. A `waveformplayer:ready` event is dispatched
1056
+ * ~100ms later, once initialization has settled.
1057
+ *
1058
+ * @param {string|HTMLElement} container - Container element, or a CSS
1059
+ * selector resolved with `document.querySelector`.
1060
+ * @param {Object} [options={}] - Player options. Accepts the shorthand
1061
+ * aliases `style` (→ `waveformStyle`) and `src` (→ `url`); the canonical
1062
+ * names win if both are supplied.
1063
+ * @throws {Error} If the container element cannot be found.
1064
+ * @fires WaveformPlayer#waveformplayer:ready
1065
+ */
1066
+ constructor(container, options = {}) {
1067
+ this.container = typeof container === "string" ? document.querySelector(container) : container;
1068
+ if (!this.container) {
1069
+ throw new Error("[WaveformPlayer] Container element not found");
1070
+ }
1071
+ const dataOptions = parseDataAttributes(this.container);
1072
+ const userOptions = { ...options };
1073
+ if (userOptions.style && !userOptions.waveformStyle) userOptions.waveformStyle = userOptions.style;
1074
+ if (userOptions.src && !userOptions.url) userOptions.url = userOptions.src;
1075
+ this.options = normalizeOptions(mergeOptions(DEFAULT_OPTIONS, dataOptions, userOptions));
1076
+ const preset = getColorPreset(this.options.colorPreset, this.container);
1077
+ this._autoTheme = this.options.colorPreset == null || !COLOR_PRESETS[this.options.colorPreset];
1078
+ this._presetKeys = [];
1079
+ this._scheme = this.options.colorPreset && COLOR_PRESETS[this.options.colorPreset] ? this.options.colorPreset : detectColorScheme(this.container);
1080
+ for (const [key, value] of Object.entries(preset)) {
1081
+ if (this.options[key] === null || this.options[key] === void 0) {
1082
+ this.options[key] = value;
1083
+ this._presetKeys.push(key);
1084
+ }
1085
+ }
1086
+ const styleDefaults = STYLE_DEFAULTS[this.options.waveformStyle];
1087
+ if (styleDefaults) {
1088
+ if (dataOptions.barWidth === void 0 && options.barWidth === void 0) {
1089
+ this.options.barWidth = styleDefaults.barWidth;
1090
+ }
1091
+ if (dataOptions.barSpacing === void 0 && options.barSpacing === void 0) {
1092
+ this.options.barSpacing = styleDefaults.barSpacing;
1093
+ }
1094
+ }
1095
+ this.audio = null;
1096
+ this.canvas = null;
1097
+ this.ctx = null;
1098
+ this.waveformData = [];
1099
+ this.progress = 0;
1100
+ this._activeMarkerIndex = -1;
1101
+ this._markerLabelTimer = null;
1102
+ this.isPlaying = false;
1103
+ this.isLoading = false;
1104
+ this.hasError = false;
1105
+ this.updateTimer = null;
1106
+ this.resizeObserver = null;
1107
+ this._ac = new AbortController();
1108
+ this.id = this.container.id || generateId(this.options.url);
1109
+ _WaveformPlayer.instances.set(this.id, this);
1110
+ _WaveformPlayer._watchTheme();
1111
+ try {
1112
+ this.init();
1113
+ } catch (error) {
1114
+ _WaveformPlayer.instances.delete(this.id);
1115
+ this._ac.abort();
1116
+ throw error;
1117
+ }
1118
+ setTimeout(() => {
1119
+ this._emit("waveformplayer:ready", { player: this, url: this.options.url });
1120
+ }, 100);
1121
+ }
1122
+ /**
1123
+ * Build and dispatch a bubbling `waveformplayer:*` CustomEvent on the
1124
+ * container, returning the event so cancelable (request-*) events can have
1125
+ * their `defaultPrevented` checked. Single source of truth for the event
1126
+ * shape — every player event bubbles and carries the supplied detail.
1127
+ * @param {string} type - Full event type, e.g. `'waveformplayer:play'`.
1128
+ * @param {Object} detail - Event detail payload.
1129
+ * @param {boolean} [cancelable=false] - Whether the event is cancelable.
1130
+ * @returns {CustomEvent} The dispatched event.
1131
+ * @private
1132
+ */
1133
+ _emit(type, detail, cancelable = false) {
1134
+ const event = new CustomEvent(type, { bubbles: true, cancelable, detail });
1135
+ this.container.dispatchEvent(event);
1136
+ return event;
1137
+ }
1138
+ /**
1139
+ * External-mode seek request: dispatch a cancelable
1140
+ * `waveformplayer:request-seek` and, unless the controller calls
1141
+ * `preventDefault()`, optimistically advance the local progress overlay so
1142
+ * the canvas repaints at once. Shared by the keyboard slider and canvas click.
1143
+ * @param {number} percent - Target position as a 0..1 fraction.
1144
+ * @private
1145
+ * @fires WaveformPlayer#waveformplayer:request-seek
1146
+ */
1147
+ _requestSeek(percent) {
1148
+ const evt = this._emit("waveformplayer:request-seek", { ...this._buildTrackDetail(), percent }, true);
1149
+ if (!evt.defaultPrevented) {
1150
+ this.progress = percent;
1151
+ this.drawWaveform?.();
1152
+ }
1153
+ }
1154
+ // ============================================
1155
+ // Initialization
1156
+ // ============================================
1157
+ /**
1158
+ * Initialize the player: build the DOM, create the audio element (self
1159
+ * mode only), wire up the feature controls (speed, keyboard, accessible
1160
+ * seek), bind events, attach the resize observer, then size the canvas and
1161
+ * — if a `url` option was given — load it and optionally autoplay.
1162
+ * @private
1163
+ */
1164
+ init() {
1165
+ this.createDOM();
1166
+ this.createAudio();
1167
+ this.initPlaybackSpeed();
1168
+ this.initKeyboardControls();
1169
+ this.initSeekControl();
1170
+ this.bindEvents();
1171
+ this.setupResizeObserver();
1172
+ requestAnimationFrame(() => {
1173
+ this.resizeCanvas();
1174
+ if (this.options.url) {
1175
+ this.load(this.options.url).then(() => {
1176
+ if (this.options.autoplay) {
1177
+ this.play()?.catch(() => {
1178
+ });
1179
+ }
1180
+ }).catch((error) => {
1181
+ console.error("[WaveformPlayer] Failed to load audio:", error);
1182
+ });
1183
+ }
1184
+ });
1185
+ }
1186
+ /**
1187
+ * Build the player's DOM tree inside the container and cache element
1188
+ * references.
1189
+ *
1190
+ * Clears the container, resolves button alignment (`auto` → `bottom` for
1191
+ * the `bars` style, `center` otherwise), and conditionally renders the play
1192
+ * button, info row (artwork/title/artist), BPM badge, playback-speed
1193
+ * menu, and time display based on the relevant `show*` options. Caches the
1194
+ * canvas, controls, and text elements onto `this`, then sizes the canvas.
1195
+ * @private
1196
+ */
1197
+ createDOM() {
1198
+ this.container.innerHTML = "";
1199
+ this.container.className = "waveform-player";
1200
+ let buttonAlign = BUTTON_ALIGNMENTS.includes(this.options.buttonAlign) ? this.options.buttonAlign : "auto";
1201
+ if (buttonAlign === "auto") {
1202
+ const style = this.options.waveformStyle;
1203
+ if (style === "bars") {
1204
+ buttonAlign = "bottom";
1205
+ } else {
1206
+ buttonAlign = "center";
1207
+ }
1208
+ }
1209
+ const isPreview = this.options.layout === "preview";
1210
+ if (isPreview) {
1211
+ this.container.classList.add("waveform-layout-preview");
1212
+ }
1213
+ this.container.classList.toggle("waveform-theme-light", this._scheme === "light");
1214
+ const buttonVars = [];
1215
+ if (this.options.buttonSize != null) {
1216
+ buttonVars.push(`--wfp-btn-size: ${formatCssLength(this.options.buttonSize)}`);
1217
+ }
1218
+ if (this.options.buttonRadius != null) {
1219
+ buttonVars.push(`--wfp-btn-radius: ${formatCssLength(this.options.buttonRadius)}`);
1220
+ }
1221
+ const buttonStyleAttr = buttonVars.length ? ` style="${buttonVars.join("; ")};"` : "";
1222
+ const artworkOnButton = this.options.artworkPosition === "button" && this.options.artwork;
1223
+ const buttonArtworkHTML = artworkOnButton ? `<img class="waveform-btn-artwork" src="${escapeHtml(this.options.artwork)}" alt="" aria-hidden="true">` : "";
1224
+ const buttonHTML = this.options.showControls ? `
1225
+ <button class="waveform-btn${this.options.buttonStyle === "minimal" ? " waveform-btn-minimal" : ""}${artworkOnButton ? " waveform-btn-has-artwork" : ""}" aria-label="${escapeHtml(this.options.playPauseLabel)}"${buttonStyleAttr}>
1226
+ ${buttonArtworkHTML}
1227
+ <span class="waveform-icon-play">${this.options.playIcon}</span>
1228
+ <span class="waveform-icon-pause" style="display:none;">${this.options.pauseIcon}</span>
1229
+ </button>
1230
+ ` : "";
1231
+ const infoHTML = this.options.showInfo ? `
1232
+ <div class="waveform-info">
1233
+ ${this.options.artworkPosition !== "button" && this.options.artwork ? `
1234
+ <img class="waveform-artwork" src="${escapeHtml(this.options.artwork)}" alt="${escapeHtml(this.options.artworkAlt)}" style="
1235
+ width: 40px;
1236
+ height: 40px;
1237
+ border-radius: 4px;
1238
+ object-fit: cover;
1239
+ flex-shrink: 0;
1240
+ ">
1241
+ ` : ""}
1242
+ <div class="waveform-text">
1243
+ <span class="waveform-title"></span>
1244
+ ${this.options.artist ? `<span class="waveform-artist">${escapeHtml(this.options.artist)}</span>` : ""}
1245
+ </div>
1246
+ <div class="waveform-meta" style="display: flex; align-items: center; gap: 1rem;">
1247
+ ${this.options.showBPM ? `
1248
+ <span class="waveform-bpm" style="display: none;">
1249
+ <span class="bpm-value">--</span> BPM
1250
+ </span>
1251
+ ` : ""}
1252
+ ${this.options.showPlaybackSpeed ? `
1253
+ <div class="waveform-speed">
1254
+ <button class="speed-btn" aria-label="${escapeHtml(this.options.speedLabel)}" aria-haspopup="menu" aria-expanded="false">
1255
+ <span class="speed-value">1x</span>
1256
+ </button>
1257
+ <div class="speed-menu" role="menu" aria-label="${escapeHtml(this.options.speedLabel)}" style="display: none;">
1258
+ ${this.options.playbackRates.map(
1259
+ (rate) => `<button class="speed-option" role="menuitemradio" tabindex="-1" aria-checked="false" data-rate="${rate}">${rate}x</button>`
1260
+ ).join("")}
1261
+ </div>
1262
+ </div>
1263
+ ` : ""}
1264
+ ${this.options.showTime ? `
1265
+ <span class="waveform-time">
1266
+ <span class="time-current">0:00</span> / <span class="time-total">0:00</span>
1267
+ </span>
1268
+ ` : ""}
1269
+ </div>
1270
+ </div>
1271
+ ` : "";
1272
+ this.container.innerHTML = `
1273
+ <div class="waveform-player-inner">
1274
+ <div class="waveform-body">
1275
+ <div class="waveform-track waveform-align-${buttonAlign}">
1276
+ ${buttonHTML}
1277
+
1278
+ <div class="waveform-container">
1279
+ <canvas></canvas>
1280
+ <div class="waveform-markers"></div>
1281
+ <div class="waveform-loading" style="display:none;"></div>
1282
+ <div class="waveform-error" style="display:none;" role="alert">
1283
+ <span class="waveform-error-text">${escapeHtml(this.options.errorText)}</span>
1284
+ </div>
1285
+ </div>
1286
+ </div>
1287
+
1288
+ ${infoHTML}
1289
+ </div>
1290
+ </div>
1291
+ `;
1292
+ this.playBtn = this.container.querySelector(".waveform-btn");
1293
+ this.canvas = this.container.querySelector("canvas");
1294
+ this.ctx = this.canvas.getContext("2d");
1295
+ this.titleEl = this.container.querySelector(".waveform-title");
1296
+ this.artistEl = this.container.querySelector(".waveform-artist");
1297
+ this.artworkEl = this.container.querySelector(".waveform-artwork, .waveform-btn-artwork");
1298
+ this.bindArtworkFallback(this.artworkEl);
1299
+ this.currentTimeEl = this.container.querySelector(".time-current");
1300
+ this.totalTimeEl = this.container.querySelector(".time-total");
1301
+ this.bpmEl = this.container.querySelector(".waveform-bpm");
1302
+ this.bpmValueEl = this.container.querySelector(".bpm-value");
1303
+ this.loadingEl = this.container.querySelector(".waveform-loading");
1304
+ this.errorEl = this.container.querySelector(".waveform-error");
1305
+ this.markersContainer = this.container.querySelector(".waveform-markers");
1306
+ this.speedBtn = this.container.querySelector(".speed-btn");
1307
+ this.speedMenu = this.container.querySelector(".speed-menu");
1308
+ this.resizeCanvas();
1309
+ this.updateBPMDisplay();
1310
+ }
1311
+ /**
1312
+ * Bind the artwork error fallback to an image element.
1313
+ *
1314
+ * @param {HTMLImageElement|null} img - Artwork image element.
1315
+ * @private
1316
+ */
1317
+ bindArtworkFallback(img) {
1318
+ if (!img) return;
1319
+ img.addEventListener("error", () => {
1320
+ if (!img.src.startsWith("data:")) img.src = ARTWORK_FALLBACK;
1321
+ }, { signal: this._ac.signal });
1322
+ }
1323
+ /**
1324
+ * Create an artwork image element matching the initial player markup.
1325
+ *
1326
+ * @returns {HTMLImageElement} Artwork image element.
1327
+ * @private
1328
+ */
1329
+ createArtworkElement() {
1330
+ const img = document.createElement("img");
1331
+ img.className = "waveform-artwork";
1332
+ img.style.width = "40px";
1333
+ img.style.height = "40px";
1334
+ img.style.borderRadius = "4px";
1335
+ img.style.objectFit = "cover";
1336
+ img.style.flexShrink = "0";
1337
+ this.bindArtworkFallback(img);
1338
+ return img;
1339
+ }
1340
+ /**
1341
+ * Create a play-button artwork image matching the initial player markup.
1342
+ *
1343
+ * Decorative by design — the button already has an accessible name from its
1344
+ * `aria-label`, so the cover is hidden from assistive tech rather than
1345
+ * given a competing one. Sizing and clipping are the stylesheet's job.
1346
+ *
1347
+ * @returns {HTMLImageElement} Play-button artwork image element.
1348
+ * @private
1349
+ */
1350
+ createButtonArtworkElement() {
1351
+ const img = document.createElement("img");
1352
+ img.className = "waveform-btn-artwork";
1353
+ img.alt = "";
1354
+ img.setAttribute("aria-hidden", "true");
1355
+ this.bindArtworkFallback(img);
1356
+ return img;
1357
+ }
1358
+ /**
1359
+ * Create an artist text element matching the initial player markup.
1360
+ *
1361
+ * @returns {HTMLSpanElement} Artist text element.
1362
+ * @private
1363
+ */
1364
+ createArtistElement() {
1365
+ const span = document.createElement("span");
1366
+ span.className = "waveform-artist";
1367
+ return span;
1368
+ }
1369
+ /**
1370
+ * Reconcile artist metadata and markup for the current track.
1371
+ *
1372
+ * @param {string|null} artist - Artist text, or a falsy value to remove it.
1373
+ * @private
1374
+ */
1375
+ syncArtist(artist) {
1376
+ this.options.artist = artist || null;
1377
+ if (!this.options.showInfo) return;
1378
+ if (!artist) {
1379
+ this.artistEl?.remove();
1380
+ this.artistEl = null;
1381
+ return;
1382
+ }
1383
+ if (!this.artistEl) {
1384
+ const titleEl = this.container.querySelector(".waveform-title");
1385
+ if (!titleEl) return;
1386
+ this.artistEl = this.createArtistElement();
1387
+ titleEl.after(this.artistEl);
1388
+ }
1389
+ this.artistEl.textContent = artist;
1390
+ this.artistEl.style.display = "";
1391
+ }
1392
+ /**
1393
+ * Reconcile the play button's artwork image (`artworkPosition: 'button'`).
1394
+ *
1395
+ * Shares {@link bindArtworkFallback} with the info-row image, so a broken
1396
+ * cover degrades to the same placeholder tile in either placement. The
1397
+ * `waveform-btn-has-artwork` class is what turns on the scrim + glyph
1398
+ * treatment, so it tracks the image's presence exactly.
1399
+ *
1400
+ * @param {string|null} artwork - Artwork image URL, or a falsy value to remove it.
1401
+ * @private
1402
+ */
1403
+ syncButtonArtwork(artwork) {
1404
+ if (!this.playBtn) return;
1405
+ if (!artwork) {
1406
+ this.artworkEl?.remove();
1407
+ this.artworkEl = null;
1408
+ this.playBtn.classList.remove("waveform-btn-has-artwork");
1409
+ return;
1410
+ }
1411
+ if (!this.artworkEl) {
1412
+ this.artworkEl = this.createButtonArtworkElement();
1413
+ this.playBtn.prepend(this.artworkEl);
1414
+ }
1415
+ this.artworkEl.src = artwork;
1416
+ this.playBtn.classList.add("waveform-btn-has-artwork");
1417
+ }
1418
+ /**
1419
+ * Reconcile artwork metadata and markup for the current track.
1420
+ *
1421
+ * The image lives in one of two homes depending on `artworkPosition` — the
1422
+ * info row (default) or the play button — and only ever one of them, so a
1423
+ * cover can't render twice.
1424
+ *
1425
+ * @param {string|null} artwork - Artwork image URL, or a falsy value to remove artwork.
1426
+ * @param {string} artworkAlt - Artwork alt text. Info-row placement only:
1427
+ * button artwork is decorative and defers to the button's own label.
1428
+ * @private
1429
+ */
1430
+ syncArtwork(artwork, artworkAlt = "") {
1431
+ this.options.artwork = artwork || null;
1432
+ this.options.artworkAlt = artworkAlt || "";
1433
+ if (this.options.artworkPosition === "button") {
1434
+ this.syncButtonArtwork(this.options.artwork);
1435
+ return;
1436
+ }
1437
+ if (!this.options.showInfo) return;
1438
+ if (!artwork) {
1439
+ this.artworkEl?.remove();
1440
+ this.artworkEl = null;
1441
+ return;
1442
+ }
1443
+ if (!this.artworkEl) {
1444
+ const textEl = this.container.querySelector(".waveform-text");
1445
+ if (!textEl) return;
1446
+ this.artworkEl = this.createArtworkElement();
1447
+ textEl.before(this.artworkEl);
1448
+ }
1449
+ this.artworkEl.src = artwork;
1450
+ this.artworkEl.alt = artworkAlt || "";
1451
+ }
1452
+ /**
1453
+ * Create audio element
1454
+ * @private
1455
+ *
1456
+ * No-op in `audioMode: 'external'` — the player has no audio of its
1457
+ * own; an external controller (e.g. WaveformBar) owns playback and
1458
+ * pushes state in via setPlayingState() / setProgress(). The
1459
+ * `this.audio` field stays null in that mode; downstream code must
1460
+ * null-check it.
1461
+ */
1462
+ createAudio() {
1463
+ if (this.options.audioMode === "external") {
1464
+ this.audio = null;
1465
+ return;
1466
+ }
1467
+ this.audio = new Audio();
1468
+ this.audio.preload = this.options.preload || "metadata";
1469
+ if (this.options.crossOrigin) {
1470
+ this.audio.crossOrigin = this.options.crossOrigin;
1471
+ }
1472
+ }
1473
+ // ============================================
1474
+ // Feature Initialization
1475
+ // ============================================
1476
+ /**
1477
+ * Apply the configured initial playback rate to the audio element (self
1478
+ * mode only) and, when `showPlaybackSpeed` is enabled, wire up the speed
1479
+ * menu UI via {@link WaveformPlayer#initSpeedControls}.
1480
+ * @private
1481
+ */
1482
+ initPlaybackSpeed() {
1483
+ if (this.audio && this.options.playbackRate && this.options.playbackRate !== 1) {
1484
+ this.audio.playbackRate = this.options.playbackRate;
1485
+ }
1486
+ if (this.options.showPlaybackSpeed) {
1487
+ this.initSpeedControls();
1488
+ }
1489
+ }
1490
+ /**
1491
+ * Wire up the playback-speed menu: toggle it open on the speed button,
1492
+ * close it on outside click or Escape (keeping `aria-expanded` on the
1493
+ * trigger in sync), and apply the chosen rate when a `.speed-option` is
1494
+ * clicked, returning focus to the trigger. All listeners are registered against the
1495
+ * instance `AbortController` signal so {@link WaveformPlayer#destroy} tears
1496
+ * them down. No-op if the speed elements are absent.
1497
+ * @private
1498
+ */
1499
+ initSpeedControls() {
1500
+ const speedBtn = this.container.querySelector(".speed-btn");
1501
+ const speedMenu = this.container.querySelector(".speed-menu");
1502
+ if (!speedBtn || !speedMenu) return;
1503
+ const options = () => Array.from(speedMenu.querySelectorAll(".speed-option"));
1504
+ const isOpen = () => speedMenu.style.display !== "none";
1505
+ const setSpeedMenu = (open) => {
1506
+ speedMenu.style.display = open ? "block" : "none";
1507
+ speedBtn.setAttribute("aria-expanded", open ? "true" : "false");
1508
+ if (open) {
1509
+ const opts = options();
1510
+ (opts.find((o) => o.getAttribute("aria-checked") === "true") || opts[0])?.focus();
1511
+ }
1512
+ };
1513
+ const focusOption = (i) => {
1514
+ const opts = options();
1515
+ if (opts.length) opts[(i + opts.length) % opts.length].focus();
1516
+ };
1517
+ const selectOption = (opt) => {
1518
+ this.setPlaybackRate(parseFloat(opt.dataset.rate));
1519
+ setSpeedMenu(false);
1520
+ speedBtn.focus();
1521
+ };
1522
+ speedBtn.addEventListener("click", (e) => {
1523
+ e.stopPropagation();
1524
+ setSpeedMenu(!isOpen());
1525
+ }, { signal: this._ac.signal });
1526
+ document.addEventListener("click", () => setSpeedMenu(false), { signal: this._ac.signal });
1527
+ speedMenu.addEventListener("click", (e) => {
1528
+ e.stopPropagation();
1529
+ const opt = e.target.closest(".speed-option");
1530
+ if (opt) selectOption(opt);
1531
+ }, { signal: this._ac.signal });
1532
+ speedBtn.closest(".waveform-speed")?.addEventListener("keydown", (e) => {
1533
+ const opts = options();
1534
+ const i = opts.indexOf(document.activeElement);
1535
+ if (!isOpen()) {
1536
+ if ((e.key === "ArrowDown" || e.key === "ArrowUp") && document.activeElement === speedBtn) {
1537
+ e.preventDefault();
1538
+ setSpeedMenu(true);
1539
+ }
1540
+ return;
1541
+ }
1542
+ switch (e.key) {
1543
+ case "ArrowDown":
1544
+ e.preventDefault();
1545
+ focusOption(i < 0 ? 0 : i + 1);
1546
+ break;
1547
+ case "ArrowUp":
1548
+ e.preventDefault();
1549
+ focusOption(i < 0 ? opts.length - 1 : i - 1);
1550
+ break;
1551
+ case "Home":
1552
+ e.preventDefault();
1553
+ focusOption(0);
1554
+ break;
1555
+ case "End":
1556
+ e.preventDefault();
1557
+ focusOption(opts.length - 1);
1558
+ break;
1559
+ case "Escape":
1560
+ e.preventDefault();
1561
+ setSpeedMenu(false);
1562
+ speedBtn.focus();
1563
+ break;
1564
+ case "Tab":
1565
+ setSpeedMenu(false);
1566
+ break;
1567
+ }
1568
+ }, { signal: this._ac.signal });
1569
+ this.updateSpeedUI();
1570
+ }
1571
+ /**
1572
+ * Enable keyboard transport controls on the container.
1573
+ *
1574
+ * The container is focusable only after it is clicked (it carries
1575
+ * `tabindex="-1"` until then, and clicking steals focus from sibling
1576
+ * players). While focused it handles: digits 0-9 (seek to that tenth of
1577
+ * the track), Space (toggle play), and — in self mode only, since
1578
+ * `this.audio` is null in external mode — arrow keys (seek ±5s, volume
1579
+ * ±0.1) and `m`/`M` (mute). Listeners use the instance abort signal.
1580
+ * @private
1581
+ */
1582
+ initKeyboardControls() {
1583
+ this.container.setAttribute("tabindex", "-1");
1584
+ this.container.addEventListener("click", (e) => {
1585
+ if (e.target.closest(INTERACTIVE_ELEMENTS)) return;
1586
+ _WaveformPlayer.getAllInstances().forEach((player) => {
1587
+ if (player !== this) {
1588
+ player.container.setAttribute("tabindex", "-1");
1589
+ }
1590
+ });
1591
+ this.container.setAttribute("tabindex", "0");
1592
+ this.container.focus();
1593
+ }, { signal: this._ac.signal });
1594
+ this.container.addEventListener("keydown", (e) => {
1595
+ if (document.activeElement !== this.container) return;
1596
+ const key = e.key;
1597
+ const hasAudio = !!this.audio;
1598
+ const currentTime = hasAudio ? this.audio.currentTime : 0;
1599
+ if (hasAudio && key >= "0" && key <= "9") {
1600
+ e.preventDefault();
1601
+ this.seekToPercent(parseInt(key) / 10);
1602
+ return;
1603
+ }
1604
+ const actions = {
1605
+ " ": () => this.togglePlay()
1606
+ };
1607
+ if (hasAudio) {
1608
+ actions["ArrowLeft"] = () => this.seekTo(clamp(currentTime - 5, 0, this.audio.duration));
1609
+ actions["ArrowRight"] = () => this.seekTo(clamp(currentTime + 5, 0, this.audio.duration));
1610
+ actions["ArrowUp"] = () => this.setVolume(clamp(this.audio.volume + 0.1));
1611
+ actions["ArrowDown"] = () => this.setVolume(clamp(this.audio.volume - 0.1));
1612
+ actions["m"] = actions["M"] = () => this.audio.muted = !this.audio.muted;
1613
+ }
1614
+ if (actions[key]) {
1615
+ e.preventDefault();
1616
+ actions[key]();
1617
+ }
1618
+ }, { signal: this._ac.signal });
1619
+ }
1620
+ /**
1621
+ * Expose the waveform as an accessible, keyboard-operable slider.
1622
+ *
1623
+ * Adds role="slider" + ARIA value attributes to the waveform surface,
1624
+ * makes it focusable in the tab order, and handles the standard slider
1625
+ * keys (arrows, Page Up/Down, Home/End) to seek. Works in both self and
1626
+ * external audio modes. Opt out with `accessibleSeek: false`.
1627
+ * @private
1628
+ */
1629
+ initSeekControl() {
1630
+ if (!this.options.accessibleSeek) return;
1631
+ this.seekEl = this.container.querySelector(".waveform-container");
1632
+ if (!this.seekEl) return;
1633
+ this.seekEl.setAttribute("role", "slider");
1634
+ this.seekEl.setAttribute("tabindex", "0");
1635
+ this.seekEl.setAttribute("aria-valuemin", "0");
1636
+ this.applySeekLabel();
1637
+ this.updateSeekAccessibility();
1638
+ this.seekEl.addEventListener("keydown", (e) => {
1639
+ if (e.key === " " || e.key === "Spacebar") {
1640
+ e.preventDefault();
1641
+ e.stopPropagation();
1642
+ this.togglePlay();
1643
+ return;
1644
+ }
1645
+ const duration = this.getSeekDuration();
1646
+ if (!duration) return;
1647
+ const current = this.getSeekCurrentTime();
1648
+ let target;
1649
+ switch (e.key) {
1650
+ case "ArrowLeft":
1651
+ case "ArrowDown":
1652
+ target = current - SEEK_STEP_SECONDS;
1653
+ break;
1654
+ case "ArrowRight":
1655
+ case "ArrowUp":
1656
+ target = current + SEEK_STEP_SECONDS;
1657
+ break;
1658
+ case "PageDown":
1659
+ target = current - SEEK_PAGE_SECONDS;
1660
+ break;
1661
+ case "PageUp":
1662
+ target = current + SEEK_PAGE_SECONDS;
1663
+ break;
1664
+ case "Home":
1665
+ target = 0;
1666
+ break;
1667
+ case "End":
1668
+ target = duration;
1669
+ break;
1670
+ default:
1671
+ return;
1672
+ }
1673
+ e.preventDefault();
1674
+ e.stopPropagation();
1675
+ this.seekToSeconds(target);
1676
+ }, { signal: this._ac.signal });
1677
+ }
1678
+ /**
1679
+ * Total seekable duration in seconds, regardless of audio mode.
1680
+ * @returns {number}
1681
+ * @private
1682
+ */
1683
+ getSeekDuration() {
1684
+ if (this.options.audioMode === "external") {
1685
+ return this._extDuration || 0;
1686
+ }
1687
+ return this.audio && Number.isFinite(this.audio.duration) ? this.audio.duration : 0;
1688
+ }
1689
+ /**
1690
+ * Current playback position in seconds, regardless of audio mode.
1691
+ * @returns {number}
1692
+ * @private
1693
+ */
1694
+ getSeekCurrentTime() {
1695
+ if (this.options.audioMode === "external") {
1696
+ return this.progress * (this._extDuration || 0);
1697
+ }
1698
+ return this.audio && Number.isFinite(this.audio.currentTime) ? this.audio.currentTime : 0;
1699
+ }
1700
+ /**
1701
+ * Seek the slider to an absolute time, clamped to the track length.
1702
+ *
1703
+ * In self mode this defers to {@link WaveformPlayer#seekTo}. In external
1704
+ * mode it dispatches a cancelable `waveformplayer:request-seek` event with
1705
+ * the target percentage; if the controller doesn't `preventDefault()`, the
1706
+ * local progress/visual is updated optimistically. Either way the ARIA
1707
+ * slider values are refreshed.
1708
+ * @param {number} seconds - Target time in seconds.
1709
+ * @private
1710
+ * @fires WaveformPlayer#waveformplayer:request-seek
1711
+ */
1712
+ seekToSeconds(seconds) {
1713
+ const duration = this.getSeekDuration();
1714
+ if (!duration) return;
1715
+ const clamped = clamp(seconds, 0, duration);
1716
+ if (this.options.audioMode === "external") {
1717
+ this._requestSeek(clamped / duration);
1718
+ this.updateSeekAccessibility();
1719
+ return;
1720
+ }
1721
+ this.seekTo(clamped);
1722
+ }
1723
+ /**
1724
+ * Set the slider's accessible name from `seekLabel`, falling back to the
1725
+ * track title, then a generic 'Seek'. No-op if the slider isn't present.
1726
+ * @param {string} [title=this.options.title] - Track title to fall back to
1727
+ * when `seekLabel` is not set.
1728
+ * @private
1729
+ */
1730
+ applySeekLabel(title = this.options.title) {
1731
+ if (!this.seekEl) return;
1732
+ const label = this.options.seekLabel || title || "Seek";
1733
+ this.seekEl.setAttribute("aria-label", label);
1734
+ }
1735
+ /**
1736
+ * Keep the slider's ARIA value attributes in sync with playback.
1737
+ * @private
1738
+ */
1739
+ updateSeekAccessibility() {
1740
+ if (!this.seekEl) return;
1741
+ const duration = this.getSeekDuration();
1742
+ const current = Math.min(this.getSeekCurrentTime(), duration);
1743
+ this.seekEl.setAttribute("aria-valuemax", String(Math.round(duration)));
1744
+ this.seekEl.setAttribute("aria-valuenow", String(Math.round(current)));
1745
+ this.seekEl.setAttribute(
1746
+ "aria-valuetext",
1747
+ formatSeekValueText(
1748
+ this.options.seekValueText || "%1$s of %2$s",
1749
+ formatTime(current),
1750
+ formatTime(duration)
1751
+ )
1752
+ );
1753
+ }
1754
+ /**
1755
+ * Initialize Media Session API for system media controls
1756
+ * @private
1757
+ */
1758
+ initMediaSession() {
1759
+ if (!("mediaSession" in navigator) || !this.options.enableMediaSession) return;
1760
+ if (!this.audio) return;
1761
+ this._applyMediaMetadata();
1762
+ navigator.mediaSession.setActionHandler("play", () => this.play());
1763
+ navigator.mediaSession.setActionHandler("pause", () => this.pause());
1764
+ navigator.mediaSession.setActionHandler("seekbackward", () => {
1765
+ this.seekTo(clamp(this.audio.currentTime - 10, 0, this.audio.duration));
1766
+ });
1767
+ navigator.mediaSession.setActionHandler("seekforward", () => {
1768
+ this.seekTo(clamp(this.audio.currentTime + 10, 0, this.audio.duration));
1769
+ });
1770
+ navigator.mediaSession.setActionHandler("seekto", (details) => {
1771
+ if (details.seekTime !== null) {
1772
+ this.seekTo(details.seekTime);
1773
+ }
1774
+ });
1775
+ const onNext = this.options.onNextTrack, onPrev = this.options.onPreviousTrack;
1776
+ try {
1777
+ navigator.mediaSession.setActionHandler("nexttrack", typeof onNext === "function" ? () => onNext(this) : null);
1778
+ } catch (e) {
1779
+ }
1780
+ try {
1781
+ navigator.mediaSession.setActionHandler("previoustrack", typeof onPrev === "function" ? () => onPrev(this) : null);
1782
+ } catch (e) {
1783
+ }
1784
+ }
1785
+ /**
1786
+ * Publish the current track's Media Session metadata (lock-screen /
1787
+ * Now-Playing title, artist, album, artwork). Idempotent — safe to re-call.
1788
+ * @private
1789
+ */
1790
+ _applyMediaMetadata() {
1791
+ if (!("mediaSession" in navigator) || !this.options.enableMediaSession) return;
1792
+ navigator.mediaSession.metadata = new MediaMetadata({
1793
+ title: this.options.title || this.options.unknownTrackText,
1794
+ artist: this.options.artist || "",
1795
+ album: this.options.album || "",
1796
+ artwork: this.options.artwork ? [
1797
+ { src: this.options.artwork, sizes: "512x512", type: "image/jpeg" }
1798
+ ] : []
1799
+ });
1800
+ }
1801
+ /**
1802
+ * Sync Media Session playback state + scrubber position on play/pause. iOS
1803
+ * ignores metadata set before the media is active, so we re-assert it on
1804
+ * play — that's what fixes the blank lock-screen card on mobile.
1805
+ * @param {'playing'|'paused'} state
1806
+ * @private
1807
+ */
1808
+ _updateMediaSession(state) {
1809
+ if (!("mediaSession" in navigator) || !this.options.enableMediaSession || !this.audio) return;
1810
+ try {
1811
+ if (state === "playing") this.initMediaSession();
1812
+ navigator.mediaSession.playbackState = state;
1813
+ const d = this.audio.duration;
1814
+ if (navigator.mediaSession.setPositionState && d && isFinite(d)) {
1815
+ navigator.mediaSession.setPositionState({
1816
+ duration: d,
1817
+ playbackRate: this.audio.playbackRate || 1,
1818
+ position: clamp(this.audio.currentTime, 0, d)
1819
+ });
1820
+ }
1821
+ } catch (e) {
1822
+ }
1823
+ }
1824
+ // ============================================
1825
+ // Event Binding
1826
+ // ============================================
1827
+ /**
1828
+ * Bind the core interaction listeners: play-button click, the `<audio>`
1829
+ * media events (self mode only — external mode is fed state via
1830
+ * {@link WaveformPlayer#setPlayingState}/{@link WaveformPlayer#setProgress}),
1831
+ * canvas click-to-seek, and a debounced window-resize redraw.
1832
+ * @private
1833
+ */
1834
+ bindEvents() {
1835
+ if (this.playBtn) {
1836
+ this.playBtn.addEventListener("click", () => this.togglePlay());
1837
+ }
1838
+ if (this.audio) {
1839
+ this.audio.addEventListener("loadstart", () => this.setLoading(true));
1840
+ this.audio.addEventListener("loadedmetadata", () => this.onMetadataLoaded());
1841
+ this.audio.addEventListener("canplay", () => this.setLoading(false));
1842
+ this.audio.addEventListener("play", () => this.onPlay());
1843
+ this.audio.addEventListener("pause", () => this.onPause());
1844
+ this.audio.addEventListener("ended", () => this.onEnded());
1845
+ this.audio.addEventListener("error", (e) => this.onError(e));
1846
+ }
1847
+ this.canvas.addEventListener("click", (e) => this.handleCanvasClick(e));
1848
+ this._dragging = false;
1849
+ this._seekHover = false;
1850
+ this._handleNear = false;
1851
+ this.canvas.addEventListener("pointerenter", () => {
1852
+ this._seekHover = true;
1853
+ this.drawWaveform();
1854
+ this._updateSeekHandle();
1855
+ });
1856
+ this.canvas.addEventListener("pointerleave", () => {
1857
+ this._seekHover = false;
1858
+ this._handleNear = false;
1859
+ if (!this._dragging) this._hideHoverTip();
1860
+ this.drawWaveform();
1861
+ this._updateSeekHandle();
1862
+ });
1863
+ this.canvas.addEventListener("pointerdown", (e) => {
1864
+ if (e.pointerType === "mouse" && e.button !== 0) return;
1865
+ this._dragging = true;
1866
+ try {
1867
+ this.canvas.setPointerCapture(e.pointerId);
1868
+ } catch (err) {
1869
+ }
1870
+ this._scrubTo(e.clientX);
1871
+ });
1872
+ this.canvas.addEventListener("pointermove", (e) => {
1873
+ if (this._dragging) {
1874
+ this._scrubTo(e.clientX);
1875
+ return;
1876
+ }
1877
+ const rect = this.canvas.getBoundingClientRect();
1878
+ if (rect.width) {
1879
+ this._handleNear = Math.abs(e.clientX - rect.left - this.progress * rect.width) <= 10;
1880
+ this._updateSeekHandle();
1881
+ }
1882
+ });
1883
+ const endDrag = (e) => {
1884
+ if (!this._dragging) return;
1885
+ this._dragging = false;
1886
+ this._suppressClick = true;
1887
+ try {
1888
+ this.canvas.releasePointerCapture(e.pointerId);
1889
+ } catch (err) {
1890
+ }
1891
+ this._seekFromPointer(e.clientX);
1892
+ if (!this._seekHover && !this.options.showHoverTime) this._hideHoverTip();
1893
+ this._updateSeekHandle();
1894
+ };
1895
+ this.canvas.addEventListener("pointerup", endDrag);
1896
+ this.canvas.addEventListener("pointercancel", endDrag);
1897
+ this.setupHoverTime();
1898
+ this.setupSeekHandle();
1899
+ this.resizeHandler = debounce(() => this.resizeCanvas(), 100);
1900
+ window.addEventListener("resize", this.resizeHandler);
1901
+ }
1902
+ /**
1903
+ * Observe the canvas's parent element for size changes and re-fit the
1904
+ * canvas on each one. No-op where `ResizeObserver` is unavailable.
1905
+ * @private
1906
+ */
1907
+ setupResizeObserver() {
1908
+ if ("ResizeObserver" in window) {
1909
+ this.resizeObserver = new ResizeObserver(() => {
1910
+ this.resizeCanvas();
1911
+ });
1912
+ if (this.canvas?.parentElement) {
1913
+ this.resizeObserver.observe(this.canvas.parentElement);
1914
+ }
1915
+ }
1916
+ }
1917
+ // ============================================
1918
+ // Audio Loading
1919
+ // ============================================
1920
+ /**
1921
+ * Load an audio source: set the title, fetch/generate the waveform peaks,
1922
+ * draw them, render markers, and initialise Media Session.
1923
+ *
1924
+ * In self mode the `<audio>` src is assigned and the method awaits
1925
+ * `loadedmetadata` before proceeding. In external mode there is no audio
1926
+ * element, so the src/metadata step is skipped and only the visualization
1927
+ * is built (duration/time come from the controller via
1928
+ * {@link WaveformPlayer#setProgress}). The title and the seek slider's
1929
+ * accessible name are written *before* the metadata wait, as are peaks
1930
+ * supplied via the `waveform` option — none of them need anything from the
1931
+ * audio element, and behind the wait they blink in on a slow origin.
1932
+ * Without inline peaks the waveform is decoded from the audio instead; a
1933
+ * decode failure falls back to a placeholder. The `onLoad` callback fires
1934
+ * on success.
1935
+ * @param {string} url - Audio URL.
1936
+ * @returns {Promise<void>} Resolves once loading settles (errors are caught
1937
+ * internally and surfaced through {@link WaveformPlayer#onError}).
1938
+ */
1939
+ async load(url) {
1940
+ try {
1941
+ this.setLoading(true);
1942
+ this.progress = 0;
1943
+ this.hasError = false;
1944
+ this.container.classList.remove("waveform-is-placeholder");
1945
+ this.options.url = url;
1946
+ const hasInlinePeaks = !!this.options.waveform;
1947
+ if (hasInlinePeaks) {
1948
+ this.setWaveformData(this.options.waveform);
1949
+ }
1950
+ const title = this.options.title || extractTitleFromUrl(url);
1951
+ if (this.titleEl) {
1952
+ this.titleEl.textContent = title;
1953
+ }
1954
+ this.applySeekLabel(title);
1955
+ if (this.audio) {
1956
+ this.audio.src = url;
1957
+ if (this.audio.preload !== "none") {
1958
+ await new Promise((resolve, reject) => {
1959
+ const metadataHandler = () => {
1960
+ this.audio.removeEventListener("loadedmetadata", metadataHandler);
1961
+ this.audio.removeEventListener("error", errorHandler);
1962
+ resolve();
1963
+ };
1964
+ const errorHandler = (e) => {
1965
+ this.audio.removeEventListener("loadedmetadata", metadataHandler);
1966
+ this.audio.removeEventListener("error", errorHandler);
1967
+ reject(e);
1968
+ };
1969
+ this.audio.addEventListener("loadedmetadata", metadataHandler);
1970
+ this.audio.addEventListener("error", errorHandler);
1971
+ });
1972
+ }
1973
+ }
1974
+ if (!hasInlinePeaks) {
1975
+ try {
1976
+ const result = await generateWaveform(url, this.options.samples, this.options.showBPM);
1977
+ this.waveformData = result.peaks;
1978
+ if (result.bpm) {
1979
+ this.detectedBPM = result.bpm;
1980
+ this.updateBPMDisplay();
1981
+ }
1982
+ } catch (error) {
1983
+ console.warn("[WaveformPlayer] Using placeholder waveform:", error);
1984
+ this.waveformData = generatePlaceholderWaveform(this.options.samples);
1985
+ this.container.classList.add("waveform-is-placeholder");
1986
+ }
1987
+ }
1988
+ this.drawWaveform();
1989
+ this.renderMarkers();
1990
+ if (this.options.onLoad) {
1991
+ this.options.onLoad(this);
1992
+ }
1993
+ } catch (error) {
1994
+ this.onError(error);
1995
+ } finally {
1996
+ this.setLoading(false);
1997
+ }
1998
+ }
1999
+ /**
2000
+ * Swap the player to a new track at runtime.
2001
+ *
2002
+ * Pauses any current playback, fully resets the audio element (self mode),
2003
+ * clears error/marker/progress state, merges the new metadata into
2004
+ * `this.options`, updates the artist/artwork DOM, then calls
2005
+ * {@link WaveformPlayer#load}. Auto-plays the new track unless
2006
+ * `options.autoplay === false`.
2007
+ * @param {string} url - Audio URL.
2008
+ * @param {string|null} [title=null] - Track title; keeps the existing
2009
+ * title when null.
2010
+ * @param {string|null} [artist=null] - Track artist; pass `''` to hide
2011
+ * the artist row, or null to keep the existing one.
2012
+ * @param {Object} [options={}] - Additional options to merge (e.g.
2013
+ * `preload`, `artwork`, `artworkAlt`, `markers`, `autoplay`).
2014
+ * @returns {Promise<void>}
2015
+ */
2016
+ async loadTrack(url, title = null, artist = null, options = {}) {
2017
+ const hasArtworkOption = Object.prototype.hasOwnProperty.call(options, "artwork");
2018
+ const hasArtworkAltOption = Object.prototype.hasOwnProperty.call(options, "artworkAlt");
2019
+ if (this.isPlaying) {
2020
+ this.pause();
2021
+ }
2022
+ if (this.audio) {
2023
+ this.audio.src = "";
2024
+ this.audio.load();
2025
+ }
2026
+ this.hasError = false;
2027
+ if (this.errorEl) {
2028
+ this.errorEl.style.display = "none";
2029
+ }
2030
+ if (this.canvas) {
2031
+ this.canvas.style.opacity = "1";
2032
+ }
2033
+ if (this.playBtn) {
2034
+ this.playBtn.disabled = false;
2035
+ }
2036
+ this.progress = 0;
2037
+ this.waveformData = [];
2038
+ this.options = normalizeOptions(mergeOptions(this.options, {
2039
+ url,
2040
+ title: title === null ? this.options.title : title,
2041
+ artist: artist === null ? this.options.artist : artist,
2042
+ ...options
2043
+ }));
2044
+ if (hasArtworkOption) {
2045
+ this.options.artwork = options.artwork || null;
2046
+ }
2047
+ if (hasArtworkAltOption) {
2048
+ this.options.artworkAlt = options.artworkAlt || "";
2049
+ } else if (hasArtworkOption) {
2050
+ this.options.artworkAlt = this.options.artwork ? DEFAULT_OPTIONS.artworkAlt : "";
2051
+ }
2052
+ if (options.preload && this.audio) {
2053
+ this.audio.preload = this.options.preload;
2054
+ }
2055
+ if (options.crossOrigin && this.audio) {
2056
+ this.audio.crossOrigin = this.options.crossOrigin;
2057
+ }
2058
+ if (artist !== null) {
2059
+ this.syncArtist(artist);
2060
+ }
2061
+ if (hasArtworkOption || hasArtworkAltOption) {
2062
+ this.syncArtwork(
2063
+ hasArtworkOption ? options.artwork : this.options.artwork,
2064
+ hasArtworkAltOption ? options.artworkAlt : this.options.artworkAlt
2065
+ );
2066
+ }
2067
+ this.options.markers = options.markers ? normalizeMarkers(options.markers) : [];
2068
+ this.options.waveform = options.waveform || null;
2069
+ await this.load(url);
2070
+ if (options.autoplay !== false) {
2071
+ this.play()?.catch(() => {
2072
+ });
2073
+ }
2074
+ }
2075
+ // ============================================
2076
+ // Visualization
2077
+ // ============================================
2078
+ /**
2079
+ * Normalise externally-supplied waveform data into `this.waveformData` and
2080
+ * redraw.
2081
+ *
2082
+ * Accepts several shapes: a `.json` URL (fetched async; peaks and any
2083
+ * embedded `markers` are applied on resolve), a JSON-encoded array string,
2084
+ * a comma-separated number string, or a plain number array. Malformed
2085
+ * input degrades to an empty array rather than throwing.
2086
+ * @param {string|number[]} data - Peaks as an array, a JSON/CSV string, or
2087
+ * a URL to a `.json` peaks file.
2088
+ * @private
2089
+ */
2090
+ setWaveformData(data) {
2091
+ if (typeof data === "string" && data.trim().endsWith(".json")) {
2092
+ fetch(data.trim()).then((r) => r.json()).then((json) => {
2093
+ this.waveformData = Array.isArray(json) ? json : json.peaks || [];
2094
+ if (json.markers && !this.options.markers?.length) {
2095
+ this.options.markers = normalizeMarkers(json.markers);
2096
+ this.renderMarkers();
2097
+ }
2098
+ this.drawWaveform();
2099
+ }).catch(() => {
2100
+ });
2101
+ return;
2102
+ }
2103
+ this.waveformData = toNumberArray(data, { fallback: [] });
2104
+ this.drawWaveform();
2105
+ }
2106
+ /**
2107
+ * Render the current waveform + progress to the canvas via the shared
2108
+ * {@link draw} routine, passing the resolved style and colours. No-op
2109
+ * before the context exists or while there is no peak data.
2110
+ * @private
2111
+ */
2112
+ drawWaveform() {
2113
+ if (!this.ctx || this.waveformData.length === 0) return;
2114
+ draw(this.ctx, this.canvas, this.waveformData, this.progress, {
2115
+ ...this.options,
2116
+ waveformStyle: this.options.waveformStyle || "bars",
2117
+ color: this.options.waveformColor,
2118
+ progressColor: this.options.progressColor,
2119
+ seekActive: this._seekHover || this._dragging
2120
+ });
2121
+ }
2122
+ /**
2123
+ * Re-fit the canvas backing store to its parent's width and the configured
2124
+ * height, scaled by the device pixel ratio for crisp rendering, then
2125
+ * redraw. Guards against running after destruction.
2126
+ * @private
2127
+ */
2128
+ resizeCanvas() {
2129
+ if (!this.canvas || this.isDestroying) {
2130
+ return;
2131
+ }
2132
+ const dpr = window.devicePixelRatio || 1;
2133
+ const rect = this.canvas.parentElement.getBoundingClientRect();
2134
+ this.canvas.width = rect.width * dpr;
2135
+ this.canvas.height = this.options.height * dpr;
2136
+ this.canvas.parentElement.style.height = this.options.height + "px";
2137
+ this.drawWaveform();
2138
+ }
2139
+ /**
2140
+ * Render the configured cue markers as positioned, clickable buttons over
2141
+ * the waveform.
2142
+ *
2143
+ * Clears any existing markers first, then bails out unless `showMarkers` is
2144
+ * on, markers exist, and a duration is known (via the mode-agnostic
2145
+ * {@link WaveformPlayer#getSeekDuration}). Each marker is placed by its
2146
+ * time-as-percentage, carries a tooltip and ARIA label, and seeks on click
2147
+ * (also starting playback when `playOnSeek` is set and currently paused).
2148
+ * Markers past the track duration are skipped with a warning.
2149
+ * @private
2150
+ */
2151
+ renderMarkers() {
2152
+ if (!this.markersContainer) return;
2153
+ this.markersContainer.innerHTML = "";
2154
+ this._activeMarkerIndex = -1;
2155
+ clearTimeout(this._markerLabelTimer);
2156
+ if (!this.options.showMarkers || !this.options.markers?.length) return;
2157
+ const duration = this.getSeekDuration();
2158
+ if (!duration) {
2159
+ return;
2160
+ }
2161
+ this.options.markers.forEach((marker, index) => {
2162
+ if (marker.time > duration) {
2163
+ console.warn(`[WaveformPlayer] Marker "${marker.label}" at ${marker.time}s exceeds audio duration of ${duration}s`);
2164
+ return;
2165
+ }
2166
+ const position = marker.time / duration * 100;
2167
+ const markerEl = document.createElement("button");
2168
+ markerEl.className = "waveform-marker";
2169
+ markerEl.style.left = `${position}%`;
2170
+ markerEl.style.backgroundColor = marker.color || "rgba(255, 255, 255, 0.5)";
2171
+ markerEl.setAttribute("aria-label", marker.label);
2172
+ markerEl.setAttribute("data-time", marker.time);
2173
+ const tooltip = document.createElement("span");
2174
+ tooltip.className = "waveform-marker-tooltip";
2175
+ tooltip.textContent = marker.label;
2176
+ markerEl.appendChild(tooltip);
2177
+ markerEl.addEventListener("click", (e) => {
2178
+ e.stopPropagation();
2179
+ this.seekTo(marker.time);
2180
+ if (this.options.playOnSeek && !this.isPlaying) {
2181
+ this.play();
2182
+ }
2183
+ });
2184
+ this.markersContainer.appendChild(markerEl);
2185
+ });
2186
+ }
2187
+ /**
2188
+ * Highlight the marker at `index` (toggling an `active` class) and clear
2189
+ * the rest. Pass `null` to clear all. Lets an external controller (e.g. a
2190
+ * DJ bar) reflect the current section without reaching into the player's
2191
+ * private marker DOM.
2192
+ * @param {number|null} index - Marker index to activate, or `null` to clear.
2193
+ */
2194
+ setActiveMarker(index) {
2195
+ if (!this.markersContainer) return;
2196
+ const markers = this.markersContainer.querySelectorAll(".waveform-marker");
2197
+ markers.forEach((el, i) => el.classList.toggle("active", i === index));
2198
+ }
2199
+ /**
2200
+ * Highlight the marker the playhead has most recently passed — the rendered
2201
+ * marker with the greatest `time` ≤ the current time — and reveal its label.
2202
+ * Driven from the progress loop; a no-op when there are no markers. Reuses
2203
+ * {@link WaveformPlayer#setActiveMarker}, and only re-applies when the active
2204
+ * marker actually changes.
2205
+ * @private
2206
+ */
2207
+ updateActiveMarker() {
2208
+ if (!this.markersContainer) return;
2209
+ const els = this.markersContainer.querySelectorAll(".waveform-marker");
2210
+ if (!els.length) return;
2211
+ const dur = this.getSeekDuration();
2212
+ const t = dur ? this.progress * dur : 0;
2213
+ let active = -1;
2214
+ let best = -Infinity;
2215
+ els.forEach((el, i) => {
2216
+ const mt = parseFloat(el.getAttribute("data-time"));
2217
+ if (Number.isFinite(mt) && mt <= t + 0.05 && mt > best) {
2218
+ best = mt;
2219
+ active = i;
2220
+ }
2221
+ });
2222
+ if (active !== this._activeMarkerIndex) {
2223
+ this._activeMarkerIndex = active;
2224
+ this.setActiveMarker(active);
2225
+ clearTimeout(this._markerLabelTimer);
2226
+ els.forEach((el, i) => el.classList.toggle("show-label", i === active));
2227
+ if (active >= 0) {
2228
+ this._markerLabelTimer = setTimeout(() => {
2229
+ this.markersContainer?.querySelectorAll(".waveform-marker").forEach((el) => el.classList.remove("show-label"));
2230
+ }, 2500);
2231
+ }
2232
+ }
2233
+ }
2234
+ /**
2235
+ * Build the time tooltip that follows the pointer over the waveform. The
2236
+ * element is always created so **drag-scrub** can show the time you're
2237
+ * dragging to; the *hover* reveal is gated on `showHoverTime`. Works in both
2238
+ * self and external modes (it only needs {@link WaveformPlayer#getSeekDuration}).
2239
+ * @private
2240
+ */
2241
+ setupHoverTime() {
2242
+ if (!this.seekEl) return;
2243
+ const tip = document.createElement("div");
2244
+ tip.className = "waveform-hover-time";
2245
+ tip.setAttribute("aria-hidden", "true");
2246
+ this.seekEl.appendChild(tip);
2247
+ this.hoverTimeEl = tip;
2248
+ if (!this.options.showHoverTime) return;
2249
+ this.seekEl.addEventListener("pointermove", (e) => {
2250
+ if (!this._dragging) this._updateHoverTip(e.clientX);
2251
+ });
2252
+ this.seekEl.addEventListener("pointerleave", () => {
2253
+ if (!this._dragging) this._hideHoverTip();
2254
+ });
2255
+ }
2256
+ /**
2257
+ * Position + fill the hover-time tooltip for a given client-X. Shared by
2258
+ * hover and drag-scrub. No-op when the tooltip isn't enabled
2259
+ * (`showHoverTime` off).
2260
+ * @param {number} clientX - Pointer client-X coordinate.
2261
+ * @private
2262
+ */
2263
+ _updateHoverTip(clientX) {
2264
+ const tip = this.hoverTimeEl;
2265
+ if (!tip) return;
2266
+ const dur = this.getSeekDuration();
2267
+ if (!dur) {
2268
+ tip.style.opacity = "0";
2269
+ return;
2270
+ }
2271
+ const rect = this.canvas.getBoundingClientRect();
2272
+ const pct = clamp((clientX - rect.left) / rect.width);
2273
+ tip.textContent = formatTime(pct * dur);
2274
+ tip.style.left = pct * 100 + "%";
2275
+ tip.style.opacity = "1";
2276
+ }
2277
+ /** Hide the hover-time tooltip. @private */
2278
+ _hideHoverTip() {
2279
+ if (this.hoverTimeEl) this.hoverTimeEl.style.opacity = "0";
2280
+ }
2281
+ /**
2282
+ * Visually preview a seek during a drag — moves the playhead + handle +
2283
+ * tooltip to the cursor WITHOUT touching the audio (playback continues; the
2284
+ * real seek is committed on release).
2285
+ * @param {number} clientX - Pointer client-X coordinate.
2286
+ * @private
2287
+ */
2288
+ _scrubTo(clientX) {
2289
+ const rect = this.canvas.getBoundingClientRect();
2290
+ if (!rect.width) return;
2291
+ this.progress = clamp((clientX - rect.left) / rect.width);
2292
+ this.drawWaveform();
2293
+ this._updateSeekHandle();
2294
+ const dur = this.getSeekDuration();
2295
+ if (dur && this.currentTimeEl) {
2296
+ this.currentTimeEl.textContent = formatTime(this.progress * dur);
2297
+ this._hideHoverTip();
2298
+ } else {
2299
+ this._updateHoverTip(clientX);
2300
+ }
2301
+ }
2302
+ /**
2303
+ * Create the draggable seek handle — a DOM circle over the playhead, shown
2304
+ * only on hover / drag (Spotify-style). Pointer-events are off so it never
2305
+ * blocks the canvas scrub; size + visibility are CSS.
2306
+ * @private
2307
+ */
2308
+ setupSeekHandle() {
2309
+ if (!this.options.seekHandle || this.options.waveformStyle !== "seekbar" || !this.seekEl) return;
2310
+ const h = document.createElement("div");
2311
+ h.className = "waveform-seek-handle";
2312
+ h.setAttribute("aria-hidden", "true");
2313
+ this.seekEl.appendChild(h);
2314
+ this.seekHandleEl = h;
2315
+ }
2316
+ /**
2317
+ * Position the seek handle at the current progress and toggle its
2318
+ * visibility (hover / drag) + expanded (drag / direct-hover) classes.
2319
+ * @private
2320
+ */
2321
+ _updateSeekHandle() {
2322
+ const h = this.seekHandleEl;
2323
+ if (!h) return;
2324
+ h.style.left = this.progress * 100 + "%";
2325
+ h.classList.toggle("is-visible", this._seekHover || this._dragging);
2326
+ h.classList.toggle("is-active", this._dragging || this._handleNear);
2327
+ }
2328
+ // ============================================
2329
+ // Event Handlers
2330
+ // ============================================
2331
+ /**
2332
+ * Seek to the clicked horizontal position on the waveform canvas.
2333
+ *
2334
+ * Converts the click X into a 0..1 percentage. In external mode it
2335
+ * dispatches a cancelable `waveformplayer:request-seek` event (updating the
2336
+ * local visual optimistically unless the controller vetoes it); in self
2337
+ * mode it seeks the owned `<audio>` via
2338
+ * {@link WaveformPlayer#seekToPercent}.
2339
+ * @param {MouseEvent} event - The canvas click event.
2340
+ * @private
2341
+ * @fires WaveformPlayer#waveformplayer:request-seek
2342
+ */
2343
+ handleCanvasClick(event) {
2344
+ if (this._suppressClick) {
2345
+ this._suppressClick = false;
2346
+ return;
2347
+ }
2348
+ this._seekFromPointer(event.clientX);
2349
+ }
2350
+ /**
2351
+ * Seek to a horizontal client-X position over the canvas — shared by
2352
+ * click and drag. In external mode the player has no audio of its own,
2353
+ * so it dispatches a cancelable `waveformplayer:request-seek` with the
2354
+ * target percentage (updating the local visual optimistically); in self
2355
+ * mode it seeks the owned `<audio>` via
2356
+ * {@link WaveformPlayer#seekToPercent}.
2357
+ * @param {number} clientX - Pointer client-X coordinate.
2358
+ * @private
2359
+ * @fires WaveformPlayer#waveformplayer:request-seek
2360
+ */
2361
+ _seekFromPointer(clientX) {
2362
+ const rect = this.canvas.getBoundingClientRect();
2363
+ if (!rect.width) return;
2364
+ const targetPercent = clamp((clientX - rect.left) / rect.width);
2365
+ if (this.options.audioMode === "external") {
2366
+ this._requestSeek(targetPercent);
2367
+ return;
2368
+ }
2369
+ if (!this.audio || !this.audio.duration) return;
2370
+ this.seekToPercent(targetPercent);
2371
+ }
2372
+ /**
2373
+ * Toggle the loading state: show/hide the spinner overlay and set
2374
+ * `aria-busy` on the accessible seek slider so assistive tech knows the
2375
+ * player is fetching/decoding.
2376
+ * @param {boolean} loading - True while audio is loading.
2377
+ * @private
2378
+ */
2379
+ setLoading(loading) {
2380
+ this.isLoading = loading;
2381
+ if (this.loadingEl) {
2382
+ const showIndicator = loading && this.waveformData.length === 0;
2383
+ this.loadingEl.style.display = showIndicator ? "block" : "none";
2384
+ }
2385
+ if (this.seekEl) {
2386
+ this.seekEl.setAttribute("aria-busy", loading ? "true" : "false");
2387
+ }
2388
+ }
2389
+ /**
2390
+ * `loadedmetadata` handler (self mode): write the total-time display, now
2391
+ * that duration is known re-render markers, and publish duration to the
2392
+ * accessible seek slider. No-op during destruction.
2393
+ * @private
2394
+ */
2395
+ onMetadataLoaded() {
2396
+ if (this.isDestroying) return;
2397
+ if (this.totalTimeEl) {
2398
+ this.totalTimeEl.textContent = formatTime(this.audio.duration);
2399
+ }
2400
+ this.renderMarkers();
2401
+ this.updateSeekAccessibility();
2402
+ }
2403
+ /**
2404
+ * Reflect play/pause state on the transport button: toggle the `playing`
2405
+ * class and swap the play/pause icon visibility. The single source of
2406
+ * truth shared by `onPlay`, `onPause`, and the external-mode
2407
+ * `setPlayingState` pump so they can't drift. No-op without a button.
2408
+ * @param {boolean} isPlaying - Whether playback is active.
2409
+ * @private
2410
+ */
2411
+ setPlayButtonState(isPlaying) {
2412
+ if (!this.playBtn) return;
2413
+ this.playBtn.classList.toggle("playing", isPlaying);
2414
+ const playIcon = this.playBtn.querySelector(".waveform-icon-play");
2415
+ const pauseIcon = this.playBtn.querySelector(".waveform-icon-pause");
2416
+ if (playIcon) playIcon.style.display = isPlaying ? "none" : "flex";
2417
+ if (pauseIcon) pauseIcon.style.display = isPlaying ? "flex" : "none";
2418
+ }
2419
+ /**
2420
+ * `play` handler (self mode): set the playing flag, swap the button to its
2421
+ * pause icon, start the smooth progress loop, dispatch
2422
+ * `waveformplayer:play`, and fire the `onPlay` callback. No-op during
2423
+ * destruction.
2424
+ * @private
2425
+ * @fires WaveformPlayer#waveformplayer:play
2426
+ */
2427
+ onPlay() {
2428
+ if (this.isDestroying) return;
2429
+ this.isPlaying = true;
2430
+ this.setPlayButtonState(true);
2431
+ this.startSmoothUpdate();
2432
+ this._updateMediaSession("playing");
2433
+ this._emit("waveformplayer:play", { player: this, url: this.options.url });
2434
+ if (this.options.onPlay) {
2435
+ this.options.onPlay(this);
2436
+ }
2437
+ }
2438
+ /**
2439
+ * `pause` handler (self mode): clear the playing flag, swap the button back
2440
+ * to its play icon, stop the smooth progress loop, dispatch
2441
+ * `waveformplayer:pause`, and fire the `onPause` callback. No-op during
2442
+ * destruction.
2443
+ * @private
2444
+ * @fires WaveformPlayer#waveformplayer:pause
2445
+ */
2446
+ onPause() {
2447
+ if (this.isDestroying) return;
2448
+ this.isPlaying = false;
2449
+ this.setPlayButtonState(false);
2450
+ this.stopSmoothUpdate();
2451
+ this._updateMediaSession("paused");
2452
+ this._emit("waveformplayer:pause", { player: this, url: this.options.url });
2453
+ if (this.options.onPause) {
2454
+ this.options.onPause(this);
2455
+ }
2456
+ }
2457
+ /**
2458
+ * `ended` handler (self mode): reset progress and `currentTime` to the
2459
+ * start, redraw, reset the time display, dispatch `waveformplayer:ended`
2460
+ * (carrying the final time), run {@link WaveformPlayer#onPause}, and fire
2461
+ * the `onEnd` callback. No-op during destruction.
2462
+ * @private
2463
+ * @fires WaveformPlayer#waveformplayer:ended
2464
+ */
2465
+ onEnded() {
2466
+ if (this.isDestroying) return;
2467
+ const duration = this.audio.duration;
2468
+ this.progress = 0;
2469
+ this.audio.currentTime = 0;
2470
+ this.drawWaveform();
2471
+ if (this.currentTimeEl) {
2472
+ this.currentTimeEl.textContent = "0:00";
2473
+ }
2474
+ this._emit("waveformplayer:ended", { player: this, url: this.options.url, currentTime: duration, duration });
2475
+ this.onPause();
2476
+ if (this.options.onEnd) {
2477
+ this.options.onEnd(this);
2478
+ }
2479
+ }
2480
+ /**
2481
+ * `error` handler: set the error flag, hide the spinner, reveal the error
2482
+ * overlay, dim the canvas, disable the play button, and fire the `onError`
2483
+ * callback. No-op during destruction.
2484
+ * @param {Event|Error} error - The audio error event, or an Error thrown
2485
+ * during loading.
2486
+ * @private
2487
+ */
2488
+ onError(error) {
2489
+ if (this.isDestroying) return;
2490
+ console.error("[WaveformPlayer] Audio error:", error);
2491
+ this.hasError = true;
2492
+ this.setLoading(false);
2493
+ if (this.errorEl) {
2494
+ this.errorEl.style.display = "flex";
2495
+ }
2496
+ if (this.canvas) {
2497
+ this.canvas.style.opacity = "0.2";
2498
+ }
2499
+ if (this.playBtn) {
2500
+ this.playBtn.disabled = true;
2501
+ }
2502
+ if (this.options.onError) {
2503
+ this.options.onError(error, this);
2504
+ }
2505
+ }
2506
+ // ============================================
2507
+ // Progress Updates
2508
+ // ============================================
2509
+ /**
2510
+ * Start the `requestAnimationFrame` loop that drives smooth progress
2511
+ * updates while playing (self mode only — external mode is redrawn by
2512
+ * controller {@link WaveformPlayer#setProgress} pushes). Cancels any
2513
+ * existing loop first so it's safe to call repeatedly.
2514
+ * @private
2515
+ */
2516
+ startSmoothUpdate() {
2517
+ this.stopSmoothUpdate();
2518
+ const update = () => {
2519
+ if (this.isPlaying && this.audio && this.audio.duration) {
2520
+ this.updateProgress();
2521
+ this.updateTimer = requestAnimationFrame(update);
2522
+ }
2523
+ };
2524
+ this.updateTimer = requestAnimationFrame(update);
2525
+ }
2526
+ /**
2527
+ * Cancel the smooth-update animation frame, if one is scheduled.
2528
+ * @private
2529
+ */
2530
+ stopSmoothUpdate() {
2531
+ if (this.updateTimer) {
2532
+ cancelAnimationFrame(this.updateTimer);
2533
+ this.updateTimer = null;
2534
+ }
2535
+ }
2536
+ /**
2537
+ * Recompute progress from the owned `<audio>` clock and reflect it
2538
+ * everywhere (self mode only — external mode uses
2539
+ * {@link WaveformPlayer#setProgress}).
2540
+ *
2541
+ * Redraws the canvas when progress moves meaningfully, updates the
2542
+ * current-time display, dispatches `waveformplayer:timeupdate`, fires the
2543
+ * `onTimeUpdate` callback, and refreshes the accessible slider values.
2544
+ * @private
2545
+ * @fires WaveformPlayer#waveformplayer:timeupdate
2546
+ */
2547
+ updateProgress() {
2548
+ if (!this.audio || !this.audio.duration) return;
2549
+ if (this._dragging) return;
2550
+ const newProgress = this.audio.currentTime / this.audio.duration;
2551
+ if (Math.abs(newProgress - this.progress) > 1e-3) {
2552
+ this.progress = newProgress;
2553
+ this.drawWaveform();
2554
+ this._updateSeekHandle();
2555
+ }
2556
+ if (this.currentTimeEl) {
2557
+ this.currentTimeEl.textContent = formatTime(this.audio.currentTime);
2558
+ }
2559
+ this._emit("waveformplayer:timeupdate", {
2560
+ player: this,
2561
+ currentTime: this.audio.currentTime,
2562
+ duration: this.audio.duration,
2563
+ progress: this.progress,
2564
+ url: this.options.url
2565
+ });
2566
+ if (this.options.onTimeUpdate) {
2567
+ this.options.onTimeUpdate(this.audio.currentTime, this.audio.duration, this);
2568
+ }
2569
+ this.updateActiveMarker();
2570
+ this.updateSeekAccessibility();
2571
+ }
2572
+ // ============================================
2573
+ // UI Updates
2574
+ // ============================================
2575
+ /**
2576
+ * Show the detected BPM in the badge, once a value has been detected.
2577
+ * @private
2578
+ */
2579
+ updateBPMDisplay() {
2580
+ const bpm = this.options.bpm || this.detectedBPM;
2581
+ if (this.bpmEl && this.bpmValueEl && bpm) {
2582
+ this.bpmValueEl.textContent = Math.round(bpm);
2583
+ this.bpmEl.style.display = "inline-flex";
2584
+ }
2585
+ }
2586
+ /**
2587
+ * Re-detect the page theme and re-apply auto colours + redraw, so an
2588
+ * auto-themed player adapts to a runtime light/dark switch (not just the
2589
+ * value present on load). No-op when the player uses an explicit
2590
+ * `colorPreset` or hand-set colours. Driven by the shared theme watcher.
2591
+ * @public
2592
+ */
2593
+ refreshTheme() {
2594
+ if (!this._autoTheme) return;
2595
+ this._scheme = detectColorScheme(this.container);
2596
+ const preset = getColorPreset(this.options.colorPreset, this.container);
2597
+ for (const key of this._presetKeys || []) {
2598
+ if (key in preset) this.options[key] = preset[key];
2599
+ }
2600
+ this._applyThemeColors();
2601
+ }
2602
+ /**
2603
+ * Sync the theme class (CSS drives the DOM chrome colours via `--wfp-*`
2604
+ * variables) and redraw the canvas with the resolved waveform colours.
2605
+ * @private
2606
+ */
2607
+ _applyThemeColors() {
2608
+ this.container.classList.toggle("waveform-theme-light", this._scheme === "light");
2609
+ if (this.canvas) this.drawWaveform();
2610
+ }
2611
+ /**
2612
+ * Lazily install ONE shared watcher that re-detects the theme for every
2613
+ * auto-themed instance when the document theme changes — a class/attribute
2614
+ * flip on `<html>`/`<body>` (Tailwind `dark`, `data-theme`,
2615
+ * `data-color-scheme`) or an OS `prefers-color-scheme` change. Event-driven
2616
+ * (MutationObserver + matchMedia), never a timer.
2617
+ * @private
2618
+ */
2619
+ static _watchTheme() {
2620
+ if (_WaveformPlayer._themeWatch || typeof document === "undefined") return;
2621
+ const refresh = () => requestAnimationFrame(() => {
2622
+ _WaveformPlayer.instances.forEach((p) => {
2623
+ try {
2624
+ p.refreshTheme();
2625
+ } catch (e) {
2626
+ }
2627
+ });
2628
+ });
2629
+ const opts = { attributes: true, attributeFilter: ["class", "data-theme", "data-color-scheme", "style"] };
2630
+ const obs = new MutationObserver(refresh);
2631
+ obs.observe(document.documentElement, opts);
2632
+ if (document.body) obs.observe(document.body, opts);
2633
+ let mq = null;
2634
+ try {
2635
+ mq = window.matchMedia("(prefers-color-scheme: dark)");
2636
+ mq.addEventListener("change", refresh);
2637
+ } catch (e) {
2638
+ }
2639
+ _WaveformPlayer._themeWatch = { obs, mq, refresh };
2640
+ }
2641
+ /**
2642
+ * Sync the speed control's label and the menu's active-option highlight to
2643
+ * the audio element's current `playbackRate`. No-op in external mode (no
2644
+ * owned `<audio>`), which also avoids reading `playbackRate` before the
2645
+ * element exists.
2646
+ * @private
2647
+ */
2648
+ updateSpeedUI() {
2649
+ if (!this.audio) return;
2650
+ const speedValue = this.container.querySelector(".speed-value");
2651
+ if (speedValue) {
2652
+ const rate = this.audio.playbackRate;
2653
+ speedValue.textContent = rate === 1 ? "1x" : `${rate}x`;
2654
+ }
2655
+ this.container.querySelectorAll(".speed-option").forEach((btn) => {
2656
+ const on = parseFloat(btn.dataset.rate) === this.audio.playbackRate;
2657
+ btn.classList.toggle("active", on);
2658
+ btn.setAttribute("aria-checked", on ? "true" : "false");
2659
+ });
2660
+ }
2661
+ // ============================================
2662
+ // Public API
2663
+ // ============================================
2664
+ /**
2665
+ * Play audio.
2666
+ *
2667
+ * In `audioMode: 'self'` (default): calls the underlying <audio>
2668
+ * element's play(). Returns the promise from HTMLMediaElement.play().
2669
+ *
2670
+ * In `audioMode: 'external'`: dispatches a cancelable
2671
+ * `waveformplayer:request-play` event with the track metadata and
2672
+ * does NOT touch any audio element. Returns `undefined`. An external
2673
+ * controller (e.g. WaveformBar) listens for this event and starts
2674
+ * playback on its own audio source, then pushes state back via
2675
+ * setPlayingState() / setProgress(). Calling preventDefault() on
2676
+ * the event lets the controller veto the play (state is unchanged).
2677
+ *
2678
+ * When `singlePlay` is enabled, any other currently-playing instance is
2679
+ * paused first.
2680
+ *
2681
+ * @return {Promise|undefined} The promise from `HTMLMediaElement.play()` in
2682
+ * self mode; `undefined` in external mode.
2683
+ * @fires WaveformPlayer#waveformplayer:request-play
2684
+ */
2685
+ play() {
2686
+ if (this.options.singlePlay && _WaveformPlayer.currentlyPlaying && _WaveformPlayer.currentlyPlaying !== this) {
2687
+ _WaveformPlayer.currentlyPlaying.pause();
2688
+ }
2689
+ if (this.options.audioMode === "external") {
2690
+ const evt = this._emit("waveformplayer:request-play", this._buildTrackDetail(), true);
2691
+ if (!evt.defaultPrevented) {
2692
+ _WaveformPlayer.currentlyPlaying = this;
2693
+ }
2694
+ return void 0;
2695
+ }
2696
+ _WaveformPlayer.currentlyPlaying = this;
2697
+ return this.audio.play();
2698
+ }
2699
+ /**
2700
+ * Pause audio.
2701
+ *
2702
+ * In `audioMode: 'external'`, dispatches `waveformplayer:request-pause`
2703
+ * (cancelable) and does NOT touch any audio element. See play().
2704
+ *
2705
+ * @fires WaveformPlayer#waveformplayer:request-pause
2706
+ */
2707
+ pause() {
2708
+ if (_WaveformPlayer.currentlyPlaying === this) {
2709
+ _WaveformPlayer.currentlyPlaying = null;
2710
+ }
2711
+ if (this.options.audioMode === "external") {
2712
+ this._emit("waveformplayer:request-pause", this._buildTrackDetail(), true);
2713
+ return;
2714
+ }
2715
+ this.audio.pause();
2716
+ }
2717
+ /**
2718
+ * Build the track detail object dispatched by request-play /
2719
+ * request-pause events in external audio mode. Mirrors the shape
2720
+ * WaveformBar.play() accepts so a controller can forward it
2721
+ * directly: `WaveformBar.play(event.detail)`.
2722
+ *
2723
+ * @private
2724
+ * @return {{url:string,title:?string,artist:?string,artwork:?string,player:WaveformPlayer}}
2725
+ */
2726
+ _buildTrackDetail() {
2727
+ return {
2728
+ url: this.options.url,
2729
+ title: this.options.title,
2730
+ artist: this.options.artist,
2731
+ artwork: this.options.artwork,
2732
+ markers: this.options.markers,
2733
+ waveform: this.options.waveform,
2734
+ id: this.id,
2735
+ player: this
2736
+ };
2737
+ }
2738
+ /**
2739
+ * External-mode state pump: flip the play/pause visual state without
2740
+ * touching audio. Mirrors what onPlay()/onPause() do but skips the
2741
+ * audio-element interactions. Safe to call repeatedly — idempotent.
2742
+ *
2743
+ * Only dispatches `waveformplayer:play`/`waveformplayer:pause` (and runs
2744
+ * the matching callback) on an actual transition, starting/stopping the
2745
+ * smooth-update loop accordingly.
2746
+ *
2747
+ * @param {boolean} playing - True to enter the playing state, false to
2748
+ * enter the paused state.
2749
+ * @fires WaveformPlayer#waveformplayer:play
2750
+ * @fires WaveformPlayer#waveformplayer:pause
2751
+ */
2752
+ setPlayingState(playing) {
2753
+ const wasPlaying = this.isPlaying;
2754
+ this.isPlaying = !!playing;
2755
+ this.setPlayButtonState(this.isPlaying);
2756
+ if (this.isPlaying && !wasPlaying) {
2757
+ this.startSmoothUpdate?.();
2758
+ this._emit("waveformplayer:play", { player: this, url: this.options.url });
2759
+ if (this.options.onPlay) this.options.onPlay(this);
2760
+ } else if (!this.isPlaying && wasPlaying) {
2761
+ this.stopSmoothUpdate?.();
2762
+ this._emit("waveformplayer:pause", { player: this, url: this.options.url });
2763
+ if (this.options.onPause) this.options.onPause(this);
2764
+ }
2765
+ }
2766
+ /**
2767
+ * External-mode state pump: update the visualization's progress
2768
+ * from an external clock (e.g. WaveformBar's audio element's
2769
+ * timeupdate). Drives the canvas redraw + the time displays.
2770
+ *
2771
+ * Redraws the canvas, updates the current/total time displays, stores the
2772
+ * external duration for the accessible slider, dispatches
2773
+ * `waveformplayer:timeupdate`, runs `onTimeUpdate`, and synthesizes a
2774
+ * one-shot `waveformplayer:ended` (with `onEnd`) when progress reaches the
2775
+ * end. No-op for a non-positive duration.
2776
+ *
2777
+ * @param {number} currentTime - Current playback position in seconds.
2778
+ * @param {number} duration - Total track duration in seconds.
2779
+ * @fires WaveformPlayer#waveformplayer:timeupdate
2780
+ * @fires WaveformPlayer#waveformplayer:ended
2781
+ */
2782
+ setProgress(currentTime, duration) {
2783
+ if (!duration || duration <= 0) return;
2784
+ this.progress = clamp(currentTime / duration);
2785
+ if (this.currentTimeEl) this.currentTimeEl.textContent = formatTime(currentTime);
2786
+ this._extDuration = duration;
2787
+ if (this.totalTimeEl && (!this.totalTimeEl.dataset._extSet || this.totalTimeEl.dataset._extDur !== String(duration))) {
2788
+ this.totalTimeEl.textContent = formatTime(duration);
2789
+ this.totalTimeEl.dataset._extSet = "1";
2790
+ this.totalTimeEl.dataset._extDur = String(duration);
2791
+ }
2792
+ this.drawWaveform?.();
2793
+ this.updateActiveMarker();
2794
+ this._emit("waveformplayer:timeupdate", { player: this, currentTime, duration, progress: this.progress, url: this.options.url });
2795
+ if (this.options.onTimeUpdate) this.options.onTimeUpdate(currentTime, duration, this);
2796
+ if (this.progress >= 1) {
2797
+ if (!this._extEnded) {
2798
+ this._extEnded = true;
2799
+ this._emit("waveformplayer:ended", { player: this, url: this.options.url, currentTime: duration, duration });
2800
+ if (this.options.onEnd) this.options.onEnd(this);
2801
+ }
2802
+ } else {
2803
+ this._extEnded = false;
2804
+ }
2805
+ this.updateSeekAccessibility();
2806
+ }
2807
+ /**
2808
+ * Toggle between play and pause based on the current `isPlaying` state.
2809
+ * Works in both audio modes (in external mode it routes through the
2810
+ * request-play/pause events).
2811
+ */
2812
+ togglePlay() {
2813
+ if (this.isPlaying) {
2814
+ this.pause();
2815
+ } else {
2816
+ this.play();
2817
+ }
2818
+ }
2819
+ /**
2820
+ * Seek the owned `<audio>` element to an absolute time, clamped to
2821
+ * `[0, duration]`, and refresh progress. Self mode only — a no-op when
2822
+ * there is no audio element or duration. External-mode keyboard/click
2823
+ * seeks go through {@link WaveformPlayer#seekToSeconds} instead.
2824
+ * @param {number} seconds - Target time in seconds.
2825
+ */
2826
+ seekTo(seconds) {
2827
+ if (this.audio && this.audio.duration) {
2828
+ this.audio.currentTime = clamp(seconds, 0, this.audio.duration);
2829
+ this.updateProgress();
2830
+ }
2831
+ }
2832
+ /**
2833
+ * Seek the owned `<audio>` element to a fraction of the track, clamped to
2834
+ * `[0, 1]`, and refresh progress. Self mode only — a no-op without an audio
2835
+ * element or duration.
2836
+ * @param {number} percent - Position as a fraction from 0 to 1.
2837
+ */
2838
+ seekToPercent(percent) {
2839
+ if (this.audio && this.audio.duration) {
2840
+ this.audio.currentTime = this.audio.duration * clamp(percent);
2841
+ this.updateProgress();
2842
+ }
2843
+ }
2844
+ /**
2845
+ * Set the owned `<audio>` element's volume, clamped to `[0, 1]`. Self mode
2846
+ * only — a no-op in external mode where the controller owns volume.
2847
+ * @param {number} volume - Volume from 0 (silent) to 1 (full).
2848
+ */
2849
+ setVolume(volume) {
2850
+ const v = Number(volume);
2851
+ if (this.audio && Number.isFinite(v)) {
2852
+ this.audio.volume = clamp(v);
2853
+ }
2854
+ }
2855
+ /**
2856
+ * Set the owned `<audio>` element's playback rate (clamped to 0.25–4),
2857
+ * persist it onto `this.options.playbackRate`, and refresh the speed UI.
2858
+ * Self mode only — a no-op in external mode.
2859
+ *
2860
+ * The clamp bounds the range browsers keep audible; the default speed menu
2861
+ * offers a narrower 0.5–2, which `playbackRates` can widen up to these
2862
+ * bounds. A non-numeric rate is ignored rather than assigned, since
2863
+ * `audio.playbackRate = NaN` throws.
2864
+ * @param {number} rate - Desired playback rate; clamped to the 0.25–4 range.
2865
+ */
2866
+ setPlaybackRate(rate) {
2867
+ if (!this.audio) return;
2868
+ const clampedRate = toFiniteNumber(rate, null, { min: PLAYBACK_RATE_MIN, max: PLAYBACK_RATE_MAX });
2869
+ if (clampedRate === null) return;
2870
+ this.audio.playbackRate = clampedRate;
2871
+ this.options.playbackRate = clampedRate;
2872
+ this.updateSpeedUI();
2873
+ }
2874
+ /**
2875
+ * Tear down the player and release all resources.
2876
+ *
2877
+ * Flags destruction (so in-flight handlers bail), dispatches
2878
+ * `waveformplayer:destroy`, stops playback and the animation loop, aborts
2879
+ * every listener registered on the instance signal, disconnects the resize
2880
+ * observer, removes the window-resize handler, drops the instance from the
2881
+ * static map and `currentlyPlaying`, resets/releases the audio element, and
2882
+ * empties the container.
2883
+ * @fires WaveformPlayer#waveformplayer:destroy
2884
+ */
2885
+ destroy() {
2886
+ this.isDestroying = true;
2887
+ this._emit("waveformplayer:destroy", { player: this, url: this.options.url });
2888
+ this.pause();
2889
+ this.stopSmoothUpdate();
2890
+ clearTimeout(this._markerLabelTimer);
2891
+ this._ac?.abort();
2892
+ if (this.resizeObserver) {
2893
+ this.resizeObserver.disconnect();
2894
+ this.resizeObserver = null;
2895
+ }
2896
+ if (this.resizeHandler) {
2897
+ window.removeEventListener("resize", this.resizeHandler);
2898
+ this.resizeHandler = null;
2899
+ }
2900
+ _WaveformPlayer.instances.delete(this.id);
2901
+ if (_WaveformPlayer.currentlyPlaying === this) {
2902
+ _WaveformPlayer.currentlyPlaying = null;
2903
+ }
2904
+ if (this.audio) {
2905
+ this.audio.pause();
2906
+ this.audio.src = "";
2907
+ this.audio.load();
2908
+ this.audio = null;
2909
+ }
2910
+ this.container.innerHTML = "";
2911
+ delete this.container.dataset.waveformInitialized;
2912
+ this.canvas = null;
2913
+ this.ctx = null;
2914
+ this.playBtn = null;
2915
+ this.waveformData = [];
2916
+ }
2917
+ // ============================================
2918
+ // Static Methods
2919
+ // ============================================
2920
+ /**
2921
+ * Get player instance by ID, element, or element ID
2922
+ * @param {string|HTMLElement} idOrElement - Player ID, element, or element ID
2923
+ * @returns {WaveformPlayer|undefined}
2924
+ */
2925
+ static getInstance(idOrElement) {
2926
+ if (typeof idOrElement === "string") {
2927
+ const instance = this.instances.get(idOrElement);
2928
+ if (instance) return instance;
2929
+ const element = document.getElementById(idOrElement);
2930
+ if (element) {
2931
+ return Array.from(this.instances.values()).find((p) => p.container === element);
2932
+ }
2933
+ }
2934
+ if (idOrElement instanceof HTMLElement) {
2935
+ return Array.from(this.instances.values()).find((p) => p.container === idOrElement);
2936
+ }
2937
+ return void 0;
2938
+ }
2939
+ /**
2940
+ * Get all player instances
2941
+ * @returns {WaveformPlayer[]}
2942
+ */
2943
+ static getAllInstances() {
2944
+ return Array.from(this.instances.values());
2945
+ }
2946
+ /**
2947
+ * Destroy all player instances
2948
+ */
2949
+ static destroyAll() {
2950
+ this.instances.forEach((player) => player.destroy());
2951
+ this.instances.clear();
2952
+ }
2953
+ /**
2954
+ * Generate waveform data from audio URL
2955
+ * @static
2956
+ * @param {string} url - Audio URL
2957
+ * @param {number} samples - Number of samples
2958
+ * @returns {Promise<number[]>} Waveform peak data
2959
+ */
2960
+ static async generateWaveformData(url, samples = DEFAULT_SAMPLES) {
2961
+ try {
2962
+ const result = await generateWaveform(url, samples);
2963
+ return result.peaks;
2964
+ } catch (error) {
2965
+ console.error("[WaveformPlayer] Failed to generate waveform:", error);
2966
+ throw error;
2967
+ }
2968
+ }
2969
+ /**
2970
+ * Derive a peaks-JSON URL from an audio URL by swapping the
2971
+ * extension. Strict counterpart to `generateWaveformData()`:
2972
+ * `generateWaveformData` decodes the audio at runtime,
2973
+ * `getPeaksUrl` assumes you generated the peaks at build time
2974
+ * (e.g. with `@arraypress/waveform-gen`) and stored the JSON
2975
+ * alongside the audio file.
2976
+ *
2977
+ * Use the result as the `waveform` option — the player detects
2978
+ * the `.json` suffix, `fetch()`es the file, and skips the Web
2979
+ * Audio decode pass entirely. Big perf win on catalogues with
2980
+ * many tracks (saves ~1-5s decode per file on slow connections).
2981
+ *
2982
+ * Recognised extensions: mp3, wav, ogg, flac, m4a, aac.
2983
+ * Preserves query strings + URL fragments. Returns `undefined`
2984
+ * for unrecognised inputs so callers can pass through
2985
+ * unconditionally:
2986
+ *
2987
+ * new WaveformPlayer('#el', {
2988
+ * url: track.audioUrl,
2989
+ * waveform: WaveformPlayer.getPeaksUrl(track.audioUrl),
2990
+ * });
2991
+ *
2992
+ * @static
2993
+ * @param {string|undefined|null} audioUrl - Audio file URL.
2994
+ * @returns {string|undefined} Peaks JSON URL, or `undefined`
2995
+ * when the input is empty / has no recognised audio extension.
2996
+ *
2997
+ * @example
2998
+ * WaveformPlayer.getPeaksUrl('/audio/track.mp3')
2999
+ * // '/audio/track.json'
3000
+ *
3001
+ * WaveformPlayer.getPeaksUrl('/audio/track.wav?v=2')
3002
+ * // '/audio/track.json?v=2'
3003
+ *
3004
+ * WaveformPlayer.getPeaksUrl(undefined)
3005
+ * // undefined
3006
+ */
3007
+ static getPeaksUrl(audioUrl) {
3008
+ if (!audioUrl) return void 0;
3009
+ const swapped = audioUrl.replace(
3010
+ /\.(mp3|wav|ogg|flac|m4a|aac)(\?[^#]*)?(#.*)?$/i,
3011
+ ".json$2$3"
3012
+ );
3013
+ return swapped === audioUrl ? void 0 : swapped;
3014
+ }
3015
+ };
3016
+
3017
+ // src/js/entry.js
3018
+ WaveformPlayer.utils = { formatTime, extractTitleFromUrl, escapeHtml, isSafeHref, parseDataAttributes, detectColorScheme };
3019
+ function initElement(element) {
3020
+ if (element.dataset.waveformInitialized === "true" || WaveformPlayer.getInstance(element)) {
3021
+ return;
3022
+ }
3023
+ try {
3024
+ new WaveformPlayer(element);
3025
+ element.dataset.waveformInitialized = "true";
3026
+ } catch (error) {
3027
+ console.error("[WaveformPlayer] Failed to initialize:", error, element);
3028
+ }
3029
+ }
3030
+ function autoInit(root = document) {
3031
+ if (!isBrowser()) return;
3032
+ const scope = root || document;
3033
+ if (scope.matches?.("[data-waveform-player]")) {
3034
+ initElement(scope);
3035
+ }
3036
+ scope.querySelectorAll("[data-waveform-player]").forEach(initElement);
3037
+ }
3038
+ WaveformPlayer.init = autoInit;
3039
+ if (isBrowser()) {
3040
+ window.WaveformPlayer = WaveformPlayer;
3041
+ }
3042
+ var entry_default = WaveformPlayer;