@arraypress/waveform-player 1.24.4 → 1.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/js/themes.js CHANGED
@@ -3,7 +3,16 @@
3
3
  * @description Color presets and default options for WaveformPlayer
4
4
  */
5
5
 
6
- import {parseColor, perceivedBrightness, DEFAULT_SAMPLES} from './utils.js';
6
+ import {
7
+ parseColor,
8
+ perceivedBrightness,
9
+ toArray,
10
+ toBool,
11
+ toEnum,
12
+ toFiniteNumber,
13
+ toNumberArray,
14
+ DEFAULT_SAMPLES
15
+ } from './utils.js';
7
16
 
8
17
  /**
9
18
  * Brightness (0–255) above which a backdrop counts as light.
@@ -400,4 +409,223 @@ export const STYLE_DEFAULTS = {
400
409
  blocks: {barWidth: 4, barSpacing: 2},
401
410
  dots: {barWidth: 3, barSpacing: 3},
402
411
  seekbar: {barWidth: 1, barSpacing: 0}
403
- };
412
+ };
413
+
414
+ /**
415
+ * Permitted `buttonAlign` values. `auto` resolves per waveform style at DOM
416
+ * build time (bottom for `bars`, center otherwise).
417
+ * @type {string[]}
418
+ */
419
+ export const BUTTON_ALIGNMENTS = ['auto', 'top', 'center', 'bottom'];
420
+
421
+ /**
422
+ * Playback-rate bounds. Single source of truth for both the `setPlaybackRate()`
423
+ * clamp and the `playbackRates` menu — an offered rate the setter would refuse
424
+ * leaves the speed label reading one thing while the audio plays another.
425
+ *
426
+ * The window is deliberately wider than the default menu (0.5–2). Audiobook and
427
+ * podcast UIs routinely want 2.5x or 3x, and there's no reason the *setter* should
428
+ * cap what the menu merely doesn't offer by default. 0.25–4 is the conservative
429
+ * limit: browsers keep audio audible and pitch-corrected across that range and
430
+ * start muting it beyond, so a rate outside these bounds would play silently.
431
+ * @type {number}
432
+ */
433
+ export const PLAYBACK_RATE_MIN = 0.25;
434
+ export const PLAYBACK_RATE_MAX = 4;
435
+
436
+ /**
437
+ * Closed vocabularies for the enumerated options, keyed by option name. Each
438
+ * unrecognised value resolves to that option's {@link DEFAULT_OPTIONS} entry.
439
+ * @type {Object<string, string[]>}
440
+ * @private
441
+ */
442
+ const ENUMS = {
443
+ buttonAlign: BUTTON_ALIGNMENTS,
444
+ layout: ['default', 'preview'],
445
+ buttonStyle: ['circle', 'minimal'],
446
+ artworkPosition: ['info', 'button'],
447
+ waveformStyle: Object.keys(STYLE_DEFAULTS),
448
+ waveformGradient: ['vertical', 'horizontal', 'diagonal'],
449
+ audioMode: ['self', 'external'],
450
+ preload: ['none', 'metadata', 'auto'],
451
+ colorPreset: Object.keys(COLOR_PRESETS),
452
+ // Anything other than these two makes the browser fall back to 'anonymous',
453
+ // which forces a CORS request the caller never asked for — so a bad value
454
+ // has to resolve to null (no crossorigin attribute), not pass through.
455
+ crossOrigin: ['anonymous', 'use-credentials']
456
+ };
457
+
458
+ /**
459
+ * Numeric options and their acceptable ranges. Out-of-range values are clamped;
460
+ * non-numeric ones fall back to the default.
461
+ * @type {Object<string, {min?: number, max?: number, integer?: boolean}>}
462
+ * @private
463
+ */
464
+ const NUMBERS = {
465
+ height: {min: 1, integer: true},
466
+ samples: {min: 1, integer: true},
467
+ barWidth: {min: 0},
468
+ barSpacing: {min: 0},
469
+ barRadius: {min: 0},
470
+ bpm: {min: 1},
471
+ // Matches the clamp in setPlaybackRate() — the menu must not offer a rate
472
+ // the setter would then silently refuse.
473
+ playbackRate: {min: PLAYBACK_RATE_MIN, max: PLAYBACK_RATE_MAX}
474
+ };
475
+
476
+ /**
477
+ * Boolean feature flags. Coerced with {@link toBool} so the string `'false'`
478
+ * (a `data-*` value, or a wrapper that stringified a prop) doesn't read as true.
479
+ * @type {string[]}
480
+ * @private
481
+ */
482
+ const BOOLEANS = [
483
+ 'autoplay', 'showControls', 'showInfo', 'showTime', 'showHoverTime',
484
+ 'seekHandle', 'showBPM', 'singlePlay', 'playOnSeek', 'enableMediaSession',
485
+ 'showMarkers', 'accessibleSeek', 'showPlaybackSpeed'
486
+ ];
487
+
488
+ /**
489
+ * Callback options. A non-function here would throw at call time, deep inside
490
+ * playback, rather than at the point the bad value was supplied.
491
+ * @type {string[]}
492
+ * @private
493
+ */
494
+ const CALLBACKS = [
495
+ 'onLoad', 'onPlay', 'onPause', 'onEnd', 'onError', 'onTimeUpdate',
496
+ 'onNextTrack', 'onPreviousTrack'
497
+ ];
498
+
499
+ /**
500
+ * Warn about an option that was supplied but unusable. Invalid options resolve
501
+ * to their default rather than throwing, so without this they'd fail silently —
502
+ * a `NaN` height renders an invisible player with an empty console.
503
+ * @param {string} key - Option name.
504
+ * @param {*} value - The rejected value.
505
+ * @private
506
+ */
507
+ function warnInvalid(key, value) {
508
+ console.warn(`[WaveformPlayer] Invalid ${key} option, using default:`, value);
509
+ }
510
+
511
+ /**
512
+ * Normalize a marker list into renderable markers.
513
+ *
514
+ * Accepts an array or a JSON array string, and keeps only entries that are
515
+ * objects with a finite, non-negative `time` — `renderMarkers()` divides by
516
+ * duration and writes the result into `style.left`, so a non-numeric time
517
+ * produces `left: NaN%` and silently stacks every bad marker at the left edge.
518
+ * A missing `label` becomes `''` rather than reaching the tooltip and the
519
+ * marker's `aria-label` as the string `"undefined"`.
520
+ *
521
+ * @param {*} value - Candidate marker list.
522
+ * @returns {Array<Object>} Renderable markers (empty when nothing survives).
523
+ */
524
+ export function normalizeMarkers(value) {
525
+ const list = toArray(value);
526
+ if (!list) {
527
+ if (value != null) warnInvalid('markers', value);
528
+ return [];
529
+ }
530
+
531
+ return list.reduce((markers, marker) => {
532
+ const time = marker && typeof marker === 'object'
533
+ ? toFiniteNumber(marker.time, null, {min: 0})
534
+ : null;
535
+
536
+ if (time === null) {
537
+ warnInvalid('marker', marker);
538
+ return markers;
539
+ }
540
+
541
+ markers.push({...marker, time, label: marker.label == null ? '' : marker.label});
542
+ return markers;
543
+ }, []);
544
+ }
545
+
546
+ /**
547
+ * Normalize a merged option set in place, resolving every unusable value to its
548
+ * {@link DEFAULT_OPTIONS} entry.
549
+ *
550
+ * Options arrive from three untyped directions — `data-*` attributes, framework
551
+ * wrappers forwarding props, and hand-written JS — and the consumers downstream
552
+ * assume shapes that none of those paths guarantee. `playbackRates.map()` and
553
+ * `markers.forEach()` throw outright on valid-but-non-array JSON (`JSON.parse`
554
+ * validates syntax, not shape); `NaN` geometry sizes the canvas to nothing; and
555
+ * unrecognised enum values reach class names and DOM properties. Normalizing
556
+ * once, on the merged object, covers both configuration paths and every wrapper
557
+ * at a single point.
558
+ *
559
+ * Mutates and returns the same object, so it can be dropped in directly after
560
+ * {@link mergeOptions}. Options left unset (`null`) are untouched — `null` is
561
+ * the documented "inherit / auto-detect" state for colours, `bpm`, `buttonSize`
562
+ * and the callbacks.
563
+ *
564
+ * @param {Object} options - Merged options object (mutated).
565
+ * @returns {Object} The same object, normalized.
566
+ */
567
+ export function normalizeOptions(options) {
568
+ // Only normalize what the caller actually supplied — mergeOptions() drops
569
+ // null/undefined sources, so a null here is a default that means "unset".
570
+ const supplied = (key) => options[key] != null;
571
+
572
+ // Fall back to the documented default, warning only when a real value was
573
+ // rejected (an unset option is not a mistake).
574
+ const reject = (key) => {
575
+ warnInvalid(key, options[key]);
576
+ options[key] = DEFAULT_OPTIONS[key];
577
+ };
578
+
579
+ for (const [key, range] of Object.entries(NUMBERS)) {
580
+ if (!supplied(key)) continue;
581
+ const n = toFiniteNumber(options[key], null, range);
582
+ if (n === null) reject(key); else options[key] = n;
583
+ }
584
+
585
+ for (const [key, allowed] of Object.entries(ENUMS)) {
586
+ if (supplied(key) && toEnum(options[key], allowed) === null) reject(key);
587
+ }
588
+
589
+ for (const key of BOOLEANS) {
590
+ options[key] = toBool(options[key]);
591
+ }
592
+
593
+ for (const key of CALLBACKS) {
594
+ if (supplied(key) && typeof options[key] !== 'function') reject(key);
595
+ }
596
+
597
+ // Speed menu: every offered rate must be one setPlaybackRate() will honour,
598
+ // or the menu label and the audio disagree. Members are interpolated into
599
+ // markup, so non-numeric entries must not survive.
600
+ if (supplied('playbackRates')) {
601
+ const rates = toNumberArray(options.playbackRates, {
602
+ min: PLAYBACK_RATE_MIN,
603
+ max: PLAYBACK_RATE_MAX,
604
+ fallback: null
605
+ });
606
+ if (rates === null) reject('playbackRates'); else options.playbackRates = rates;
607
+ }
608
+
609
+ options.markers = normalizeMarkers(options.markers);
610
+
611
+ // A CSS length is a number (px) or a verbatim unit string ('4rem'); both
612
+ // reach an inline style attribute, escaped, via formatCssLength().
613
+ for (const key of ['buttonSize', 'buttonRadius']) {
614
+ if (!supplied(key)) continue;
615
+ const value = options[key];
616
+ const ok = typeof value === 'number'
617
+ ? Number.isFinite(value)
618
+ : typeof value === 'string' && value.trim() !== '';
619
+ if (!ok) reject(key);
620
+ }
621
+
622
+ // A colour is a CSS colour string or an array of gradient stops; anything
623
+ // else resolves to null so the theme preset fills it in instead.
624
+ for (const key of ['waveformColor', 'progressColor']) {
625
+ if (!supplied(key)) continue;
626
+ const value = options[key];
627
+ if (!(typeof value === 'string' && value.trim() !== '') && !Array.isArray(value)) reject(key);
628
+ }
629
+
630
+ return options;
631
+ }
package/src/js/utils.js CHANGED
@@ -87,6 +87,131 @@ export function clamp(value, min = 0, max = 1) {
87
87
  return Math.max(min, Math.min(value, max));
88
88
  }
