@arraypress/waveform-sounds 0.2.0 → 0.3.1

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,68 @@
1
+ /**
2
+ * The BPM range control's arithmetic: between the two slider handles and the
3
+ * filter, and the label its menu button shows. Pure, so the server renderer
4
+ * and the runtime agree.
5
+ *
6
+ * A handle resting at an END of the pack's range is "no limit on that side",
7
+ * not a limit at that value: sounds with no BPM are hidden by any BPM filter,
8
+ * so a slider left wide open must not filter at all.
9
+ *
10
+ * @module bpm
11
+ */
12
+
13
+ /**
14
+ * The filter for a pair of handle positions.
15
+ *
16
+ * @param {number} lo - The lower handle.
17
+ * @param {number} hi - The upper handle.
18
+ * @param {{min: number, max: number}} extent - The pack's BPM range (`facets().bpm`).
19
+ * @returns {{bpmMin: string, bpmMax: string}} `''` for an open end.
20
+ */
21
+ export function bpmFilterFromRange(lo, hi, extent) {
22
+ const a = Math.min(lo, hi), b = Math.max(lo, hi);
23
+ return {
24
+ bpmMin: a > extent.min ? String(a) : '',
25
+ bpmMax: b < extent.max ? String(b) : '',
26
+ };
27
+ }
28
+
29
+ /**
30
+ * Where the handles sit for a filter: an open end at the pack's own end, a
31
+ * set one at its value (clamped into the pack's range, so a link with
32
+ * `?bpm=60-300` still shows sensible handles).
33
+ *
34
+ * @param {{bpmMin?: string|number, bpmMax?: string|number}} filter
35
+ * @param {{min: number, max: number}} extent
36
+ * @returns {{lo: number, hi: number}}
37
+ */
38
+ export function bpmRangeFromFilter(filter, extent) {
39
+ const read = (v, fallback) => {
40
+ const n = Number(v);
41
+ return v === '' || v == null || !Number.isFinite(n) ? fallback : Math.min(Math.max(n, extent.min), extent.max);
42
+ };
43
+ const lo = read(filter.bpmMin, extent.min);
44
+ const hi = read(filter.bpmMax, extent.max);
45
+ return lo <= hi ? {lo, hi} : {lo: hi, hi: lo};
46
+ }
47
+
48
+ /**
49
+ * A handle's position along the track, 0..1.
50
+ *
51
+ * @param {number} value
52
+ * @param {{min: number, max: number}} extent
53
+ * @returns {number}
54
+ */
55
+ export function bpmFraction(value, extent) {
56
+ const span = extent.max - extent.min;
57
+ return span > 0 ? Math.min(Math.max((value - extent.min) / span, 0), 1) : 0;
58
+ }
59
+
60
+ /**
61
+ * Is a BPM limit set on either side?
62
+ *
63
+ * @param {{bpmMin?: string|number, bpmMax?: string|number}} filter
64
+ * @returns {boolean}
65
+ */
66
+ export function hasBpmFilter(filter) {
67
+ return (filter.bpmMin != null && filter.bpmMin !== '') || (filter.bpmMax != null && filter.bpmMax !== '');
68
+ }
@@ -86,7 +86,8 @@ function keyRank(key) {
86
86
  }
87
87
 
