@arraypress/waveform-sounds 0.3.1 → 2.1.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.
Files changed (89) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +43 -3
  3. package/dist/waveform-sounds-no-autoinit.esm.js +607 -178
  4. package/dist/waveform-sounds-render.esm.js +79 -15
  5. package/dist/waveform-sounds.css +136 -79
  6. package/dist/waveform-sounds.esm.js +611 -181
  7. package/dist/waveform-sounds.js +608 -181
  8. package/dist/waveform-sounds.min.css +1 -1
  9. package/dist/waveform-sounds.min.js +3 -3
  10. package/package.json +36 -33
  11. package/src/css/waveform-sounds.css +136 -79
  12. package/src/js/core/WaveformSounds.ts +1366 -0
  13. package/src/js/core/element.ts +208 -0
  14. package/src/js/core/engine.ts +107 -0
  15. package/src/js/core/{options.js → options.ts} +28 -28
  16. package/src/js/data/{bpm.js → bpm.ts} +27 -17
  17. package/src/js/data/{navigation.js → navigation.ts} +31 -18
  18. package/src/js/data/{sounds.js → sounds.ts} +97 -66
  19. package/src/js/data/url-state.ts +130 -0
  20. package/src/js/dom/colors.ts +86 -0
  21. package/src/js/dom/{draw.js → draw.ts} +16 -17
  22. package/src/js/dom/{menus.js → menus.ts} +70 -55
  23. package/src/js/dom/{rows.js → rows.ts} +15 -17
  24. package/src/js/entry.ts +60 -0
  25. package/src/js/{index.js → index.ts} +7 -3
  26. package/src/js/render/{html.js → html.ts} +16 -12
  27. package/src/js/render/{icons.js → icons.ts} +3 -4
  28. package/src/js/render/{markup.js → markup.ts} +114 -64
  29. package/src/js/render/options.ts +118 -0
  30. package/src/js/render/{strings.js → strings.ts} +18 -16
  31. package/src/js/{render-entry.js → render-entry.ts} +2 -1
  32. package/src/js/shared/{utils.js → utils.ts} +24 -24
  33. package/{index.d.ts → src/js/types.ts} +40 -88
  34. package/types/core/WaveformSounds.d.ts +175 -0
  35. package/types/core/WaveformSounds.d.ts.map +1 -0
  36. package/types/core/element.d.ts +84 -0
  37. package/types/core/element.d.ts.map +1 -0
  38. package/types/core/engine.d.ts +72 -0
  39. package/types/core/engine.d.ts.map +1 -0
  40. package/types/core/options.d.ts +71 -0
  41. package/types/core/options.d.ts.map +1 -0
  42. package/types/data/bpm.d.ts +80 -0
  43. package/types/data/bpm.d.ts.map +1 -0
  44. package/types/data/navigation.d.ts +62 -0
  45. package/types/data/navigation.d.ts.map +1 -0
  46. package/types/data/sounds.d.ts +168 -0
  47. package/types/data/sounds.d.ts.map +1 -0
  48. package/types/data/url-state.d.ts +109 -0
  49. package/types/data/url-state.d.ts.map +1 -0
  50. package/types/dom/colors.d.ts +48 -0
  51. package/types/dom/colors.d.ts.map +1 -0
  52. package/types/dom/draw.d.ts +72 -0
  53. package/types/dom/draw.d.ts.map +1 -0
  54. package/types/dom/menus.d.ts +75 -0
  55. package/types/dom/menus.d.ts.map +1 -0
  56. package/types/dom/rows.d.ts +39 -0
  57. package/types/dom/rows.d.ts.map +1 -0
  58. package/types/entry.d.ts +28 -0
  59. package/types/entry.d.ts.map +1 -0
  60. package/types/index.d.ts +16 -0
  61. package/types/index.d.ts.map +1 -0
  62. package/types/render/html.d.ts +37 -0
  63. package/types/render/html.d.ts.map +1 -0
  64. package/types/render/icons.d.ts +17 -0
  65. package/types/render/icons.d.ts.map +1 -0
  66. package/types/render/markup.d.ts +141 -0
  67. package/types/render/markup.d.ts.map +1 -0
  68. package/types/render/options.d.ts +69 -0
  69. package/types/render/options.d.ts.map +1 -0
  70. package/types/render/strings.d.ts +43 -0
  71. package/types/render/strings.d.ts.map +1 -0
  72. package/types/render-entry.d.ts +8 -0
  73. package/types/render-entry.d.ts.map +1 -0
  74. package/types/shared/utils.d.ts +57 -0
  75. package/types/shared/utils.d.ts.map +1 -0
  76. package/types/types.d.ts +280 -0
  77. package/types/types.d.ts.map +1 -0
  78. package/types/vendor/arraypress-text.d.ts +250 -0
  79. package/dist/waveform-sounds-no-autoinit.cjs +0 -2159
  80. package/dist/waveform-sounds-render.cjs +0 -614
  81. package/dist/waveform-sounds.cjs +0 -2181
  82. package/no-autoinit.d.ts +0 -2
  83. package/render.d.ts +0 -5
  84. package/src/js/core/WaveformSounds.js +0 -993
  85. package/src/js/core/engine.js +0 -57
  86. package/src/js/data/url-state.js +0 -106
  87. package/src/js/dom/colors.js +0 -59
  88. package/src/js/entry.js +0 -25
  89. package/src/js/render/options.js +0 -90
