@arraypress/waveform-player 1.24.5 → 1.25.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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');