88
88
  /**
89
- * Format seconds as m:ss, or as tenths under a second.
89
+ * Format seconds as m:ss (whole seconds, rounded down like a player's
90
+ * clock), or as tenths under a second.
90
91
  *
91
92
  * A one-shot (a kick, a hat) is often shorter than a second, and m:ss would
92
93
  * round it to "0:00", which reads as a missing length.
@@ -101,7 +102,9 @@ export function formatDuration(seconds) {
101
102
  if (!Number.isFinite(s) || s < 0) return '';
102
103
  // Anything that would round to "1.0s" is shown as "0:01" instead.
103
104
  if (s > 0 && s < 0.95) return `${Math.max(0.1, Math.round(s * 10) / 10).toFixed(1)}s`;
104
- const total = Math.round(s);
105
+ // Whole seconds DOWN, as the player's own clock counts them, so a row
106
+ // and the docked player never disagree (7.6s is 0:07 in both).
107
+ const total = s < 1 ? Math.ceil(s) : Math.floor(s);
105
108
  return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`;
106
109
  }
107
110
 
@@ -5,6 +5,10 @@
5
5
  * the active option is `aria-activedescendant`, ↑/↓ move, Enter picks,
6
6
  * Esc closes and returns focus to the button.
7
7
  *
8
+ * A menu without a listbox is a PANEL (the BPM range): a button and a popup
9
+ * dialog of its own controls. It shares the opening, closing, outside-press
10
+ * and Esc handling; what's inside it reports its own changes.
11
+ *
8
12
  * The markup comes from `renderMenu()` (server or client); this module
9
13
  * only adds behaviour.
10
14
  *
@@ -50,8 +54,8 @@ function partsOf(menu) {
50
54
  };
51
55
  }
52
56
 
53
- /** The element that owns focus while a menu is open. */
54
- const focusOwner = (p) => p.search || p.list;
57
+ /** The element that owns focus while a menu is open (a panel: its first field, else its first button). */
58
+ const focusOwner = (p) => p.search || p.list || p.pop.querySelector('input') || p.pop.querySelector('button');
55
59
 
56
60
  /** A menu's options, optionally only the ones not filtered out. */
57
61
  const optionsOf = (p, visibleOnly = false) => [...p.list.querySelectorAll('[role="option"]')].filter((o) => !visibleOnly || !o.hidden);
@@ -89,6 +93,16 @@ export class Menus {
89
93
  p.button.addEventListener('keydown', (e) => {
90
94
  if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); this.open(menu); }
91
95
  }, sig);
