@arraypress/waveform-sounds 0.3.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +19 -1
  3. package/dist/waveform-sounds-no-autoinit.esm.js +145 -98
  4. package/dist/waveform-sounds-render.esm.js +25 -11
  5. package/dist/waveform-sounds.css +66 -78
  6. package/dist/waveform-sounds.esm.js +146 -99
  7. package/dist/waveform-sounds.js +147 -99
  8. package/dist/waveform-sounds.min.css +1 -1
  9. package/dist/waveform-sounds.min.js +1 -1
  10. package/package.json +36 -33
  11. package/src/css/waveform-sounds.css +66 -78
  12. package/src/js/core/{WaveformSounds.js → WaveformSounds.ts} +328 -189
  13. package/src/js/core/engine.ts +101 -0
  14. package/src/js/core/{options.js → options.ts} +33 -28
  15. package/src/js/data/{bpm.js → bpm.ts} +17 -17
  16. package/src/js/data/{navigation.js → navigation.ts} +17 -17
  17. package/src/js/data/{sounds.js → sounds.ts} +67 -63
  18. package/src/js/data/{url-state.js → url-state.ts} +27 -26
  19. package/src/js/dom/{colors.js → colors.ts} +12 -12
  20. package/src/js/dom/{draw.js → draw.ts} +17 -17
  21. package/src/js/dom/{menus.js → menus.ts} +72 -55
  22. package/src/js/dom/{rows.js → rows.ts} +18 -17
  23. package/src/js/{entry.js → entry.ts} +25 -0
  24. package/src/js/render/{html.js → html.ts} +18 -12
  25. package/src/js/render/{icons.js → icons.ts} +4 -4
  26. package/src/js/render/{markup.js → markup.ts} +82 -60
  27. package/src/js/render/{options.js → options.ts} +26 -20
  28. package/src/js/render/{strings.js → strings.ts} +17 -16
  29. package/src/js/{render-entry.js → render-entry.ts} +1 -0
  30. package/src/js/shared/{utils.js → utils.ts} +22 -22
  31. package/{index.d.ts → src/js/types.ts} +12 -87
  32. package/types/core/WaveformSounds.d.ts +145 -0
  33. package/types/core/WaveformSounds.d.ts.map +1 -0
  34. package/types/core/engine.d.ts +67 -0
  35. package/types/core/engine.d.ts.map +1 -0
  36. package/types/core/options.d.ts +76 -0
  37. package/types/core/options.d.ts.map +1 -0
  38. package/types/data/bpm.d.ts +67 -0
  39. package/types/data/bpm.d.ts.map +1 -0
  40. package/types/data/navigation.d.ts +53 -0
  41. package/types/data/navigation.d.ts.map +1 -0
  42. package/types/data/sounds.d.ts +167 -0
  43. package/types/data/sounds.d.ts.map +1 -0
  44. package/types/data/url-state.d.ts +83 -0
  45. package/types/data/url-state.d.ts.map +1 -0
  46. package/types/dom/colors.d.ts +35 -0
  47. package/types/dom/colors.d.ts.map +1 -0
  48. package/types/dom/draw.d.ts +73 -0
  49. package/types/dom/draw.d.ts.map +1 -0
  50. package/types/dom/menus.d.ts +77 -0
  51. package/types/dom/menus.d.ts.map +1 -0
  52. package/types/dom/rows.d.ts +42 -0
  53. package/types/dom/rows.d.ts.map +1 -0
  54. package/types/entry.d.ts +22 -0
  55. package/types/entry.d.ts.map +1 -0
  56. package/types/index.d.ts +16 -0
  57. package/types/index.d.ts.map +1 -0
  58. package/types/render/html.d.ts +39 -0
  59. package/types/render/html.d.ts.map +1 -0
  60. package/types/render/icons.d.ts +17 -0
  61. package/types/render/icons.d.ts.map +1 -0
  62. package/types/render/markup.d.ts +132 -0
  63. package/types/render/markup.d.ts.map +1 -0
  64. package/types/render/options.d.ts +56 -0
  65. package/types/render/options.d.ts.map +1 -0
  66. package/types/render/strings.d.ts +46 -0
  67. package/types/render/strings.d.ts.map +1 -0
  68. package/types/render-entry.d.ts +8 -0
  69. package/types/render-entry.d.ts.map +1 -0
  70. package/types/shared/utils.d.ts +57 -0
  71. package/types/shared/utils.d.ts.map +1 -0
  72. package/types/types.d.ts +254 -0
  73. package/types/types.d.ts.map +1 -0
  74. package/types/vendor/arraypress-text.d.ts +250 -0
  75. package/dist/waveform-sounds-no-autoinit.cjs +0 -2136
  76. package/dist/waveform-sounds-render.cjs +0 -614
  77. package/dist/waveform-sounds.cjs +0 -2158
  78. package/no-autoinit.d.ts +0 -2
  79. package/render.d.ts +0 -5
  80. package/src/js/core/engine.js +0 -57
  81. /package/src/js/{index.js → index.ts} +0 -0