89
89
 
90
+ /**
91
+ * Coerce a value to a finite number, clamped into an optional range.
92
+ *
93
+ * Options reach the player from three untyped directions — `data-*` attributes,
94
+ * framework wrappers that forward strings, and hand-written JS — so a value that
95
+ * *should* be a number routinely isn't. Anything non-numeric (`NaN`,
96
+ * `Infinity`, `null`, `''`, objects, arrays) returns `fallback` rather than
97
+ * poisoning arithmetic downstream: a `NaN` height silently sizes the canvas to
98
+ * zero, which looks like a broken player rather than a bad option.
99
+ *
100
+ * Numeric strings are accepted (`'64'` → `64`) but non-numeric ones are not
101
+ * (`'64px'` → `fallback`); the `data-*` layer has already run `parseInt`/
102
+ * `parseFloat` by the time values arrive here.
103
+ *
104
+ * @param {*} value - Candidate value.
105
+ * @param {*} [fallback=null] - Returned when `value` isn't a finite number.
106
+ * @param {Object} [opts={}] - Bounds.
107
+ * @param {number} [opts.min=-Infinity] - Lower bound (clamped, not rejected).
108
+ * @param {number} [opts.max=Infinity] - Upper bound (clamped, not rejected).
109
+ * @param {boolean} [opts.integer=false] - Round the result to a whole number.
110
+ * @returns {number|*} The finite, clamped number, or `fallback`.
111
+ */
112
+ export function toFiniteNumber(value, fallback = null, opts = {}) {
113
+ const {min = -Infinity, max = Infinity, integer = false} = opts;
114
+ const n = typeof value === 'number'
115
+ ? value
116
+ : (typeof value === 'string' && value.trim() !== '' ? Number(value) : NaN);
117
+
118
+ if (!Number.isFinite(n)) return fallback;
119
+
120
+ const bounded = clamp(n, min, max);
121
+ return integer ? Math.round(bounded) : bounded;
122
+ }
123
+
124
+ /**
125
+ * Coerce a value to an array, accepting either a real array or a JSON string
126
+ * that parses to one (`'[1,2]'`). Anything else — including valid JSON that
127
+ * isn't an array, like `'2'` or `'{"a":1}'` — returns `fallback`.
128
+ *
129
+ * This is the guard `JSON.parse` alone doesn't give you: parsing only validates
130
+ * *syntax*, so well-formed non-array JSON sails through and detonates at the
131
+ * first `.map()`/`.forEach()` call site.
132
+ *
133
+ * @param {*} value - Candidate value.
134
+ * @param {*} [fallback=null] - Returned when `value` isn't (or doesn't parse to) an array.
135
+ * @returns {Array|*} The array, or `fallback`.
136
+ */
137
+ export function toArray(value, fallback = null) {
138
+ if (Array.isArray(value)) return value;
139
+
140
+ if (typeof value === 'string' && value.trim().startsWith('[')) {
141
+ try {
142
+ const parsed = JSON.parse(value);
143
+ if (Array.isArray(parsed)) return parsed;
144
+ } catch (e) { /* fall through to the fallback */ }
145
+ }
146
+
147
+ return fallback;
148
+ }
149
+
150
+ /**
151
+ * Coerce a value to an array of finite numbers.
152
+ *
153
+ * Accepts a real array, a JSON array string (`'[0.5,1,2]'`), or a plain
154
+ * delimited list (`'0.5, 1, 2'`) — the last of which is what an author naturally
155
+ * types into a `data-*` attribute. Members that aren't finite numbers, or that
156
+ * fall outside `[min, max]`, are **dropped** rather than clamped, so a
157
+ * mistyped entry can't quietly masquerade as a supported one. An empty result
158
+ * returns `fallback`.
159
+ *
160
+ * @param {*} value - Candidate value.
161
+ * @param {Object} [opts={}] - Bounds and fallback.
162
+ * @param {number} [opts.min=-Infinity] - Lowest acceptable member.
163
+ * @param {number} [opts.max=Infinity] - Highest acceptable member.
164
+ * @param {*} [opts.fallback=null] - Returned when nothing usable survives.
165
+ * @returns {number[]|*} Numbers within range, or `fallback`.
166
+ */
167
+ export function toNumberArray(value, opts = {}) {
168
+ const {min = -Infinity, max = Infinity, fallback = null} = opts;
169
+
170
+ let list = toArray(value);
171
+ if (!list && typeof value === 'string' && value.trim() !== '') {
172
+ list = value.split(/[,\s]+/);
173
+ }
174
+ if (!list) return fallback;
175
+
176
+ const numbers = list
177
+ .map(v => toFiniteNumber(v))
178
+ .filter(n => n !== null && n >= min && n <= max);
179
+
180
+ return numbers.length ? numbers : fallback;
181
+ }
182
+
183
+ /**
184
+ * Return `value` when it is one of `allowed`, else `fallback`. Used for the
185
+ * option surface's closed vocabularies (`layout`, `preload`, `audioMode`, …) so
186
+ * an unrecognised value resolves to the documented default instead of reaching
187
+ * a class name, a DOM property, or a lookup that silently misses.
188
+ *
189
+ * @param {*} value - Candidate value.
190
+ * @param {Array} allowed - Permitted values.
191
+ * @param {*} [fallback=null] - Returned when `value` isn't permitted.
192
+ * @returns {*} `value` if allowed, else `fallback`.
193
+ */
194
+ export function toEnum(value, allowed, fallback = null) {
195
+ return allowed.includes(value) ? value : fallback;
196
+ }
197
+
198
+ /**
199
+ * Coerce a value to a boolean, treating the strings `'false'` and `'0'` as
200
+ * false. Plain `Boolean()` would make both truthy, and both arrive routinely
201
+ * from attribute-shaped sources (a `data-*` value, or a framework wrapper that
202
+ * stringifies props before forwarding them).
203
+ *
204
+ * @param {*} value - Candidate value.
205
+ * @returns {boolean} The coerced boolean.
206
+ */
207
+ export function toBool(value) {
208
+ if (typeof value === 'string') {
209
+ const v = value.trim().toLowerCase();
210
+ return v !== '' && v !== 'false' && v !== '0';
211
+ }
212
+ return !!value;
213
+ }
214
+
90
215
  /**
91
216
  * Read a boolean `data-*` flag. Returns `undefined` when the attribute is
92
217
  * absent (preserving the sparse-options contract) and otherwise compares the
@@ -119,9 +244,13 @@ function parseColorValue(value) {
119
244
  * Only attributes that are actually present are copied, so the returned object
120
245
  * is sparse and never overrides defaults with `undefined`. Numeric attributes
121
246
  * are coerced with `parseInt`/`parseFloat`, boolean flags are compared against
122
- * the literal string `'true'`, and JSON-valued attributes (`markers`,
123
- * `playbackRates`) are parsed defensively — a parse failure is warned about and
124
- * the attribute is skipped rather than thrown.
247
+ * the literal string `'true'`, and list-valued attributes (`markers`,
248
+ * `playbackRates`) are parsed defensively — anything that isn't a list is
249
+ * warned about and skipped rather than thrown or passed on.
250
+ *
251
+ * This layer only reads and shapes; it does not police values. Ranges and
252
+ * vocabularies are enforced by `normalizeOptions` on the merged result, so the
253
+ * constructor path gets the same guarantees as the `data-*` path.
125
254
  *
126
255
  * Several attributes are shorthand aliases of a canonical long form: `data-src`
127
256
  * → `url`, `data-style` → `waveformStyle`. When both are present the canonical
@@ -158,12 +287,16 @@ export function parseDataAttributes(element) {
158
287
  options[optKey] = /^\d+(\.\d+)?$/.test(raw.trim()) ? parseFloat(raw) : raw;
159
288
  };
160
289
 
161
- // Parse a JSON-valued attribute defensively — warn and skip on bad JSON.
162
- const setJson = (optKey, dataKey = optKey) => {
290
+ // Parse a JSON-array attribute defensively — warn and skip anything that
291
+ // isn't an array. Checking the SHAPE (not just that JSON.parse succeeded)
292
+ // is what stops well-formed non-array JSON like `2` or `{"a":1}` reaching a
293
+ // consumer that will call .map()/.forEach() on it.
294
+ const setJsonArray = (optKey, dataKey = optKey) => {
163
295
  const raw = element.dataset[dataKey];
164
296
  if (!raw) return;
165
- try { options[optKey] = JSON.parse(raw); }
166
- catch (e) { console.warn(`[WaveformPlayer] Invalid ${dataKey} JSON:`, e); }
297
+ const parsed = toArray(raw);
298
+ if (parsed) options[optKey] = parsed;
299
+ else console.warn(`[WaveformPlayer] Invalid ${dataKey} attribute, expected a JSON array:`, raw);
167
300
  };
168
301
 
169
302
  // Core attributes. `data-src` is a shorthand alias for `data-url`;
@@ -228,12 +361,19 @@ export function parseDataAttributes(element) {
228
361
  if (element.dataset.waveform) options.waveform = element.dataset.waveform;
229
362
 
230
363
  // Markers
231
- setJson('markers');
364
+ setJsonArray('markers');
232
365
 
233
366
  // Playback controls
234
367
  setNum('playbackRate', 'playbackRate', true);
235
368
  setBool('showPlaybackSpeed');
236
- setJson('playbackRates');
369
+ // Rates accept a JSON array (`[0.5,1,2]`) or the bare list an author is
370
+ // more likely to type (`0.5, 1, 2`). Range is enforced later, against the
371
+ // same bounds setPlaybackRate() clamps to.
372
+ if (element.dataset.playbackRates) {
373
+ const rates = toNumberArray(element.dataset.playbackRates);
374
+ if (rates) options.playbackRates = rates;
375
+ else console.warn('[WaveformPlayer] Invalid playbackRates attribute:', element.dataset.playbackRates);
376
+ }
237
377
 
238
378
  // Media Session API
239
379
  setBool('enableMediaSession');