@arraypress/waveform-sounds 0.1.3 → 0.3.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.
@@ -33,9 +33,10 @@ import {Menus} from '../dom/menus.js';
33
33
  import {limitToReveal, pageWindow, rowTarget, seekTarget} from '../data/navigation.js';
34
34
  import {DEFAULT_OPTIONS, mergeOptions, readDataOptions} from './options.js';
35
35
  import {resolveRenderOptions} from '../render/options.js';
36
- import {renderSounds} from '../render/markup.js';
36
+ import {loopsByDefault, renderSounds} from '../render/markup.js';
37
37
  import {indexRows, orderRows, readRows, visibleRows} from '../dom/rows.js';
38
- import {countText, DEFAULT_STRINGS, fill} from '../render/strings.js';
38
+ import {bpmLabel, countText, DEFAULT_STRINGS, fill} from '../render/strings.js';
39
+ import {bpmFilterFromRange, bpmFraction, bpmRangeFromFilter} from '../data/bpm.js';
39
40
  import {pageSurface, resolveCssColor} from '../dom/colors.js';
40
41
  import {readUrlState, urlKeys, writeUrlState} from '../data/url-state.js';
41
42
  import {emit, isTyping, LOG, pointerFraction} from '../shared/utils.js';
@@ -43,7 +44,7 @@ import {emit, isTyping, LOG, pointerFraction} from '../shared/utils.js';
43
44
  export {DEFAULT_OPTIONS};
44
45
 
45
46
  /** An empty filter: everything matches. */
46
- const NO_FILTER = Object.freeze({query: '', type: '', key: '', bpmMin: '', bpmMax: ''});
47
+ const NO_FILTER = Object.freeze({query: '', type: '', key: '', bpmMin: '', bpmMax: '', loop: ''});
47
48
 
48
49
  /** Debounce for typing in the search box and the BPM fields (ms). */
49
50
  const SEARCH_DELAY = 120;
@@ -131,7 +132,11 @@ export class WaveformSounds {
131
132
  this._bind();
132
133
  this._observe();
133
134
  this._resolveColors();
135
+ // Unless set (option or an early setLoop()), Loop starts on exactly
136
+ // when the list marks loops — only those repeat.
137
+ if (!this._loopSet) this.loop = loopsByDefault(this.options.loop, facets(this.sounds));
134
138
  this._setLoop(this.loop);
139
+ this._bpmExtent = facets(this.sounds).bpm;
135
140
 
136
141
  // The starting order is the first one offered, unless setSort()
137
142
  // already chose one; then the address may override both.
@@ -176,6 +181,10 @@ export class WaveformSounds {
176
181
  search: q('[data-ws-search]'),
177
182
  bpmMin: q('[data-ws-bpm-min]'),
178
183
  bpmMax: q('[data-ws-bpm-max]'),
184
+ bpmRange: q('[data-ws-bpm-range]'),
185
+ bpmReadout: q('[data-ws-bpm-readout]'),
186
+ bpmClear: q('[data-ws-bpm-clear]'),
187
+ bpmLabel: q('[data-ws-menu="bpm"] [data-ws-menu-value]'),
179
188
  loop: q('[data-ws-loop]'),
180
189
  count: q('[data-ws-count]'),
181
190
  empty: q('[data-ws-empty]'),
@@ -183,6 +192,7 @@ export class WaveformSounds {
183
192
  engine: q('[data-ws-engine]'),
184
193
  status: q('[data-ws-status]'),
185
194
  chips: [...this.container.querySelectorAll('[data-ws-type]')],
195
+ loopFilter: [...this.container.querySelectorAll('[data-ws-loop-filter]')],
186
196
  };
187
197
  this.rows = indexRows(this.$.list);
188
198
  }
@@ -210,12 +220,22 @@ export class WaveformSounds {
210
220
  if (e.key === 'ArrowDown') { e.preventDefault(); this._focusRow(visibleRows($.list)[0]); }
211
221
  if (e.key === 'Escape' && $.search.value) { e.preventDefault(); $.search.value = ''; this.setFilter({query: ''}); }
212
222
  }, sig);