96
+ if (!p.list) {
97
+ // A panel: Esc anywhere inside it closes it.
98
+ p.pop.addEventListener('keydown', (e) => {
99
+ if (e.key !== 'Escape') return;
100
+ e.preventDefault();
101
+ e.stopPropagation();
102
+ this.close(true);
103
+ }, sig);
104
+ continue;
105
+ }
92
106
  p.list.addEventListener('click', (e) => {
93
107
  const opt = e.target.closest('[role="option"]');
94
108
  if (opt) this._pick(name, opt.dataset.value);
@@ -122,8 +136,8 @@ export class Menus {
122
136
  if (p.search) { p.search.value = ''; this._filter(menu, ''); }
123
137
  menu.classList.remove('ws-menu--end');
124
138
  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();
139
+ if (p.list) this._activate(menu, p.list.querySelector('[role="option"][aria-selected="true"]'));
140
+ focusOwner(p)?.focus();
127
141
  }
128
142
 
129
143
  /**
@@ -153,6 +167,7 @@ export class Menus {
153
167
  const menu = this.menus[name];
154
168
  if (!menu) return;
155
169
  const p = partsOf(menu);
170
+ if (!p.list) return; // a panel shows its own value
156
171
  let label = null;
157
172
  for (const opt of optionsOf(p)) {
158
173
  const on = opt.dataset.value === String(value ?? '');
@@ -20,7 +20,7 @@ import {availableSorts, encodePeaks, facets, formatDuration, normalizeSounds} fr
20
20
  import {h, text} from './html.js';
21
21
  import {ICONS} from './icons.js';
22
22
  import {RENDER_DEFAULTS, resolveRenderOptions} from './options.js';
23
- import {countText, DEFAULT_STRINGS, fill, SORT_LABEL_KEYS} from './strings.js';
23
+ import {bpmLabel, countText, DEFAULT_STRINGS, fill, SORT_LABEL_KEYS} from './strings.js';
24
24
  import {hashString} from '../shared/utils.js';
25
25
 
26
26
  export {escapeHtml, RENDER_DEFAULTS, resolveRenderOptions, DEFAULT_STRINGS, countText, fill, availableSorts};
@@ -65,6 +65,19 @@ export function toolbarPlan(f, o) {
65
65
  };
66
66
  }
67
67
 
68
+ /**
69
+ * Does the Loop toggle start on? An explicit `loop` option decides; left
70
+ * unset, it's on exactly when the list marks loops (only those repeat, so
71
+ * a one-shot still plays once).
72
+ *
73
+ * @param {boolean|null|undefined} loop - The `loop` option.
74
+ * @param {{loops: number}} f - The sounds' facets.
75
+ * @returns {boolean}
76
+ */
77
+ export function loopsByDefault(loop, f) {
78
+ return loop == null ? f.loops > 0 : !!loop;
79
+ }
80
+
68
81
  /* ── Controls ───────────────────────────────────────────────────────── */
69
82
 
70
83
  /** The search field. */
@@ -126,14 +139,41 @@ export function renderMenu(name, m) {
126
139
  );
127
140
  }
128
141
 
129
- /** The BPM range: two number fields, with the data's range as placeholders. */
130
- function renderBpmRange(s, range) {
131
- const field = (attr, label, placeholder) => h('input', {type: 'number', inputmode: 'numeric', [attr]: true, 'aria-label': label, placeholder, min: '0', step: '1'});
132
- return h('span', {class: 'ws-bpm-range', role: 'group', 'aria-label': s.bpm},
133
- field('data-ws-bpm-min', s.bpmMin, range.min),
134
- h('span', {'aria-hidden': 'true'}, '–'),
135
- field('data-ws-bpm-max', s.bpmMax, range.max),
136
- h('span', {class: 'ws-bpm-unit', 'aria-hidden': 'true'}, text(s.bpm)),
142
+ /**
143
+ * The BPM menu: a button ("Any BPM" / "120–128 BPM") opening a panel with a
144
+ * two-handle range across the pack's own tempos. Each handle is a native
145
+ * range input (keyboard, screen readers and touch for free); the two share
146
+ * one track. The runtime (`menus.js` + the core) wires it.
147
+ *
148
+ * @param {Object} m
149
+ * @param {string} m.id - Id prefix for this list.
150
+ * @param {typeof DEFAULT_STRINGS} m.s
151
+ * @param {{min: number, max: number}} m.range - The pack's BPM range.
152
+ * @returns {string}
153
+ */
154
+ function renderBpmMenu({id, s, range}) {
155
+ const popId = `${id}-bpm-pop`;
156
+ const handle = (attr, label, value) => h('input', {
157
+ type: 'range', class: 'ws-range-input', [attr]: true, 'aria-label': label,
158
+ min: range.min, max: range.max, step: '1', value,
159
+ });
160
+ return h('div', {class: 'ws-menu ws-menu--bpm', 'data-ws-menu': 'bpm'},
161
+ h('button', {type: 'button', class: 'ws-menu-btn', 'data-ws-menu-btn': true, 'aria-haspopup': 'dialog', 'aria-expanded': 'false', 'aria-controls': popId},
162
+ h('span', {class: 'ws-sr'}, text(`${s.bpm}: `)),
163
+ h('span', {class: 'ws-menu-value', 'data-ws-menu-value': true}, text(bpmLabel({}, range, s))),
164
+ ICONS.chevron,
165
+ ),
166
+ h('div', {class: 'ws-menu-pop ws-bpm-pop', id: popId, role: 'dialog', 'aria-label': s.bpm, 'data-ws-menu-pop': true, hidden: true},
167
+ h('div', {class: 'ws-bpm-head'},
168
+ h('span', {class: 'ws-bpm-readout', 'data-ws-bpm-readout': true, 'aria-live': 'polite'}, text(fill(s.bpmRange, range))),
169
+ h('button', {type: 'button', class: 'ws-bpm-clear', 'data-ws-bpm-clear': true}, text(s.anyBpm)),
170
+ ),
171
+ h('div', {class: 'ws-range', 'data-ws-bpm-range': true},
172
+ handle('data-ws-bpm-min', s.bpmMin, range.min),
173
+ handle('data-ws-bpm-max', s.bpmMax, range.max),
174
+ ),
175
+ h('div', {class: 'ws-range-ends', 'aria-hidden': 'true'}, h('span', {}, text(range.min)), h('span', {}, text(range.max))),
176
+ ),
137
177
  );
138
178
  }
139
179
 
@@ -147,9 +187,9 @@ function renderLoopFilter(s) {
147
187
  button('', s.all), button('loop', s.loops), button('one-shot', s.oneShots));
148
188
  }
149
189
 
150
- /** The Loop toggle. */
151
- function renderLoopToggle(s) {
152
- return h('button', {type: 'button', class: 'ws-loop', 'data-ws-loop': true, 'aria-pressed': 'false'}, ICONS.loop, h('span', {}, text(s.loop)));
190
+ /** The Loop toggle, pressed or not. */
191
+ function renderLoopToggle(s, pressed) {
192
+ return h('button', {type: 'button', class: 'ws-loop', 'data-ws-loop': true, 'aria-pressed': String(pressed)}, ICONS.loop, h('span', {}, text(s.loop)));
153
193
  }
154
194
 
155
195
  /** One type chip ('' = all). */
@@ -177,13 +217,13 @@ function renderToolbar(plan, {o, s, f, total, id}) {
177
217
  label: s.key, value: '', placeholder: s.findKey,
178
218
  options: [{value: '', label: s.anyKey}, ...f.keys.map((k) => ({value: k, label: k}))],
179
219
  }),
180
- plan.bpm && renderBpmRange(s, f.bpm),
220
+ plan.bpm && renderBpmMenu({id, s, range: f.bpm}),
181
221
  plan.loops && renderLoopFilter(s),
182
222
  plan.sorts.length > 0 && menu('sort', {
183
223
  label: s.sort, prefix: s.sortBy, value: plan.sorts[0],
184
224
  options: plan.sorts.map((k) => ({value: k, label: s[SORT_LABEL_KEYS[k]]})),
185
225
  }),
186
- plan.loop && renderLoopToggle(s),
226
+ plan.loop && renderLoopToggle(s, loopsByDefault(o.loop, f)),
187
227
  ].filter(Boolean);
188
228
 
189
229
  const chips = plan.types === 'chips' && h('div', {class: 'ws-types', role: 'group', 'aria-label': s.types},
@@ -6,6 +6,8 @@
6
6
  * @module strings
7
7
  */
8
8
 
9
+ import {bpmRangeFromFilter, hasBpmFilter} from '../data/bpm.js';
10
+
9
11
  /** The English defaults. */
10
12
  export const DEFAULT_STRINGS = {
11
13
  search: 'Search sounds',
@@ -21,6 +23,8 @@ export const DEFAULT_STRINGS = {
21
23
  bpm: 'BPM',
22
24
  bpmMin: 'Min BPM',
23
25
  bpmMax: 'Max BPM',
26
+ anyBpm: 'Any BPM',
27
+ bpmRange: '{min}–{max} BPM',
24
28
  sort: 'Sort',
25
29
  sortBy: 'Sort by',
26
30
  sortDefault: 'Default',
@@ -66,6 +70,21 @@ export function fill(template, vars = {}) {
66
70
  return String(template).replace(/\{(\w+)\}/g, (match, name) => (name in vars ? String(vars[name]) : match));
67
71
  }
68
72
 
73
+ /**
74
+ * The BPM menu's label: "Any BPM", or the range the handles hold
75
+ * ("120–128 BPM"; an open end shows the pack's own end).
76
+ *
77
+ * @param {{bpmMin?: string|number, bpmMax?: string|number}} filter
78
+ * @param {{min: number, max: number}} extent - The pack's BPM range.
79
+ * @param {typeof DEFAULT_STRINGS} [strings]
80
+ * @returns {string}
81
+ */
82
+ export function bpmLabel(filter, extent, strings = DEFAULT_STRINGS) {
83
+ if (!hasBpmFilter(filter)) return strings.anyBpm;
84
+ const {lo, hi} = bpmRangeFromFilter(filter, extent);
85
+ return fill(strings.bpmRange, {min: lo, max: hi});
86
+ }
87
+
69
88
  /**
70
89
  * The count line: "300 sounds", "1 sound", "12 of 300 sounds".
71
90
  *