@@ -19,21 +19,23 @@ import {escapeHtml} from '@arraypress/text';
19
19
  import {availableSorts, encodePeaks, facets, formatDuration, normalizeSounds} from '../data/sounds.js';
20
20
  import {h, text} from './html.js';
21
21
  import {ICONS} from './icons.js';
22
- import {RENDER_DEFAULTS, resolveRenderOptions} from './options.js';
22
+ import {defined, pickRenderOptions, RENDER_DEFAULTS, RENDER_OPTION_KEYS, resolveRenderOptions} from './options.js';
23
23
  import {bpmLabel, countText, DEFAULT_STRINGS, fill, SORT_LABEL_KEYS} from './strings.js';
24
24
  import {hashString} from '../shared/utils.js';
25
+ import {bpmExtent} from '../data/bpm.js';
26
+ import type {Sound, SoundInput, SoundsSort, WaveformSoundsOptions, WaveformSoundsStrings} from '../types.js';
25
27
 
26
- export {escapeHtml, RENDER_DEFAULTS, resolveRenderOptions, DEFAULT_STRINGS, countText, fill, availableSorts};
28
+ export {escapeHtml, RENDER_DEFAULTS, RENDER_OPTION_KEYS, pickRenderOptions, resolveRenderOptions, DEFAULT_STRINGS, countText, fill, availableSorts};
27
29
 
28
30
  /**
29
31
  * A stable id prefix for a list's dropdowns, from its sounds: the same on
30
32
  * the server and in the browser. Two lists of the SAME sounds on one page
31
33
  * collide, so they need an `idPrefix` each.
32
34
  *
33
- * @param {{url: string}[]} sounds
34
- * @returns {string} e.g. `ws1x9k2f`.
35
+ * @param sounds
36
+ * @returns e.g. `ws1x9k2f`.
35
37
  */
