@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,102 @@
1
+ /**
2
+ * Filters in the address (`urlState`): which query parameters hold them,
3
+ * reading them into a filter, and writing a filter back into a URL. Pure:
4
+ * the runtime passes `location.search` / `location.href` in and calls
5
+ * `history.replaceState` with what comes out.
6
+ *
7
+ * ?q=bass&type=Bass+loops&key=Fm&bpm=120-130&sort=bpm
8
+ *
9
+ * @module url-state
10
+ */
11
+
12
+ import {normalizeKey} from './sounds.js';
13
+
14
+ /**
15
+ * The parameter names, or null when urlState is off. A string urlState
16
+ * prefixes them (`'pack'` → `pack-q`, `pack-type`, …) so two lists on one
17
+ * page don't share a filter.
18
+ *
19
+ * @param {boolean|string|null|undefined} urlState
20
+ * @returns {{q: string, type: string, key: string, bpm: string, sort: string}|null}
21
+ */
22
+ export function urlKeys(urlState) {
23
+ if (!urlState) return null;
24
+ const p = typeof urlState === 'string' ? `${urlState}-` : '';
25
+ return {q: `${p}q`, type: `${p}type`, key: `${p}key`, bpm: `${p}bpm`, sort: `${p}sort`};
26
+ }
27
+
28
+ /**
29
+ * A BPM range parameter: "120-130", "120-" or "-130".
30
+ *
31
+ * @param {string|null|undefined} value
32
+ * @returns {{bpmMin: string, bpmMax: string}|null} null if malformed.
33
+ */
34
+ export function parseBpmRange(value) {
35
+ const m = String(value ?? '').match(/^(\d*)-(\d*)$/);
36
+ return m && (m[1] || m[2]) ? {bpmMin: m[1], bpmMax: m[2]} : null;
37
+ }
38
+
39
+ /**
40
+ * The inverse of {@link parseBpmRange}; '' when neither end is set.
41
+ *
42
+ * @param {string|number|null|undefined} min
43
+ * @param {string|number|null|undefined} max
44
+ * @returns {string}
45
+ */
46
+ export function formatBpmRange(min, max) {
47
+ const lo = min ?? '', hi = max ?? '';
48
+ return lo !== '' || hi !== '' ? `${lo}-${hi}` : '';
49
+ }
50
+
51
+ /**
52
+ * Read the filter and sort from a query string. Values the list can't use
53
+ * (a type it doesn't have, a key no sound is in, a sort it doesn't offer)
54
+ * are ignored, never applied: a stale link shows the whole list, not an
55
+ * empty one.
56
+ *
57
+ * @param {string} search - `location.search`.
58
+ * @param {ReturnType<typeof urlKeys>} keys
59
+ * @param {{types: {name: string}[], keys: string[]}} available - From `facets()`.
60
+ * @param {string[]} sorts - The sort orders offered.
61
+ * @returns {{filter: Object, sort: string|null}} A filter patch, and the sort (or null).
62
+ */
63
+ export function readUrlState(search, keys, available, sorts) {
64
+ const out = {filter: {}, sort: null};
65
+ if (!keys) return out;
66
+ const sp = new URLSearchParams(search);
67
+ const q = sp.get(keys.q);
68
+ if (q) out.filter.query = q;
69
+ const type = sp.get(keys.type);
70
+ if (type && available.types.some((t) => t.name === type)) out.filter.type = type;
71
+ const key = normalizeKey(sp.get(keys.key));
72
+ if (key && available.keys.includes(key)) out.filter.key = key;
73
+ const bpm = parseBpmRange(sp.get(keys.bpm));
74
+ if (bpm) Object.assign(out.filter, bpm);
75
+ const sort = sp.get(keys.sort);
76
+ if (sort && sorts.includes(sort)) out.sort = sort;
77
+ return out;
78
+ }
79
+
80
+ /**
81
+ * The URL with the filter written in. Empty values (and the starting sort)
82
+ * are removed rather than written empty; every other parameter and the
83
+ * hash are kept.
84
+ *
85
+ * @param {string} href - `location.href`.
86
+ * @param {ReturnType<typeof urlKeys>} keys
87
+ * @param {{query: string, type: string, key: string, bpmMin: string, bpmMax: string}} filter
88
+ * @param {string} sort
89
+ * @param {string} defaultSort - The starting order (not written).
90
+ * @returns {string} The new href (equal to `href` when nothing changed).
91
+ */
92
+ export function writeUrlState(href, keys, filter, sort, defaultSort) {
93
+ if (!keys) return href;
94
+ const url = new URL(href);
95
+ const set = (name, v) => (v ? url.searchParams.set(name, v) : url.searchParams.delete(name));
96
+ set(keys.q, String(filter.query ?? '').trim());
97
+ set(keys.type, filter.type);
98
+ set(keys.key, filter.key);
99
+ set(keys.bpm, formatBpmRange(filter.bpmMin, filter.bpmMax));
100
+ set(keys.sort, sort !== defaultSort ? sort : '');
101
+ return url.href;
102
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Colours the CSS can't hand the runtime directly: the canvas needs real
3
+ * colour values (it can't read `var()` or `color-mix()`), and the inverted
4
+ * "on" states need the page surface behind the list.
5
+ *
6
+ * @module colors
7
+ */
8
+
9
+ /**
10
+ * The alpha of a computed colour string: `rgba(0, 0, 0, 0)`,
11
+ * `rgb(1 2 3 / 50%)`, `oklab(… / 0.9)`, `transparent`. Opaque when no alpha
12
+ * is written.
13
+ *
14
+ * @param {string|null|undefined} color
15
+ * @returns {number} 0..1.
16
+ */
17
+ export function parseAlpha(color) {
18
+ const c = String(color ?? '').trim();
19
+ if (!c || c === 'transparent') return 0;
20
+ const slash = c.match(/\/\s*([\d.]+)(%?)\s*\)$/);
21
+ if (slash) return Number(slash[1]) / (slash[2] ? 100 : 1);
22
+ const rgba = c.match(/^rgba\(\s*[^,]+,[^,]+,[^,]+,\s*([\d.]+)\s*\)$/);
23
+ if (rgba) return Number(rgba[1]);
24
+ return 1;
25
+ }
26
+
27
+ /**
28
+ * The first (near-)opaque background at or above an element — the page
29
+ * surface the list sits on. Crosses shadow-root boundaries.
30
+ *
31
+ * @param {Element} el
32
+ * @param {number} [minAlpha=0.95] - How opaque counts as "the surface".
33
+ * @returns {string} A computed colour, or `#fff` when nothing is painted.
34
+ */
35
+ export function pageSurface(el, minAlpha = 0.95) {
36
+ for (let node = el; node && node.nodeType === 1; node = node.parentElement || node.getRootNode?.().host) {
37
+ const bg = getComputedStyle(node).backgroundColor;
38
+ if (parseAlpha(bg) > minAlpha) return bg;
39
+ }
40
+ return '#fff';
41
+ }
42
+
43
+ /**
44
+ * Resolve any CSS colour (a `var()`, `color-mix()`, `currentColor`) to a
45
+ * concrete value, as it would compute inside `container`.
46
+ *
47
+ * @param {Element} container
48
+ * @param {string} value - A CSS colour expression.
49
+ * @returns {string} The computed colour.
50
+ */
51
+ export function resolveCssColor(container, value) {
52
+ const probe = document.createElement('span');
53
+ probe.style.cssText = 'position:absolute;width:0;height:0;overflow:hidden;visibility:hidden';
54
+ probe.style.color = value;
55
+ container.appendChild(probe);
56
+ const color = getComputedStyle(probe).color;
57
+ probe.remove();
58
+ return color;
59
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * The row waveform: a small canvas of mirrored bars (or plain bars) drawn
3
+ * from low-resolution peaks, with the played part in the progress colour.
4
+ *
5
+ * Deliberately NOT a WaveformPlayer per row. A pack can have 300 sounds;
6
+ * 300 players would be 300 resize observers, theme watchers and option
7
+ * pipelines for what is, until one is played, a static picture. One engine
8
+ * player does the audio; these are pictures with a progress fill.
9
+ *
10
+ * @module draw
11
+ */
12
+
13
+ /**
14
+ * Size a canvas to its box at the device pixel ratio. Returns the CSS size,
15
+ * or null when the canvas has no box (hidden row, jsdom).
16
+ * @param {HTMLCanvasElement} canvas
17
+ */
18
+ export function fitCanvas(canvas) {
19
+ const rect = canvas.getBoundingClientRect();
20
+ if (!rect.width || !rect.height) return null;
21
+ const dpr = Math.min(window.devicePixelRatio || 1, 3);
22
+ const w = Math.round(rect.width * dpr), h = Math.round(rect.height * dpr);
23
+ if (canvas.width !== w) canvas.width = w;
24
+ if (canvas.height !== h) canvas.height = h;
25
+ return {width: rect.width, height: rect.height, dpr};
26
+ }
27
+
28
+ /**
29
+ * Resample peaks to `count` bars (max of each bucket, so transients
30
+ * survive the downsample).
31
+ * @param {number[]} peaks
32
+ * @param {number} count
33
+ */
34
+ export function resample(peaks, count) {
35
+ if (!peaks?.length || count <= 0) return [];
36
+ if (peaks.length === count) return peaks;
37
+ const out = new Array(count);
38
+ const step = peaks.length / count;
39
+ for (let i = 0; i < count; i++) {
40
+ const start = Math.floor(i * step);
41
+ const end = Math.max(start + 1, Math.floor((i + 1) * step));
42
+ let m = 0;
43
+ for (let j = start; j < end && j < peaks.length; j++) if (peaks[j] > m) m = peaks[j];
44
+ out[i] = m;
45
+ }
46
+ return out;
47
+ }
48
+
49
+ /**
50
+ * Draw a row waveform.
51
+ *
52
+ * @param {HTMLCanvasElement} canvas
53
+ * @param {number[]|null} peaks - 0..1. Null draws a flat placeholder line.
54
+ * @param {number} progress - 0..1 played.
55
+ * @param {{style: 'mirror'|'bars', color: string, progressColor: string, barWidth: number, barGap: number}} o
56
+ */
57
+ export function drawRowWaveform(canvas, peaks, progress, o) {
58
+ const size = fitCanvas(canvas);
59
+ const ctx = size && canvas.getContext && canvas.getContext('2d');
60
+ if (!ctx) return;
61
+ const {width, height, dpr} = size;
62
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
63
+ ctx.clearRect(0, 0, width, height);
64
+
65
+ if (!peaks?.length) {
66
+ ctx.fillStyle = o.color;
67
+ ctx.fillRect(0, Math.floor(height / 2), width, 1);
68
+ return;
69
+ }
70
+
71
+ const step = o.barWidth + o.barGap;
72
+ const count = Math.max(1, Math.floor((width + o.barGap) / step));
73
+ const bars = resample(peaks, count);
74
+ // Normalise to the loudest bar so quiet one-shots aren't a flat line.
75
+ let max = 0;
76
+ for (const b of bars) if (b > max) max = b;
77
+ const scale = max > 0 ? 1 / max : 1;
78
+ const split = progress * width;
79
+ const mid = height / 2;
80
+
81
+ for (let i = 0; i < bars.length; i++) {
82
+ const x = i * step;
83
+ const v = Math.max(bars[i] * scale, 0.04);
84
+ ctx.fillStyle = x + o.barWidth / 2 <= split ? o.progressColor : o.color;
85
+ if (o.style === 'bars') {
86
+ const h = Math.max(1, v * height);
87
+ ctx.fillRect(x, height - h, o.barWidth, h);
88
+ } else {
89
+ const h = Math.max(1, v * (height - 2));
90
+ ctx.fillRect(x, mid - h / 2, o.barWidth, h);
91
+ }
92
+ }
93
+ }
@@ -0,0 +1,232 @@
1
+ /**
2
+ * The dropdowns (type / key / sort): a button and a popup listbox, with a
3
+ * search field when it has many options. Follows the WAI-ARIA
4
+ * combobox/listbox pattern: focus stays in the search field (or the list),
5
+ * the active option is `aria-activedescendant`, ↑/↓ move, Enter picks,
6
+ * Esc closes and returns focus to the button.
7
+ *
8
+ * The markup comes from `renderMenu()` (server or client); this module
9
+ * only adds behaviour.
10
+ *
11
+ * @module menus
12
+ */
13
+
14
+ import {fold} from '@arraypress/text';
15
+
16
+ /**
17
+ * Does an option's label match what's typed in a menu's search field?
18
+ * Case- and accent-insensitive substring.
19
+ *
20
+ * @param {string} label
21
+ * @param {string} query
22
+ * @returns {boolean}
23
+ */
24
+ export function optionMatches(label, query) {
25
+ const q = fold(String(query ?? '')).trim();
26
+ return !q || fold(String(label ?? '')).includes(q);
27
+ }
28
+
29
+ /**
30
+ * Move an index by `delta`, clamped to `0..length-1`.
31
+ *
32
+ * @param {number} current - -1 when nothing is active.
33
+ * @param {number} delta
34
+ * @param {number} length
35
+ * @returns {number}
36
+ */
37
+ export function stepIndex(current, delta, length) {
38
+ return Math.max(0, Math.min(length - 1, current + delta));
39
+ }
40
+
41
+ /** The parts of one dropdown. */
42
+ function partsOf(menu) {
43
+ return {
44
+ button: menu.querySelector('[data-ws-menu-btn]'),
45
+ pop: menu.querySelector('[data-ws-menu-pop]'),
46
+ search: menu.querySelector('[data-ws-menu-search]'),
47
+ list: menu.querySelector('[data-ws-menu-list]'),
48
+ none: menu.querySelector('[data-ws-menu-none]'),
49
+ value: menu.querySelector('[data-ws-menu-value]'),
50
+ };
51
+ }
52
+
53
+ /** The element that owns focus while a menu is open. */
54
+ const focusOwner = (p) => p.search || p.list;
55
+
56
+ /** A menu's options, optionally only the ones not filtered out. */
57
+ const optionsOf = (p, visibleOnly = false) => [...p.list.querySelectorAll('[role="option"]')].filter((o) => !visibleOnly || !o.hidden);
58
+
59
+ /**
60
+ * Every dropdown inside one list, with one shared "which is open" state.
61
+ */
62
+ export class Menus {
63
+ /**
64
+ * @param {HTMLElement} container - The list's root element.
65
+ * @param {Object} opts
66
+ * @param {(name: string, value: string) => void} opts.onPick - A value was chosen.
67
+ * @param {AbortSignal} opts.signal - Removes every listener on abort.
68
+ */
69
+ constructor(container, {onPick, signal}) {
70
+ this.container = container;
71
+ this.onPick = onPick;
72
+ /** @type {Record<string, HTMLElement>} */
73
+ this.menus = Object.fromEntries([...container.querySelectorAll('[data-ws-menu]')].map((m) => [m.dataset.wsMenu, m]));
74
+ /** @type {HTMLElement|null} */
75
+ this.openMenu = null;
76
+ this._bind(signal);
77
+ }
78
+
79
+ /**
80
+ * Wire every menu, plus closing on an outside press or focus leaving.
81
+ * @param {AbortSignal} signal
82
+ * @private
83
+ */
84
+ _bind(signal) {
85
+ const sig = {signal};
86
+ for (const [name, menu] of Object.entries(this.menus)) {
87
+ const p = partsOf(menu);
88
+ p.button.addEventListener('click', () => (this.openMenu === menu ? this.close(true) : this.open(menu)), sig);
89
+ p.button.addEventListener('keydown', (e) => {
90
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); this.open(menu); }
91
+ }, sig);
92
+ p.list.addEventListener('click', (e) => {
93
+ const opt = e.target.closest('[role="option"]');
94
+ if (opt) this._pick(name, opt.dataset.value);
95
+ }, sig);
96
+ // Keep focus in the field while an option is pressed.
97
+ p.list.addEventListener('mousedown', (e) => e.preventDefault(), sig);
98
+ p.search?.addEventListener('input', () => this._filter(menu, p.search.value), sig);
99
+ focusOwner(p).addEventListener('keydown', (e) => this._onKey(e, name, menu), sig);
100
+ }
101
+ document.addEventListener('pointerdown', (e) => {
102
+ if (this.openMenu && !this.openMenu.contains(e.target)) this.close(false);
103
+ }, sig);
104
+ this.container.addEventListener('focusout', (e) => {
105
+ if (this.openMenu && !this.openMenu.contains(e.relatedTarget)) this.close(false);
106
+ }, sig);
107
+ }
108
+
109
+ /**
110
+ * Open a menu (closing any other), with the selected option active and
111
+ * focus in its search field or list. Flips to open over the end edge
112
+ * when it would overflow the list.
113
+ *
114
+ * @param {HTMLElement} menu
115
+ */
116
+ open(menu) {
117
+ if (this.openMenu && this.openMenu !== menu) this.close(false);
118
+ const p = partsOf(menu);
119
+ p.button.setAttribute('aria-expanded', 'true');
120
+ p.pop.hidden = false;
121
+ this.openMenu = menu;
122
+ if (p.search) { p.search.value = ''; this._filter(menu, ''); }
123
+ menu.classList.remove('ws-menu--end');
124
+ if (p.pop.getBoundingClientRect().right > this.container.getBoundingClientRect().right + 1) menu.classList.add('ws-menu--end');
125
+ this._activate(menu, p.list.querySelector('[role="option"][aria-selected="true"]'));
126
+ focusOwner(p).focus();
127
+ }
128
+
129
+ /**
130
+ * Close the open menu, if any.
131
+ *
132
+ * @param {boolean} focusButton - Return focus to its button (after a
133
+ * pick or Esc; not after a click elsewhere).
134
+ */
135
+ close(focusButton) {
136
+ const menu = this.openMenu;
137
+ if (!menu) return;
138
+ this.openMenu = null;
139
+ const p = partsOf(menu);
140
+ p.pop.hidden = true;
141
+ p.button.setAttribute('aria-expanded', 'false');
142
+ if (focusButton) p.button.focus();
143
+ }
144
+
145
+ /**
146
+ * Show `value` as a menu's choice (button text + `aria-selected`). Used
147
+ * after a pick and when the filter is changed from code.
148
+ *
149
+ * @param {string} name - 'type' | 'key' | 'sort'.
150
+ * @param {string} value
151
+ */
152
+ setValue(name, value) {
153
+ const menu = this.menus[name];
154
+ if (!menu) return;
155
+ const p = partsOf(menu);
156
+ let label = null;
157
+ for (const opt of optionsOf(p)) {
158
+ const on = opt.dataset.value === String(value ?? '');
159
+ opt.setAttribute('aria-selected', String(on));
160
+ if (on) label = opt.querySelector('.ws-menu-text')?.textContent ?? '';
161
+ }
162
+ if (label !== null) p.value.textContent = label;
163
+ }
164
+
165
+ /**
166
+ * Narrow a menu to the options matching the search, and make the first
167
+ * match active.
168
+ * @private
169
+ */
170
+ _filter(menu, query) {
171
+ const p = partsOf(menu);
172
+ let first = null;
173
+ for (const opt of optionsOf(p)) {
174
+ opt.hidden = !optionMatches(opt.textContent, query);
175
+ if (!opt.hidden) first ??= opt;
176
+ }
177
+ p.none.hidden = first !== null;
178
+ this._activate(menu, first);
179
+ }
180
+
181
+ /**
182
+ * Mark one option active (`aria-activedescendant`) and scroll it into
183
+ * the list's view.
184
+ * @private
185
+ */
186
+ _activate(menu, opt) {
187
+ const p = partsOf(menu);
188
+ for (const o of p.list.querySelectorAll('.is-active')) o.classList.remove('is-active');
189
+ const owner = focusOwner(p);
190
+ if (!opt || opt.hidden) { owner.removeAttribute('aria-activedescendant'); return; }
191
+ opt.classList.add('is-active');
192
+ owner.setAttribute('aria-activedescendant', opt.id);
193
+ opt.scrollIntoView?.({block: 'nearest'});
194
+ }
195
+
196
+ /**
197
+ * Keys inside an open menu.
198
+ * @private
199
+ */
200
+ _onKey(e, name, menu) {
201
+ const p = partsOf(menu);
202
+ const opts = optionsOf(p, true);
203
+ const at = opts.indexOf(p.list.querySelector('.is-active'));
204
+ const moveTo = (i) => { e.preventDefault(); this._activate(menu, opts[i]); };
205
+ const inField = e.target.matches('input');
206
+ switch (e.key) {
207
+ case 'ArrowDown': return moveTo(stepIndex(at, 1, opts.length));
208
+ case 'ArrowUp': return moveTo(stepIndex(at, -1, opts.length));
209
+ case 'Home': return inField ? undefined : moveTo(0);
210
+ case 'End': return inField ? undefined : moveTo(opts.length - 1);
211
+ case 'Enter':
212
+ e.preventDefault();
213
+ if (at >= 0) this._pick(name, opts[at].dataset.value);
214
+ return undefined;
215
+ case 'Escape':
216
+ e.preventDefault();
217
+ e.stopPropagation();
218
+ return this.close(true);
219
+ case 'Tab': return this.close(false);
220
+ default: return undefined;
221
+ }
222
+ }
223
+
224
+ /**
225
+ * A value was chosen: close, then report it.
226
+ * @private
227
+ */
228
+ _pick(name, value) {
229
+ this.close(true);
230
+ this.onPick(name, value);
231
+ }
232
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The rows in the DOM: reading server-rendered rows back into sounds, and
3
+ * finding a row by the sound it shows.
4
+ *
5
+ * @module rows
6
+ */
7
+
8
+ import {normalizeSound} from '../data/sounds.js';
9
+
10
+ /** A list's row elements, in DOM order. */
11
+ const ROW = ':scope > [data-ws-index]';
12
+
13
+ /**
14
+ * Read server-rendered rows back into sounds. Rows are taken in their
15
+ * original order (`data-ws-index`) and renumbered 0..n-1, and a row whose
16
+ * data is unusable (no url) is removed — so a row missing from the markup
17
+ * can't leave a hole that would misalign rows and sounds.
18
+ *
19
+ * @param {HTMLElement} list - The `[data-ws-list]` element.
20
+ * @returns {import('../../../index').Sound[]}
21
+ */
22
+ export function readRows(list) {
23
+ const rows = [...list.querySelectorAll(ROW)]
24
+ .sort((a, b) => Number(a.dataset.wsIndex) - Number(b.dataset.wsIndex));
25
+ const sounds = [];
26
+ for (const row of rows) {
27
+ const d = row.dataset;
28
+ const sound = normalizeSound({
29
+ id: d.wsId, url: d.url, title: d.title, type: d.type, bpm: d.bpm, key: d.key,
30
+ duration: d.duration, tags: d.tags, peaks: d.peaks, waveform: d.waveform, download: d.download,
31
+ }, sounds.length);
32
+ if (!sound) { row.remove(); continue; }
33
+ row.dataset.wsIndex = String(sounds.length);
34
+ sounds.push(sound);
35
+ }
36
+ return sounds;
37
+ }
38
+
39
+ /**
40
+ * The row elements, indexed by the sound each one shows (whatever order
41
+ * they're displayed in).
42
+ *
43
+ * @param {HTMLElement} list
44
+ * @returns {HTMLElement[]}
45
+ */
46
+ export function indexRows(list) {
47
+ const rows = [];
48
+ list.querySelectorAll(ROW).forEach((row) => { rows[Number(row.dataset.wsIndex)] = row; });
49
+ return rows;
50
+ }
51
+
52
+ /**
53
+ * The rows currently visible (not hidden by the filter or the page), in
54
+ * display order.
55
+ *
56
+ * @param {HTMLElement} list
57
+ * @returns {HTMLElement[]}
58
+ */
59
+ export function visibleRows(list) {
60
+ return [...list.querySelectorAll(ROW)].filter((r) => !r.hidden);
61
+ }
62
+
63
+ /**
64
+ * Put the rows in the given order. Every row moves (hidden ones too), so
65
+ * clearing a filter keeps the order.
66
+ *
67
+ * @param {HTMLElement} list
68
+ * @param {HTMLElement[]} rows - In the order to show them.
69
+ */
70
+ export function orderRows(list, rows) {
71
+ const frag = document.createDocumentFragment();
72
+ for (const row of rows) if (row) frag.appendChild(row);
73
+ list.appendChild(frag);
74
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @arraypress/waveform-sounds — public surface, without the import-time
3
+ * auto-init scan (`index.js` adds that). Anything new belongs here.
4
+ *
5
+ * @module entry
6
+ */
7
+ import {WaveformSounds, DEFAULT_OPTIONS} from './core/WaveformSounds.js';
8
+ import {
9
+ encodePeaks, decodePeaks, normalizeKey, normalizeSounds, parseManifest, facets, matches, sortSounds, formatDuration,
10
+ } from './data/sounds.js';
11
+ import {renderSounds, renderSoundsElement, DEFAULT_STRINGS} from './render/markup.js';
12
+
13
+ WaveformSounds.utils = {encodePeaks, decodePeaks, normalizeKey, normalizeSounds, parseManifest, facets, matches, sortSounds, formatDuration, renderSounds};
14
+ WaveformSounds.DEFAULT_OPTIONS = DEFAULT_OPTIONS;
15
+ WaveformSounds.DEFAULT_STRINGS = DEFAULT_STRINGS;
16
+
17
+ // CDN / <script> usage: a global, like the rest of the family.
18
+ if (typeof window !== 'undefined') window.WaveformSounds = WaveformSounds;
19
+
20
+ export default WaveformSounds;
21
+ export {
22
+ WaveformSounds, DEFAULT_OPTIONS, DEFAULT_STRINGS,
23
+ encodePeaks, decodePeaks, normalizeKey, normalizeSounds, parseManifest, facets, matches, sortSounds, formatDuration,
24
+ renderSounds, renderSoundsElement,
25
+ };
@@ -0,0 +1,24 @@
1
+ /**
2
+ * @arraypress/waveform-sounds
3
+ * A searchable, filterable list of sounds for WaveformPlayer.
4
+ *
5
+ * Importing this entry initialises every `[data-waveform-sounds]` element
6
+ * once the DOM is ready. Opt out page-wide with
7
+ * `<html data-waveform-autoinit="false">` (the family's switch), or import
8
+ * `@arraypress/waveform-sounds/no-autoinit`.
9
+ *
10
+ * @author ArrayPress
11
+ * @license MIT
12
+ */
13
+ import WaveformSounds from './entry.js';
14
+
15
+ export * from './entry.js';
16
+ export default WaveformSounds;
17
+
18
+ if (typeof document !== 'undefined' && document.documentElement?.dataset?.waveformAutoinit !== 'false') {
19
+ if (document.readyState === 'loading') {
20
+ document.addEventListener('DOMContentLoaded', () => WaveformSounds.init(), {once: true});
21
+ } else {
22
+ WaveformSounds.init();
23
+ }
24
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * A tiny HTML string builder for the server-safe renderer. Two rules make
3
+ * it safe to use everywhere:
4
+ *
5
+ * - ATTRIBUTE values are always escaped. `true` writes a bare attribute
6
+ * (`hidden`, `download`); `false`, `null` and `undefined` leave it out.
7
+ * ARIA states are strings, so pass `String(bool)` for those.
8
+ * - CHILDREN are HTML. Text goes through {@link text} first.
9
+ *
10
+ * @module html
11
+ */
12
+
13
+ import {escapeHtml} from '@arraypress/text';
14
+
15
+ /** Elements with no closing tag. */
16
+ const VOID = new Set(['input', 'br', 'img']);
17
+
18
+ /**
19
+ * Escape text for use as a child.
20
+ *
21
+ * @param {unknown} value
22
+ * @returns {string}
23
+ */
24
+ export function text(value) {
25
+ return escapeHtml(value ?? '');
26
+ }
27
+
28
+ /**
29
+ * Serialise attributes, in the order given.
30
+ *
31
+ * @param {Record<string, string|number|boolean|null|undefined>} map
32
+ * @returns {string} e.g. ` class="ws-row" hidden` (leading space included).
33
+ */
34
+ export function attrs(map = {}) {
35
+ let out = '';
36
+ for (const [name, value] of Object.entries(map)) {
37
+ if (value === true) out += ` ${name}`;
38
+ else if (value !== false && value != null) out += ` ${name}="${escapeHtml(value)}"`;
39
+ }
40
+ return out;
41
+ }
42
+
43
+ /**
44
+ * Build an element.
45
+ *
46
+ * @param {string} tag
47
+ * @param {Record<string, string|number|boolean|null|undefined>} [attributes]
48
+ * @param {...(string|false|null|undefined|Array)} children - HTML strings; falsy ones and nested arrays are flattened away.
49
+ * @returns {string}
50
+ */
51
+ export function h(tag, attributes = {}, ...children) {
52
+ const open = `<${tag}${attrs(attributes)}>`;
53
+ if (VOID.has(tag)) return open;
54
+ return open + children.flat(Infinity).filter((c) => c != null && c !== false && c !== '').join('') + `</${tag}>`;
55
+ }