@arraypress/waveform-sounds 2.0.0 → 2.2.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 (79) hide show
  1. package/README.md +44 -2
  2. package/dist/waveform-sounds-no-autoinit.esm.js +914 -208
  3. package/dist/waveform-sounds-render.esm.js +274 -82
  4. package/dist/waveform-sounds.css +92 -17
  5. package/dist/waveform-sounds.esm.js +917 -210
  6. package/dist/waveform-sounds.js +913 -210
  7. package/dist/waveform-sounds.min.css +1 -1
  8. package/dist/waveform-sounds.min.js +3 -3
  9. package/package.json +1 -1
  10. package/src/css/waveform-sounds.css +92 -17
  11. package/src/js/core/WaveformSounds.ts +540 -120
  12. package/src/js/core/element.ts +208 -0
  13. package/src/js/core/engine.ts +9 -3
  14. package/src/js/core/options.ts +1 -5
  15. package/src/js/data/bpm.ts +14 -4
  16. package/src/js/data/keys.ts +156 -0
  17. package/src/js/data/navigation.ts +51 -11
  18. package/src/js/data/sounds.ts +73 -36
  19. package/src/js/data/url-state.ts +39 -12
  20. package/src/js/dom/colors.ts +28 -1
  21. package/src/js/dom/draw.ts +16 -3
  22. package/src/js/dom/menus.ts +2 -3
  23. package/src/js/dom/rows.ts +38 -15
  24. package/src/js/entry.ts +13 -3
  25. package/src/js/index.ts +7 -3
  26. package/src/js/render/html.ts +0 -2
  27. package/src/js/render/icons.ts +59 -17
  28. package/src/js/render/markup.ts +156 -62
  29. package/src/js/render/options.ts +29 -5
  30. package/src/js/render/strings.ts +57 -4
  31. package/src/js/render-entry.ts +1 -1
  32. package/src/js/shared/utils.ts +4 -4
  33. package/src/js/types.ts +54 -3
  34. package/types/core/WaveformSounds.d.ts +41 -11
  35. package/types/core/WaveformSounds.d.ts.map +1 -1
  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 +8 -3
  39. package/types/core/engine.d.ts.map +1 -1
  40. package/types/core/options.d.ts +0 -5
  41. package/types/core/options.d.ts.map +1 -1
  42. package/types/data/bpm.d.ts +17 -4
  43. package/types/data/bpm.d.ts.map +1 -1
  44. package/types/data/keys.d.ts +88 -0
  45. package/types/data/keys.d.ts.map +1 -0
  46. package/types/data/navigation.d.ts +38 -11
  47. package/types/data/navigation.d.ts.map +1 -1
  48. package/types/data/sounds.d.ts +33 -17
  49. package/types/data/sounds.d.ts.map +1 -1
  50. package/types/data/url-state.d.ts +38 -7
  51. package/types/data/url-state.d.ts.map +1 -1
  52. package/types/dom/colors.d.ts +13 -0
  53. package/types/dom/colors.d.ts.map +1 -1
  54. package/types/dom/draw.d.ts +5 -3
  55. package/types/dom/draw.d.ts.map +1 -1
  56. package/types/dom/menus.d.ts +0 -2
  57. package/types/dom/menus.d.ts.map +1 -1
  58. package/types/dom/rows.d.ts +19 -11
  59. package/types/dom/rows.d.ts.map +1 -1
  60. package/types/entry.d.ts +10 -4
  61. package/types/entry.d.ts.map +1 -1
  62. package/types/index.d.ts +2 -2
  63. package/types/index.d.ts.map +1 -1
  64. package/types/render/html.d.ts +0 -2
  65. package/types/render/html.d.ts.map +1 -1
  66. package/types/render/icons.d.ts +41 -3
  67. package/types/render/icons.d.ts.map +1 -1
  68. package/types/render/markup.d.ts +44 -12
  69. package/types/render/markup.d.ts.map +1 -1
  70. package/types/render/options.d.ts +18 -5
  71. package/types/render/options.d.ts.map +1 -1
  72. package/types/render/strings.d.ts +22 -4
  73. package/types/render/strings.d.ts.map +1 -1
  74. package/types/render-entry.d.ts +1 -1
  75. package/types/render-entry.d.ts.map +1 -1
  76. package/types/shared/utils.d.ts +3 -3
  77. package/types/shared/utils.d.ts.map +1 -1
  78. package/types/types.d.ts +53 -3
  79. package/types/types.d.ts.map +1 -1
@@ -1,29 +1,71 @@
1
1
  /**
2
2
  * The list's icons: 24×24 single-path SVGs that take `currentColor`, so
3
- * they follow whatever colour their control has. Decorative (aria-hidden);
4
- * every control carries its own label.
3
+ * they follow whatever colour their control has (and the system colours
4
+ * under forced colours). Decorative (aria-hidden); every control carries
5
+ * its own label.
6
+ *
7
+ * Each icon is defined ONCE per list, as a `<symbol>` in a hidden sprite
8
+ * ({@link iconSprite}), and every use is a `<use>` of it ({@link icon}):
9
+ * a row's play and pause icons were ~240 bytes of inline paths, on every
10
+ * row. The symbol ids carry the list's id prefix, so two lists on a page
11
+ * never share (or break) each other's icons. Since 2.2.0.
5
12
  *
6
13
  * @module icons
7
14
  */
8
15
 