@@ -0,0 +1,101 @@
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; `WaveformSounds.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
+ * Player options that describe ONE track. The engine plays every sound in
14
+ * the list, so a site value would be wrong for all but one of them; the
15
+ * list passes each sound's own to `loadTrack()` instead (and the core resets
16
+ * them on every `loadTrack()` that doesn't).
17
+ */
18
+ const PER_TRACK = ['duration', 'downloadUrl', 'downloadName'];
19
+
20
+ /**
21
+ * The engine player's options. The site's `playerOptions` override the
22
+ * defaults, except what the list depends on:
23
+ * - `audioMode` is always `'self'` (the list owns its audio);
24
+ * - `loop` and `showLoop` are always off: the list owns looping (its Loop
25
+ * toggle, which repeats only the sounds marked as loops). The player's
26
+ * own loop would stop `ended`, so `autoAdvance` and the row state would
27
+ * stall, and its toggle would loop one-shots behind the list's back;
28
+ * - the per-track options (`duration`, `downloadUrl`, `downloadName`) are
29
+ * dropped: each sound's come with it (see {@link engineTrack});
30
+ * - the six callbacks always reach the list — a site's own callback of
31
+ * the same name runs as well, after it, with the same arguments.
32
+ *
33
+ * @param user - The site's `playerOptions`.
34
+ * @param layout - Strip shows the engine, so it's taller.
35
+ * @param handlers - The list's callbacks, keyed by
36
+ * option name (`onPlay`, …).
37
+ * @returns Options for `new WaveformPlayer(el, options)`.
38
+ */
39
+ export function engineOptions(user: Record<string, any> | null | undefined, layout: 'inline' | 'strip', handlers: Record<string, (...args: any[]) => void>): Record<string, any> {
40
+ const site = user || {};
41
+ const strip = layout === 'strip';
42
+ const options: Record<string, any> = {
43
+ height: strip ? 48 : 32,
44
+ waveformStyle: strip ? 'mirror' : 'bars',
45
+ preload: 'metadata',
46
+ singlePlay: true,
47
+ ...site,
48
+ audioMode: 'self',
49
+ loop: false,
50
+ showLoop: false,
51
+ };
52
+ for (const name of PER_TRACK) delete options[name];
53
+ for (const name of CALLBACKS) {
54
+ options[name] = (...args: any[]) => {
55
+ handlers[name]?.(...args);
56
+ if (typeof site[name] === 'function') site[name](...args);
57
+ };
58
+ }
59
+ return options;
60
+ }
61
+
62
+ /**
63
+ * The waveform data to hand the engine for a sound: in the strip a
64
+ * full-resolution sidecar when there is one, otherwise the row's peaks.
65
+ * Supplied peaks also stop a hidden engine from downloading and decoding
66
+ * the whole file just to draw it.
67
+ *
68
+ * @param sound
69
+ * @param layout
70
+ * @returns
71
+ */
72
+ export function enginePeaks(sound: {peaks: number[]|null, waveform: string|null}, layout: 'inline' | 'strip'): number[] | string | null {
73
+ return (layout === 'strip' && sound.waveform) || sound.peaks || null;
74
+ }
75
+
76
+ /** What `loadTrack()` is given for one sound (see {@link engineTrack}). */
77
+ export interface EngineTrack {
78
+ waveform: number[] | string | null;
79
+ autoplay: boolean;
80
+ duration?: number;
81
+ downloadUrl?: string;
82
+ }
83
+
84
+ /**
85
+ * The `loadTrack()` options for a sound: its peaks (see {@link enginePeaks}),
86
+ * its known length — so the player shows the right total, places a seek and
87
+ * fills the Media Session scrubber before the audio's metadata arrives,
88
+ * which with `preload: 'none'` is only once it plays — and its download
89
+ * link, so a `showDownload` engine offers what the row offers.
90
+ *
91
+ * @param sound
92
+ * @param layout
93
+ * @param autoplay - Start once loaded (false: cue only).
94
+ * @returns
95
+ */
96
+ export function engineTrack(sound: {peaks: number[]|null, waveform: string|null, duration: number|null, download: string|null}, layout: 'inline' | 'strip', autoplay: boolean): EngineTrack {
97
+ const track: EngineTrack = {waveform: enginePeaks(sound, layout), autoplay};
98
+ if (sound.duration != null && sound.duration > 0) track.duration = sound.duration;
99
+ if (sound.download) track.downloadUrl = sound.download;
100
+ return track;
101
+ }
@@ -2,8 +2,10 @@
2
2
  * The runtime's option surface: every option with its default, the
3
3
  * `data-*` form a container (or a server-rendering wrapper) uses, and the
4
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`.
5
+ * with the renderer (`render/options.ts`) and included here. `types.ts`
6
+ * documents each option; the wrappers' drift guards compare their
7
+ * forwarding against `WaveformSoundsOptions` (in the generated
8
+ * `types/types.d.ts`).
7
9
  *