36
- export function idBase(sounds) {
38
+ export function idBase(sounds: {url: string}[]): string {
37
39
  const signature = [sounds.length, ...sounds.map((s) => s.url)].join('|');
38
40
  return `ws${hashString(signature).toString(36)}`;
39
41
  }
@@ -46,11 +48,10 @@ export function idBase(sounds) {
46
48
  * one usable order. Types past `maxTypeChips` become a menu (a
47
49
  * pack has a handful; a whole library can have fifty).
48
50
  *
49
- * @param {ReturnType<typeof facets>} f - The sounds' facets.
50
- * @param {ReturnType<typeof resolveRenderOptions>} o - Resolved options.
51
- * @returns {{types: 'chips'|'menu'|null, key: boolean, bpm: boolean, loops: boolean, sorts: string[], search: boolean, loop: boolean, count: boolean}}
51
+ * @param f - The sounds' facets.
52
+ * @param o - Resolved options.
52
53
  */
53
- export function toolbarPlan(f, o) {
54
+ export function toolbarPlan(f: ReturnType<typeof facets>, o: ReturnType<typeof resolveRenderOptions>): {types: 'chips'|'menu'|null, key: boolean, bpm: boolean, loops: boolean, sorts: string[], search: boolean, loop: boolean, count: boolean} {
54
55
  const typed = o.filters.includes('type') && f.types.length > 1;
55
56
  const sorts = availableSorts(o.sorts, f);
56
57
  return {
@@ -70,18 +71,38 @@ export function toolbarPlan(f, o) {
70
71
  * unset, it's on exactly when the list marks loops (only those repeat, so
71
72
  * a one-shot still plays once).
72
73
  *
73
- * @param {boolean|null|undefined} loop - The `loop` option.
74
- * @param {{loops: number}} f - The sounds' facets.
75
- * @returns {boolean}
74
+ * @param loop - The `loop` option.
75
+ * @param f - The sounds' facets.
76
76
  */
77
- export function loopsByDefault(loop, f) {
77
+ export function loopsByDefault(loop: boolean | null | undefined, f: {loops: number}): boolean {
78
78
  return loop == null ? f.loops > 0 : !!loop;
79
79
  }
80
80
 
81
+ /** What every part of the list's markup is built from ({@link renderSounds}). */
82
+ interface RenderContext {
83
+ o: ReturnType<typeof resolveRenderOptions>;
84
+ s: WaveformSoundsStrings;
85
+ f: ReturnType<typeof facets>;
86
+ total: number;
87
+ id: string;
88
+ }
89
+
90
+ /** A dropdown's content ({@link renderMenu}). */
91
+ export interface MenuSpec {
92
+ id: string;
93
+ label: string;
94
+ prefix?: string;
95
+ value: string;
96
+ options: {value: string, label: string, count?: number}[];
97
+ searchFrom: number;
98
+ placeholder?: string;
99
+ noMatches: string;
100
+ }
101
+
81
102
  /* ── Controls ───────────────────────────────────────────────────────── */
82
103
 
83
104
  /** The search field. */
84
- function renderSearch(s) {
105
+ function renderSearch(s: WaveformSoundsStrings): string {
85
106
  return h('label', {class: 'ws-search'},
86
107
  ICONS.search,
87
108
  h('span', {class: 'ws-sr'}, text(s.search)),
@@ -94,19 +115,18 @@ function renderSearch(s) {
94
115
  * has more than `searchFrom` options. The runtime (`menus.js`) opens,
95
116
  * filters and navigates it; without JS the button still shows the value.
96
117
  *
97
- * @param {string} name - 'type' | 'key' | 'sort' (the runtime routes by it).
98
- * @param {Object} m
99
- * @param {string} m.id - Id prefix for this list.
100
- * @param {string} m.label - Accessible name ("Type").
101
- * @param {string} [m.prefix] - Visible lead-in ("Sort by"); otherwise the label is screen-reader only.
102
- * @param {string} m.value - The selected value.
103
- * @param {{value: string, label: string, count?: number}[]} m.options
104
- * @param {number} m.searchFrom - Options above which a search field is added.
105
- * @param {string} [m.placeholder] - The search field's placeholder (no field without one).
106
- * @param {string} m.noMatches - Shown when the search matches nothing.
107
- * @returns {string}
118
+ * @param name - 'type' | 'key' | 'sort' (the runtime routes by it).
119
+ * @param m
120
+ * @param m.id - Id prefix for this list.
121
+ * @param m.label - Accessible name ("Type").
122
+ * @param [m.prefix] - Visible lead-in ("Sort by"); otherwise the label is screen-reader only.
123
+ * @param m.value - The selected value.
124
+ * @param m.options
125
+ * @param m.searchFrom - Options above which a search field is added.
126
+ * @param [m.placeholder] - The search field's placeholder (no field without one).
127
+ * @param m.noMatches - Shown when the search matches nothing.
108
128
  */
109
- export function renderMenu(name, m) {
129
+ export function renderMenu(name: string, m: MenuSpec): string {
110
130
  const listId = `${m.id}-${name}-list`;
111
131
  const current = m.options.find((o) => o.value === m.value) ?? m.options[0];
112
132
  const searchable = m.placeholder && m.options.length > m.searchFrom;
@@ -145,15 +165,15 @@ export function renderMenu(name, m) {
145
165
  * range input (keyboard, screen readers and touch for free); the two share
146
166
  * one track. The runtime (`menus.js` + the core) wires it.
147
167
  *
148
- * @param {Object} m
149
- * @param {string} m.id - Id prefix for this list.
150
- * @param {typeof DEFAULT_STRINGS} m.s
151
- * @param {{min: number, max: number}} m.range - The pack's BPM range.
152
- * @returns {string}
168
+ * @param m
169
+ * @param m.id - Id prefix for this list.
170
+ * @param m.s
171
+ * @param m.range - The slider's range: the pack's, widened to whole BPMs
172
+ * ({@link bpmExtent}; a pack of whole BPMs renders as it always did).
153
173
  */
154
- function renderBpmMenu({id, s, range}) {
174
+ function renderBpmMenu({id, s, range}: {id: string, s: WaveformSoundsStrings, range: {min: number, max: number}}): string {
155
175
  const popId = `${id}-bpm-pop`;
156
- const handle = (attr, label, value) => h('input', {
176
+ const handle = (attr: string, label: string, value: number) => h('input', {
157
177
  type: 'range', class: 'ws-range-input', [attr]: true, 'aria-label': label,
158
178
  min: range.min, max: range.max, step: '1', value,
159
179
  });
@@ -180,20 +200,20 @@ function renderBpmMenu({id, s, range}) {
180
200
  /**
181
201
  * Loops or one-shots: three buttons, one pressed ('' = both).
182
202
  */
183
- function renderLoopFilter(s) {
184
- const button = (value, label) => h('button', {type: 'button', class: 'ws-seg-btn', 'data-ws-loop-filter': value, 'aria-pressed': String(value === '')},
203
+ function renderLoopFilter(s: WaveformSoundsStrings): string {
204
+ const button = (value: string, label: string) => h('button', {type: 'button', class: 'ws-seg-btn', 'data-ws-loop-filter': value, 'aria-pressed': String(value === '')},
185
205
  h('span', {}, text(label)));
186
206
  return h('div', {class: 'ws-seg', role: 'group', 'aria-label': s.loopFilter},
187
207
  button('', s.all), button('loop', s.loops), button('one-shot', s.oneShots));
188
208
  }
189
209
 
190
210
  /** The Loop toggle, pressed or not. */
191
- function renderLoopToggle(s, pressed) {
211
+ function renderLoopToggle(s: WaveformSoundsStrings, pressed: boolean): string {
192
212
  return h('button', {type: 'button', class: 'ws-loop', 'data-ws-loop': true, 'aria-pressed': String(pressed)}, ICONS.loop, h('span', {}, text(s.loop)));
193
213
  }
194
214
 
195
215
  /** One type chip ('' = all). */
196
- function renderChip(value, label, count, pressed) {
216
+ function renderChip(value: string, label: string, count: number, pressed: boolean): string {
197
217
  return h('button', {type: 'button', class: 'ws-chip', 'data-ws-type': value, 'aria-pressed': String(pressed)},
198
218
  h('span', {class: 'ws-chip-label'}, text(label)), ' ', h('span', {class: 'ws-chip-count'}, text(count)));
199
219
  }
@@ -202,12 +222,11 @@ function renderChip(value, label, count, pressed) {
202
222
  * The toolbar: search, the controls row (type menu, key menu, BPM range,
203
223
  * loops or one-shots, sort menu, Loop) and the meta row (type chips + the count).
204
224
  *
205
- * @param {ReturnType<typeof toolbarPlan>} plan
206
- * @param {Object} ctx - `{o, s, f, total, id}` from {@link renderSounds}.
207
- * @returns {string}
225
+ * @param plan
226
+ * @param ctx - `{o, s, f, total, id}` from {@link renderSounds}.
208
227
  */
209
- function renderToolbar(plan, {o, s, f, total, id}) {
210
- const menu = (name, m) => renderMenu(name, {id, searchFrom: o.menuSearch, noMatches: s.noMatches, ...m});
228
+ function renderToolbar(plan: ReturnType<typeof toolbarPlan>, {o, s, f, total, id}: RenderContext): string {
229
+ const menu = (name: string, m: Omit<MenuSpec, 'id' | 'searchFrom' | 'noMatches'>) => renderMenu(name, {id, searchFrom: o.menuSearch, noMatches: s.noMatches, ...m});
211
230
  const controls = [
212
231
  plan.types === 'menu' && menu('type', {
213
232
  label: s.types, value: '', placeholder: s.findType,
@@ -217,11 +236,11 @@ function renderToolbar(plan, {o, s, f, total, id}) {
217
236
  label: s.key, value: '', placeholder: s.findKey,
218
237
  options: [{value: '', label: s.anyKey}, ...f.keys.map((k) => ({value: k, label: k}))],
219
238
  }),
220
- plan.bpm && renderBpmMenu({id, s, range: f.bpm}),
239
+ plan.bpm && renderBpmMenu({id, s, range: bpmExtent(f.bpm)!}),
221
240
  plan.loops && renderLoopFilter(s),
222
241
  plan.sorts.length > 0 && menu('sort', {
223
242
  label: s.sort, prefix: s.sortBy, value: plan.sorts[0],
224
- options: plan.sorts.map((k) => ({value: k, label: s[SORT_LABEL_KEYS[k]]})),
243
+ options: plan.sorts.map((k) => ({value: k, label: s[SORT_LABEL_KEYS[k as SoundsSort]]})),
225
244
  }),
226
245
  plan.loop && renderLoopToggle(s, loopsByDefault(o.loop, f)),
227
246
  ].filter(Boolean);
@@ -243,7 +262,7 @@ function renderToolbar(plan, {o, s, f, total, id}) {
243
262
  /* ── Rows ───────────────────────────────────────────────────────────── */
244
263
 
245
264
  /** The cells a column shows for a sound. */
246
- const CELLS = {
265
+ const CELLS: Record<string, (sound: Sound) => string> = {
247
266
  type: (sound) => text(sound.type),
248
267
  bpm: (sound) => text(sound.bpm ?? ''),
249
268
  key: (sound) => text(sound.key),
@@ -256,13 +275,12 @@ const CELLS = {
256
275
  * sorted into. Every field is also written as a `data-*` attribute, so the
257
276
  * runtime can rebuild the sounds from server markup.
258
277
  *
259
- * @param {import('../../../index').Sound} sound - Normalised.
260
- * @param {number} index
261
- * @param {ReturnType<typeof resolveRenderOptions>} o
262
- * @param {boolean} [hidden] - Past the first page.
263
- * @returns {string}
278
+ * @param sound - Normalised.
279
+ * @param index
280
+ * @param o
281
+ * @param hidden - Past the first page.
264
282
  */
265
- export function renderRow(sound, index, o, hidden = false) {
283
+ export function renderRow(sound: Sound, index: number, o: ReturnType<typeof resolveRenderOptions>, hidden: boolean = false): string {
266
284
  const s = o.strings;
267
285
  const vars = {title: sound.title};
268
286
  const cells = o.columns.map((c) => h('span', {class: `ws-cell ws-${c}`}, CELLS[c](sound)));
@@ -306,7 +324,7 @@ export function renderRow(sound, index, o, hidden = false) {
306
324
  * What follows the rows: the empty state, "Show more", the engine's slot
307
325
  * (visible only in the strip layout) and a live region for announcements.
308
326
  */
309
- function renderFooter({o, s, total}) {
327
+ function renderFooter({o, s, total}: RenderContext): string {
310
328
  const page = o.pageSize > 0 ? o.pageSize : total;
311
329
  const more = Math.max(0, total - page);
312
330
  const strip = o.player === 'strip';
@@ -322,14 +340,14 @@ function renderFooter({o, s, total}) {
322
340
  /**
323
341
  * The whole component's inner markup.
324
342
  *
325
- * @param {Object[]} sounds - Sounds (normalised or raw; normalised here).
326
- * @param {Object} [options] - Render options (see `WaveformSoundsOptions`).
327
- * @returns {string} HTML for the inside of `[data-waveform-sounds]`.
343
+ * @param sounds - Sounds (normalised or raw; normalised here).
344
+ * @param options - Render options (see `WaveformSoundsOptions`).
345
+ * @returns HTML for the inside of `[data-waveform-sounds]`.
328
346
  */
329
- export function renderSounds(sounds, options = {}) {
347
+ export function renderSounds(sounds: SoundInput[], options: WaveformSoundsOptions = {}): string {
330
348
  const o = resolveRenderOptions(options);
331
349
  const list = normalizeSounds(sounds);
332
- const ctx = {o, s: o.strings, f: facets(list), total: list.length, id: o.idPrefix || idBase(list)};
350
+ const ctx: RenderContext = {o, s: o.strings, f: facets(list), total: list.length, id: o.idPrefix || idBase(list)};
333
351
  const page = o.pageSize > 0 ? o.pageSize : Infinity;
334
352
  return renderToolbar(toolbarPlan(ctx.f, o), ctx)
335
353
  + h('ul', {class: `ws-list ws-list--${o.player}`, role: 'list', 'data-ws-list': true},
@@ -337,17 +355,49 @@ export function renderSounds(sounds, options = {}) {
337
355
  + renderFooter(ctx);
338
356
  }
339
357
 
358
+ /**
359
+ * The `data-*` attributes that carry the render options set in `options` to
360
+ * the runtime (`data-page-size="20"`, `data-filters=""`, `data-strings='{…}'`),
361
+ * in the form `readDataOptions` reads — so the browser keeps what the server
362
+ * drew instead of falling back to the defaults (re-paging 20 rows to 50).
363
+ * Only options that are set are written; `player` is always written by
364
+ * {@link renderSoundsElement}. Since 2.1.0.
365
+ *
366
+ * @param options
367
+ * @returns Attributes, in {@link RENDER_OPTION_KEYS} order.
368
+ */
369
+ export function renderOptionAttributes(options: WaveformSoundsOptions = {}): Record<string, string> {
370
+ const set = pickRenderOptions(options) as Record<string, unknown>;
371
+ const o = resolveRenderOptions(options) as Record<string, unknown>;
372
+ const out: Record<string, string> = {};
373
+ for (const key of RENDER_OPTION_KEYS) {
374
+ if (key === 'player' || !(key in set)) continue;
375
+ const name = `data-${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`;
376
+ if (key === 'strings') {
377
+ const strings = defined(set.strings as Record<string, unknown>);
378
+ if (Object.keys(strings).length) out[name] = JSON.stringify(strings);
379
+ } else if (key === 'loop' || key === 'idPrefix') {
380
+ out[name] = String(set[key]);
381
+ } else {
382
+ const value = o[key];
383
+ out[name] = Array.isArray(value) ? value.join(',') : String(value);
384
+ }
385
+ }
386
+ return out;
387
+ }
388
+
340
389
  /**
341
390
  * The full element, for callers who want one string: the wrapper div with
342
- * its `data-waveform-sounds` marker, its `data-player` and the inner markup.
391
+ * its `data-waveform-sounds` marker, its `data-player`, a `data-*` attribute
392
+ * for every other render option set (see {@link renderOptionAttributes}) and
393
+ * the inner markup. The inner markup is exactly {@link renderSounds}'.
343
394
  *
344
- * @param {Object[]} sounds
345
- * @param {Object} [options]
346
- * @param {string} [className] - Extra classes for the wrapper.
347
- * @returns {string}
395
+ * @param sounds
396
+ * @param options
397
+ * @param className - Extra classes for the wrapper.
348
398
  */
349
- export function renderSoundsElement(sounds, options = {}, className = '') {
399
+ export function renderSoundsElement(sounds: SoundInput[], options: WaveformSoundsOptions = {}, className: string = ''): string {
350
400
  const o = resolveRenderOptions(options);
351
401
  const cls = ['waveform-sounds', `waveform-sounds--${o.player}`, className].filter(Boolean).join(' ');
352
- return h('div', {class: cls, 'data-waveform-sounds': true, 'data-player': o.player}, renderSounds(sounds, options));
402
+ return h('div', {class: cls, 'data-waveform-sounds': true, 'data-player': o.player, ...renderOptionAttributes(options)}, renderSounds(sounds, options));
353
403
  }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * The options that shape the markup — the renderer's whole input — with
3
+ * their defaults and validation. DOM-free: the server renderer uses it,
4
+ * and the runtime's option surface (`core/options.js`) builds on it.
5
+ *
6
+ * @module render/options
7
+ */
8
+
9
+ import {SORTS} from '../data/sounds.js';
10
+ import {DEFAULT_STRINGS} from './strings.js';
11
+ import type {SoundsColumn, SoundsFilterControl, WaveformSoundsOptions, WaveformSoundsStrings} from '../types.js';
12
+
13
+ /** The filter controls a list can offer. */
14
+ export const FILTERS: SoundsFilterControl[] = ['type', 'key', 'bpm', 'loop'];
15
+
16
+ /** The columns a row can show after its title. */
17
+ export const COLUMNS: SoundsColumn[] = ['type', 'bpm', 'key', 'duration'];
18
+
19
+ /** The options that shape the markup (the renderer's whole input). */
20
+ export const RENDER_DEFAULTS: Required<Pick<WaveformSoundsOptions,
21
+ 'player' | 'search' | 'filters' | 'sorts' | 'loopToggle' | 'showCount' | 'menuSearch' | 'pageSize' | 'columns' | 'maxTypeChips'>> = {
22
+ player: 'inline',
23
+ search: true,
24
+ filters: [...FILTERS],
25
+ sorts: [...SORTS],
26
+ loopToggle: true,
27
+ showCount: true,
28
+ menuSearch: 8,
29
+ pageSize: 50,
30
+ columns: [...COLUMNS],
31
+ maxTypeChips: 10,
32
+ };
33
+
34
+ /** {@link resolveRenderOptions}' result: the render options, complete, plus
35
+ * whatever else the caller passed. */
36
+ export type RenderOptions = typeof RENDER_DEFAULTS & {strings: WaveformSoundsStrings, idPrefix?: string, loop?: boolean | null};
37
+
38
+ /**
39
+ * Every option that shapes the server markup: the render defaults, plus
40
+ * `idPrefix` (the dropdowns' ids), `loop` (whether the Loop toggle starts
41
+ * pressed) and `strings`. A wrapper that renders on the server passes
42
+ * exactly these to `renderSounds` — and the same values to the runtime, or
43
+ * the browser re-lays out what the server drew. Since 2.1.0.
44
+ */
45
+ export const RENDER_OPTION_KEYS = [...Object.keys(RENDER_DEFAULTS), 'idPrefix', 'loop', 'strings'] as (keyof WaveformSoundsOptions)[];
46
+
47
+ /**
48
+ * The render options set in `options` (those in {@link RENDER_OPTION_KEYS}
49
+ * that aren't null or undefined), for handing a component's options to
50
+ * `renderSounds` on the server. Since 2.1.0.
51
+ *
52
+ * @param options - Any `WaveformSoundsOptions` (or a component's props).
53
+ * @returns Just the render options that are set.
54
+ */
55
+ export function pickRenderOptions(options: WaveformSoundsOptions | null | undefined): WaveformSoundsOptions {
56
+ const out: Record<string, unknown> = {};
57
+ for (const key of RENDER_OPTION_KEYS) {
58
+ const value = (options as Record<string, unknown> | null | undefined)?.[key];
59
+ if (value != null) out[key] = value;
60
+ }
61
+ return out as WaveformSoundsOptions;
62
+ }
63
+
64
+ /**
65
+ * The object without its `undefined` entries (so spreading it can't erase
66
+ * a default).
67
+ *
68
+ * @param obj
69
+ */
70
+ export function defined(obj: Record<string, any> | null | undefined): Record<string, any> {
71
+ const out: Record<string, any> = {};
72
+ for (const k in obj ?? {}) if (obj![k] !== undefined) out[k] = obj![k];
73
+ return out;
74
+ }
75
+
76
+ /**
77
+ * The entries of `values` that are allowed, in the caller's order; the
78
+ * fallback when `values` isn't a list.
79
+ *
80
+ * @param values
81
+ * @param allowed
82
+ * @param fallback
83
+ */
84
+ export function allowedList<T extends string>(values: unknown, allowed: T[], fallback: T[]): T[] {
85
+ return Array.isArray(values) ? values.filter((v) => allowed.includes(v)) : fallback;
86
+ }
87
+
88
+ /**
89
+ * A whole number ≥ 0, or the fallback.
90
+ *
91
+ * @param value
92
+ * @param fallback
93
+ */
94
+ export function wholeNumber(value: unknown, fallback: number): number {
95
+ const n = Number(value);
96
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : fallback;
97
+ }
98
+
99
+ /**
100
+ * The render options, defaulted and validated: unknown filters, sorts and
101
+ * columns are dropped, counts are whole numbers, `strings` is complete.
102
+ *
103
+ * @param options
104
+ */
105
+ export function resolveRenderOptions(options: WaveformSoundsOptions = {}): RenderOptions {
106
+ const o = {...RENDER_DEFAULTS, ...defined(options)};
107
+ return {
108
+ ...o,
109
+ player: o.player === 'strip' ? 'strip' : 'inline',
110
+ filters: allowedList(o.filters, FILTERS, RENDER_DEFAULTS.filters),
111
+ sorts: allowedList(o.sorts, SORTS, RENDER_DEFAULTS.sorts),
112
+ columns: allowedList(o.columns, COLUMNS, RENDER_DEFAULTS.columns),
113
+ menuSearch: wholeNumber(o.menuSearch, RENDER_DEFAULTS.menuSearch),
114
+ maxTypeChips: wholeNumber(o.maxTypeChips, RENDER_DEFAULTS.maxTypeChips),
115
+ pageSize: wholeNumber(o.pageSize, RENDER_DEFAULTS.pageSize),
116
+ strings: {...DEFAULT_STRINGS, ...defined(options.strings)},
117
+ };
118
+ }
@@ -7,9 +7,10 @@
7
7
  */
8
8
 
9
9
  import {bpmRangeFromFilter, hasBpmFilter} from '../data/bpm.js';
10
+ import type {SoundsSort, WaveformSoundsStrings} from '../types.js';
10
11
 
11
12
  /** The English defaults. */
12
- export const DEFAULT_STRINGS = {
13
+ export const DEFAULT_STRINGS: WaveformSoundsStrings = {
13
14
  search: 'Search sounds',
14
15
  searchPlaceholder: 'Search sounds…',
15
16
  all: 'All',
@@ -40,6 +41,7 @@ export const DEFAULT_STRINGS = {
40
41
  play: 'Play {title}',
41
42
  pause: 'Pause {title}',
42
43
  seek: 'Seek {title}',
44
+ seekValue: '{time} of {duration}',
43
45
  download: 'Download {title}',
44
46
  count: '{count} sounds',
45
47
  countOne: '1 sound',
@@ -48,10 +50,13 @@ export const DEFAULT_STRINGS = {
48
50
  empty: 'No sounds match.',
49
51
  clear: 'Clear filters',
50
52
  nowPlaying: 'Playing {title}',
53
+ playError: 'Could not play {title}',
54
+ loadError: 'Could not load the sounds.',
55
+ noSounds: 'No sounds.',
51
56
  };
52
57
 
53
58
  /** The label each sort order shows in the Sort menu. */
54
- export const SORT_LABEL_KEYS = {
59
+ export const SORT_LABEL_KEYS: Record<SoundsSort, keyof WaveformSoundsStrings> = {
55
60
  default: 'sortDefault',
56
61
  title: 'sortTitle',
57
62
  bpm: 'sortBpm',
@@ -62,11 +67,10 @@ export const SORT_LABEL_KEYS = {
62
67
  /**
63
68
  * Fill `{name}` placeholders; unknown ones are left as written.
64
69
  *
65
- * @param {string} template
66
- * @param {Record<string, string|number>} [vars]
67
- * @returns {string}
70
+ * @param template
71
+ * @param vars
68
72
  */
69
- export function fill(template, vars = {}) {
73
+ export function fill(template: string, vars: Record<string, string|number> = {}): string {
70
74
  return String(template).replace(/\{(\w+)\}/g, (match, name) => (name in vars ? String(vars[name]) : match));
71
75
  }
72
76
 
@@ -74,12 +78,11 @@ export function fill(template, vars = {}) {
74
78
  * The BPM menu's label: "Any BPM", or the range the handles hold
75
79
  * ("120–128 BPM"; an open end shows the pack's own end).
76
80
  *
77
- * @param {{bpmMin?: string|number, bpmMax?: string|number}} filter
78
- * @param {{min: number, max: number}} extent - The pack's BPM range.
79
- * @param {typeof DEFAULT_STRINGS} [strings]
80
- * @returns {string}
81
+ * @param filter
82
+ * @param extent - The pack's BPM range.
83
+ * @param strings
81
84
  */
82
- export function bpmLabel(filter, extent, strings = DEFAULT_STRINGS) {
85
+ export function bpmLabel(filter: {bpmMin?: string|number, bpmMax?: string|number}, extent: {min: number, max: number}, strings: typeof DEFAULT_STRINGS = DEFAULT_STRINGS): string {
83
86
  if (!hasBpmFilter(filter)) return strings.anyBpm;
84
87
  const {lo, hi} = bpmRangeFromFilter(filter, extent);
85
88
  return fill(strings.bpmRange, {min: lo, max: hi});
@@ -88,12 +91,11 @@ export function bpmLabel(filter, extent, strings = DEFAULT_STRINGS) {
88
91
  /**
89
92
  * The count line: "300 sounds", "1 sound", "12 of 300 sounds".
90
93
  *
91
- * @param {number} shown - Sounds matching the filter.
92
- * @param {number} total - All sounds.
93
- * @param {typeof DEFAULT_STRINGS} [strings]
94
- * @returns {string}
94
+ * @param shown - Sounds matching the filter.
95
+ * @param total - All sounds.
96
+ * @param strings
95
97
  */
96
- export function countText(shown, total, strings = DEFAULT_STRINGS) {
98
+ export function countText(shown: number, total: number, strings: typeof DEFAULT_STRINGS = DEFAULT_STRINGS): string {
97
99
  if (shown !== total) return fill(strings.countFiltered, {count: shown, total});
98
100
  return total === 1 ? strings.countOne : fill(strings.count, {count: total});
99
101
  }
@@ -2,5 +2,6 @@
2
2
  * `@arraypress/waveform-sounds/render` — the DOM-free half, for server
3
3
  * rendering. Importing it never touches `window` or `document`.
4
4
  */
5
- export {renderSounds, renderSoundsElement, DEFAULT_STRINGS, escapeHtml} from './render/markup.js';
5
+ export {renderSounds, renderSoundsElement, DEFAULT_STRINGS, escapeHtml, RENDER_OPTION_KEYS, pickRenderOptions} from './render/markup.js';
6
6
  export {normalizeSounds, parseManifest, encodePeaks, decodePeaks, normalizeKey, facets, formatDuration} from './data/sounds.js';
7
+ export type {SoundInput, Sound, SoundsManifest, WaveformSoundsOptions, WaveformSoundsStrings} from './types.js';
@@ -11,12 +11,11 @@ export const LOG = '[WaveformSounds]';
11
11
  /**
12
12
  * Clamp a number into a range.
13
13
  *
14
- * @param {number} value
15
- * @param {number} [min=0]
16
- * @param {number} [max=1]
17
- * @returns {number}
14
+ * @param value
15
+ * @param min
16
+ * @param max
18
17
  */
19
- export function clamp(value, min = 0, max = 1) {
18
+ export function clamp(value: number, min: number = 0, max: number = 1): number {
20
19
  return Math.min(Math.max(value, min), max);
21
20
  }
22
21
 
@@ -24,11 +23,11 @@ export function clamp(value, min = 0, max = 1) {
24
23
  * Where a pointer sits across a box, as a fraction 0..1 — the seek
25
24
  * position of a click on a row waveform.
26
25
  *
27
- * @param {number} clientX - The pointer's x (viewport coordinates).
28
- * @param {{left: number, width: number}} rect - The box (getBoundingClientRect()).
29
- * @returns {number} 0..1; 0 for a box with no width.
26
+ * @param clientX - The pointer's x (viewport coordinates).
27
+ * @param rect - The box (getBoundingClientRect()).
28
+ * @returns 0..1; 0 for a box with no width.
30
29
  */
31
- export function pointerFraction(clientX, rect) {
30
+ export function pointerFraction(clientX: number, rect: {left: number, width: number}): number {
32
31
  return rect && rect.width ? clamp((clientX - rect.left) / rect.width) : 0;
33
32
  }
34
33
 
@@ -36,25 +35,26 @@ export function pointerFraction(clientX, rect) {
36
35
  * Is the element a place the user types into? Keyboard shortcuts (`/`)
37
36
  * must not fire there.
38
37
  *
39
- * @param {Element|null|undefined} el
40
- * @returns {boolean}
38
+ * @param el
41
39
  */
42
- export function isTyping(el) {
43
- return !!el && (el.isContentEditable || /^(INPUT|SELECT|TEXTAREA)$/.test(el.tagName));
40
+ export function isTyping(el: Element | null | undefined): boolean {
41
+ return !!el && ((el as HTMLElement).isContentEditable || /^(INPUT|SELECT|TEXTAREA)$/.test(el.tagName));
44
42
  }
45
43
 
46
44
  /**
47
- * Dispatch a bubbling `waveformsounds:<name>` CustomEvent from an element.
45
+ * Dispatch a bubbling, composed `waveformsounds:<name>` CustomEvent from an
46
+ * element (composed: it leaves a shadow root, like the core's lifecycle
47
+ * events).
48
48
  * Every event the list emits goes through here, so they share one shape:
49
49
  * the detail plus the instance that sent it.
50
50
  *
51
- * @param {EventTarget} target
52
- * @param {string} name - Without the prefix (`'play'`).
53
- * @param {Object} detail
54
- * @returns {CustomEvent} The event dispatched.
51
+ * @param target
52
+ * @param name - Without the prefix (`'play'`).
53
+ * @param detail
54
+ * @returns The event dispatched.
55
55
  */
56
- export function emit(target, name, detail) {
57
- const event = new CustomEvent(`waveformsounds:${name}`, {bubbles: true, detail});
56
+ export function emit(target: EventTarget, name: string, detail: Record<string, any>): CustomEvent {
57
+ const event = new CustomEvent(`waveformsounds:${name}`, {bubbles: true, composed: true, detail});
58
58
  target.dispatchEvent(event);
59
59
  return event;
60
60
  }
@@ -63,11 +63,11 @@ export function emit(target, name, detail) {
63
63
  * A small, stable string hash (djb2, 32-bit) — for ids that must come out
64
64
  * the same on the server and in the browser. Not cryptographic.
65
65
  *
66
- * @param {string} str
67
- * @returns {number} An unsigned 32-bit integer.
66
+ * @param str
67
+ * @returns An unsigned 32-bit integer.
68
68
  */
69
- export function hashString(str) {
69
+ export function hashString(str: string): number {
70
70
  let hash = 5381;
71
- for (const char of str) hash = (hash * 33 + char.codePointAt(0)) >>> 0;
71
+ for (const char of str) hash = (hash * 33 + char.codePointAt(0)!) >>> 0;
72
72
  return hash;
73
73
  }