16
+ import {escapeHtml} from '@arraypress/text';
17
+
18
+ /** Every icon's path data. */
19
+ export const ICON_PATHS = {
20
+ play: 'M8 5.5v13l11-6.5z',
21
+ pause: 'M7 5h3.5v14H7zM13.5 5H17v14h-3.5z',
22
+ search: 'M10.5 4a6.5 6.5 0 1 0 4.03 11.6l4.43 4.43 1.41-1.41-4.43-4.43A6.5 6.5 0 0 0 10.5 4zm0 2a4.5 4.5 0 1 1 0 9 4.5 4.5 0 0 1 0-9z',
23
+ chevron: 'M6.4 8.6 12 14.2l5.6-5.6L19 10l-7 7-7-7z',
24
+ check: 'M9.5 16.2 5.3 12l-1.4 1.4 5.6 5.6 11-11-1.4-1.4z',
25
+ download: 'M11 4h2v8.6l3.3-3.3 1.4 1.4L12 16.4l-5.7-5.7 1.4-1.4 3.3 3.3zM5 18h14v2H5z',
26
+ loop: 'M17 4l3 3-3 3V8H8a3 3 0 0 0-3 3v1H3v-1a5 5 0 0 1 5-5h9V4zM7 20l-3-3 3-3v2h9a3 3 0 0 0 3-3v-1h2v1a5 5 0 0 1-5 5H7v2z',
27
+ };
28
+
29
+ /** An icon's name. */
30
+ export type IconName = keyof typeof ICON_PATHS;
31
+
32
+ /** Every icon, in sprite order. */
33
+ export const ICON_NAMES = Object.keys(ICON_PATHS) as IconName[];
34
+
35
+ /**
36
+ * A symbol's id: the list's id prefix + the icon (`ws1x9k2f-i-play`).
37
+ *
38
+ * @param id - The list's id prefix.
39
+ * @param name
40
+ */
41
+ export function iconId(id: string, name: IconName): string {
42
+ return `${id}-i-${name}`;
43
+ }
44
+
9
45
  /**
10
- * One icon.
46
+ * The sprite: one hidden `<svg>` holding a `<symbol>` for each icon the
47
+ * list uses. Zero-sized by its attributes (no CSS needed, no style
48
+ * attribute for a CSP to block), not `display: none` (some engines drop
49
+ * what a hidden SVG defines). `data-ws-sprite` names the id prefix, so the
50
+ * runtime renders new rows against the same symbols.
11
51
  *
12
- * @param path - The SVG path data.
52
+ * @param id - The list's id prefix.
53
+ * @param names - The icons to define.
54
+ */
55
+ export function iconSprite(id: string, names: IconName[]): string {
56
+ const symbols = ICON_NAMES.filter((n) => names.includes(n))
57
+ .map((n) => `<symbol id="${escapeHtml(iconId(id, n))}" viewBox="0 0 24 24"><path d="${ICON_PATHS[n]}"/></symbol>`).join('');
58
+ return `<svg class="ws-sprite" data-ws-sprite="${escapeHtml(id)}" width="0" height="0" aria-hidden="true" focusable="false">${symbols}</svg>`;
59
+ }
60
+
61
+ /**
62
+ * One icon: a `<use>` of its symbol in the list's sprite.
63
+ *
64
+ * @param id - The list's id prefix.
65
+ * @param name
13
66
  * @param extraClass - Classes beyond `ws-icon`.
14
- * @returns
15
67
  */
