@arraypress/waveform-sounds 0.0.0-stage → 0.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.
@@ -0,0 +1,57 @@
1
+ /**
2
+ * The audio engine: ONE `WaveformPlayer` (self mode) that every sound in
3
+ * the list plays through. These helpers decide how it's configured and
4
+ * what it's given per sound; `core.js` owns its lifecycle.
5
+ *
6
+ * @module engine
7
+ */
8
+
9
+ /** The engine's own callbacks, which the list must always receive. */
10
+ const CALLBACKS = ['onLoad', 'onPlay', 'onPause', 'onEnd', 'onTimeUpdate', 'onError'];
11
+
12
+ /**
13
+ * The engine player's options. The site's `playerOptions` override the
14
+ * defaults, except two things the list depends on:
15
+ * - `audioMode` is always `'self'` (the list owns its audio);
16
+ * - the six callbacks always reach the list — a site's own callback of
17
+ * the same name runs as well, after it, with the same arguments.
18
+ *
19
+ * @param {Object|null|undefined} user - The site's `playerOptions`.
20
+ * @param {'inline'|'strip'} layout - Strip shows the engine, so it's taller.
21
+ * @param {Record<string, Function>} handlers - The list's callbacks, keyed by
22
+ * option name (`onPlay`, …).
23
+ * @returns {Object} Options for `new WaveformPlayer(el, options)`.
24
+ */
25
+ export function engineOptions(user, layout, handlers) {
26
+ const site = user || {};
27
+ const strip = layout === 'strip';
28
+ const options = {
29
+ height: strip ? 48 : 32,
30
+ waveformStyle: strip ? 'mirror' : 'bars',
31
+ preload: 'metadata',
32
+ singlePlay: true,
33
+ ...site,
34
+ audioMode: 'self',
35
+ };
36
+ for (const name of CALLBACKS) {
37
+ options[name] = (...args) => {
38
+ handlers[name]?.(...args);
39
+ if (typeof site[name] === 'function') site[name](...args);
40
+ };
41
+ }
42
+ return options;
43
+ }
44
+
45
+ /**
46
+ * The waveform data to hand the engine for a sound: in the strip a
47
+ * full-resolution sidecar when there is one, otherwise the row's peaks.
48
+ * Supplied peaks also stop a hidden engine from downloading and decoding
49
+ * the whole file just to draw it.
50
+ *
51
+ * @param {{peaks: number[]|null, waveform: string|null}} sound
52
+ * @param {'inline'|'strip'} layout
53
+ * @returns {number[]|string|null}
54
+ */
55
+ export function enginePeaks(sound, layout) {
56
+ return (layout === 'strip' && sound.waveform) || sound.peaks || null;
57
+ }
@@ -0,0 +1,163 @@
1
+ /**
2
+ * The runtime's option surface: every option with its default, the
3
+ * `data-*` form a container (or a server-rendering wrapper) uses, and the
4
+ * merge that resolves them. The options that shape the markup are defined
5
+ * with the renderer (`render/options.js`) and included here. `index.d.ts` documents each option; the wrappers' drift
6
+ * guards compare their forwarding against `DEFAULT_OPTIONS`.
7
+ *
8
+ * Precedence, as across the waveform family: data-* > constructor > default.
9
+ *
10
+ * @module options
11
+ */
12
+
13
+ import {RENDER_DEFAULTS} from '../render/options.js';
14
+ import {LOG} from '../shared/utils.js';
15
+
16
+ export {RENDER_DEFAULTS};
17
+
18
+ /** Every option, with its default. */
19
+ export const DEFAULT_OPTIONS = {
20
+ ...RENDER_DEFAULTS,
21
+ sounds: null,
22
+ manifest: null,
23
+ waveformStyle: 'mirror',
24
+ waveformColor: null,
25
+ progressColor: null,
26
+ barWidth: 2,
27
+ barGap: 1,
28
+ loop: false,
29
+ autoAdvance: false,
30
+ arrowAudition: true,
31
+ idPrefix: null,
32
+ urlState: false,
33
+ playerOptions: null,
34
+ playerClass: null,
35
+ strings: null,
36
+ onReady: null,
37
+ onPlay: null,
38
+ onPause: null,
39
+ onEnd: null,
40
+ onFilter: null,
41
+ onError: null,
42
+ };
43
+
44
+ /**
45
+ * A boolean attribute: present-and-empty or "true" → true, "false" → false.
46
+ *
47
+ * @param {string|undefined} value
48
+ * @returns {boolean|undefined} undefined for anything else (not set).
49
+ */
50
+ export function parseBool(value) {
51
+ if (value === '' || value === 'true') return true;
52
+ if (value === 'false') return false;
53
+ return undefined;
54
+ }
55
+
56
+ /**
57
+ * A comma list attribute ("type, key" → ['type', 'key']). An empty string
58
+ * is an empty list (e.g. `data-sorts=""` = no sort menu).
59
+ *
60
+ * @param {string|undefined} value
61
+ * @returns {string[]|undefined}
62
+ */
63
+ export function parseList(value) {
64
+ if (value == null) return undefined;
65
+ return value.split(',').map((x) => x.trim()).filter(Boolean);
66
+ }
67
+
68
+ /**
69
+ * A number attribute; an empty string is "not set".
70
+ *
71
+ * @param {string|undefined} value
72
+ * @returns {number|undefined}
73
+ */
74
+ export function parseNumber(value) {
75
+ return value === undefined || value === '' ? undefined : Number(value);
76
+ }
77
+
78
+ /**
79
+ * `data-url-state`: "true"/empty → true, "false" → false, anything else is
80
+ * the parameter prefix.
81
+ *
82
+ * @param {string|undefined} value
83
+ * @returns {boolean|string|undefined}
84
+ */
85
+ export function parseUrlState(value) {
86
+ if (value === undefined) return undefined;
87
+ const b = parseBool(value);
88
+ return b === undefined ? value : b;
89
+ }
90
+
91
+ /**
92
+ * A JSON attribute (`data-strings`, `data-player-options`). Invalid JSON is
93
+ * reported and ignored, never thrown: a typo in markup must not take the
94
+ * whole list down.
95
+ *
96
+ * @param {string|undefined} value
97
+ * @param {string} name - The attribute name, for the warning.
98
+ * @returns {Object|undefined}
99
+ */
100
+ export function parseJson(value, name) {
101
+ if (!value) return undefined;
102
+ try {
103
+ return JSON.parse(value);
104
+ } catch {
105
+ console.warn(`${LOG} Ignoring invalid JSON in data-${name}`);
106
+ return undefined;
107
+ }
108
+ }
109
+
110
+ /**
111
+ * The options set on a container as `data-*` attributes (kebab-case:
112
+ * `data-page-size` → `pageSize`). Attributes that are absent (or unusable)
113
+ * are left out, so they never override a constructor option.
114
+ *
115
+ * @param {HTMLElement} el
116
+ * @returns {Object} The options found.
117
+ */
118
+ export function readDataOptions(el) {
119
+ const d = el.dataset || {};
120
+ const out = {
121
+ player: d.player || undefined,
122
+ manifest: d.manifest || undefined,
123
+ search: parseBool(d.search),
124
+ filters: parseList(d.filters),
125
+ sorts: parseList(d.sorts),
126
+ showCount: parseBool(d.showCount),
127
+ menuSearch: parseNumber(d.menuSearch),
128
+ idPrefix: d.idPrefix || undefined,
129
+ urlState: parseUrlState(d.urlState),
130
+ loopToggle: parseBool(d.loopToggle),
131
+ pageSize: parseNumber(d.pageSize),
132
+ maxTypeChips: parseNumber(d.maxTypeChips),
133
+ columns: parseList(d.columns),
134
+ waveformStyle: d.waveformStyle || undefined,
135
+ waveformColor: d.waveformColor || undefined,
136
+ progressColor: d.progressColor || undefined,
137
+ barWidth: parseNumber(d.barWidth),
138
+ barGap: parseNumber(d.barGap),
139
+ loop: parseBool(d.loop),
140
+ autoAdvance: parseBool(d.autoAdvance),
141
+ arrowAudition: parseBool(d.arrowAudition),
142
+ strings: parseJson(d.strings, 'strings'),
143
+ playerOptions: parseJson(d.playerOptions, 'player-options'),
144
+ };
145
+ for (const k of Object.keys(out)) if (out[k] === undefined) delete out[k];
146
+ return out;
147
+ }
148
+
149
+ /**
150
+ * Merge option sources: later ones win, and null/undefined never
151
+ * overwrite (an unset prop must not erase a default).
152
+ *
153
+ * @param {...(Object|null|undefined)} sources
154
+ * @returns {Object}
155
+ */
156
+ export function mergeOptions(...sources) {
157
+ const out = {};
158
+ for (const src of sources) {
159
+ if (!src) continue;
160
+ for (const k in src) if (src[k] !== null && src[k] !== undefined) out[k] = src[k];
161
+ }
162
+ return out;
163
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Moving through the list: which row a key lands on, how far an arrow
3
+ * seeks, and which rows the current page shows. Pure — the runtime maps
4
+ * the results onto rows and the engine.
5
+ *
6
+ * @module navigation
7
+ */
8
+
9
+ import {clamp} from '../shared/utils.js';
10
+
11
+ /** How far ←/→ seek, as a fraction of the sound. */
12
+ export const SEEK_STEP = 0.1;
13
+
14
+ /**
15
+ * Where a navigation key moves from position `at` in a list of `count`
16
+ * visible rows.
17
+ *
18
+ * @param {string} key - `KeyboardEvent.key`.
19
+ * @param {number} at - The focused row's position among the visible rows.
20
+ * @param {number} count - How many rows are visible.
21
+ * @returns {number|'search'|null} The new position; `'search'` for ↑ on
22
+ * the first row (back to the search field); null when the key isn't a
23
+ * move or there is nowhere to go.
24
+ */
25
+ export function rowTarget(key, at, count) {
26
+ if (!count) return null;
27
+ switch (key) {
28
+ case 'ArrowDown': return at + 1 < count ? at + 1 : null;
29
+ case 'ArrowUp': return at > 0 ? at - 1 : 'search';
30
+ case 'Home': return 0;
31
+ case 'End': return count - 1;
32
+ default: return null;
33
+ }
34
+ }
35
+
36
+ /**
37
+ * The position an ←/→ press seeks to. Stops just short of the end, so a
38
+ * held → can't end the sound by accident.
39
+ *
40
+ * @param {number} progress - Current position, 0..1.
41
+ * @param {string} key - `'ArrowRight'` or `'ArrowLeft'`.
42
+ * @returns {number|null} The new position, or null for any other key.
43
+ */
44
+ export function seekTarget(progress, key) {
45
+ if (key !== 'ArrowRight' && key !== 'ArrowLeft') return null;
46
+ return clamp(progress + (key === 'ArrowRight' ? SEEK_STEP : -SEEK_STEP), 0, 0.999);
47
+ }
48
+
49
+ /**
50
+ * Which of the matching sounds the current page shows, and how many more
51
+ * "Show more" would reveal.
52
+ *
53
+ * @template T
54
+ * @param {T[]} shown - The sounds that match, in display order.
55
+ * @param {number} limit - How many to show (Infinity for all).
56
+ * @returns {{visible: Set<T>, remaining: number}}
57
+ */
58
+ export function pageWindow(shown, limit) {
59
+ const visible = new Set(shown.slice(0, limit));
60
+ return {visible, remaining: shown.length - visible.size};
61
+ }
62
+
63
+ /**
64
+ * The page limit that reveals position `pos` (used when playing past the
65
+ * end of the current page, e.g. by `next()` or auto-advance).
66
+ *
67
+ * @param {number} limit - The current limit.
68
+ * @param {number} pos - The position that must be visible.
69
+ * @returns {number}
70
+ */
71
+ export function limitToReveal(limit, pos) {
72
+ return pos >= limit ? pos + 1 : limit;
73
+ }
@@ -0,0 +1,306 @@
1
+ import {fold, matchesAll, words} from '@arraypress/text';
2
+
3
+ /**
4
+ * Pure data helpers: no DOM, no window. Shared by the browser runtime and
5
+ * the server renderer (`@arraypress/waveform-sounds/render`), so a wrapper
6
+ * that renders the list on the server produces exactly what the client
7
+ * would.
8
+ *
9
+ * @module data
10
+ */
11
+
12
+ /**
13
+ * Peaks travel as an 8-bit hex string, two characters per bar ("00"–"ff").
14
+ * A sound browser draws ~48–64 bars per row, so that is ~100 characters a
15
+ * sound: 300 sounds is ~30 KB in a manifest or in row attributes, against
16
+ * ~3x that as a JSON number array.
17
+ *
18
+ * @param {number[]} peaks - Values 0..1.
19
+ * @returns {string} Hex string.
20
+ */
21
+ export function encodePeaks(peaks) {
22
+ if (!Array.isArray(peaks)) return '';
23
+ let out = '';
24
+ for (const p of peaks) {
25
+ const v = Math.round(Math.min(Math.max(Number(p) || 0, 0), 1) * 255);
26
+ out += (v < 16 ? '0' : '') + v.toString(16);
27
+ }
28
+ return out;
29
+ }
30
+
31
+ /**
32
+ * Decode peaks from any accepted form into numbers 0..1.
33
+ *
34
+ * Accepts the hex string from {@link encodePeaks}, an array of 0..1
35
+ * numbers, or an array of integers on a larger scale (e.g. 0..100 or
36
+ * 0..255) together with that `scale`.
37
+ *
38
+ * @param {string|number[]|null|undefined} value
39
+ * @param {number} [scale=1] - The maximum of an integer array.
40
+ * @returns {number[]|null} Peaks, or null when there are none.
41
+ */
42
+ export function decodePeaks(value, scale = 1) {
43
+ if (value == null || value === '') return null;
44
+ if (typeof value === 'string') {
45
+ if (!/^[0-9a-f]+$/i.test(value) || value.length % 2) return null;
46
+ const out = new Array(value.length / 2);
47
+ for (let i = 0; i < out.length; i++) out[i] = parseInt(value.substr(i * 2, 2), 16) / 255;
48
+ return out;
49
+ }
50
+ if (!Array.isArray(value)) return null;
51
+ const s = Number(scale) > 0 ? Number(scale) : 1;
52
+ const out = value.map((v) => Math.min(Math.max((Number(v) || 0) / s, 0), 1));
53
+ return out.length ? out : null;
54
+ }
55
+
56
+ /**
57
+ * Normalise a musical key to a short canonical form: root, accidental
58
+ * (`#` or `b`), and `m` for minor. "F minor", "Fmin", "f m" → "Fm";
59
+ * "C# Major", "C♯" → "C#". Anything unparseable comes back trimmed, as
60
+ * given, so an unusual label still displays.
61
+ *
62
+ * @param {string|null|undefined} key
63
+ * @returns {string} Canonical key, or '' for none.
64
+ */
65
+ export function normalizeKey(key) {
66
+ if (key == null) return '';
67
+ const raw = String(key).trim();
68
+ const m = raw.match(/^([A-Ga-g])[\s_-]*([#♯b♭]?)[\s_-]*(m|min|minor|maj|major)?$/i);
69
+ if (!m) return raw;
70
+ const root = m[1].toUpperCase();
71
+ const acc = m[2] === '♯' ? '#' : m[2] === '♭' ? 'b' : m[2];
72
+ const minor = m[3] && /^m(in(or)?)?$/i.test(m[3]) && m[3] !== 'M';
73
+ return root + acc + (minor ? 'm' : '');
74
+ }
75
+
76
+ /** Pitch class of each root, for sorting keys: C, C#, D … B, majors before minors. */
77
+ const KEY_PITCH = {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};
78
+
79
+ /** Sort rank of a canonical key; unknown keys sort last. */
80
+ function keyRank(key) {
81
+ if (!key) return Infinity;
82
+ const minor = key.endsWith('m');
83
+ const root = minor ? key.slice(0, -1) : key;
84
+ const p = KEY_PITCH[root];
85
+ return p === undefined ? 1000 : p * 2 + (minor ? 1 : 0);
86
+ }
87
+
88
+ /**
89
+ * Format seconds as m:ss.
90
+ * @param {number|null|undefined} seconds
91
+ * @returns {string} e.g. "0:08", or '' when unknown.
92
+ */
93
+ export function formatDuration(seconds) {
94
+ // Number(null) is 0: an unknown length must not render as "0:00".
95
+ if (seconds == null || seconds === '') return '';
96
+ const s = Number(seconds);
97
+ if (!Number.isFinite(s) || s < 0) return '';
98
+ const total = Math.round(s);
99
+ return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`;
100
+ }
101
+
102
+ /**
103
+ * Parse a duration given as seconds (8.02) or as "m:ss" / "h:mm:ss".
104
+ * @param {number|string|null|undefined} value
105
+ * @returns {number|null}
106
+ */
107
+ export function parseDuration(value) {
108
+ if (value == null || value === '') return null;
109
+ if (typeof value === 'number') return Number.isFinite(value) && value >= 0 ? value : null;
110
+ const str = String(value).trim();
111
+ if (/^\d+(\.\d+)?$/.test(str)) return Number(str);
112
+ const parts = str.split(':').map(Number);
113
+ if (parts.length < 2 || parts.some((n) => !Number.isFinite(n))) return null;
114
+ return parts.reduce((acc, n) => acc * 60 + n, 0);
115
+ }
116
+
117
+ /**
118
+ * The title a file name implies: extension and separators dropped,
119
+ * leading pack prefixes kept (they are often the label's code).
120
+ * "NW_Bass_Loop_04_128_Fmin.wav" → "NW Bass Loop 04 128 Fmin".
121
+ * @param {string} url
122
+ * @returns {string}
123
+ */
124
+ export function titleFromUrl(url) {
125
+ const file = String(url || '').split(/[?#]/)[0].split('/').pop() || '';
126
+ let name = file.replace(/\.[a-z0-9]+$/i, '');
127
+ try { name = decodeURIComponent(name); } catch { /* keep as is */ }
128
+ return name.replace(/[_]+/g, ' ').replace(/\s+/g, ' ').trim();
129
+ }
130
+
131
+ /**
132
+ * Normalise one sound into the shape the runtime and renderer use.
133
+ *
134
+ * @param {Object} input - A sound: `{url, title?, type?, bpm?, key?,
135
+ * duration?, tags?, peaks?, waveform?, id?}`.
136
+ * @param {number} index - Its position (used for a fallback id).
137
+ * @param {number} [peakScale=1] - Scale of an integer `peaks` array.
138
+ * @returns {import('../../../index').Sound|null} The sound, or null if it has
139
+ * no url.
140
+ */
141
+ export function normalizeSound(input, index, peakScale = 1) {
142
+ if (!input || typeof input !== 'object' || !input.url) return null;
143
+ const bpm = Number(input.bpm);
144
+ const tags = Array.isArray(input.tags)
145
+ ? input.tags.map((t) => String(t).trim()).filter(Boolean)
146
+ : typeof input.tags === 'string'
147
+ ? input.tags.split(',').map((t) => t.trim()).filter(Boolean)
148
+ : [];
149
+ return {
150
+ id: input.id != null && input.id !== '' ? String(input.id) : `sound-${index + 1}`,
151
+ url: String(input.url),
152
+ title: input.title ? String(input.title) : titleFromUrl(input.url),
153
+ type: input.type ? String(input.type) : '',
154
+ bpm: Number.isFinite(bpm) && bpm > 0 ? Math.round(bpm * 100) / 100 : null,
155
+ key: normalizeKey(input.key),
156
+ duration: parseDuration(input.duration),
157
+ tags,
158
+ peaks: decodePeaks(input.peaks, peakScale),
159
+ waveform: input.waveform ? String(input.waveform) : null,
160
+ download: input.download ? String(input.download) : null,
161
+ };
162
+ }
163
+
164
+ /**
165
+ * Read a sounds manifest. Accepts `{version, peakScale?, sounds: [...]}`
166
+ * (what `waveform-gen --manifest` writes) or a bare array of sounds.
167
+ * Sounds without a url are dropped.
168
+ *
169
+ * @param {Object|Array} manifest
170
+ * @returns {import('../../../index').Sound[]}
171
+ */
172
+ export function parseManifest(manifest) {
173
+ const list = Array.isArray(manifest) ? manifest : Array.isArray(manifest?.sounds) ? manifest.sounds : [];
174
+ const scale = Array.isArray(manifest) ? 1 : Number(manifest?.peakScale) || 1;
175
+ return normalizeSounds(list, scale);
176
+ }
177
+
178
+ /**
179
+ * Normalise a list of sounds, dropping invalid ones and de-duplicating ids
180
+ * (a repeated id would make two rows answer to one play() call).
181
+ * @param {Array} list
182
+ * @param {number} [peakScale=1]
183
+ * @returns {import('../../../index').Sound[]}
184
+ */
185
+ export function normalizeSounds(list, peakScale = 1) {
186
+ const seen = new Set();
187
+ const out = [];
188
+ (Array.isArray(list) ? list : []).forEach((item, i) => {
189
+ const s = normalizeSound(item, i, peakScale);
190
+ if (!s) return;
191
+ let id = s.id, n = 2;
192
+ while (seen.has(id)) id = `${s.id}-${n++}`;
193
+ s.id = id;
194
+ seen.add(id);
195
+ out.push(s);
196
+ });
197
+ return out;
198
+ }
199
+
200
+ /**
201
+ * What the filter controls offer, derived from the sounds: each type with
202
+ * its count (in first-seen order), each key (in musical order), and the
203
+ * BPM range. A control with nothing to offer is not rendered.
204
+ *
205
+ * @param {import('../../../index').Sound[]} sounds
206
+ * @returns {{types: {name: string, count: number}[], keys: string[], bpm: {min: number, max: number}|null, hasDuration: boolean}}
207
+ */
208
+ export function facets(sounds) {
209
+ const types = new Map();
210
+ const keys = new Set();
211
+ let min = Infinity, max = -Infinity, hasDuration = false;
212
+ for (const s of sounds) {
213
+ if (s.type) types.set(s.type, (types.get(s.type) || 0) + 1);
214
+ if (s.key) keys.add(s.key);
215
+ if (s.bpm != null) { min = Math.min(min, s.bpm); max = Math.max(max, s.bpm); }
216
+ if (s.duration != null) hasDuration = true;
217
+ }
218
+ return {
219
+ types: [...types].map(([name, count]) => ({name, count})),
220
+ keys: [...keys].sort((a, b) => keyRank(a) - keyRank(b) || a.localeCompare(b)),
221
+ bpm: min === Infinity ? null : {min, max},
222
+ hasDuration,
223
+ };
224
+ }
225
+
226
+ /**
227
+ * Does a sound match the filter? Every set criterion must hold.
228
+ *
229
+ * `query` matches the title, type, key and tags with
230
+ * `@arraypress/text`'s `matchesAll`: every word, in any order, forgiving
231
+ * one typo in words of four letters or more ("drun" finds drum loops). A
232
+ * number in the query also matches the BPM exactly, so "bass 128" finds
233
+ * 128 BPM bass loops.
234
+ *
235
+ * @param {import('../../../index').Sound} sound
236
+ * @param {import('../../../index').SoundsFilter} filter
237
+ * @returns {boolean}
238
+ */
239
+ export function matches(sound, filter = {}) {
240
+ if (filter.type && sound.type !== filter.type) return false;
241
+ if (filter.key && sound.key !== normalizeKey(filter.key)) return false;
242
+ const lo = Number(filter.bpmMin), hi = Number(filter.bpmMax);
243
+ if ((filter.bpmMin != null && filter.bpmMin !== '' && Number.isFinite(lo)) ||
244
+ (filter.bpmMax != null && filter.bpmMax !== '' && Number.isFinite(hi))) {
245
+ if (sound.bpm == null) return false;
246
+ if (filter.bpmMin != null && filter.bpmMin !== '' && sound.bpm < lo) return false;
247
+ if (filter.bpmMax != null && filter.bpmMax !== '' && sound.bpm > hi) return false;
248
+ }
249
+ const terms = words(filter.query || '');
250
+ if (terms.length) {
251
+ const hay = [sound.title, sound.type, sound.key, ...(sound.tags || [])].join(' ');
252
+ const folded = fold(hay);
253
+ // A number naming this sound's BPM is satisfied; the rest is text.
254
+ const rest = terms.filter((w) => !(/^\d+$/.test(w) && !folded.includes(w)
255
+ && sound.bpm != null && Math.round(sound.bpm) === Number(w)));
256
+ if (rest.length && !matchesAll(hay, rest.join(' '))) return false;
257
+ }
258
+ return true;
259
+ }
260
+
261
+ /** The sort orders the toolbar offers. */
262
+ export const SORTS = ['default', 'title', 'bpm', 'key', 'duration'];
263
+
264
+ /** What each sort order needs from the data before it's worth offering. */
265
+ const SORT_NEEDS = {
266
+ default: () => true,
267
+ title: () => true,
268
+ bpm: (f) => f.bpm !== null,
269
+ key: (f) => f.keys.length > 0,
270
+ duration: (f) => f.hasDuration,
271
+ };
272
+
273
+ /**
274
+ * The configured sort orders the data can use (no BPM sort without BPMs),
275
+ * in the configured order. Shared by the renderer and the runtime, so the
276
+ * menu and the starting order always agree.
277
+ *
278
+ * @param {string[]} sorts - The configured orders.
279
+ * @param {ReturnType<typeof facets>} f - The sounds' facets.
280
+ * @returns {string[]}
281
+ */
282
+ export function availableSorts(sorts, f) {
283
+ return sorts.filter((sort) => SORT_NEEDS[sort]?.(f));
284
+ }
285
+
286
+ /**
287
+ * Sort sounds (returns a new array; `default` keeps the given order).
288
+ * Missing values sort last in every order.
289
+ *
290
+ * @param {import('../../../index').Sound[]} sounds
291
+ * @param {string} [by='default']
292
+ * @returns {import('../../../index').Sound[]}
293
+ */
294
+ export function sortSounds(sounds, by = 'default') {
295
+ const list = sounds.map((s, i) => ({s, i}));
296
+ const last = (v) => (v == null ? Infinity : v);
297
+ const cmp = {
298
+ title: (a, b) => a.s.title.localeCompare(b.s.title, undefined, {numeric: true, sensitivity: 'base'}),
299
+ bpm: (a, b) => last(a.s.bpm) - last(b.s.bpm),
300
+ key: (a, b) => keyRank(a.s.key) - keyRank(b.s.key),
301
+ duration: (a, b) => last(a.s.duration) - last(b.s.duration),
302
+ }[by];
303
+ if (cmp) list.sort((a, b) => cmp(a, b) || a.i - b.i);
304
+ return list.map((x) => x.s);
305
+ }
306
+