8
10
  * Precedence, as across the waveform family: data-* > constructor > default.
9
11
  *
@@ -12,11 +14,12 @@
12
14
 
13
15
  import {RENDER_DEFAULTS} from '../render/options.js';
14
16
  import {LOG} from '../shared/utils.js';
17
+ import type {WaveformSoundsOptions} from '../types.js';
15
18
 
16
19
  export {RENDER_DEFAULTS};
17
20
 
18
21
  /** Every option, with its default. */
19
- export const DEFAULT_OPTIONS = {
22
+ export const DEFAULT_OPTIONS: WaveformSoundsOptions = {
20
23
  ...RENDER_DEFAULTS,
21
24
  sounds: null,
22
25
  manifest: null,
@@ -28,7 +31,9 @@ export const DEFAULT_OPTIONS = {
28
31
  loop: null,
29
32
  autoAdvance: false,
30
33
  arrowAudition: true,
31
- idPrefix: null,
34
+ // null is "unset" (the container's id, else a hash); the public type,
35
+ // unchanged from 0.3.1, has no null, hence the cast (it emits nothing).
36
+ idPrefix: null as unknown as string,
32
37
  urlState: false,
33
38
  playerOptions: null,
34
39
  playerClass: null,
@@ -44,10 +49,10 @@ export const DEFAULT_OPTIONS = {
44
49
  /**
45
50
  * A boolean attribute: present-and-empty or "true" → true, "false" → false.
46
51
  *
47
- * @param {string|undefined} value
48
- * @returns {boolean|undefined} undefined for anything else (not set).
52
+ * @param value
53
+ * @returns undefined for anything else (not set).
49
54
  */
50
- export function parseBool(value) {
55
+ export function parseBool(value: string | undefined): boolean | undefined {
51
56
  if (value === '' || value === 'true') return true;
52
57
  if (value === 'false') return false;
53
58
  return undefined;
@@ -57,10 +62,10 @@ export function parseBool(value) {
57
62
  * A comma list attribute ("type, key" → ['type', 'key']). An empty string
58
63
  * is an empty list (e.g. `data-sorts=""` = no sort menu).
59
64
  *
60
- * @param {string|undefined} value
61
- * @returns {string[]|undefined}
65
+ * @param value
66
+ * @returns
62
67
  */
63
- export function parseList(value) {
68
+ export function parseList(value: string | undefined): string[] | undefined {
64
69
  if (value == null) return undefined;
65
70
  return value.split(',').map((x) => x.trim()).filter(Boolean);
66
71
  }
@@ -68,10 +73,10 @@ export function parseList(value) {
68
73
  /**
69
74
  * A number attribute; an empty string is "not set".
70
75
  *
71
- * @param {string|undefined} value
72
- * @returns {number|undefined}
76
+ * @param value
77
+ * @returns
73
78
  */
74
- export function parseNumber(value) {
79
+ export function parseNumber(value: string | undefined): number | undefined {
75
80
  return value === undefined || value === '' ? undefined : Number(value);
76
81
  }
77
82
 
@@ -79,10 +84,10 @@ export function parseNumber(value) {
79
84
  * `data-url-state`: "true"/empty → true, "false" → false, anything else is
80
85
  * the parameter prefix.
81
86
  *
82
- * @param {string|undefined} value
83
- * @returns {boolean|string|undefined}
87
+ * @param value
88
+ * @returns
84
89
  */
85
- export function parseUrlState(value) {
90
+ export function parseUrlState(value: string | undefined): boolean | string | undefined {
86
91
  if (value === undefined) return undefined;
87
92
  const b = parseBool(value);
88
93
  return b === undefined ? value : b;
@@ -93,11 +98,11 @@ export function parseUrlState(value) {
93
98
  * reported and ignored, never thrown: a typo in markup must not take the
94
99
  * whole list down.
95
100
  *
96
- * @param {string|undefined} value
97
- * @param {string} name - The attribute name, for the warning.
98
- * @returns {Object|undefined}
101
+ * @param value
102
+ * @param name - The attribute name, for the warning.
103
+ * @returns
99
104
  */
100
- export function parseJson(value, name) {
105
+ export function parseJson(value: string | undefined, name: string): Record<string, any> | undefined {
101
106
  if (!value) return undefined;
102
107
  try {
103
108
  return JSON.parse(value);
@@ -112,12 +117,12 @@ export function parseJson(value, name) {
112
117
  * `data-page-size` → `pageSize`). Attributes that are absent (or unusable)
113
118
  * are left out, so they never override a constructor option.
114
119
  *
115
- * @param {HTMLElement} el
116
- * @returns {Object} The options found.
120
+ * @param el
121
+ * @returns The options found.
117
122
  */
118
- export function readDataOptions(el) {
123
+ export function readDataOptions(el: HTMLElement): Record<string, any> {
119
124
  const d = el.dataset || {};
120
- const out = {
125
+ const out: Record<string, any> = {
121
126
  player: d.player || undefined,
122
127
  manifest: d.manifest || undefined,
123
128
  search: parseBool(d.search),
@@ -150,11 +155,11 @@ export function readDataOptions(el) {
150
155
  * Merge option sources: later ones win, and null/undefined never
151
156
  * overwrite (an unset prop must not erase a default).
152
157
  *
153
- * @param {...(Object|null|undefined)} sources
154
- * @returns {Object}
158
+ * @param sources
159
+ * @returns
155
160
  */
156
- export function mergeOptions(...sources) {
157
- const out = {};
161
+ export function mergeOptions(...sources: (Record<string, any> | null | undefined)[]): Record<string, any> {
162
+ const out: Record<string, any> = {};
158
163
  for (const src of sources) {
159
164
  if (!src) continue;
160
165
  for (const k in src) if (src[k] !== null && src[k] !== undefined) out[k] = src[k];
@@ -13,12 +13,12 @@
13
13
  /**
14
14
  * The filter for a pair of handle positions.
15
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.
16
+ * @param lo - The lower handle.
17
+ * @param hi - The upper handle.
18
+ * @param extent - The pack's BPM range (`facets().bpm`).
19
+ * @returns `''` for an open end.
20
20
  */
21
- export function bpmFilterFromRange(lo, hi, extent) {
21
+ export function bpmFilterFromRange(lo: number, hi: number, extent: {min: number, max: number}): {bpmMin: string, bpmMax: string} {
22
22
  const a = Math.min(lo, hi), b = Math.max(lo, hi);
23
23
  return {
24
24
  bpmMin: a > extent.min ? String(a) : '',
@@ -31,12 +31,12 @@ export function bpmFilterFromRange(lo, hi, extent) {
31
31
  * set one at its value (clamped into the pack's range, so a link with
32
32
  * `?bpm=60-300` still shows sensible handles).
33
33
  *
34
- * @param {{bpmMin?: string|number, bpmMax?: string|number}} filter
35
- * @param {{min: number, max: number}} extent
36
- * @returns {{lo: number, hi: number}}
34
+ * @param filter
35
+ * @param extent
36
+ * @returns
37
37
  */
38
- export function bpmRangeFromFilter(filter, extent) {
39
- const read = (v, fallback) => {
38
+ export function bpmRangeFromFilter(filter: {bpmMin?: string|number, bpmMax?: string|number}, extent: {min: number, max: number}): {lo: number, hi: number} {
39
+ const read = (v: string | number | undefined, fallback: number): number => {
40
40
  const n = Number(v);
41
41
  return v === '' || v == null || !Number.isFinite(n) ? fallback : Math.min(Math.max(n, extent.min), extent.max);
42
42
  };
@@ -48,11 +48,11 @@ export function bpmRangeFromFilter(filter, extent) {
48
48
  /**
49
49
  * A handle's position along the track, 0..1.
50
50
  *
51
- * @param {number} value
52
- * @param {{min: number, max: number}} extent
53
- * @returns {number}
51
+ * @param value
52
+ * @param extent
53
+ * @returns
54
54
  */
55
- export function bpmFraction(value, extent) {
55
+ export function bpmFraction(value: number, extent: {min: number, max: number}): number {
56
56
  const span = extent.max - extent.min;
57
57
  return span > 0 ? Math.min(Math.max((value - extent.min) / span, 0), 1) : 0;
58
58
  }
@@ -60,9 +60,9 @@ export function bpmFraction(value, extent) {
60
60
  /**
61
61
  * Is a BPM limit set on either side?
62
62
  *
63
- * @param {{bpmMin?: string|number, bpmMax?: string|number}} filter
64
- * @returns {boolean}
63
+ * @param filter
64
+ * @returns
65
65
  */
66
- export function hasBpmFilter(filter) {
66
+ export function hasBpmFilter(filter: {bpmMin?: string|number, bpmMax?: string|number}): boolean {
67
67
  return (filter.bpmMin != null && filter.bpmMin !== '') || (filter.bpmMax != null && filter.bpmMax !== '');
68
68
  }
@@ -15,14 +15,14 @@ export const SEEK_STEP = 0.1;
15
15
  * Where a navigation key moves from position `at` in a list of `count`
16
16
  * visible rows.
17
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
18
+ * @param key - `KeyboardEvent.key`.
19
+ * @param at - The focused row's position among the visible rows.
20
+ * @param count - How many rows are visible.
21
+ * @returns The new position; `'search'` for ↑ on
22
22
  * the first row (back to the search field); null when the key isn't a
23
23
  * move or there is nowhere to go.
24
24
  */
25
- export function rowTarget(key, at, count) {
25
+ export function rowTarget(key: string, at: number, count: number): number | 'search' | null {
26
26
  if (!count) return null;
27
27
  switch (key) {
28
28
  case 'ArrowDown': return at + 1 < count ? at + 1 : null;
@@ -37,11 +37,11 @@ export function rowTarget(key, at, count) {
37
37
  * The position an ←/→ press seeks to. Stops just short of the end, so a
38
38
  * held → can't end the sound by accident.
39
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.
40
+ * @param progress - Current position, 0..1.
41
+ * @param key - `'ArrowRight'` or `'ArrowLeft'`.
42
+ * @returns The new position, or null for any other key.
43
43
  */
44
- export function seekTarget(progress, key) {
44
+ export function seekTarget(progress: number, key: string): number | null {
45
45
  if (key !== 'ArrowRight' && key !== 'ArrowLeft') return null;
46
46
  return clamp(progress + (key === 'ArrowRight' ? SEEK_STEP : -SEEK_STEP), 0, 0.999);
47
47
  }
@@ -51,11 +51,11 @@ export function seekTarget(progress, key) {
51
51
  * "Show more" would reveal.
52
52
  *
53
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}}
54
+ * @param shown - The sounds that match, in display order.
55
+ * @param limit - How many to show (Infinity for all).
56
+ * @returns
57
57
  */
58
- export function pageWindow(shown, limit) {
58
+ export function pageWindow<T>(shown: T[], limit: number): {visible: Set<T>, remaining: number} {
59
59
  const visible = new Set(shown.slice(0, limit));
60
60
  return {visible, remaining: shown.length - visible.size};
61
61
  }
@@ -64,10 +64,10 @@ export function pageWindow(shown, limit) {
64
64
  * The page limit that reveals position `pos` (used when playing past the
65
65
  * end of the current page, e.g. by `next()` or auto-advance).
66
66
  *
67
- * @param {number} limit - The current limit.
68
- * @param {number} pos - The position that must be visible.
69
- * @returns {number}
67
+ * @param limit - The current limit.
68
+ * @param pos - The position that must be visible.
69
+ * @returns
70
70
  */
71
- export function limitToReveal(limit, pos) {
71
+ export function limitToReveal(limit: number, pos: number): number {
72
72
  return pos >= limit ? pos + 1 : limit;
73
73
  }
@@ -1,4 +1,5 @@
1
1
  import {fold, matchesAll, words} from '@arraypress/text';
2
+ import type {Sound, SoundInput, SoundsFilter, SoundsManifest, SoundsSort} from '../types.js';
2
3
 
3
4
  /**
4
5
  * Pure data helpers: no DOM, no window. Shared by the browser runtime and
@@ -15,10 +16,10 @@ import {fold, matchesAll, words} from '@arraypress/text';
15
16
  * sound: 300 sounds is ~30 KB in a manifest or in row attributes, against
16
17
  * ~3x that as a JSON number array.
17
18
  *
18
- * @param {number[]} peaks - Values 0..1.
19
- * @returns {string} Hex string.
19
+ * @param peaks - Values 0..1.
20
+ * @returns Hex string.
20
21
  */
21
- export function encodePeaks(peaks) {
22
+ export function encodePeaks(peaks: number[]): string {
22
23
  if (!Array.isArray(peaks)) return '';
23
24
  let out = '';
24
25
  for (const p of peaks) {
@@ -35,11 +36,11 @@ export function encodePeaks(peaks) {
35
36
  * numbers, or an array of integers on a larger scale (e.g. 0..100 or
36
37
  * 0..255) together with that `scale`.
37
38
  *
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.
39
+ * @param value
40
+ * @param scale - The maximum of an integer array.
41
+ * @returns Peaks, or null when there are none.
41
42
  */
42
- export function decodePeaks(value, scale = 1) {
43
+ export function decodePeaks(value: string | number[] | null | undefined, scale: number = 1): number[] | null {
43
44
  if (value == null || value === '') return null;
44
45
  if (typeof value === 'string') {
45
46
  if (!/^[0-9a-f]+$/i.test(value) || value.length % 2) return null;
@@ -59,10 +60,10 @@ export function decodePeaks(value, scale = 1) {
59
60
  * "C# Major", "C♯" → "C#". Anything unparseable comes back trimmed, as
60
61
  * given, so an unusual label still displays.
61
62
  *
62
- * @param {string|null|undefined} key
63
- * @returns {string} Canonical key, or '' for none.
63
+ * @param key
64
+ * @returns Canonical key, or '' for none.
64
65
  */
65
- export function normalizeKey(key) {
66
+ export function normalizeKey(key: string | null | undefined): string {
66
67
  if (key == null) return '';
67
68
  const raw = String(key).trim();
68
69
  const m = raw.match(/^([A-Ga-g])[\s_-]*([#♯b♭]?)[\s_-]*(m|min|minor|maj|major)?$/i);
@@ -74,10 +75,10 @@ export function normalizeKey(key) {
74
75
  }
75
76
 
76
77
  /** 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
+ const KEY_PITCH: Record<string, number> = {C: 0, 'C#': 1, Db: 1, D: 2, 'D#': 3, Eb: 3, E: 4, F: 5, 'F#': 6, Gb: 6, G: 7, 'G#': 8, Ab: 8, A: 9, 'A#': 10, Bb: 10, B: 11};
78
79
 
79
80
  /** Sort rank of a canonical key; unknown keys sort last. */
80
- function keyRank(key) {
81
+ function keyRank(key: string): number {
81
82
  if (!key) return Infinity;
82
83
  const minor = key.endsWith('m');
83
84
  const root = minor ? key.slice(0, -1) : key;
@@ -86,31 +87,34 @@ function keyRank(key) {
86
87
  }
87
88
 
88
89
  /**
89
- * Format seconds as m:ss, or as tenths under a second.
90
+ * Format seconds as m:ss (whole seconds, rounded down like a player's
91
+ * clock), or as tenths under a second.
90
92
  *
91
93
  * A one-shot (a kick, a hat) is often shorter than a second, and m:ss would
92
94
  * round it to "0:00", which reads as a missing length.
93
95
  *
94
- * @param {number|null|undefined} seconds
95
- * @returns {string} e.g. "0:08", "0.4s", or '' when unknown.
96
+ * @param seconds
97
+ * @returns e.g. "0:08", "0.4s", or '' when unknown.
96
98
  */
97
- export function formatDuration(seconds) {
99
+ export function formatDuration(seconds: number | null | undefined): string {
98
100
  // Number(null) is 0: an unknown length must not render as "0:00".
99
- if (seconds == null || seconds === '') return '';
101
+ if (seconds == null || (seconds as unknown) === '') return '';
100
102
  const s = Number(seconds);
101
103
  if (!Number.isFinite(s) || s < 0) return '';
102
104
  // Anything that would round to "1.0s" is shown as "0:01" instead.
103
105
  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);
106
+ // Whole seconds DOWN, as the player's own clock counts them, so a row
107
+ // and the docked player never disagree (7.6s is 0:07 in both).
108
+ const total = s < 1 ? Math.ceil(s) : Math.floor(s);
105
109
  return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`;
106
110
  }
107
111
 
108
112
  /**
109
113
  * Parse a duration given as seconds (8.02) or as "m:ss" / "h:mm:ss".
110
- * @param {number|string|null|undefined} value
111
- * @returns {number|null}
114
+ * @param value
115
+ * @returns
112
116
  */
113
- export function parseDuration(value) {
117
+ export function parseDuration(value: number | string | null | undefined): number | null {
114
118
  if (value == null || value === '') return null;
115
119
  if (typeof value === 'number') return Number.isFinite(value) && value >= 0 ? value : null;
116
120
  const str = String(value).trim();
@@ -124,10 +128,10 @@ export function parseDuration(value) {
124
128
  * The title a file name implies: extension and separators dropped,
125
129
  * leading pack prefixes kept (they are often the label's code).
126
130
  * "NW_Bass_Loop_04_128_Fmin.wav" → "NW Bass Loop 04 128 Fmin".
127
- * @param {string} url
128
- * @returns {string}
131
+ * @param url
132
+ * @returns
129
133
  */
130
- export function titleFromUrl(url) {
134
+ export function titleFromUrl(url: string): string {
131
135
  const file = String(url || '').split(/[?#]/)[0].split('/').pop() || '';
132
136
  let name = file.replace(/\.[a-z0-9]+$/i, '');
133
137
  try { name = decodeURIComponent(name); } catch { /* keep as is */ }
@@ -137,14 +141,14 @@ export function titleFromUrl(url) {
137
141
  /**
138
142
  * Normalise one sound into the shape the runtime and renderer use.
139
143
  *
140
- * @param {Object} input - A sound: `{url, title?, type?, bpm?, key?,
144
+ * @param input - A sound: `{url, title?, type?, bpm?, key?,
141
145
  * duration?, tags?, peaks?, waveform?, download?, loop?, id?}`.
142
- * @param {number} index - Its position (used for a fallback id).
143
- * @param {number} [peakScale=1] - Scale of an integer `peaks` array.
144
- * @returns {import('../../../index').Sound|null} The sound, or null if it has
146
+ * @param index - Its position (used for a fallback id).
147
+ * @param peakScale - Scale of an integer `peaks` array.
148
+ * @returns The sound, or null if it has
145
149
  * no url.
146
150
  */
147
- export function normalizeSound(input, index, peakScale = 1) {
151
+ export function normalizeSound(input: Record<string, any>, index: number, peakScale: number = 1): Sound | null {
148
152
  if (!input || typeof input !== 'object' || !input.url) return null;
149
153
  const bpm = Number(input.bpm);
150
154
  const tags = Array.isArray(input.tags)
@@ -178,10 +182,10 @@ export const LOOP_FILTERS = ['loop', 'one-shot'];
178
182
  * Is this a loop? Only an explicit yes counts: `true`, or `"true"` / `"1"`
179
183
  * as an attribute or a CSV-ish manifest writes it. Unset is a one-shot.
180
184
  *
181
- * @param {unknown} value
182
- * @returns {boolean}
185
+ * @param value
186
+ * @returns
183
187
  */
184
- export function isLoop(value) {
188
+ export function isLoop(value: unknown): boolean {
185
189
  return value === true || value === 1 || value === 'true' || value === '1';
186
190
  }
187
191
 
@@ -190,10 +194,10 @@ export function isLoop(value) {
190
194
  * (what `waveform-gen --manifest` writes) or a bare array of sounds.
191
195
  * Sounds without a url are dropped.
192
196
  *
193
- * @param {Object|Array} manifest
194
- * @returns {import('../../../index').Sound[]}
197
+ * @param manifest
198
+ * @returns
195
199
  */
196
- export function parseManifest(manifest) {
200
+ export function parseManifest(manifest: SoundsManifest | SoundInput[]): Sound[] {
197
201
  const list = Array.isArray(manifest) ? manifest : Array.isArray(manifest?.sounds) ? manifest.sounds : [];
198
202
  const scale = Array.isArray(manifest) ? 1 : Number(manifest?.peakScale) || 1;
199
203
  return normalizeSounds(list, scale);
@@ -202,13 +206,13 @@ export function parseManifest(manifest) {
202
206
  /**
203
207
  * Normalise a list of sounds, dropping invalid ones and de-duplicating ids
204
208
  * (a repeated id would make two rows answer to one play() call).
205
- * @param {Array} list
206
- * @param {number} [peakScale=1]
207
- * @returns {import('../../../index').Sound[]}
209
+ * @param list
210
+ * @param peakScale
211
+ * @returns
208
212
  */
209
- export function normalizeSounds(list, peakScale = 1) {
210
- const seen = new Set();
211
- const out = [];
213
+ export function normalizeSounds(list: SoundInput[], peakScale: number = 1): Sound[] {
214
+ const seen = new Set<string>();
215
+ const out: Sound[] = [];
212
216
  (Array.isArray(list) ? list : []).forEach((item, i) => {
213
217
  const s = normalizeSound(item, i, peakScale);
214
218
  if (!s) return;
@@ -227,12 +231,12 @@ export function normalizeSounds(list, peakScale = 1) {
227
231
  * range, and how many are loops and one-shots. A control with nothing to
228
232
  * offer is not rendered.
229
233
  *
230
- * @param {import('../../../index').Sound[]} sounds
231
- * @returns {{types: {name: string, count: number}[], keys: string[], bpm: {min: number, max: number}|null, hasDuration: boolean, loops: number, oneShots: number}}
234
+ * @param sounds
235
+ * @returns
232
236
  */
233
- export function facets(sounds) {
234
- const types = new Map();
235
- const keys = new Set();
237
+ export function facets(sounds: Sound[]): {types: {name: string, count: number}[], keys: string[], bpm: {min: number, max: number}|null, hasDuration: boolean, loops: number, oneShots: number} {
238
+ const types = new Map<string, number>();
239
+ const keys = new Set<string>();
236
240
  let min = Infinity, max = -Infinity, hasDuration = false, loops = 0;
237
241
  for (const s of sounds) {
238
242
  if (s.type) types.set(s.type, (types.get(s.type) || 0) + 1);
@@ -261,11 +265,11 @@ export function facets(sounds) {
261
265
  * number in the query also matches the BPM exactly, so "bass 128" finds
262
266
  * 128 BPM bass loops.
263
267
  *
264
- * @param {import('../../../index').Sound} sound
265
- * @param {import('../../../index').SoundsFilter} filter
266
- * @returns {boolean}
268
+ * @param sound
269
+ * @param filter
270
+ * @returns
267
271
  */
268
- export function matches(sound, filter = {}) {
272
+ export function matches(sound: Sound, filter: Partial<SoundsFilter> = {}): boolean {
269
273
  if (filter.type && sound.type !== filter.type) return false;
270
274
  if (filter.key && sound.key !== normalizeKey(filter.key)) return false;
271
275
  if (filter.loop === 'loop' && !sound.loop) return false;
@@ -290,10 +294,10 @@ export function matches(sound, filter = {}) {
290
294
  }
291
295
 
292
296
  /** The sort orders the toolbar offers. */
293
- export const SORTS = ['default', 'title', 'bpm', 'key', 'duration'];
297
+ export const SORTS: SoundsSort[] = ['default', 'title', 'bpm', 'key', 'duration'];
294
298
 
295
299
  /** What each sort order needs from the data before it's worth offering. */
296
- const SORT_NEEDS = {
300
+ const SORT_NEEDS: Record<string, (f: ReturnType<typeof facets>) => boolean> = {
297
301
  default: () => true,
298
302
  title: () => true,
299
303
  bpm: (f) => f.bpm !== null,
@@ -306,11 +310,11 @@ const SORT_NEEDS = {
306
310
  * in the configured order. Shared by the renderer and the runtime, so the
307
311
  * menu and the starting order always agree.
308
312
  *
309
- * @param {string[]} sorts - The configured orders.
310
- * @param {ReturnType<typeof facets>} f - The sounds' facets.
311
- * @returns {string[]}
313
+ * @param sorts - The configured orders.
314
+ * @param f - The sounds' facets.
315
+ * @returns
312
316
  */
313
- export function availableSorts(sorts, f) {
317
+ export function availableSorts(sorts: string[], f: ReturnType<typeof facets>): string[] {
314
318
  return sorts.filter((sort) => SORT_NEEDS[sort]?.(f));
315
319
  }
316
320
 
@@ -318,19 +322,19 @@ export function availableSorts(sorts, f) {
318
322
  * Sort sounds (returns a new array; `default` keeps the given order).
319
323
  * Missing values sort last in every order.
320
324
  *
321
- * @param {import('../../../index').Sound[]} sounds
322
- * @param {string} [by='default']
323
- * @returns {import('../../../index').Sound[]}
325
+ * @param sounds
326
+ * @param by
327
+ * @returns
324
328
  */
325
- export function sortSounds(sounds, by = 'default') {
329
+ export function sortSounds(sounds: Sound[], by: SoundsSort = 'default'): Sound[] {
326
330
  const list = sounds.map((s, i) => ({s, i}));
327
- const last = (v) => (v == null ? Infinity : v);
328
- const cmp = {
331
+ const last = (v: number | null): number => (v == null ? Infinity : v);
332
+ const cmp = ({
329
333
  title: (a, b) => a.s.title.localeCompare(b.s.title, undefined, {numeric: true, sensitivity: 'base'}),
330
334
  bpm: (a, b) => last(a.s.bpm) - last(b.s.bpm),
331
335
  key: (a, b) => keyRank(a.s.key) - keyRank(b.s.key),
332
336
  duration: (a, b) => last(a.s.duration) - last(b.s.duration),
333
- }[by];
337
+ } as Record<string, (a: {s: Sound, i: number}, b: {s: Sound, i: number}) => number>)[by];
334
338
  if (cmp) list.sort((a, b) => cmp(a, b) || a.i - b.i);
335
339
  return list.map((x) => x.s);
336
340
  }