@arraypress/waveform-sounds 2.1.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 (51) hide show
  1. package/README.md +21 -1
  2. package/dist/waveform-sounds-no-autoinit.esm.js +445 -144
  3. package/dist/waveform-sounds-render.esm.js +220 -78
  4. package/dist/waveform-sounds.css +4 -0
  5. package/dist/waveform-sounds.esm.js +445 -144
  6. package/dist/waveform-sounds.js +445 -144
  7. package/dist/waveform-sounds.min.css +1 -1
  8. package/dist/waveform-sounds.min.js +1 -1
  9. package/package.json +1 -1
  10. package/src/css/waveform-sounds.css +4 -0
  11. package/src/js/core/WaveformSounds.ts +224 -67
  12. package/src/js/core/element.ts +1 -1
  13. package/src/js/core/options.ts +1 -0
  14. package/src/js/data/keys.ts +156 -0
  15. package/src/js/data/navigation.ts +35 -8
  16. package/src/js/data/sounds.ts +29 -22
  17. package/src/js/data/url-state.ts +7 -3
  18. package/src/js/dom/draw.ts +16 -2
  19. package/src/js/dom/menus.ts +2 -1
  20. package/src/js/dom/rows.ts +38 -12
  21. package/src/js/render/icons.ts +59 -16
  22. package/src/js/render/markup.ts +115 -49
  23. package/src/js/render/options.ts +3 -1
  24. package/src/js/render/strings.ts +53 -1
  25. package/src/js/types.ts +24 -0
  26. package/types/core/WaveformSounds.d.ts +3 -3
  27. package/types/core/WaveformSounds.d.ts.map +1 -1
  28. package/types/core/options.d.ts.map +1 -1
  29. package/types/data/keys.d.ts +88 -0
  30. package/types/data/keys.d.ts.map +1 -0
  31. package/types/data/navigation.d.ts +27 -9
  32. package/types/data/navigation.d.ts.map +1 -1
  33. package/types/data/sounds.d.ts +20 -5
  34. package/types/data/sounds.d.ts.map +1 -1
  35. package/types/data/url-state.d.ts +6 -1
  36. package/types/data/url-state.d.ts.map +1 -1
  37. package/types/dom/draw.d.ts +5 -2
  38. package/types/dom/draw.d.ts.map +1 -1
  39. package/types/dom/menus.d.ts.map +1 -1
  40. package/types/dom/rows.d.ts +19 -8
  41. package/types/dom/rows.d.ts.map +1 -1
  42. package/types/render/icons.d.ts +41 -3
  43. package/types/render/icons.d.ts.map +1 -1
  44. package/types/render/markup.d.ts +27 -4
  45. package/types/render/markup.d.ts.map +1 -1
  46. package/types/render/options.d.ts +1 -1
  47. package/types/render/options.d.ts.map +1 -1
  48. package/types/render/strings.d.ts +22 -1
  49. package/types/render/strings.d.ts.map +1 -1
  50. package/types/types.d.ts +24 -0
  51. package/types/types.d.ts.map +1 -1
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Musical keys beyond their spelling: which keys sound the same
3
+ * (enharmonics: A#m and Bbm), which spelling a merged filter entry shows,
4
+ * and how keys sort. Pure — shared by the renderer and the runtime.
5
+ *
6
+ * Keys arrive here already in the short form `normalizeKey()` writes
7
+ * (`'Fm'`, `'C#'`, `'Bb'`); anything else is a label to keep as given.
8
+ *
9
+ * @module keys
10
+ */
11
+
12
+ /** Pitch class of each root spelling, C = 0. The theoretical spellings
13
+ * (Cb, B#, E#, Fb) are here so they merge with the keys they sound as. */
14
+ export const KEY_PITCH: Record<string, number> = {
15
+ C: 0, 'B#': 0, 'C#': 1, Db: 1, D: 2, 'D#': 3, Eb: 3, E: 4, Fb: 4, 'E#': 5, F: 5, 'F#': 6, Gb: 6,
16
+ G: 7, 'G#': 8, Ab: 8, A: 9, 'A#': 10, Bb: 10, B: 11, Cb: 11,
17
+ };
18
+
19
+ /**
20
+ * The conventional spelling of each key: its key signature with the fewest
21
+ * accidentals (Db major has 5 flats, C# major 7 sharps), and for the two
22
+ * six-and-six ties the Camelot wheel's (F# major, Eb minor). Index = pitch
23
+ * class.
24
+ */
25
+ const CONVENTIONAL_MAJOR = ['C', 'Db', 'D', 'Eb', 'E', 'F', 'F#', 'G', 'Ab', 'A', 'Bb', 'B'];
26
+ const CONVENTIONAL_MINOR = ['Cm', 'C#m', 'Dm', 'Ebm', 'Em', 'Fm', 'F#m', 'Gm', 'G#m', 'Am', 'Bbm', 'Bm'];
27
+
28
+ /** The sharp and flat spelling of each pitch class (for search). */
29
+ const SHARPS = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
30
+ const FLATS = ['C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B'];
31
+
32
+ /**
33
+ * A key's parts: its root spelling, pitch class and mode.
34
+ *
35
+ * @param key - A normalised key (`'A#m'`).
36
+ * @returns null for a label that isn't a key.
37
+ */
38
+ export function parseKey(key: string | null | undefined): {root: string, pitch: number, minor: boolean} | null {
39
+ const m = /^([A-G][#b]?)(m?)$/.exec(String(key ?? ''));
40
+ if (!m || KEY_PITCH[m[1]] === undefined) return null;
41
+ return {root: m[1], pitch: KEY_PITCH[m[1]], minor: m[2] === 'm'};
42
+ }
43
+
44
+ /**
45
+ * What a key sounds as: pitch class and mode (`'10m'` for A#m and Bbm).
46
+ * Two keys are enharmonic when their classes match.
47
+ *
48
+ * @param key - A normalised key.
49
+ * @returns The class, or the label itself when it isn't a key (so it only
50
+ * ever matches itself).
51
+ */
52
+ export function keyClass(key: string): string {
53
+ const k = parseKey(key);
54
+ return k ? `${k.pitch}${k.minor ? 'm' : ''}` : key;
55
+ }
56
+
57
+ /**
58
+ * Is a sound in key `b` (the filter's) when it is written `a`? The same
59
+ * spelling always is; with `merge`, so is any enharmonic one.
60
+ *
61
+ * @param a - The sound's key.
62
+ * @param b - The filter's key.
63
+ * @param merge - Treat enharmonic spellings as one key.
64
+ */
65
+ export function sameKey(a: string, b: string, merge: boolean = true): boolean {
66
+ return a === b || (merge && !!a && keyClass(a) === keyClass(b));
67
+ }
68
+
69
+ /**
70
+ * Sort rank of a key: by pitch from C, majors before minors; unknown
71
+ * labels after every key, no key at all last.
72
+ *
73
+ * @param key
74
+ */
75
+ export function keyRank(key: string): number {
76
+ if (!key) return Infinity;
77
+ const k = parseKey(key);
78
+ return k ? k.pitch * 2 + (k.minor ? 1 : 0) : 1000;
79
+ }
80
+
81
+ /**
82
+ * Every common spelling of a key (`'A#m'` → `['A#m', 'Bbm']`), for search:
83
+ * typing either finds both when keys are merged.
84
+ *
85
+ * @param key
86
+ */
87
+ export function enharmonics(key: string): string[] {
88
+ const k = parseKey(key);
89
+ if (!k) return key ? [key] : [];
90
+ const mode = k.minor ? 'm' : '';
91
+ return [...new Set([key, SHARPS[k.pitch] + mode, FLATS[k.pitch] + mode])];
92
+ }
93
+
94
+ /**
95
+ * The spelling a merged key entry shows: the one the pack uses most; a
96
+ * tie goes to the conventional spelling (see {@link CONVENTIONAL_MAJOR})
97
+ * when it is one of the tied, else to the first in alphabetical order.
98
+ *
99
+ * @param counts - Each spelling of ONE key, with how many sounds use it.
100
+ */
101
+ export function canonicalSpelling(counts: Map<string, number>): string {
102
+ let best = 0;
103
+ for (const n of counts.values()) if (n > best) best = n;
104
+ const tied = [...counts].filter(([, n]) => n === best).map(([k]) => k).sort();
105
+ if (tied.length === 1) return tied[0];
106
+ const k = parseKey(tied[0]);
107
+ const conventional = k ? (k.minor ? CONVENTIONAL_MINOR : CONVENTIONAL_MAJOR)[k.pitch] : '';
108
+ return tied.includes(conventional) ? conventional : tied[0];
109
+ }
110
+
111
+ /**
112
+ * The keys a list offers, merged or not: each entry once, in musical
113
+ * order, with the other spellings merged into it.
114
+ *
115
+ * @param keys - Every sound's key ('' for none), duplicates included.
116
+ * @param merge - Merge enharmonic spellings into one entry.
117
+ * @returns `keys` (the entries) and `aliases` (entry → the other spellings
118
+ * the list uses for it; only entries that have some).
119
+ */
120
+ export function keyEntries(keys: string[], merge: boolean = true): {keys: string[], aliases: Record<string, string[]>} {
121
+ const groups = new Map<string, Map<string, number>>();
122
+ for (const key of keys) {
123
+ if (!key) continue;
124
+ const cls = merge ? keyClass(key) : key;
125
+ const g = groups.get(cls) ?? new Map<string, number>();
126
+ groups.set(cls, g);
127
+ g.set(key, (g.get(key) || 0) + 1);
128
+ }
129
+ const out: string[] = [];
130
+ const aliases: Record<string, string[]> = {};
131
+ for (const g of groups.values()) {
132
+ const entry = canonicalSpelling(g);
133
+ out.push(entry);
134
+ const others = [...g.keys()].filter((k) => k !== entry).sort();
135
+ if (others.length) aliases[entry] = others;
136
+ }
137
+ out.sort((a, b) => keyRank(a) - keyRank(b) || a.localeCompare(b));
138
+ return {keys: out, aliases};
139
+ }
140
+
141
+ /**
142
+ * The entry of `entries` a key belongs to: itself, or with `merge` the
143
+ * entry it is enharmonic to (`?key=A#m` on a list whose entry is Bbm).
144
+ *
145
+ * @param key - A normalised key.
146
+ * @param entries - The list's key entries ({@link keyEntries}).
147
+ * @param merge
148
+ * @returns The entry, or '' when the list has no such key.
149
+ */
150
+ export function keyEntry(key: string, entries: string[], merge: boolean = true): string {
151
+ if (!key) return '';
152
+ if (entries.includes(key)) return key;
153
+ if (!merge) return '';
154
+ const cls = keyClass(key);
155
+ return entries.find((e) => keyClass(e) === cls) ?? '';
156
+ }
@@ -62,16 +62,43 @@ export function sliderEdgeTarget(key: string): number | null {
62
62
  }
63
63
 
64
64
  /**
65
- * Which of the matching sounds the current page shows, and how many more
66
- * "Show more" would reveal.
65
+ * Rows are rendered as they are revealed, never all up front: a page's
66
+ * worth, or with paging off this many at a time, more as the list
67
+ * scrolls toward its end. Since 2.2.0.
68
+ */
69
+ export const RENDER_CHUNK = 50;
70
+
71
+ /**
72
+ * How many of the matching sounds have rows: the page, or with paging off
73
+ * the rows rendered so far (`budget`). The server renders the first of
74
+ * these ({@link firstRender}).
75
+ *
76
+ * @param matching - How many sounds match.
77
+ * @param limit - The page limit (Infinity when paging is off).
78
+ * @param budget - Rows rendered so far when paging is off.
79
+ */
80
+ export function renderedCount(matching: number, limit: number, budget: number): number {
81
+ return Math.min(matching, limit === Infinity ? budget : limit);
82
+ }
83
+
84
+ /**
85
+ * How many rows a list starts with: a page, or with paging off
86
+ * {@link RENDER_CHUNK}.
87
+ *
88
+ * @param pageSize - The `pageSize` option (0 = paging off).
89
+ */
90
+ export function firstRender(pageSize: number): number {
91
+ return pageSize > 0 ? pageSize : RENDER_CHUNK;
92
+ }
93
+
94
+ /**
95
+ * The budget that renders position `pos` with paging off: whole chunks.
67
96
  *
68
- * @template T
69
- * @param shown - The sounds that match, in display order.
70
- * @param limit - How many to show (Infinity for all).
97
+ * @param budget - Rows rendered so far.
98
+ * @param pos - The position that must have a row.
71
99
  */
72
- export function pageWindow<T>(shown: T[], limit: number): {visible: Set<T>, remaining: number} {
73
- const visible = new Set(shown.slice(0, limit));
74
- return {visible, remaining: shown.length - visible.size};
100
+ export function budgetToReveal(budget: number, pos: number): number {
101
+ return pos < budget ? budget : Math.ceil((pos + 1) / RENDER_CHUNK) * RENDER_CHUNK;
75
102
  }
76
103
 
77
104
  /**
@@ -1,4 +1,5 @@
1
1
  import {fold, matchesAll, words} from '@arraypress/text';
2
+ import {enharmonics, keyEntries, keyRank, sameKey} from './keys.js';
2
3
  import type {Sound, SoundInput, SoundsFilter, SoundsManifest, SoundsSort} from '../types.js';
3
4
 
4
5
  /**
@@ -99,18 +100,6 @@ export function normalizeKey(key: string | null | undefined): string {
99
100
  return root + acc + (minor ? 'm' : '');
100
101
  }
101
102
 
102
- /** Pitch class of each root, for sorting keys: C, C#, D … B, majors before minors. */
103
- const KEY_PITCH: Record<string, number> = {C: 0, 'C#': 1, Db: 1, D: 2, 'D#': 3, Eb: 3, E: 4, F: 5, 'F#': 6, Gb: 6, G: 7, 'G#': 8, Ab: 8, A: 9, 'A#': 10, Bb: 10, B: 11};
104
-
105
- /** Sort rank of a canonical key; unknown keys sort last. */
106
- function keyRank(key: string): number {
107
- if (!key) return Infinity;
108
- const minor = key.endsWith('m');
109
- const root = minor ? key.slice(0, -1) : key;
110
- const p = KEY_PITCH[root];
111
- return p === undefined ? 1000 : p * 2 + (minor ? 1 : 0);
112
- }
113
-
114
103
  /**
115
104
  * Format seconds as m:ss (whole seconds, rounded down like a player's
116
105
  * clock), or as tenths under a second.
@@ -259,28 +248,40 @@ export function normalizeSounds(list: SoundInput[], peakScale: number = 1): Soun
259
248
  return out;
260
249
  }
261
250
 
251
+ /** Options of the pure filter helpers ({@link facets}, {@link matches}). */
252
+ export interface KeyOptions {
253
+ /** Enharmonic keys (A#m and Bbm) are one key. Default true. Since 2.2.0. */
254
+ mergeEnharmonicKeys?: boolean;
255
+ }
256
+
262
257
  /**
263
258
  * What the filter controls offer, derived from the sounds: each type with
264
- * its count (in first-seen order), each key (in musical order), the BPM
265
- * range, and how many are loops and one-shots. A control with nothing to
266
- * offer is not rendered.
259
+ * its count (in first-seen order), each key (in musical order; enharmonic
260
+ * spellings merged into one entry unless `mergeEnharmonicKeys` is false —
261
+ * see `keyEntries` for the spelling it shows), the BPM range, and how many
262
+ * are loops and one-shots. A control with nothing to offer is not rendered.
267
263
  *
268
264
  * @param sounds
265
+ * @param options
266
+ * @returns `keyAliases`: each merged key entry's other spellings in the
267
+ * list (since 2.2.0).
269
268
  */
270
- export function facets(sounds: Sound[]): {types: {name: string, count: number}[], keys: string[], bpm: {min: number, max: number}|null, hasDuration: boolean, loops: number, oneShots: number} {
269
+ export function facets(sounds: Sound[], options: KeyOptions = {}): {types: {name: string, count: number}[], keys: string[], keyAliases: Record<string, string[]>, bpm: {min: number, max: number}|null, hasDuration: boolean, loops: number, oneShots: number} {
271
270
  const types = new Map<string, number>();
272
- const keys = new Set<string>();
271
+ const keys: string[] = [];
273
272
  let min = Infinity, max = -Infinity, hasDuration = false, loops = 0;
274
273
  for (const s of sounds) {
275
274
  if (s.type) types.set(s.type, (types.get(s.type) || 0) + 1);
276
- if (s.key) keys.add(s.key);
275
+ if (s.key) keys.push(s.key);
277
276
  if (s.bpm != null) { min = Math.min(min, s.bpm); max = Math.max(max, s.bpm); }
278
277
  if (s.duration != null) hasDuration = true;
279
278
  if (s.loop) loops++;
280
279
  }
280
+ const entries = keyEntries(keys, options.mergeEnharmonicKeys !== false);
281
281
  return {
282
282
  types: [...types].map(([name, count]) => ({name, count})),
283
- keys: [...keys].sort((a, b) => keyRank(a) - keyRank(b) || a.localeCompare(b)),
283
+ keys: entries.keys,
284
+ keyAliases: entries.aliases,
284
285
  bpm: min === Infinity ? null : {min, max},
285
286
  hasDuration,
286
287
  loops,
@@ -298,12 +299,18 @@ export function facets(sounds: Sound[]): {types: {name: string, count: number}[]
298
299
  * number in the query also matches the BPM exactly, so "bass 128" finds
299
300
  * 128 BPM bass loops.
300
301
  *
302
+ * Keys: unless `mergeEnharmonicKeys` is false, a key filter matches every
303
+ * spelling of that key (A#m finds Bbm too), and a key typed in the search
304
+ * finds its other spellings.
305
+ *
301
306
  * @param sound
302
307
  * @param filter
308
+ * @param options
303
309
  */
304
- export function matches(sound: Sound, filter: Partial<SoundsFilter> = {}): boolean {
310
+ export function matches(sound: Sound, filter: Partial<SoundsFilter> = {}, options: KeyOptions = {}): boolean {
311
+ const merge = options.mergeEnharmonicKeys !== false;
305
312
  if (filter.type && sound.type !== filter.type) return false;
306
- if (filter.key && sound.key !== normalizeKey(filter.key)) return false;
313
+ if (filter.key && !sameKey(sound.key, normalizeKey(filter.key), merge)) return false;
307
314
  if (filter.loop === 'loop' && !sound.loop) return false;
308
315
  if (filter.loop === 'one-shot' && sound.loop) return false;
309
316
  const lo = Number(filter.bpmMin), hi = Number(filter.bpmMax);
@@ -315,7 +322,7 @@ export function matches(sound: Sound, filter: Partial<SoundsFilter> = {}): boole
315
322
  }
316
323
  const terms = words(filter.query || '');
317
324
  if (terms.length) {
318
- const hay = [sound.title, sound.type, sound.key, ...(sound.tags || [])].join(' ');
325
+ const hay = [sound.title, sound.type, ...(merge ? enharmonics(sound.key) : [sound.key]), ...(sound.tags || [])].join(' ');
319
326
  const folded = fold(hay);
320
327
  // A number naming this sound's BPM is satisfied; the rest is text.
321
328
  const rest = terms.filter((w) => !(/^\d+$/.test(w) && !folded.includes(w)
@@ -10,6 +10,7 @@
10
10
  */
11
11
 
12
12
  import {LOOP_FILTERS, normalizeKey} from './sounds.js';
13
+ import {keyEntry} from './keys.js';
13
14
  import type {SoundsFilter, SoundsLoopFilter} from '../types.js';
14
15
 
15
16
  /**
@@ -81,9 +82,12 @@ export function formatBpmRange(min: string | number | null | undefined, max: str
81
82
  * @param available - From `facets()`, with `bpm` as the slider's range
82
83
  * (`bpmExtent()`).
83
84
  * @param sorts - The sort orders offered.
85
+ * @param options
86
+ * @param options.mergeEnharmonicKeys - A key in either spelling selects
87
+ * the list's entry for it (`?key=A#m` → `Bbm`). Default true. Since 2.2.0.
84
88
  * @returns A filter patch, and the sort (or null).
85
89
  */
86
- export function readUrlState(search: string, keys: ReturnType<typeof urlKeys>, available: {types: {name: string}[], keys: string[], loops?: number, oneShots?: number, bpm?: {min: number, max: number} | null}, sorts: string[]): {filter: Partial<SoundsFilter>, sort: string|null} {
90
+ export function readUrlState(search: string, keys: ReturnType<typeof urlKeys>, available: {types: {name: string}[], keys: string[], loops?: number, oneShots?: number, bpm?: {min: number, max: number} | null}, sorts: string[], options: {mergeEnharmonicKeys?: boolean} = {}): {filter: Partial<SoundsFilter>, sort: string|null} {
87
91
  const out: {filter: Partial<SoundsFilter>, sort: string | null} = {filter: {}, sort: null};
88
92
  if (!keys) return out;
89
93
  const sp = new URLSearchParams(search);
@@ -91,8 +95,8 @@ export function readUrlState(search: string, keys: ReturnType<typeof urlKeys>, a
91
95
  if (q) out.filter.query = q;
92
96
  const type = sp.get(keys.type);
93
97
  if (type && available.types.some((t) => t.name === type)) out.filter.type = type;
94
- const key = normalizeKey(sp.get(keys.key));
95
- if (key && available.keys.includes(key)) out.filter.key = key;
98
+ const key = keyEntry(normalizeKey(sp.get(keys.key)), available.keys, options.mergeEnharmonicKeys !== false);
99
+ if (key) out.filter.key = key;
96
100
  const parsed = parseBpmRange(sp.get(keys.bpm));
97
101
  // Without the pack's range (an older caller), the limits apply as given.
98
102
  const bpm = parsed && available.bpm !== undefined ? bpmRangeWithin(parsed, available.bpm) : parsed;
@@ -26,8 +26,11 @@ export function fitCanvas(canvas: HTMLCanvasElement) {
26
26
  }
27
27
 
28
28
  /**
29
- * Resample peaks to `count` bars (max of each bucket, so transients
30
- * survive the downsample).
29
+ * Resample peaks to `count` bars, whatever their number (64 or 128 from
30
+ * waveform-gen, any length of `wp1:`). Fewer bars than peaks: the max of
31
+ * each bucket, so transients survive. More bars than peaks: linear
32
+ * interpolation between neighbouring peaks — repeating each peak drew
33
+ * flat steps (64 peaks across a 400px row were plateaus three bars wide).
31
34
  * @param peaks
32
35
  * @param count
33
36
  */
@@ -35,6 +38,17 @@ export function resample(peaks: number[], count: number) {
35
38
  if (!peaks?.length || count <= 0) return [];
36
39
  if (peaks.length === count) return peaks;
37
40
  const out = new Array(count);
41
+ if (count > peaks.length) {
42
+ // Bar i's centre, on the peaks' own axis (peak j's centre is j).
43
+ const last = peaks.length - 1;
44
+ const ratio = peaks.length / count;
45
+ for (let i = 0; i < count; i++) {
46
+ const x = Math.min(Math.max((i + 0.5) * ratio - 0.5, 0), last);
47
+ const j = Math.floor(x), t = x - j;
48
+ out[i] = j >= last ? peaks[last] : peaks[j] + (peaks[j + 1] - peaks[j]) * t;
49
+ }
50
+ return out;
51
+ }
38
52
  const step = peaks.length / count;
39
53
  for (let i = 0; i < count; i++) {
40
54
  const start = Math.floor(i * step);
@@ -201,7 +201,8 @@ export class Menus {
201
201
  const p = partsOf(menu);
202
202
  let first: HTMLElement | null = null;
203
203
  for (const opt of optionsOf(p)) {
204
- opt.hidden = !optionMatches(opt.textContent, query);
204
+ // A merged key is found by any of its spellings (`data-alt`).
205
+ opt.hidden = !optionMatches(`${opt.textContent} ${opt.dataset.alt ?? ''}`, query);
205
206
  if (!opt.hidden) first ??= opt;
206
207
  }
207
208
  p.none!.hidden = first !== null;
@@ -1,18 +1,39 @@
1
1
  /**
2
- * The rows in the DOM: reading server-rendered rows back into sounds, and
3
- * finding a row by the sound it shows.
2
+ * The rows in the DOM: reading server-rendered sounds back, finding a row
3
+ * by the sound it shows, and putting exactly the rows shown in the list.
4
4
  *
5
5
  * @module rows
6
6
  */
7
7
 
8
- import {normalizeSound} from '../data/sounds.js';
8
+ import {normalizeSound, normalizeSounds} from '../data/sounds.js';
9
+ import {LOG} from '../shared/utils.js';
9
10
  import type {Sound} from '../types.js';
10
11
 
11
12
  /** A list's row elements, in DOM order. */
12
13
  const ROW = ':scope > [data-ws-index]';
13
14
 
14
15
  /**
15
- * Read server-rendered rows back into sounds. Rows are taken in their
16
+ * Read the sounds of server-rendered markup from its JSON
17
+ * (`<script type="application/json" data-ws-sounds>`, since 2.2.0).
18
+ *
19
+ * @param root - The list's container.
20
+ * @returns The sounds, or null when there is no (usable) JSON — then the
21
+ * rows themselves are read ({@link readRows}, markup from before 2.2).
22
+ */
23
+ export function readSoundsData(root: HTMLElement): Sound[] | null {
24
+ const script = root.querySelector(':scope > script[data-ws-sounds]');
25
+ if (!script) return null;
26
+ try {
27
+ const list = JSON.parse(script.textContent || '');
28
+ if (Array.isArray(list)) return normalizeSounds(list);
29
+ } catch { /* reported below */ }
30
+ console.warn(`${LOG} Ignoring unreadable sounds JSON (data-ws-sounds)`);
31
+ return null;
32
+ }
33
+
34
+ /**
35
+ * Read server-rendered rows back into sounds (markup from before 2.2.0,
36
+ * whose rows carry every field as a `data-*` attribute). Rows are taken in their
16
37
  * original order (`data-ws-index`) and renumbered 0..n-1, and a row whose
17
38
  * data is unusable (no url) is removed — so a row missing from the markup
18
39
  * can't leave a hole that would misalign rows and sounds.
@@ -49,8 +70,7 @@ export function indexRows(list: HTMLElement): HTMLElement[] {
49
70
  }
50
71
 
51
72
  /**
52
- * The rows currently visible (not hidden by the filter or the page), in
53
- * display order.
73
+ * The rows in the list (not hidden), in display order.
54
74
  *
55
75
  * @param list
56
76
  */
@@ -59,14 +79,20 @@ export function visibleRows(list: HTMLElement): HTMLElement[] {
59
79
  }
60
80
 
61
81
  /**
62
- * Put the rows in the given order. Every row moves (hidden ones too), so
63
- * clearing a filter keeps the order.
82
+ * Make the list hold exactly `rows`, in that order: rows not among them
83
+ * leave the DOM, new ones go in, and rows already in order are not moved
84
+ * (moving an element drops its focus, so a filter change keeps focus
85
+ * where it was; only a re-sort moves rows).
64
86
  *
65
87
  * @param list
66
88
  * @param rows - In the order to show them.
67
89
  */
68
- export function orderRows(list: HTMLElement, rows: HTMLElement[]) {
69
- const frag = document.createDocumentFragment();
70
- for (const row of rows) if (row) frag.appendChild(row);
71
- list.appendChild(frag);
90
+ export function layoutRows(list: HTMLElement, rows: HTMLElement[]): void {
91
+ const keep = new Set(rows);
92
+ for (const el of [...list.children]) if (!keep.has(el as HTMLElement)) el.remove();
93
+ let cursor = list.firstElementChild;
94
+ for (const row of rows) {
95
+ if (row === cursor) cursor = cursor.nextElementSibling;
96
+ else list.insertBefore(row, cursor);
97
+ }
72
98
  }
@@ -1,28 +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
67
  */
15
- function icon(path: string, extraClass: string = ''): string {
68
+ export function icon(id: string, name: IconName, extraClass: string = ''): string {
16
69
  const cls = extraClass ? `ws-icon ${extraClass}` : 'ws-icon';
17
- 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>`;
18
71
  }
19
-
20
- export const ICONS = {
21
- play: icon('M8 5.5v13l11-6.5z', 'ws-icon-play'),
22
- pause: icon('M7 5h3.5v14H7zM13.5 5H17v14h-3.5z', 'ws-icon-pause'),
23
- 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'),
24
- chevron: icon('M6.4 8.6 12 14.2l5.6-5.6L19 10l-7 7-7-7z', 'ws-menu-chevron'),
25
- 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'),
26
- 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'),
27
- 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'),
28
- };