16
- function icon(path: string, extraClass: string = ''): string {
68
+ export function icon(id: string, name: IconName, extraClass: string = ''): string {
17
69
  const cls = extraClass ? `ws-icon ${extraClass}` : 'ws-icon';
18
- return `<svg class="${cls}" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="${path}"/></svg>`;
70
+ return `<svg class="${cls}" aria-hidden="true" focusable="false"><use href="#${escapeHtml(iconId(id, name))}"/></svg>`;
19
71
  }
20
-
21
- export const ICONS = {
22
- play: icon('M8 5.5v13l11-6.5z', 'ws-icon-play'),
23
- pause: icon('M7 5h3.5v14H7zM13.5 5H17v14h-3.5z', 'ws-icon-pause'),
24
- search: icon('M10.5 4a6.5 6.5 0 1 0 4.03 11.6l4.43 4.43 1.41-1.41-4.43-4.43A6.5 6.5 0 0 0 10.5 4zm0 2a4.5 4.5 0 1 1 0 9 4.5 4.5 0 0 1 0-9z'),
25
- chevron: icon('M6.4 8.6 12 14.2l5.6-5.6L19 10l-7 7-7-7z', 'ws-menu-chevron'),
26
- check: icon('M9.5 16.2 5.3 12l-1.4 1.4 5.6 5.6 11-11-1.4-1.4z', 'ws-menu-check'),
27
- download: icon('M11 4h2v8.6l3.3-3.3 1.4 1.4L12 16.4l-5.7-5.7 1.4-1.4 3.3 3.3zM5 18h14v2H5z'),
28
- loop: icon('M17 4l3 3-3 3V8H8a3 3 0 0 0-3 3v1H3v-1a5 5 0 0 1 5-5h9V4zM7 20l-3-3 3-3v2h9a3 3 0 0 0 3-3v-1h2v1a5 5 0 0 1-5 5H7v2z'),
29
- };
@@ -12,19 +12,28 @@
12
12
  * `data-ws-*` attribute here is read by the runtime (`core.js`,
13
13
  * `menus.js`, `rows.js`).
14
14
  *
15
+ * Since 2.2.0 the markup carries the rows the list starts with (a page, or
16
+ * with paging off the first `RENDER_CHUNK`), in its starting order,
17
+ * and EVERY sound as JSON (`<script type="application/json"
18
+ * data-ws-sounds>`); the runtime renders the other rows from it as they
19
+ * are revealed. Icons are `<use>`s of one sprite per list.
20
+ *
15
21
  * @module render
16
22
  */
17
23
 
18
24
  import {escapeHtml} from '@arraypress/text';
19
- import {availableSorts, encodePeaks, facets, formatDuration, normalizeSounds} from '../data/sounds.js';
25
+ import {availableSorts, encodePeaks, facets, formatDuration, normalizeSounds, sortSounds} from '../data/sounds.js';
26
+ import {firstRender} from '../data/navigation.js';
20
27
  import {h, text} from './html.js';
21
- import {ICONS} from './icons.js';
22
- import {RENDER_DEFAULTS, resolveRenderOptions} from './options.js';
23
- import {bpmLabel, countText, DEFAULT_STRINGS, fill, SORT_LABEL_KEYS} from './strings.js';
28
+ import {icon, iconSprite} from './icons.js';
29
+ import type {IconName} from './icons.js';
30
+ import {defined, pickRenderOptions, RENDER_DEFAULTS, RENDER_OPTION_KEYS, resolveRenderOptions} from './options.js';
31
+ import {bpmLabel, countText, DEFAULT_STRINGS, fill, rowSummary, SORT_LABEL_KEYS} from './strings.js';
24
32
  import {hashString} from '../shared/utils.js';
33
+ import {bpmExtent} from '../data/bpm.js';
25
34
  import type {Sound, SoundInput, SoundsSort, WaveformSoundsOptions, WaveformSoundsStrings} from '../types.js';
26
35
 
27
- export {escapeHtml, RENDER_DEFAULTS, resolveRenderOptions, DEFAULT_STRINGS, countText, fill, availableSorts};
36
+ export {escapeHtml, RENDER_DEFAULTS, RENDER_OPTION_KEYS, pickRenderOptions, resolveRenderOptions, DEFAULT_STRINGS, countText, fill, availableSorts};
28
37
 
29
38
  /**
30
39
  * A stable id prefix for a list's dropdowns, from its sounds: the same on
@@ -49,7 +58,6 @@ export function idBase(sounds: {url: string}[]): string {
49
58
  *
50
59
  * @param f - The sounds' facets.
51
60
  * @param o - Resolved options.
52
- * @returns
53
61
  */
54
62
  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} {
55
63
  const typed = o.filters.includes('type') && f.types.length > 1;
@@ -73,7 +81,6 @@ export function toolbarPlan(f: ReturnType<typeof facets>, o: ReturnType<typeof r
73
81
  *
74
82
  * @param loop - The `loop` option.
75
83
  * @param f - The sounds' facets.
76
- * @returns
77
84
  */
78
85
  export function loopsByDefault(loop: boolean | null | undefined, f: {loops: number}): boolean {
79
86
  return loop == null ? f.loops > 0 : !!loop;
@@ -94,7 +101,9 @@ export interface MenuSpec {
94
101
  label: string;
95
102
  prefix?: string;
96
103
  value: string;
97
- options: {value: string, label: string, count?: number}[];
104
+ /** `alt`: other names the menu's search finds the option by (a merged
105
+ * key's other spellings). */
106
+ options: {value: string, label: string, count?: number, alt?: string}[];
98
107
  searchFrom: number;
99
108
  placeholder?: string;
100
109
  noMatches: string;
@@ -103,9 +112,9 @@ export interface MenuSpec {
103
112
  /* ── Controls ───────────────────────────────────────────────────────── */
104
113
 
105
114
  /** The search field. */
106
- function renderSearch(s: WaveformSoundsStrings): string {
115
+ function renderSearch(s: WaveformSoundsStrings, id: string): string {
107
116
  return h('label', {class: 'ws-search'},
108
- ICONS.search,
117
+ icon(id, 'search'),
109
118
  h('span', {class: 'ws-sr'}, text(s.search)),
110
119
  h('input', {type: 'search', class: 'ws-search-input', 'data-ws-search': true, placeholder: s.searchPlaceholder, autocomplete: 'off', spellcheck: 'false'}),
111
120
  );
@@ -126,7 +135,6 @@ function renderSearch(s: WaveformSoundsStrings): string {
126
135
  * @param m.searchFrom - Options above which a search field is added.
127
136
  * @param [m.placeholder] - The search field's placeholder (no field without one).
128
137
  * @param m.noMatches - Shown when the search matches nothing.
129
- * @returns
130
138
  */
131
139
  export function renderMenu(name: string, m: MenuSpec): string {
132
140
  const listId = `${m.id}-${name}-list`;
@@ -138,15 +146,15 @@ export function renderMenu(name: string, m: MenuSpec): string {
138
146
  ? h('span', {class: 'ws-menu-prefix'}, text(m.prefix))
139
147
  : h('span', {class: 'ws-sr'}, text(`${m.label}: `)),
140
148
  h('span', {class: 'ws-menu-value', 'data-ws-menu-value': true}, text(current.label)),
141
- ICONS.chevron,
149
+ icon(m.id, 'chevron', 'ws-menu-chevron'),
142
150
  );
143
151
  const search = searchable && h('input', {
144
152
  type: 'search', class: 'ws-menu-search', 'data-ws-menu-search': true, role: 'combobox',
145
153
  'aria-expanded': 'true', 'aria-controls': listId, 'aria-autocomplete': 'list',
146
154
  'aria-label': m.placeholder, placeholder: m.placeholder, autocomplete: 'off', spellcheck: 'false',
147
155
  });
148
- const options = m.options.map((o, i) => h('li', {role: 'option', id: `${m.id}-${name}-${i}`, class: 'ws-menu-option', 'data-value': o.value, 'aria-selected': String(o === current)},
149
- ICONS.check,
156
+ const options = m.options.map((o, i) => h('li', {role: 'option', id: `${m.id}-${name}-${i}`, class: 'ws-menu-option', 'data-value': o.value, 'data-alt': o.alt, 'aria-selected': String(o === current)},
157
+ icon(m.id, 'check', 'ws-menu-check'),
150
158
  h('span', {class: 'ws-menu-text'}, text(o.label)),
151
159
  o.count != null && h('span', {class: 'ws-menu-count'}, text(o.count)),
152
160
  ));
@@ -170,8 +178,8 @@ export function renderMenu(name: string, m: MenuSpec): string {
170
178
  * @param m
171
179
  * @param m.id - Id prefix for this list.
172
180
  * @param m.s
173
- * @param m.range - The pack's BPM range.
174
- * @returns
181
+ * @param m.range - The slider's range: the pack's, widened to whole BPMs
182
+ * ({@link bpmExtent}; a pack of whole BPMs renders as it always did).
175
183
  */
176
184
  function renderBpmMenu({id, s, range}: {id: string, s: WaveformSoundsStrings, range: {min: number, max: number}}): string {
177
185
  const popId = `${id}-bpm-pop`;
@@ -183,7 +191,7 @@ function renderBpmMenu({id, s, range}: {id: string, s: WaveformSoundsStrings, ra
183
191
  h('button', {type: 'button', class: 'ws-menu-btn', 'data-ws-menu-btn': true, 'aria-haspopup': 'dialog', 'aria-expanded': 'false', 'aria-controls': popId},
184
192
  h('span', {class: 'ws-sr'}, text(`${s.bpm}: `)),
185
193
  h('span', {class: 'ws-menu-value', 'data-ws-menu-value': true}, text(bpmLabel({}, range, s))),
186
- ICONS.chevron,
194
+ icon(id, 'chevron', 'ws-menu-chevron'),
187
195
  ),
188
196
  h('div', {class: 'ws-menu-pop ws-bpm-pop', id: popId, role: 'dialog', 'aria-label': s.bpm, 'data-ws-menu-pop': true, hidden: true},
189
197
  h('div', {class: 'ws-bpm-head'},
@@ -210,8 +218,8 @@ function renderLoopFilter(s: WaveformSoundsStrings): string {
210
218
  }
211
219
 
212
220
  /** The Loop toggle, pressed or not. */
213
- function renderLoopToggle(s: WaveformSoundsStrings, pressed: boolean): string {
214
- return h('button', {type: 'button', class: 'ws-loop', 'data-ws-loop': true, 'aria-pressed': String(pressed)}, ICONS.loop, h('span', {}, text(s.loop)));
221
+ function renderLoopToggle(s: WaveformSoundsStrings, pressed: boolean, id: string): string {
222
+ return h('button', {type: 'button', class: 'ws-loop', 'data-ws-loop': true, 'aria-pressed': String(pressed)}, icon(id, 'loop'), h('span', {}, text(s.loop)));
215
223
  }
216
224
 
217
225
  /** One type chip ('' = all). */
@@ -226,7 +234,6 @@ function renderChip(value: string, label: string, count: number, pressed: boolea
226
234
  *
227
235
  * @param plan
228
236
  * @param ctx - `{o, s, f, total, id}` from {@link renderSounds}.
229
- * @returns
230
237
  */
231
238
  function renderToolbar(plan: ReturnType<typeof toolbarPlan>, {o, s, f, total, id}: RenderContext): string {
232
239
  const menu = (name: string, m: Omit<MenuSpec, 'id' | 'searchFrom' | 'noMatches'>) => renderMenu(name, {id, searchFrom: o.menuSearch, noMatches: s.noMatches, ...m});
@@ -237,15 +244,15 @@ function renderToolbar(plan: ReturnType<typeof toolbarPlan>, {o, s, f, total, id
237
244
  }),
238
245
  plan.key && menu('key', {
239
246
  label: s.key, value: '', placeholder: s.findKey,
240
- options: [{value: '', label: s.anyKey}, ...f.keys.map((k) => ({value: k, label: k}))],
247
+ options: [{value: '', label: s.anyKey}, ...f.keys.map((k) => ({value: k, label: k, alt: f.keyAliases[k]?.join(' ')}))],
241
248
  }),
242
- plan.bpm && renderBpmMenu({id, s, range: f.bpm!}),
249
+ plan.bpm && renderBpmMenu({id, s, range: bpmExtent(f.bpm)!}),
243
250
  plan.loops && renderLoopFilter(s),
244
251
  plan.sorts.length > 0 && menu('sort', {
245
252
  label: s.sort, prefix: s.sortBy, value: plan.sorts[0],
246
253
  options: plan.sorts.map((k) => ({value: k, label: s[SORT_LABEL_KEYS[k as SoundsSort]]})),
247
254
  }),
248
- plan.loop && renderLoopToggle(s, loopsByDefault(o.loop, f)),
255
+ plan.loop && renderLoopToggle(s, loopsByDefault(o.loop, f), id),
249
256
  ].filter(Boolean);
250
257
 
251
258
  const chips = plan.types === 'chips' && h('div', {class: 'ws-types', role: 'group', 'aria-label': s.types},
@@ -255,7 +262,7 @@ function renderToolbar(plan: ReturnType<typeof toolbarPlan>, {o, s, f, total, id
255
262
  const count = plan.count && h('p', {class: 'ws-count', 'data-ws-count': true, 'aria-live': 'polite'}, text(countText(total, total, s)));
256
263
 
257
264
  return h('div', {class: 'ws-toolbar'},
258
- plan.search && renderSearch(s),
265
+ plan.search && renderSearch(s, id),
259
266
  controls.length > 0 && h('div', {class: 'ws-controls'}, controls),
260
267
  // The chips and the count share a row (the count alone without chips).
261
268
  (chips || count) && h('div', {class: 'ws-meta'}, chips, count),
@@ -275,53 +282,90 @@ const CELLS: Record<string, (sound: Sound) => string> = {
275
282
  /**
276
283
  * One row. `index` is the sound's position in the ORIGINAL list: the
277
284
  * runtime maps rows back to sounds through it, whatever order they are
278
- * sorted into. Every field is also written as a `data-*` attribute, so the
279
- * runtime can rebuild the sounds from server markup.
285
+ * sorted into. The sound's data is not on the row (since 2.2.0): it travels
286
+ * once, in the list's JSON ({@link renderSoundsData}).
287
+ *
288
+ * For a screen reader the cells are one read-out ("Bass loops, 130 BPM,
289
+ * key B minor, 0:07") that also describes the play button; the visible
290
+ * cells are hidden from it. The waveform is a picture until its sound is
291
+ * current: the runtime makes the current row's the seek slider.
280
292
  *
281
293
  * @param sound - Normalised.
282
294
  * @param index
283
295
  * @param o
284
- * @param hidden - Past the first page.
285
- * @returns
296
+ * @param id - The list's id prefix (its icons, the read-out's id).
286
297
  */
287
- export function renderRow(sound: Sound, index: number, o: ReturnType<typeof resolveRenderOptions>, hidden: boolean = false): string {
298
+ export function renderRow(sound: Sound, index: number, o: ReturnType<typeof resolveRenderOptions>, id: string): string {
288
299
  const s = o.strings;
289
300
  const vars = {title: sound.title};
290
301
  const cells = o.columns.map((c) => h('span', {class: `ws-cell ws-${c}`}, CELLS[c](sound)));
302
+ const summary = rowSummary(sound, o.columns, s);
303
+ const described = summary ? `${id}-d${index}` : null;
291
304
 
292
- return h('li', {
293
- class: 'ws-row',
294
- 'data-ws-index': index,
295
- 'data-ws-id': sound.id,
296
- 'data-url': sound.url,
297
- 'data-title': sound.title,
298
- 'data-type': sound.type || null,
299
- 'data-bpm': sound.bpm,
300
- 'data-key': sound.key || null,
301
- 'data-duration': sound.duration,
302
- 'data-tags': sound.tags?.length ? sound.tags.join(',') : null,
303
- 'data-peaks': sound.peaks ? encodePeaks(sound.peaks) : null,
304
- 'data-waveform': sound.waveform,
305
- 'data-download': sound.download,
306
- 'data-loop': sound.loop ? 'true' : null,
307
- hidden,
308
- },
309
- h('button', {type: 'button', class: 'ws-play', 'aria-pressed': 'false', 'aria-label': fill(s.play, vars)}, ICONS.play, ICONS.pause),
305
+ return h('li', {class: 'ws-row', 'data-ws-index': index},
306
+ h('button', {type: 'button', class: 'ws-play', 'aria-pressed': 'false', 'aria-label': fill(s.play, vars), 'aria-describedby': described},
307
+ icon(id, 'play', 'ws-icon-play'), icon(id, 'pause', 'ws-icon-pause')),
310
308
  h('span', {class: 'ws-cell ws-title'},
311
309
  h('span', {class: 'ws-title-text'}, text(sound.title)),
312
- // A loop says so beside its name; a one-shot carries nothing.
313
- sound.loop && h('span', {class: 'ws-loop-mark', title: s.isLoop}, ICONS.loop, h('span', {class: 'ws-sr'}, text(s.isLoop))),
310
+ // A loop says so beside its name (and in the read-out); a one-shot carries nothing.
311
+ sound.loop && h('span', {class: 'ws-loop-mark', title: s.isLoop, 'aria-hidden': 'true'}, icon(id, 'loop')),
314
312
  ),
315
313
  // Wide rows: `display: contents` makes each cell a column. Narrow
316
314
  // rows: one line under the title.
317
- cells.length > 0 && h('span', {class: 'ws-cells'}, cells),
318
- o.player === 'inline' && h('span', {class: 'ws-wave', role: 'slider', 'aria-label': fill(s.seek, vars), 'aria-valuemin': '0', 'aria-valuemax': '100', 'aria-valuenow': '0', tabindex: '-1'},
319
- h('canvas', {class: 'ws-canvas', 'aria-hidden': 'true'})),
315
+ cells.length > 0 && h('span', {class: 'ws-cells', 'aria-hidden': 'true'}, cells),
316
+ summary && h('span', {class: 'ws-sr', id: described}, text(summary)),
317
+ o.player === 'inline' && h('span', {class: 'ws-wave', 'aria-hidden': 'true'}, h('canvas', {class: 'ws-canvas'})),
320
318
  // Optional, per sound: a plain link. Rows without one carry nothing.
321
- sound.download && h('a', {class: 'ws-download', href: sound.download, download: true, 'aria-label': fill(s.download, vars)}, ICONS.download),
319
+ sound.download && h('a', {class: 'ws-download', href: sound.download, download: true, 'aria-label': fill(s.download, vars)}, icon(id, 'download')),
322
320
  );
323
321
  }
324
322
 
323
+ /**
324
+ * Every sound, as the JSON the runtime reads back (`readSoundsData`):
325
+ * normalised, with what normalising would fill in left out (an id that is
326
+ * the default `sound-<n>`, empty fields), peaks as hex. `<` is escaped, so
327
+ * no value can close the script element.
328
+ *
329
+ * @param list - Normalised.
330
+ */
331
+ export function renderSoundsData(list: Sound[]): string {
332
+ const data = list.map((s, i) => {
333
+ const d: Record<string, unknown> = {};
334
+ if (s.id !== `sound-${i + 1}`) d.id = s.id;
335
+ d.url = s.url;
336
+ d.title = s.title;
337
+ if (s.type) d.type = s.type;
338
+ if (s.bpm != null) d.bpm = s.bpm;
339
+ if (s.key) d.key = s.key;
340
+ if (s.duration != null) d.duration = s.duration;
341
+ if (s.tags.length) d.tags = s.tags;
342
+ if (s.peaks) d.peaks = encodePeaks(s.peaks);
343
+ if (s.waveform) d.waveform = s.waveform;
344
+ if (s.download) d.download = s.download;
345
+ if (s.loop) d.loop = true;
346
+ return d;
347
+ });
348
+ return `<script type="application/json" data-ws-sounds>${JSON.stringify(data).replace(/</g, '\\u003c')}</script>`;
349
+ }
350
+
351
+ /**
352
+ * The icons a list uses: its toolbar's, and its rows' — for every sound, as
353
+ * rows the runtime renders later use the same sprite.
354
+ *
355
+ * @param plan
356
+ * @param list
357
+ */
358
+ function iconsUsed(plan: ReturnType<typeof toolbarPlan>, list: Sound[]): IconName[] {
359
+ const names: IconName[] = [];
360
+ if (list.length) names.push('play', 'pause');
361
+ if (plan.search) names.push('search');
362
+ if (plan.types === 'menu' || plan.key || plan.sorts.length) names.push('chevron', 'check');
363
+ else if (plan.bpm) names.push('chevron');
364
+ if (plan.loop || list.some((s) => s.loop)) names.push('loop');
365
+ if (list.some((s) => s.download)) names.push('download');
366
+ return names;
367
+ }
368
+
325
369
  /* ── The whole list ─────────────────────────────────────────────────── */
326
370
 
327
371
  /**
@@ -349,27 +393,77 @@ function renderFooter({o, s, total}: RenderContext): string {
349
393
  * @returns HTML for the inside of `[data-waveform-sounds]`.
350
394
  */
351
395
  export function renderSounds(sounds: SoundInput[], options: WaveformSoundsOptions = {}): string {
396
+ return renderList(normalizeSounds(sounds), options, true);
397
+ }
398
+
399
+ /**
400
+ * {@link renderSounds}, from normalised sounds. The runtime renders a list
401
+ * it built itself through this without the JSON (it holds the sounds).
402
+ *
403
+ * @param list - Normalised.
404
+ * @param options
405
+ * @param withData - Append the sounds' JSON.
406
+ * @internal
407
+ */
408
+ export function renderList(list: Sound[], options: WaveformSoundsOptions, withData: boolean): string {
352
409
  const o = resolveRenderOptions(options);
353
- const list = normalizeSounds(sounds);
354
- const ctx: RenderContext = {o, s: o.strings, f: facets(list), total: list.length, id: o.idPrefix || idBase(list)};
355
- const page = o.pageSize > 0 ? o.pageSize : Infinity;
356
- return renderToolbar(toolbarPlan(ctx.f, o), ctx)
410
+ const ctx: RenderContext = {o, s: o.strings, f: facets(list, o), total: list.length, id: o.idPrefix || idBase(list)};
411
+ const plan = toolbarPlan(ctx.f, o);
412
+ // The rows the list starts with, in its starting order (the first sort
413
+ // offered, as the runtime starts): it adopts them as they are.
414
+ const index = new Map(list.map((sound, i) => [sound, i]));
415
+ const first = sortSounds(list, (availableSorts(o.sorts, ctx.f)[0] || 'default') as SoundsSort).slice(0, firstRender(o.pageSize));
416
+ return iconSprite(ctx.id, iconsUsed(plan, list))
417
+ + renderToolbar(plan, ctx)
357
418
  + h('ul', {class: `ws-list ws-list--${o.player}`, role: 'list', 'data-ws-list': true},
358
- list.map((sound, i) => renderRow(sound, i, o, i >= page)))
359
- + renderFooter(ctx);
419
+ first.map((sound) => renderRow(sound, index.get(sound)!, o, ctx.id)))
420
+ + renderFooter(ctx)
421
+ + (withData ? renderSoundsData(list) : '');
422
+ }
423
+
424
+ /**
425
+ * The `data-*` attributes that carry the render options set in `options` to
426
+ * the runtime (`data-page-size="20"`, `data-filters=""`, `data-strings='{…}'`),
427
+ * in the form `readDataOptions` reads — so the browser keeps what the server
428
+ * drew instead of falling back to the defaults (re-paging 20 rows to 50).
429
+ * Only options that are set are written; `player` is always written by
430
+ * {@link renderSoundsElement}. Since 2.1.0.
431
+ *
432
+ * @param options
433
+ * @returns Attributes, in {@link RENDER_OPTION_KEYS} order.
434
+ */
435
+ export function renderOptionAttributes(options: WaveformSoundsOptions = {}): Record<string, string> {
436
+ const set = pickRenderOptions(options) as Record<string, unknown>;
437
+ const o = resolveRenderOptions(options) as Record<string, unknown>;
438
+ const out: Record<string, string> = {};
439
+ for (const key of RENDER_OPTION_KEYS) {
440
+ if (key === 'player' || !(key in set)) continue;
441
+ const name = `data-${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`;
442
+ if (key === 'strings') {
443
+ const strings = defined(set.strings as Record<string, unknown>);
444
+ if (Object.keys(strings).length) out[name] = JSON.stringify(strings);
445
+ } else if (key === 'loop' || key === 'idPrefix') {
446
+ out[name] = String(set[key]);
447
+ } else {
448
+ const value = o[key];
449
+ out[name] = Array.isArray(value) ? value.join(',') : String(value);
450
+ }
451
+ }
452
+ return out;
360
453
  }
361
454
 
362
455
  /**
363
456
  * The full element, for callers who want one string: the wrapper div with
364
- * its `data-waveform-sounds` marker, its `data-player` and the inner markup.
457
+ * its `data-waveform-sounds` marker, its `data-player`, a `data-*` attribute
458
+ * for every other render option set (see {@link renderOptionAttributes}) and
459
+ * the inner markup. The inner markup is exactly {@link renderSounds}'.
365
460
  *
366
461
  * @param sounds
367
462
  * @param options
368
463
  * @param className - Extra classes for the wrapper.
369
- * @returns
370
464
  */
371
465
  export function renderSoundsElement(sounds: SoundInput[], options: WaveformSoundsOptions = {}, className: string = ''): string {
372
466
  const o = resolveRenderOptions(options);
373
467
  const cls = ['waveform-sounds', `waveform-sounds--${o.player}`, className].filter(Boolean).join(' ');
374
- return h('div', {class: cls, 'data-waveform-sounds': true, 'data-player': o.player}, renderSounds(sounds, options));
468
+ return h('div', {class: cls, 'data-waveform-sounds': true, 'data-player': o.player, ...renderOptionAttributes(options)}, renderSounds(sounds, options));
375
469
  }
@@ -18,7 +18,7 @@ export const COLUMNS: SoundsColumn[] = ['type', 'bpm', 'key', 'duration'];
18
18
 
19
19
  /** The options that shape the markup (the renderer's whole input). */
20
20
  export const RENDER_DEFAULTS: Required<Pick<WaveformSoundsOptions,
21
- 'player' | 'search' | 'filters' | 'sorts' | 'loopToggle' | 'showCount' | 'menuSearch' | 'pageSize' | 'columns' | 'maxTypeChips'>> = {
21
+ 'player' | 'search' | 'filters' | 'sorts' | 'loopToggle' | 'showCount' | 'menuSearch' | 'pageSize' | 'columns' | 'maxTypeChips' | 'mergeEnharmonicKeys'>> = {
22
22
  player: 'inline',
23
23
  search: true,
24
24
  filters: [...FILTERS],
@@ -29,18 +29,44 @@ export const RENDER_DEFAULTS: Required<Pick<WaveformSoundsOptions,
29
29
  pageSize: 50,
30
30
  columns: [...COLUMNS],
31
31
  maxTypeChips: 10,
32
+ mergeEnharmonicKeys: true,
32
33
  };
33
34
 
34
35
  /** {@link resolveRenderOptions}' result: the render options, complete, plus
35
36
  * whatever else the caller passed. */
36
37
  export type RenderOptions = typeof RENDER_DEFAULTS & {strings: WaveformSoundsStrings, idPrefix?: string, loop?: boolean | null};
37
38
 
39
+ /**
40
+ * Every option that shapes the server markup: the render defaults, plus
41
+ * `idPrefix` (the dropdowns' ids), `loop` (whether the Loop toggle starts
42
+ * pressed) and `strings`. A wrapper that renders on the server passes
43
+ * exactly these to `renderSounds` — and the same values to the runtime, or
44
+ * the browser re-lays out what the server drew. Since 2.1.0.
45
+ */
46
+ export const RENDER_OPTION_KEYS = [...Object.keys(RENDER_DEFAULTS), 'idPrefix', 'loop', 'strings'] as (keyof WaveformSoundsOptions)[];
47
+
48
+ /**
49
+ * The render options set in `options` (those in {@link RENDER_OPTION_KEYS}
50
+ * that aren't null or undefined), for handing a component's options to
51
+ * `renderSounds` on the server. Since 2.1.0.
52
+ *
53
+ * @param options - Any `WaveformSoundsOptions` (or a component's props).
54
+ * @returns Just the render options that are set.
55
+ */
56
+ export function pickRenderOptions(options: WaveformSoundsOptions | null | undefined): WaveformSoundsOptions {
57
+ const out: Record<string, unknown> = {};
58
+ for (const key of RENDER_OPTION_KEYS) {
59
+ const value = (options as Record<string, unknown> | null | undefined)?.[key];
60
+ if (value != null) out[key] = value;
61
+ }
62
+ return out as WaveformSoundsOptions;
63
+ }
64
+
38
65
  /**
39
66
  * The object without its `undefined` entries (so spreading it can't erase
40
67
  * a default).
41
68
  *
42
69
  * @param obj
43
- * @returns
44
70
  */
45
71
  export function defined(obj: Record<string, any> | null | undefined): Record<string, any> {
46
72
  const out: Record<string, any> = {};
@@ -55,7 +81,6 @@ export function defined(obj: Record<string, any> | null | undefined): Record<str
55
81
  * @param values
56
82
  * @param allowed
57
83
  * @param fallback
58
- * @returns
59
84
  */
60
85
  export function allowedList<T extends string>(values: unknown, allowed: T[], fallback: T[]): T[] {
61
86
  return Array.isArray(values) ? values.filter((v) => allowed.includes(v)) : fallback;
@@ -66,7 +91,6 @@ export function allowedList<T extends string>(values: unknown, allowed: T[], fal
66
91
  *
67
92
  * @param value
68
93
  * @param fallback
69
- * @returns
70
94
  */
71
95
  export function wholeNumber(value: unknown, fallback: number): number {
72
96
  const n = Number(value);
@@ -78,7 +102,6 @@ export function wholeNumber(value: unknown, fallback: number): number {
78
102
  * columns are dropped, counts are whole numbers, `strings` is complete.
79
103
  *
80
104
  * @param options
81
- * @returns
82
105
  */
83
106
  export function resolveRenderOptions(options: WaveformSoundsOptions = {}): RenderOptions {
84
107
  const o = {...RENDER_DEFAULTS, ...defined(options)};
@@ -91,6 +114,7 @@ export function resolveRenderOptions(options: WaveformSoundsOptions = {}): Rende
91
114
  menuSearch: wholeNumber(o.menuSearch, RENDER_DEFAULTS.menuSearch),
92
115
  maxTypeChips: wholeNumber(o.maxTypeChips, RENDER_DEFAULTS.maxTypeChips),
93
116
  pageSize: wholeNumber(o.pageSize, RENDER_DEFAULTS.pageSize),
117
+ mergeEnharmonicKeys: o.mergeEnharmonicKeys !== false,
94
118
  strings: {...DEFAULT_STRINGS, ...defined(options.strings)},
95
119
  };
96
120
  }
@@ -7,7 +7,9 @@
7
7
  */
8
8
 
9
9
  import {bpmRangeFromFilter, hasBpmFilter} from '../data/bpm.js';
10
- import type {SoundsSort, WaveformSoundsStrings} from '../types.js';
10
+ import {parseKey} from '../data/keys.js';
11
+ import {formatDuration} from '../data/sounds.js';
12
+ import type {Sound, SoundsColumn, SoundsSort, WaveformSoundsStrings} from '../types.js';
11
13
 
12
14
  /** The English defaults. */
13
15
  export const DEFAULT_STRINGS: WaveformSoundsStrings = {
@@ -41,6 +43,7 @@ export const DEFAULT_STRINGS: WaveformSoundsStrings = {
41
43
  play: 'Play {title}',
42
44
  pause: 'Pause {title}',
43
45
  seek: 'Seek {title}',
46
+ seekValue: '{time} of {duration}',
44
47
  download: 'Download {title}',
45
48
  count: '{count} sounds',
46
49
  countOne: '1 sound',
@@ -49,6 +52,17 @@ export const DEFAULT_STRINGS: WaveformSoundsStrings = {
49
52
  empty: 'No sounds match.',
50
53
  clear: 'Clear filters',
51
54
  nowPlaying: 'Playing {title}',
55
+ playError: 'Could not play {title}',
56
+ loadError: 'Could not load the sounds.',
57
+ noSounds: 'No sounds.',
58
+ rowBpm: '{bpm} BPM',
59
+ rowKey: 'key {key}',
60
+ rowDuration: '{duration}',
61
+ keyMajor: '{note} major',
62
+ keyMinor: '{note} minor',
63
+ noteSharp: '{note} sharp',
64
+ noteFlat: '{note} flat',
65
+ listSeparator: ', ',
52
66
  };
53
67
 
54
68
  /** The label each sort order shows in the Sort menu. */
@@ -65,7 +79,6 @@ export const SORT_LABEL_KEYS: Record<SoundsSort, keyof WaveformSoundsStrings> =
65
79
  *
66
80
  * @param template
67
81
  * @param vars
68
- * @returns
69
82
  */
70
83
  export function fill(template: string, vars: Record<string, string|number> = {}): string {
71
84
  return String(template).replace(/\{(\w+)\}/g, (match, name) => (name in vars ? String(vars[name]) : match));
@@ -78,7 +91,6 @@ export function fill(template: string, vars: Record<string, string|number> = {})
78
91
  * @param filter
79
92
  * @param extent - The pack's BPM range.
80
93
  * @param strings
81
- * @returns
82
94
  */
83
95
  export function bpmLabel(filter: {bpmMin?: string|number, bpmMax?: string|number}, extent: {min: number, max: number}, strings: typeof DEFAULT_STRINGS = DEFAULT_STRINGS): string {
84
96
  if (!hasBpmFilter(filter)) return strings.anyBpm;
@@ -92,9 +104,50 @@ export function bpmLabel(filter: {bpmMin?: string|number, bpmMax?: string|number
92
104
  * @param shown - Sounds matching the filter.
93
105
  * @param total - All sounds.
94
106
  * @param strings
95
- * @returns
96
107
  */
97
108
  export function countText(shown: number, total: number, strings: typeof DEFAULT_STRINGS = DEFAULT_STRINGS): string {
98
109
  if (shown !== total) return fill(strings.countFiltered, {count: shown, total});
99
110
  return total === 1 ? strings.countOne : fill(strings.count, {count: total});
100
111
  }
112
+
113
+ /**
114
+ * A key as a screen reader should say it: "Bm" → "B minor", "F#" → "F
115
+ * sharp major" (a bare "F#m" is read "F number m"). A label that isn't a
116
+ * key is said as written.
117
+ *
118
+ * @param key - A normalised key.
119
+ * @param strings
120
+ */
121
+ export function spokenKey(key: string, strings: WaveformSoundsStrings = DEFAULT_STRINGS): string {
122
+ const k = parseKey(key);
123
+ if (!k) return key;
124
+ const letter = k.root[0], acc = k.root.slice(1);
125
+ const note = acc === '#' ? fill(strings.noteSharp, {note: letter}) : acc === 'b' ? fill(strings.noteFlat, {note: letter}) : letter;
126
+ return fill(k.minor ? strings.keyMinor : strings.keyMajor, {note});
127
+ }
128
+
129
+ /**
130
+ * What a row's cells say, for a screen reader: the visible cells read "Bass
131
+ * loops 130 Bm 0:07"; this reads "Bass loops, 130 BPM, key B minor, 0:07"
132
+ * (and ", Loop" for a loop). Only the columns the row shows, only the
133
+ * values it has. Since 2.2.0.
134
+ *
135
+ * @param sound
136
+ * @param columns - The row's columns, in order.
137
+ * @param strings
138
+ * @returns '' when there is nothing to say.
139
+ */
140
+ export function rowSummary(sound: Sound, columns: SoundsColumn[], strings: WaveformSoundsStrings = DEFAULT_STRINGS): string {
141
+ const parts: string[] = [];
142
+ for (const c of columns) {
143
+ if (c === 'type' && sound.type) parts.push(sound.type);
144
+ else if (c === 'bpm' && sound.bpm != null) parts.push(fill(strings.rowBpm, {bpm: sound.bpm}));
145
+ else if (c === 'key' && sound.key) parts.push(fill(strings.rowKey, {key: spokenKey(sound.key, strings)}));
146
+ else if (c === 'duration') {
147
+ const d = formatDuration(sound.duration);
148
+ if (d) parts.push(fill(strings.rowDuration, {duration: d}));
149
+ }
150
+ }
151
+ if (sound.loop) parts.push(strings.isLoop);
152
+ return parts.join(strings.listSeparator);
153
+ }