213
- const onBpm = () => {
223
+ // The BPM handles: the label and the track follow the drag at once;
224
+ // the list re-filters once it settles. A handle can't pass the other.
225
+ const onBpm = (moved) => {
226
+ const lo = Number($.bpmMin.value), hi = Number($.bpmMax.value);
227
+ if (lo > hi) moved.value = String(moved === $.bpmMin ? hi : lo);
228
+ const f = bpmFilterFromRange(Number($.bpmMin.value), Number($.bpmMax.value), this._bpmExtent);
229
+ this._showBpm(f);
214
230
  clearTimeout(bpmTimer);
215
- bpmTimer = setTimeout(() => this.setFilter({bpmMin: $.bpmMin?.value ?? '', bpmMax: $.bpmMax?.value ?? ''}), BPM_DELAY);
231
+ bpmTimer = setTimeout(() => this.setFilter(f), BPM_DELAY);
216
232
  };
217
- $.bpmMin?.addEventListener('input', onBpm, sig);
218
- $.bpmMax?.addEventListener('input', onBpm, sig);
233
+ $.bpmMin?.addEventListener('input', () => onBpm($.bpmMin), sig);
234
+ $.bpmMax?.addEventListener('input', () => onBpm($.bpmMax), sig);
235
+ $.bpmClear?.addEventListener('click', () => {
236
+ clearTimeout(bpmTimer);
237
+ this.setFilter({bpmMin: '', bpmMax: ''});
238
+ }, sig);
219
239
 
220
240
  this.menus = new Menus(root, {
221
241
  signal: this._ctl.signal,
@@ -235,7 +255,7 @@ export class WaveformSounds {
235
255
  /* ── Input ────────────────────────────────────────────────────────── */
236
256
 
237
257
  /**
238
- * Clicks: type chips, Show more, Clear, Loop, a touch tap on a waveform
258
+ * Clicks: type chips, loops or one-shots, Show more, Clear, Loop, a touch tap on a waveform
239
259
  * (seek), and anywhere else on a row (play/pause).
240
260
  * @private
241
261
  */
@@ -243,6 +263,8 @@ export class WaveformSounds {
243
263
  const t = e.target;
244
264
  const chip = t.closest('[data-ws-type]');
245
265
  if (chip) { this.setFilter({type: chip.dataset.wsType}); return; }
266
+ const seg = t.closest('[data-ws-loop-filter]');
267
+ if (seg) { this.setFilter({loop: seg.dataset.wsLoopFilter}); return; }
246
268
  if (t.closest('[data-ws-more]')) { this.showMore(); return; }
247
269
  if (t.closest('[data-ws-clear]')) { this.clearFilters(); return; }
248
270
  if (t.closest('[data-ws-loop]')) { this.setLoop(!this.loop); return; }
@@ -513,9 +535,33 @@ export class WaveformSounds {
513
535
  this.menus?.setValue('type', f.type || '');
514
536
  this.menus?.setValue('key', f.key || '');
515
537
  this.menus?.setValue('sort', this.sortBy);
516
- if ($.bpmMin && $.bpmMin.value !== String(f.bpmMin)) $.bpmMin.value = f.bpmMin;
517
- if ($.bpmMax && $.bpmMax.value !== String(f.bpmMax)) $.bpmMax.value = f.bpmMax;
538
+ if ($.bpmMin && $.bpmMax && this._bpmExtent) {
539
+ const {lo, hi} = bpmRangeFromFilter(f, this._bpmExtent);
540
+ $.bpmMin.value = String(lo);
541
+ $.bpmMax.value = String(hi);
542
+ this._showBpm(f);
543
+ }
518
544
  $.chips.forEach((c) => c.setAttribute('aria-pressed', String(c.dataset.wsType === (f.type || ''))));
545
+ $.loopFilter.forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.wsLoopFilter === (f.loop || ''))));
546
+ }
547
+
548
+ /**
549
+ * Show a BPM filter in its menu: the button label, the panel's readout,
550
+ * the filled part of the track, and which handle sits on top (the one
551
+ * that can still move, when they meet).
552
+ * @private
553
+ */
554
+ _showBpm(f) {
555
+ const $ = this.$, extent = this._bpmExtent;
556
+ if (!$?.bpmRange || !extent) return;
557
+ const {lo, hi} = bpmRangeFromFilter(f, extent);
558
+ if ($.bpmLabel) $.bpmLabel.textContent = bpmLabel(f, extent, this.strings);
559
+ if ($.bpmReadout) $.bpmReadout.textContent = fill(this.strings.bpmRange, {min: lo, max: hi});
560
+ // CSSOM, not a style attribute: works under a strict CSP.
561
+ $.bpmRange.style.setProperty('--ws-lo', String(bpmFraction(lo, extent)));
562
+ $.bpmRange.style.setProperty('--ws-hi', String(bpmFraction(hi, extent)));
563
+ $.bpmRange.classList.toggle('is-min-top', lo >= hi && lo > extent.min);
564
+ $.bpmRange.classList.toggle('is-active', lo > extent.min || hi < extent.max);
519
565
  }
520
566
 
521
567
  /**
@@ -686,10 +732,13 @@ export class WaveformSounds {
686
732
  }
687
733
 
688
734
  /**
689
- * Loop the current sound (auditioning a loop is the common case).
735
+ * Loop the current sound (auditioning a loop is the common case). When
736
+ * the list marks its loops (`loop: true` on any sound), only those
737
+ * repeat: a one-shot always plays once.
690
738
  * @param {boolean} on
691
739
  */
692
740
  setLoop(on) {
741
+ this._loopSet = true;
693
742
  this.loop = !!on;
694
743
  this._setLoop(this.loop);
695
744
  }
@@ -700,7 +749,18 @@ export class WaveformSounds {
700
749
  */
701
750
  _setLoop(on) {
702
751
  this.$?.loop?.setAttribute('aria-pressed', String(on));
703
- if (this.engine?.audio) this.engine.audio.loop = on;
752
+ if (this.engine?.audio) this.engine.audio.loop = this._repeats();
753
+ }
754
+
755
+ /**
756
+ * Should the current sound repeat? The Loop toggle is on, and either
757
+ * the list doesn't say which sounds are loops or this one is.
758
+ * @private
759
+ */
760
+ _repeats() {
761
+ if (!this.loop) return false;
762
+ const marksLoops = this.sounds.some((s) => s.loop);
763
+ return !marksLoops || !!this.sounds[this.currentIndex]?.loop;
704
764
  }
705
765
 
706
766
  /**
@@ -724,7 +784,7 @@ export class WaveformSounds {
724
784
  * @private
725
785
  */
726
786
  _onEngineLoad() {
727
- if (this.engine?.audio) this.engine.audio.loop = this.loop;
787
+ if (this.engine?.audio) this.engine.audio.loop = this._repeats();
728
788
  const sound = this.sounds[this.currentIndex];
729
789
  if (sound && !sound.peaks && this.engine?.waveformData?.length) {
730
790
  sound.peaks = resample(this.engine.waveformData, 96);
@@ -25,7 +25,7 @@ export const DEFAULT_OPTIONS = {
25
25
  progressColor: null,
26
26
  barWidth: 2,
27
27
  barGap: 1,
28
- loop: false,
28
+ loop: null,
29
29
  autoAdvance: false,
30
30
  arrowAudition: true,
31
31
  idPrefix: null,
@@ -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
+ }
@@ -138,7 +138,7 @@ export function titleFromUrl(url) {
138
138
  * Normalise one sound into the shape the runtime and renderer use.
139
139
  *
140
140
  * @param {Object} input - A sound: `{url, title?, type?, bpm?, key?,
141
- * duration?, tags?, peaks?, waveform?, id?}`.
141
+ * duration?, tags?, peaks?, waveform?, download?, loop?, id?}`.
142
142
  * @param {number} index - Its position (used for a fallback id).
143
143
  * @param {number} [peakScale=1] - Scale of an integer `peaks` array.
144
144
  * @returns {import('../../../index').Sound|null} The sound, or null if it has
@@ -164,9 +164,27 @@ export function normalizeSound(input, index, peakScale = 1) {
164
164
  peaks: decodePeaks(input.peaks, peakScale),
165
165
  waveform: input.waveform ? String(input.waveform) : null,
166
166
  download: input.download ? String(input.download) : null,
167
+ loop: isLoop(input.loop),
167
168
  };
168
169
  }
169
170
 
171
+ /**
172
+ * The values of the loops-or-one-shots filter. A sound is a loop only when
173
+ * it says so (`loop: true`); everything else is a one-shot.
174
+ */
175
+ export const LOOP_FILTERS = ['loop', 'one-shot'];
176
+
177
+ /**
178
+ * Is this a loop? Only an explicit yes counts: `true`, or `"true"` / `"1"`
179
+ * as an attribute or a CSV-ish manifest writes it. Unset is a one-shot.
180
+ *
181
+ * @param {unknown} value
182
+ * @returns {boolean}
183
+ */
184
+ export function isLoop(value) {
185
+ return value === true || value === 1 || value === 'true' || value === '1';
186
+ }
187
+
170
188
  /**
171
189
  * Read a sounds manifest. Accepts `{version, peakScale?, sounds: [...]}`
172
190
  * (what `waveform-gen --manifest` writes) or a bare array of sounds.
@@ -205,32 +223,37 @@ export function normalizeSounds(list, peakScale = 1) {
205
223
 
206
224
  /**
207
225
  * What the filter controls offer, derived from the sounds: each type with
208
- * its count (in first-seen order), each key (in musical order), and the
209
- * BPM range. A control with nothing to offer is not rendered.
226
+ * its count (in first-seen order), each key (in musical order), the BPM
227
+ * range, and how many are loops and one-shots. A control with nothing to
228
+ * offer is not rendered.
210
229
  *
211
230
  * @param {import('../../../index').Sound[]} sounds
212
- * @returns {{types: {name: string, count: number}[], keys: string[], bpm: {min: number, max: number}|null, hasDuration: boolean}}
231
+ * @returns {{types: {name: string, count: number}[], keys: string[], bpm: {min: number, max: number}|null, hasDuration: boolean, loops: number, oneShots: number}}
213
232
  */
214
233
  export function facets(sounds) {
215
234
  const types = new Map();
216
235
  const keys = new Set();
217
- let min = Infinity, max = -Infinity, hasDuration = false;
236
+ let min = Infinity, max = -Infinity, hasDuration = false, loops = 0;
218
237
  for (const s of sounds) {
219
238
  if (s.type) types.set(s.type, (types.get(s.type) || 0) + 1);
220
239
  if (s.key) keys.add(s.key);
221
240
  if (s.bpm != null) { min = Math.min(min, s.bpm); max = Math.max(max, s.bpm); }
222
241
  if (s.duration != null) hasDuration = true;
242
+ if (s.loop) loops++;
223
243
  }
224
244
  return {
225
245
  types: [...types].map(([name, count]) => ({name, count})),
226
246
  keys: [...keys].sort((a, b) => keyRank(a) - keyRank(b) || a.localeCompare(b)),
227
247
  bpm: min === Infinity ? null : {min, max},
228
248
  hasDuration,
249
+ loops,
250
+ oneShots: sounds.length - loops,
229
251
  };
230
252
  }
231
253
 
232
254
  /**
233
- * Does a sound match the filter? Every set criterion must hold.
255
+ * Does a sound match the filter? Every set criterion must hold. `loop` is
256
+ * `'loop'` (loops only), `'one-shot'` (everything else) or empty (both).
234
257
  *
235
258
  * `query` matches the title, type, key and tags with
236
259
  * `@arraypress/text`'s `matchesAll`: every word, in any order, forgiving
@@ -245,6 +268,8 @@ export function facets(sounds) {
245
268
  export function matches(sound, filter = {}) {
246
269
  if (filter.type && sound.type !== filter.type) return false;
247
270
  if (filter.key && sound.key !== normalizeKey(filter.key)) return false;
271
+ if (filter.loop === 'loop' && !sound.loop) return false;
272
+ if (filter.loop === 'one-shot' && sound.loop) return false;
248
273
  const lo = Number(filter.bpmMin), hi = Number(filter.bpmMax);
249
274
  if ((filter.bpmMin != null && filter.bpmMin !== '' && Number.isFinite(lo)) ||
250
275
  (filter.bpmMax != null && filter.bpmMax !== '' && Number.isFinite(hi))) {
@@ -4,12 +4,12 @@
4
4
  * the runtime passes `location.search` / `location.href` in and calls
5
5
  * `history.replaceState` with what comes out.
6
6
  *
7
- * ?q=bass&type=Bass+loops&key=Fm&bpm=120-130&sort=bpm
7
+ * ?q=bass&type=Bass+loops&key=Fm&bpm=120-130&loop=one-shot&sort=bpm
8
8
  *
9
9
  * @module url-state
10
10
  */
11
11
 
12
- import {normalizeKey} from './sounds.js';
12
+ import {LOOP_FILTERS, normalizeKey} from './sounds.js';
13
13
 
14
14
  /**
15
15
  * The parameter names, or null when urlState is off. A string urlState
@@ -17,12 +17,12 @@ import {normalizeKey} from './sounds.js';
17
17
  * page don't share a filter.
18
18
  *
19
19
  * @param {boolean|string|null|undefined} urlState
20
- * @returns {{q: string, type: string, key: string, bpm: string, sort: string}|null}
20
+ * @returns {{q: string, type: string, key: string, bpm: string, loop: string, sort: string}|null}
21
21
  */
22
22
  export function urlKeys(urlState) {
23
23
  if (!urlState) return null;
24
24
  const p = typeof urlState === 'string' ? `${urlState}-` : '';
25
- return {q: `${p}q`, type: `${p}type`, key: `${p}key`, bpm: `${p}bpm`, sort: `${p}sort`};
25
+ return {q: `${p}q`, type: `${p}type`, key: `${p}key`, bpm: `${p}bpm`, loop: `${p}loop`, sort: `${p}sort`};
26
26
  }
27
27
 
28
28
  /**
@@ -50,13 +50,14 @@ export function formatBpmRange(min, max) {
50
50
 
51
51
  /**
52
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)
53
+ * (a type it doesn't have, a key no sound is in, a loops filter on a list
54
+ * that isn't a mix of loops and one-shots, a sort it doesn't offer)
54
55
  * are ignored, never applied: a stale link shows the whole list, not an
55
56
  * empty one.
56
57
  *
57
58
  * @param {string} search - `location.search`.
58
59
  * @param {ReturnType<typeof urlKeys>} keys
59
- * @param {{types: {name: string}[], keys: string[]}} available - From `facets()`.
60
+ * @param {{types: {name: string}[], keys: string[], loops?: number, oneShots?: number}} available - From `facets()`.
60
61
  * @param {string[]} sorts - The sort orders offered.
61
62
  * @returns {{filter: Object, sort: string|null}} A filter patch, and the sort (or null).
62
63
  */
@@ -72,6 +73,8 @@ export function readUrlState(search, keys, available, sorts) {
72
73
  if (key && available.keys.includes(key)) out.filter.key = key;
73
74
  const bpm = parseBpmRange(sp.get(keys.bpm));
74
75
  if (bpm) Object.assign(out.filter, bpm);
76
+ const loop = sp.get(keys.loop);
77
+ if (LOOP_FILTERS.includes(loop) && available.loops > 0 && available.oneShots > 0) out.filter.loop = loop;
75
78
  const sort = sp.get(keys.sort);
76
79
  if (sort && sorts.includes(sort)) out.sort = sort;
77
80
  return out;
@@ -84,7 +87,7 @@ export function readUrlState(search, keys, available, sorts) {
84
87
  *
85
88
  * @param {string} href - `location.href`.
86
89
  * @param {ReturnType<typeof urlKeys>} keys
87
- * @param {{query: string, type: string, key: string, bpmMin: string, bpmMax: string}} filter
90
+ * @param {{query: string, type: string, key: string, bpmMin: string, bpmMax: string, loop?: string}} filter
88
91
  * @param {string} sort
89
92
  * @param {string} defaultSort - The starting order (not written).
90
93
  * @returns {string} The new href (equal to `href` when nothing changed).
@@ -97,6 +100,7 @@ export function writeUrlState(href, keys, filter, sort, defaultSort) {
97
100
  set(keys.type, filter.type);
98
101
  set(keys.key, filter.key);
99
102
  set(keys.bpm, formatBpmRange(filter.bpmMin, filter.bpmMax));
103
+ set(keys.loop, filter.loop);
100
104
  set(keys.sort, sort !== defaultSort ? sort : '');
101
105
  return url.href;
102
106
  }
@@ -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 ?? '');
@@ -27,7 +27,7 @@ export function readRows(list) {
27
27
  const d = row.dataset;
28
28
  const sound = normalizeSound({
29
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,
30
+ duration: d.duration, tags: d.tags, peaks: d.peaks, waveform: d.waveform, download: d.download, loop: d.loop,
31
31
  }, sounds.length);
32
32
  if (!sound) { row.remove(); continue; }
33
33
  row.dataset.wsIndex = String(sounds.length);
@@ -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};
@@ -41,13 +41,14 @@ export function idBase(sounds) {
41
41
  /**
42
42
  * Which controls the toolbar shows. Each appears only when it's enabled
43
43
  * AND the data gives it something to do: no type filter for one type, no
44
- * key menu for one key, no BPM range without a spread of BPMs, no sort
45
- * menu with one usable order. Types past `maxTypeChips` become a menu (a
44
+ * key menu for one key, no BPM range without a spread of BPMs, no loops
45
+ * filter unless the list has both loops and one-shots, no sort menu with
46
+ * one usable order. Types past `maxTypeChips` become a menu (a
46
47
  * pack has a handful; a whole library can have fifty).
47
48
  *
48
49
  * @param {ReturnType<typeof facets>} f - The sounds' facets.
49
50
  * @param {ReturnType<typeof resolveRenderOptions>} o - Resolved options.
50
- * @returns {{types: 'chips'|'menu'|null, key: boolean, bpm: boolean, sorts: string[], search: boolean, loop: boolean, count: boolean}}
51
+ * @returns {{types: 'chips'|'menu'|null, key: boolean, bpm: boolean, loops: boolean, sorts: string[], search: boolean, loop: boolean, count: boolean}}
51
52
  */
52
53
  export function toolbarPlan(f, o) {
53
54
  const typed = o.filters.includes('type') && f.types.length > 1;
@@ -56,6 +57,7 @@ export function toolbarPlan(f, o) {
56
57
  types: !typed ? null : f.types.length > o.maxTypeChips ? 'menu' : 'chips',
57
58
  key: o.filters.includes('key') && f.keys.length > 1,
58
59
  bpm: o.filters.includes('bpm') && f.bpm !== null && f.bpm.max > f.bpm.min,
60
+ loops: o.filters.includes('loop') && f.loops > 0 && f.oneShots > 0,
59
61
  sorts: sorts.length > 1 ? sorts : [],
60
62
  search: !!o.search,
61
63
  loop: !!o.loopToggle,
@@ -63,6 +65,19 @@ export function toolbarPlan(f, o) {
63
65
  };
64
66
  }
65
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
+
66
81
  /* ── Controls ───────────────────────────────────────────────────────── */
67
82
 
68
83
  /** The search field. */
@@ -124,20 +139,57 @@ export function renderMenu(name, m) {
124
139
  );
125
140
  }
126
141
 
127
- /** The BPM range: two number fields, with the data's range as placeholders. */
128
- function renderBpmRange(s, range) {
129
- const field = (attr, label, placeholder) => h('input', {type: 'number', inputmode: 'numeric', [attr]: true, 'aria-label': label, placeholder, min: '0', step: '1'});
130
- return h('span', {class: 'ws-bpm-range', role: 'group', 'aria-label': s.bpm},
131
- field('data-ws-bpm-min', s.bpmMin, range.min),
132
- h('span', {'aria-hidden': 'true'}, '–'),
133
- field('data-ws-bpm-max', s.bpmMax, range.max),
134
- 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
+ ),
135
177
  );
136
178
  }
137
179
 
138
- /** The Loop toggle. */
139
- function renderLoopToggle(s) {
140
- return h('button', {type: 'button', class: 'ws-loop', 'data-ws-loop': true, 'aria-pressed': 'false'}, ICONS.loop, h('span', {}, text(s.loop)));
180
+ /**
181
+ * Loops or one-shots: three buttons, one pressed ('' = both).
182
+ */
183
+ function renderLoopFilter(s) {
184
+ const button = (value, label) => h('button', {type: 'button', class: 'ws-seg-btn', 'data-ws-loop-filter': value, 'aria-pressed': String(value === '')},
185
+ h('span', {}, text(label)));
186
+ return h('div', {class: 'ws-seg', role: 'group', 'aria-label': s.loopFilter},
187
+ button('', s.all), button('loop', s.loops), button('one-shot', s.oneShots));
188
+ }
189
+
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)));
141
193
  }
142
194
 
143
195
  /** One type chip ('' = all). */
@@ -148,7 +200,7 @@ function renderChip(value, label, count, pressed) {
148
200
 
149
201
  /**
150
202
  * The toolbar: search, the controls row (type menu, key menu, BPM range,
151
- * sort menu, Loop) and the meta row (type chips + the count).
203
+ * loops or one-shots, sort menu, Loop) and the meta row (type chips + the count).
152
204
  *
153
205
  * @param {ReturnType<typeof toolbarPlan>} plan
154
206
  * @param {Object} ctx - `{o, s, f, total, id}` from {@link renderSounds}.
@@ -165,12 +217,13 @@ function renderToolbar(plan, {o, s, f, total, id}) {
165
217
  label: s.key, value: '', placeholder: s.findKey,
166
218
  options: [{value: '', label: s.anyKey}, ...f.keys.map((k) => ({value: k, label: k}))],
167
219
  }),
168
- plan.bpm && renderBpmRange(s, f.bpm),
220
+ plan.bpm && renderBpmMenu({id, s, range: f.bpm}),
221
+ plan.loops && renderLoopFilter(s),
169
222
  plan.sorts.length > 0 && menu('sort', {
170
223
  label: s.sort, prefix: s.sortBy, value: plan.sorts[0],
171
224
  options: plan.sorts.map((k) => ({value: k, label: s[SORT_LABEL_KEYS[k]]})),
172
225
  }),
173
- plan.loop && renderLoopToggle(s),
226
+ plan.loop && renderLoopToggle(s, loopsByDefault(o.loop, f)),
174
227
  ].filter(Boolean);
175
228
 
176
229
  const chips = plan.types === 'chips' && h('div', {class: 'ws-types', role: 'group', 'aria-label': s.types},
@@ -228,10 +281,15 @@ export function renderRow(sound, index, o, hidden = false) {
228
281
  'data-peaks': sound.peaks ? encodePeaks(sound.peaks) : null,
229
282
  'data-waveform': sound.waveform,
230
283
  'data-download': sound.download,
284
+ 'data-loop': sound.loop ? 'true' : null,
231
285
  hidden,
232
286
  },
233
287
  h('button', {type: 'button', class: 'ws-play', 'aria-pressed': 'false', 'aria-label': fill(s.play, vars)}, ICONS.play, ICONS.pause),
234
- h('span', {class: 'ws-cell ws-title'}, text(sound.title)),
288
+ h('span', {class: 'ws-cell ws-title'},
289
+ h('span', {class: 'ws-title-text'}, text(sound.title)),
290
+ // A loop says so beside its name; a one-shot carries nothing.
291
+ sound.loop && h('span', {class: 'ws-loop-mark', title: s.isLoop}, ICONS.loop, h('span', {class: 'ws-sr'}, text(s.isLoop))),
292
+ ),
235
293
  // Wide rows: `display: contents` makes each cell a column. Narrow
236
294
  // rows: one line under the title.
237
295
  cells.length > 0 && h('span', {class: 'ws-cells'}, cells),
@@ -10,7 +10,7 @@ import {SORTS} from '../data/sounds.js';
10
10
  import {DEFAULT_STRINGS} from './strings.js';
11
11
 
12
12
  /** The filter controls a list can offer. */
13
- export const FILTERS = ['type', 'key', 'bpm'];
13
+ export const FILTERS = ['type', 'key', 'bpm', 'loop'];
14
14
 
15
15
  /** The columns a row can show after its title. */
16
16
  export const COLUMNS = ['type', 'bpm', 'key', 'duration'];