@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.
- package/LICENSE +21 -0
- package/README.md +123 -2
- package/dist/waveform-sounds-no-autoinit.cjs +1935 -0
- package/dist/waveform-sounds-no-autoinit.esm.js +1913 -0
- package/dist/waveform-sounds-render.cjs +525 -0
- package/dist/waveform-sounds-render.esm.js +503 -0
- package/dist/waveform-sounds.cjs +1957 -0
- package/dist/waveform-sounds.css +378 -0
- package/dist/waveform-sounds.esm.js +1935 -0
- package/dist/waveform-sounds.js +1920 -0
- package/dist/waveform-sounds.min.css +1 -0
- package/dist/waveform-sounds.min.js +13 -0
- package/index.d.ts +291 -0
- package/no-autoinit.d.ts +2 -0
- package/package.json +96 -4
- package/render.d.ts +3 -0
- package/src/css/waveform-sounds.css +378 -0
- package/src/js/core/WaveformSounds.js +883 -0
- package/src/js/core/engine.js +57 -0
- package/src/js/core/options.js +163 -0
- package/src/js/data/navigation.js +73 -0
- package/src/js/data/sounds.js +306 -0
- package/src/js/data/url-state.js +102 -0
- package/src/js/dom/colors.js +59 -0
- package/src/js/dom/draw.js +93 -0
- package/src/js/dom/menus.js +232 -0
- package/src/js/dom/rows.js +74 -0
- package/src/js/entry.js +25 -0
- package/src/js/index.js +24 -0
- package/src/js/render/html.js +55 -0
- package/src/js/render/icons.js +29 -0
- package/src/js/render/markup.js +295 -0
- package/src/js/render/options.js +90 -0
- package/src/js/render/strings.js +76 -0
- package/src/js/render-entry.js +6 -0
- package/src/js/shared/utils.js +73 -0
|
@@ -0,0 +1,1957 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __export = (target, all) => {
|
|
6
|
+
for (var name in all)
|
|
7
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
8
|
+
};
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
18
|
+
|
|
19
|
+
// src/js/index.js
|
|
20
|
+
var index_exports = {};
|
|
21
|
+
__export(index_exports, {
|
|
22
|
+
DEFAULT_OPTIONS: () => DEFAULT_OPTIONS,
|
|
23
|
+
DEFAULT_STRINGS: () => DEFAULT_STRINGS,
|
|
24
|
+
WaveformSounds: () => WaveformSounds,
|
|
25
|
+
decodePeaks: () => decodePeaks,
|
|
26
|
+
default: () => index_default,
|
|
27
|
+
encodePeaks: () => encodePeaks,
|
|
28
|
+
facets: () => facets,
|
|
29
|
+
formatDuration: () => formatDuration,
|
|
30
|
+
matches: () => matches,
|
|
31
|
+
normalizeKey: () => normalizeKey,
|
|
32
|
+
normalizeSounds: () => normalizeSounds,
|
|
33
|
+
parseManifest: () => parseManifest,
|
|
34
|
+
renderSounds: () => renderSounds,
|
|
35
|
+
renderSoundsElement: () => renderSoundsElement,
|
|
36
|
+
sortSounds: () => sortSounds
|
|
37
|
+
});
|
|
38
|
+
module.exports = __toCommonJS(index_exports);
|
|
39
|
+
|
|
40
|
+
// ../../Core/text/src/index.js
|
|
41
|
+
var HTML_ESCAPES = Object.freeze({
|
|
42
|
+
"&": "&",
|
|
43
|
+
"<": "<",
|
|
44
|
+
">": ">",
|
|
45
|
+
'"': """,
|
|
46
|
+
"'": "'"
|
|
47
|
+
});
|
|
48
|
+
function escapeHtml(input) {
|
|
49
|
+
if (input === null || input === void 0) return "";
|
|
50
|
+
return String(input).replace(/[&<>"']/g, (c) => HTML_ESCAPES[c]);
|
|
51
|
+
}
|
|
52
|
+
var NOT_A_WORD = /[^\p{L}\p{N}]+/u;
|
|
53
|
+
var COMBINING_MARKS = /\p{Mn}+/gu;
|
|
54
|
+
function fold(text2) {
|
|
55
|
+
if (!text2 || typeof text2 !== "string") return "";
|
|
56
|
+
return text2.toLowerCase().normalize("NFD").replace(COMBINING_MARKS, "");
|
|
57
|
+
}
|
|
58
|
+
function words(text2) {
|
|
59
|
+
return fold(text2).split(NOT_A_WORD).filter((word) => word !== "");
|
|
60
|
+
}
|
|
61
|
+
function editDistance(a, b) {
|
|
62
|
+
const s = Array.from(a ?? "");
|
|
63
|
+
const t = Array.from(b ?? "");
|
|
64
|
+
let before = [];
|
|
65
|
+
let previous = Array.from({ length: t.length + 1 }, (_, i) => i);
|
|
66
|
+
for (let i = 1; i <= s.length; i++) {
|
|
67
|
+
const current = [i];
|
|
68
|
+
for (let j = 1; j <= t.length; j++) {
|
|
69
|
+
const cost = s[i - 1] === t[j - 1] ? 0 : 1;
|
|
70
|
+
current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + cost);
|
|
71
|
+
if (i > 1 && j > 1 && s[i - 1] === t[j - 2] && s[i - 2] === t[j - 1]) {
|
|
72
|
+
current[j] = Math.min(current[j], before[j - 2] + 1);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
before = previous;
|
|
76
|
+
previous = current;
|
|
77
|
+
}
|
|
78
|
+
return previous[t.length];
|
|
79
|
+
}
|
|
80
|
+
function matchesAll(name, query, options = {}) {
|
|
81
|
+
const fuzzyFrom = options.fuzzyFrom ?? 4;
|
|
82
|
+
const folded = fold(name);
|
|
83
|
+
const nameWords = words(name);
|
|
84
|
+
return words(query).every((term) => {
|
|
85
|
+
if (folded.includes(term)) return true;
|
|
86
|
+
const length = Array.from(term).length;
|
|
87
|
+
if (length < fuzzyFrom) return false;
|
|
88
|
+
return nameWords.some(
|
|
89
|
+
(word) => editDistance(term, word) <= 1 || editDistance(term, Array.from(word).slice(0, length).join("")) <= 1
|
|
90
|
+
);
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// src/js/data/sounds.js
|
|
95
|
+
function encodePeaks(peaks) {
|
|
96
|
+
if (!Array.isArray(peaks)) return "";
|
|
97
|
+
let out = "";
|
|
98
|
+
for (const p of peaks) {
|
|
99
|
+
const v = Math.round(Math.min(Math.max(Number(p) || 0, 0), 1) * 255);
|
|
100
|
+
out += (v < 16 ? "0" : "") + v.toString(16);
|
|
101
|
+
}
|
|
102
|
+
return out;
|
|
103
|
+
}
|
|
104
|
+
function decodePeaks(value, scale = 1) {
|
|
105
|
+
if (value == null || value === "") return null;
|
|
106
|
+
if (typeof value === "string") {
|
|
107
|
+
if (!/^[0-9a-f]+$/i.test(value) || value.length % 2) return null;
|
|
108
|
+
const out2 = new Array(value.length / 2);
|
|
109
|
+
for (let i = 0; i < out2.length; i++) out2[i] = parseInt(value.substr(i * 2, 2), 16) / 255;
|
|
110
|
+
return out2;
|
|
111
|
+
}
|
|
112
|
+
if (!Array.isArray(value)) return null;
|
|
113
|
+
const s = Number(scale) > 0 ? Number(scale) : 1;
|
|
114
|
+
const out = value.map((v) => Math.min(Math.max((Number(v) || 0) / s, 0), 1));
|
|
115
|
+
return out.length ? out : null;
|
|
116
|
+
}
|
|
117
|
+
function normalizeKey(key) {
|
|
118
|
+
if (key == null) return "";
|
|
119
|
+
const raw = String(key).trim();
|
|
120
|
+
const m = raw.match(/^([A-Ga-g])[\s_-]*([#♯b♭]?)[\s_-]*(m|min|minor|maj|major)?$/i);
|
|
121
|
+
if (!m) return raw;
|
|
122
|
+
const root = m[1].toUpperCase();
|
|
123
|
+
const acc = m[2] === "\u266F" ? "#" : m[2] === "\u266D" ? "b" : m[2];
|
|
124
|
+
const minor = m[3] && /^m(in(or)?)?$/i.test(m[3]) && m[3] !== "M";
|
|
125
|
+
return root + acc + (minor ? "m" : "");
|
|
126
|
+
}
|
|
127
|
+
var 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 };
|
|
128
|
+
function keyRank(key) {
|
|
129
|
+
if (!key) return Infinity;
|
|
130
|
+
const minor = key.endsWith("m");
|
|
131
|
+
const root = minor ? key.slice(0, -1) : key;
|
|
132
|
+
const p = KEY_PITCH[root];
|
|
133
|
+
return p === void 0 ? 1e3 : p * 2 + (minor ? 1 : 0);
|
|
134
|
+
}
|
|
135
|
+
function formatDuration(seconds) {
|
|
136
|
+
if (seconds == null || seconds === "") return "";
|
|
137
|
+
const s = Number(seconds);
|
|
138
|
+
if (!Number.isFinite(s) || s < 0) return "";
|
|
139
|
+
const total = Math.round(s);
|
|
140
|
+
return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`;
|
|
141
|
+
}
|
|
142
|
+
function parseDuration(value) {
|
|
143
|
+
if (value == null || value === "") return null;
|
|
144
|
+
if (typeof value === "number") return Number.isFinite(value) && value >= 0 ? value : null;
|
|
145
|
+
const str = String(value).trim();
|
|
146
|
+
if (/^\d+(\.\d+)?$/.test(str)) return Number(str);
|
|
147
|
+
const parts = str.split(":").map(Number);
|
|
148
|
+
if (parts.length < 2 || parts.some((n) => !Number.isFinite(n))) return null;
|
|
149
|
+
return parts.reduce((acc, n) => acc * 60 + n, 0);
|
|
150
|
+
}
|
|
151
|
+
function titleFromUrl(url) {
|
|
152
|
+
const file = String(url || "").split(/[?#]/)[0].split("/").pop() || "";
|
|
153
|
+
let name = file.replace(/\.[a-z0-9]+$/i, "");
|
|
154
|
+
try {
|
|
155
|
+
name = decodeURIComponent(name);
|
|
156
|
+
} catch {
|
|
157
|
+
}
|
|
158
|
+
return name.replace(/[_]+/g, " ").replace(/\s+/g, " ").trim();
|
|
159
|
+
}
|
|
160
|
+
function normalizeSound(input, index, peakScale = 1) {
|
|
161
|
+
if (!input || typeof input !== "object" || !input.url) return null;
|
|
162
|
+
const bpm = Number(input.bpm);
|
|
163
|
+
const tags = Array.isArray(input.tags) ? input.tags.map((t) => String(t).trim()).filter(Boolean) : typeof input.tags === "string" ? input.tags.split(",").map((t) => t.trim()).filter(Boolean) : [];
|
|
164
|
+
return {
|
|
165
|
+
id: input.id != null && input.id !== "" ? String(input.id) : `sound-${index + 1}`,
|
|
166
|
+
url: String(input.url),
|
|
167
|
+
title: input.title ? String(input.title) : titleFromUrl(input.url),
|
|
168
|
+
type: input.type ? String(input.type) : "",
|
|
169
|
+
bpm: Number.isFinite(bpm) && bpm > 0 ? Math.round(bpm * 100) / 100 : null,
|
|
170
|
+
key: normalizeKey(input.key),
|
|
171
|
+
duration: parseDuration(input.duration),
|
|
172
|
+
tags,
|
|
173
|
+
peaks: decodePeaks(input.peaks, peakScale),
|
|
174
|
+
waveform: input.waveform ? String(input.waveform) : null,
|
|
175
|
+
download: input.download ? String(input.download) : null
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
function parseManifest(manifest) {
|
|
179
|
+
const list = Array.isArray(manifest) ? manifest : Array.isArray(manifest?.sounds) ? manifest.sounds : [];
|
|
180
|
+
const scale = Array.isArray(manifest) ? 1 : Number(manifest?.peakScale) || 1;
|
|
181
|
+
return normalizeSounds(list, scale);
|
|
182
|
+
}
|
|
183
|
+
function normalizeSounds(list, peakScale = 1) {
|
|
184
|
+
const seen = /* @__PURE__ */ new Set();
|
|
185
|
+
const out = [];
|
|
186
|
+
(Array.isArray(list) ? list : []).forEach((item, i) => {
|
|
187
|
+
const s = normalizeSound(item, i, peakScale);
|
|
188
|
+
if (!s) return;
|
|
189
|
+
let id = s.id, n = 2;
|
|
190
|
+
while (seen.has(id)) id = `${s.id}-${n++}`;
|
|
191
|
+
s.id = id;
|
|
192
|
+
seen.add(id);
|
|
193
|
+
out.push(s);
|
|
194
|
+
});
|
|
195
|
+
return out;
|
|
196
|
+
}
|
|
197
|
+
function facets(sounds) {
|
|
198
|
+
const types = /* @__PURE__ */ new Map();
|
|
199
|
+
const keys = /* @__PURE__ */ new Set();
|
|
200
|
+
let min = Infinity, max = -Infinity, hasDuration = false;
|
|
201
|
+
for (const s of sounds) {
|
|
202
|
+
if (s.type) types.set(s.type, (types.get(s.type) || 0) + 1);
|
|
203
|
+
if (s.key) keys.add(s.key);
|
|
204
|
+
if (s.bpm != null) {
|
|
205
|
+
min = Math.min(min, s.bpm);
|
|
206
|
+
max = Math.max(max, s.bpm);
|
|
207
|
+
}
|
|
208
|
+
if (s.duration != null) hasDuration = true;
|
|
209
|
+
}
|
|
210
|
+
return {
|
|
211
|
+
types: [...types].map(([name, count]) => ({ name, count })),
|
|
212
|
+
keys: [...keys].sort((a, b) => keyRank(a) - keyRank(b) || a.localeCompare(b)),
|
|
213
|
+
bpm: min === Infinity ? null : { min, max },
|
|
214
|
+
hasDuration
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
function matches(sound, filter = {}) {
|
|
218
|
+
if (filter.type && sound.type !== filter.type) return false;
|
|
219
|
+
if (filter.key && sound.key !== normalizeKey(filter.key)) return false;
|
|
220
|
+
const lo = Number(filter.bpmMin), hi = Number(filter.bpmMax);
|
|
221
|
+
if (filter.bpmMin != null && filter.bpmMin !== "" && Number.isFinite(lo) || filter.bpmMax != null && filter.bpmMax !== "" && Number.isFinite(hi)) {
|
|
222
|
+
if (sound.bpm == null) return false;
|
|
223
|
+
if (filter.bpmMin != null && filter.bpmMin !== "" && sound.bpm < lo) return false;
|
|
224
|
+
if (filter.bpmMax != null && filter.bpmMax !== "" && sound.bpm > hi) return false;
|
|
225
|
+
}
|
|
226
|
+
const terms = words(filter.query || "");
|
|
227
|
+
if (terms.length) {
|
|
228
|
+
const hay = [sound.title, sound.type, sound.key, ...sound.tags || []].join(" ");
|
|
229
|
+
const folded = fold(hay);
|
|
230
|
+
const rest = terms.filter((w) => !(/^\d+$/.test(w) && !folded.includes(w) && sound.bpm != null && Math.round(sound.bpm) === Number(w)));
|
|
231
|
+
if (rest.length && !matchesAll(hay, rest.join(" "))) return false;
|
|
232
|
+
}
|
|
233
|
+
return true;
|
|
234
|
+
}
|
|
235
|
+
var SORTS = ["default", "title", "bpm", "key", "duration"];
|
|
236
|
+
var SORT_NEEDS = {
|
|
237
|
+
default: () => true,
|
|
238
|
+
title: () => true,
|
|
239
|
+
bpm: (f) => f.bpm !== null,
|
|
240
|
+
key: (f) => f.keys.length > 0,
|
|
241
|
+
duration: (f) => f.hasDuration
|
|
242
|
+
};
|
|
243
|
+
function availableSorts(sorts, f) {
|
|
244
|
+
return sorts.filter((sort) => SORT_NEEDS[sort]?.(f));
|
|
245
|
+
}
|
|
246
|
+
function sortSounds(sounds, by = "default") {
|
|
247
|
+
const list = sounds.map((s, i) => ({ s, i }));
|
|
248
|
+
const last = (v) => v == null ? Infinity : v;
|
|
249
|
+
const cmp = {
|
|
250
|
+
title: (a, b) => a.s.title.localeCompare(b.s.title, void 0, { numeric: true, sensitivity: "base" }),
|
|
251
|
+
bpm: (a, b) => last(a.s.bpm) - last(b.s.bpm),
|
|
252
|
+
key: (a, b) => keyRank(a.s.key) - keyRank(b.s.key),
|
|
253
|
+
duration: (a, b) => last(a.s.duration) - last(b.s.duration)
|
|
254
|
+
}[by];
|
|
255
|
+
if (cmp) list.sort((a, b) => cmp(a, b) || a.i - b.i);
|
|
256
|
+
return list.map((x) => x.s);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// src/js/dom/draw.js
|
|
260
|
+
function fitCanvas(canvas) {
|
|
261
|
+
const rect = canvas.getBoundingClientRect();
|
|
262
|
+
if (!rect.width || !rect.height) return null;
|
|
263
|
+
const dpr = Math.min(window.devicePixelRatio || 1, 3);
|
|
264
|
+
const w = Math.round(rect.width * dpr), h2 = Math.round(rect.height * dpr);
|
|
265
|
+
if (canvas.width !== w) canvas.width = w;
|
|
266
|
+
if (canvas.height !== h2) canvas.height = h2;
|
|
267
|
+
return { width: rect.width, height: rect.height, dpr };
|
|
268
|
+
}
|
|
269
|
+
function resample(peaks, count) {
|
|
270
|
+
if (!peaks?.length || count <= 0) return [];
|
|
271
|
+
if (peaks.length === count) return peaks;
|
|
272
|
+
const out = new Array(count);
|
|
273
|
+
const step = peaks.length / count;
|
|
274
|
+
for (let i = 0; i < count; i++) {
|
|
275
|
+
const start = Math.floor(i * step);
|
|
276
|
+
const end = Math.max(start + 1, Math.floor((i + 1) * step));
|
|
277
|
+
let m = 0;
|
|
278
|
+
for (let j = start; j < end && j < peaks.length; j++) if (peaks[j] > m) m = peaks[j];
|
|
279
|
+
out[i] = m;
|
|
280
|
+
}
|
|
281
|
+
return out;
|
|
282
|
+
}
|
|
283
|
+
function drawRowWaveform(canvas, peaks, progress, o) {
|
|
284
|
+
const size = fitCanvas(canvas);
|
|
285
|
+
const ctx = size && canvas.getContext && canvas.getContext("2d");
|
|
286
|
+
if (!ctx) return;
|
|
287
|
+
const { width, height, dpr } = size;
|
|
288
|
+
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
|
289
|
+
ctx.clearRect(0, 0, width, height);
|
|
290
|
+
if (!peaks?.length) {
|
|
291
|
+
ctx.fillStyle = o.color;
|
|
292
|
+
ctx.fillRect(0, Math.floor(height / 2), width, 1);
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
const step = o.barWidth + o.barGap;
|
|
296
|
+
const count = Math.max(1, Math.floor((width + o.barGap) / step));
|
|
297
|
+
const bars = resample(peaks, count);
|
|
298
|
+
let max = 0;
|
|
299
|
+
for (const b of bars) if (b > max) max = b;
|
|
300
|
+
const scale = max > 0 ? 1 / max : 1;
|
|
301
|
+
const split = progress * width;
|
|
302
|
+
const mid = height / 2;
|
|
303
|
+
for (let i = 0; i < bars.length; i++) {
|
|
304
|
+
const x = i * step;
|
|
305
|
+
const v = Math.max(bars[i] * scale, 0.04);
|
|
306
|
+
ctx.fillStyle = x + o.barWidth / 2 <= split ? o.progressColor : o.color;
|
|
307
|
+
if (o.style === "bars") {
|
|
308
|
+
const h2 = Math.max(1, v * height);
|
|
309
|
+
ctx.fillRect(x, height - h2, o.barWidth, h2);
|
|
310
|
+
} else {
|
|
311
|
+
const h2 = Math.max(1, v * (height - 2));
|
|
312
|
+
ctx.fillRect(x, mid - h2 / 2, o.barWidth, h2);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// src/js/core/engine.js
|
|
318
|
+
var CALLBACKS = ["onLoad", "onPlay", "onPause", "onEnd", "onTimeUpdate", "onError"];
|
|
319
|
+
function engineOptions(user, layout, handlers) {
|
|
320
|
+
const site = user || {};
|
|
321
|
+
const strip = layout === "strip";
|
|
322
|
+
const options = {
|
|
323
|
+
height: strip ? 48 : 32,
|
|
324
|
+
waveformStyle: strip ? "mirror" : "bars",
|
|
325
|
+
preload: "metadata",
|
|
326
|
+
singlePlay: true,
|
|
327
|
+
...site,
|
|
328
|
+
audioMode: "self"
|
|
329
|
+
};
|
|
330
|
+
for (const name of CALLBACKS) {
|
|
331
|
+
options[name] = (...args) => {
|
|
332
|
+
handlers[name]?.(...args);
|
|
333
|
+
if (typeof site[name] === "function") site[name](...args);
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
return options;
|
|
337
|
+
}
|
|
338
|
+
function enginePeaks(sound, layout) {
|
|
339
|
+
return layout === "strip" && sound.waveform || sound.peaks || null;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// src/js/dom/menus.js
|
|
343
|
+
function optionMatches(label, query) {
|
|
344
|
+
const q = fold(String(query ?? "")).trim();
|
|
345
|
+
return !q || fold(String(label ?? "")).includes(q);
|
|
346
|
+
}
|
|
347
|
+
function stepIndex(current, delta, length) {
|
|
348
|
+
return Math.max(0, Math.min(length - 1, current + delta));
|
|
349
|
+
}
|
|
350
|
+
function partsOf(menu) {
|
|
351
|
+
return {
|
|
352
|
+
button: menu.querySelector("[data-ws-menu-btn]"),
|
|
353
|
+
pop: menu.querySelector("[data-ws-menu-pop]"),
|
|
354
|
+
search: menu.querySelector("[data-ws-menu-search]"),
|
|
355
|
+
list: menu.querySelector("[data-ws-menu-list]"),
|
|
356
|
+
none: menu.querySelector("[data-ws-menu-none]"),
|
|
357
|
+
value: menu.querySelector("[data-ws-menu-value]")
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
var focusOwner = (p) => p.search || p.list;
|
|
361
|
+
var optionsOf = (p, visibleOnly = false) => [...p.list.querySelectorAll('[role="option"]')].filter((o) => !visibleOnly || !o.hidden);
|
|
362
|
+
var Menus = class {
|
|
363
|
+
/**
|
|
364
|
+
* @param {HTMLElement} container - The list's root element.
|
|
365
|
+
* @param {Object} opts
|
|
366
|
+
* @param {(name: string, value: string) => void} opts.onPick - A value was chosen.
|
|
367
|
+
* @param {AbortSignal} opts.signal - Removes every listener on abort.
|
|
368
|
+
*/
|
|
369
|
+
constructor(container, { onPick, signal }) {
|
|
370
|
+
this.container = container;
|
|
371
|
+
this.onPick = onPick;
|
|
372
|
+
this.menus = Object.fromEntries([...container.querySelectorAll("[data-ws-menu]")].map((m) => [m.dataset.wsMenu, m]));
|
|
373
|
+
this.openMenu = null;
|
|
374
|
+
this._bind(signal);
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* Wire every menu, plus closing on an outside press or focus leaving.
|
|
378
|
+
* @param {AbortSignal} signal
|
|
379
|
+
* @private
|
|
380
|
+
*/
|
|
381
|
+
_bind(signal) {
|
|
382
|
+
const sig = { signal };
|
|
383
|
+
for (const [name, menu] of Object.entries(this.menus)) {
|
|
384
|
+
const p = partsOf(menu);
|
|
385
|
+
p.button.addEventListener("click", () => this.openMenu === menu ? this.close(true) : this.open(menu), sig);
|
|
386
|
+
p.button.addEventListener("keydown", (e) => {
|
|
387
|
+
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
|
|
388
|
+
e.preventDefault();
|
|
389
|
+
this.open(menu);
|
|
390
|
+
}
|
|
391
|
+
}, sig);
|
|
392
|
+
p.list.addEventListener("click", (e) => {
|
|
393
|
+
const opt = e.target.closest('[role="option"]');
|
|
394
|
+
if (opt) this._pick(name, opt.dataset.value);
|
|
395
|
+
}, sig);
|
|
396
|
+
p.list.addEventListener("mousedown", (e) => e.preventDefault(), sig);
|
|
397
|
+
p.search?.addEventListener("input", () => this._filter(menu, p.search.value), sig);
|
|
398
|
+
focusOwner(p).addEventListener("keydown", (e) => this._onKey(e, name, menu), sig);
|
|
399
|
+
}
|
|
400
|
+
document.addEventListener("pointerdown", (e) => {
|
|
401
|
+
if (this.openMenu && !this.openMenu.contains(e.target)) this.close(false);
|
|
402
|
+
}, sig);
|
|
403
|
+
this.container.addEventListener("focusout", (e) => {
|
|
404
|
+
if (this.openMenu && !this.openMenu.contains(e.relatedTarget)) this.close(false);
|
|
405
|
+
}, sig);
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Open a menu (closing any other), with the selected option active and
|
|
409
|
+
* focus in its search field or list. Flips to open over the end edge
|
|
410
|
+
* when it would overflow the list.
|
|
411
|
+
*
|
|
412
|
+
* @param {HTMLElement} menu
|
|
413
|
+
*/
|
|
414
|
+
open(menu) {
|
|
415
|
+
if (this.openMenu && this.openMenu !== menu) this.close(false);
|
|
416
|
+
const p = partsOf(menu);
|
|
417
|
+
p.button.setAttribute("aria-expanded", "true");
|
|
418
|
+
p.pop.hidden = false;
|
|
419
|
+
this.openMenu = menu;
|
|
420
|
+
if (p.search) {
|
|
421
|
+
p.search.value = "";
|
|
422
|
+
this._filter(menu, "");
|
|
423
|
+
}
|
|
424
|
+
menu.classList.remove("ws-menu--end");
|
|
425
|
+
if (p.pop.getBoundingClientRect().right > this.container.getBoundingClientRect().right + 1) menu.classList.add("ws-menu--end");
|
|
426
|
+
this._activate(menu, p.list.querySelector('[role="option"][aria-selected="true"]'));
|
|
427
|
+
focusOwner(p).focus();
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* Close the open menu, if any.
|
|
431
|
+
*
|
|
432
|
+
* @param {boolean} focusButton - Return focus to its button (after a
|
|
433
|
+
* pick or Esc; not after a click elsewhere).
|
|
434
|
+
*/
|
|
435
|
+
close(focusButton) {
|
|
436
|
+
const menu = this.openMenu;
|
|
437
|
+
if (!menu) return;
|
|
438
|
+
this.openMenu = null;
|
|
439
|
+
const p = partsOf(menu);
|
|
440
|
+
p.pop.hidden = true;
|
|
441
|
+
p.button.setAttribute("aria-expanded", "false");
|
|
442
|
+
if (focusButton) p.button.focus();
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* Show `value` as a menu's choice (button text + `aria-selected`). Used
|
|
446
|
+
* after a pick and when the filter is changed from code.
|
|
447
|
+
*
|
|
448
|
+
* @param {string} name - 'type' | 'key' | 'sort'.
|
|
449
|
+
* @param {string} value
|
|
450
|
+
*/
|
|
451
|
+
setValue(name, value) {
|
|
452
|
+
const menu = this.menus[name];
|
|
453
|
+
if (!menu) return;
|
|
454
|
+
const p = partsOf(menu);
|
|
455
|
+
let label = null;
|
|
456
|
+
for (const opt of optionsOf(p)) {
|
|
457
|
+
const on = opt.dataset.value === String(value ?? "");
|
|
458
|
+
opt.setAttribute("aria-selected", String(on));
|
|
459
|
+
if (on) label = opt.querySelector(".ws-menu-text")?.textContent ?? "";
|
|
460
|
+
}
|
|
461
|
+
if (label !== null) p.value.textContent = label;
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* Narrow a menu to the options matching the search, and make the first
|
|
465
|
+
* match active.
|
|
466
|
+
* @private
|
|
467
|
+
*/
|
|
468
|
+
_filter(menu, query) {
|
|
469
|
+
const p = partsOf(menu);
|
|
470
|
+
let first = null;
|
|
471
|
+
for (const opt of optionsOf(p)) {
|
|
472
|
+
opt.hidden = !optionMatches(opt.textContent, query);
|
|
473
|
+
if (!opt.hidden) first ??= opt;
|
|
474
|
+
}
|
|
475
|
+
p.none.hidden = first !== null;
|
|
476
|
+
this._activate(menu, first);
|
|
477
|
+
}
|
|
478
|
+
/**
|
|
479
|
+
* Mark one option active (`aria-activedescendant`) and scroll it into
|
|
480
|
+
* the list's view.
|
|
481
|
+
* @private
|
|
482
|
+
*/
|
|
483
|
+
_activate(menu, opt) {
|
|
484
|
+
const p = partsOf(menu);
|
|
485
|
+
for (const o of p.list.querySelectorAll(".is-active")) o.classList.remove("is-active");
|
|
486
|
+
const owner = focusOwner(p);
|
|
487
|
+
if (!opt || opt.hidden) {
|
|
488
|
+
owner.removeAttribute("aria-activedescendant");
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
opt.classList.add("is-active");
|
|
492
|
+
owner.setAttribute("aria-activedescendant", opt.id);
|
|
493
|
+
opt.scrollIntoView?.({ block: "nearest" });
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* Keys inside an open menu.
|
|
497
|
+
* @private
|
|
498
|
+
*/
|
|
499
|
+
_onKey(e, name, menu) {
|
|
500
|
+
const p = partsOf(menu);
|
|
501
|
+
const opts = optionsOf(p, true);
|
|
502
|
+
const at = opts.indexOf(p.list.querySelector(".is-active"));
|
|
503
|
+
const moveTo = (i) => {
|
|
504
|
+
e.preventDefault();
|
|
505
|
+
this._activate(menu, opts[i]);
|
|
506
|
+
};
|
|
507
|
+
const inField = e.target.matches("input");
|
|
508
|
+
switch (e.key) {
|
|
509
|
+
case "ArrowDown":
|
|
510
|
+
return moveTo(stepIndex(at, 1, opts.length));
|
|
511
|
+
case "ArrowUp":
|
|
512
|
+
return moveTo(stepIndex(at, -1, opts.length));
|
|
513
|
+
case "Home":
|
|
514
|
+
return inField ? void 0 : moveTo(0);
|
|
515
|
+
case "End":
|
|
516
|
+
return inField ? void 0 : moveTo(opts.length - 1);
|
|
517
|
+
case "Enter":
|
|
518
|
+
e.preventDefault();
|
|
519
|
+
if (at >= 0) this._pick(name, opts[at].dataset.value);
|
|
520
|
+
return void 0;
|
|
521
|
+
case "Escape":
|
|
522
|
+
e.preventDefault();
|
|
523
|
+
e.stopPropagation();
|
|
524
|
+
return this.close(true);
|
|
525
|
+
case "Tab":
|
|
526
|
+
return this.close(false);
|
|
527
|
+
default:
|
|
528
|
+
return void 0;
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* A value was chosen: close, then report it.
|
|
533
|
+
* @private
|
|
534
|
+
*/
|
|
535
|
+
_pick(name, value) {
|
|
536
|
+
this.close(true);
|
|
537
|
+
this.onPick(name, value);
|
|
538
|
+
}
|
|
539
|
+
};
|
|
540
|
+
|
|
541
|
+
// src/js/shared/utils.js
|
|
542
|
+
var LOG = "[WaveformSounds]";
|
|
543
|
+
function clamp(value, min = 0, max = 1) {
|
|
544
|
+
return Math.min(Math.max(value, min), max);
|
|
545
|
+
}
|
|
546
|
+
function pointerFraction(clientX, rect) {
|
|
547
|
+
return rect && rect.width ? clamp((clientX - rect.left) / rect.width) : 0;
|
|
548
|
+
}
|
|
549
|
+
function isTyping(el) {
|
|
550
|
+
return !!el && (el.isContentEditable || /^(INPUT|SELECT|TEXTAREA)$/.test(el.tagName));
|
|
551
|
+
}
|
|
552
|
+
function emit(target, name, detail) {
|
|
553
|
+
const event = new CustomEvent(`waveformsounds:${name}`, { bubbles: true, detail });
|
|
554
|
+
target.dispatchEvent(event);
|
|
555
|
+
return event;
|
|
556
|
+
}
|
|
557
|
+
function hashString(str) {
|
|
558
|
+
let hash = 5381;
|
|
559
|
+
for (const char of str) hash = hash * 33 + char.codePointAt(0) >>> 0;
|
|
560
|
+
return hash;
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
// src/js/data/navigation.js
|
|
564
|
+
var SEEK_STEP = 0.1;
|
|
565
|
+
function rowTarget(key, at, count) {
|
|
566
|
+
if (!count) return null;
|
|
567
|
+
switch (key) {
|
|
568
|
+
case "ArrowDown":
|
|
569
|
+
return at + 1 < count ? at + 1 : null;
|
|
570
|
+
case "ArrowUp":
|
|
571
|
+
return at > 0 ? at - 1 : "search";
|
|
572
|
+
case "Home":
|
|
573
|
+
return 0;
|
|
574
|
+
case "End":
|
|
575
|
+
return count - 1;
|
|
576
|
+
default:
|
|
577
|
+
return null;
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
function seekTarget(progress, key) {
|
|
581
|
+
if (key !== "ArrowRight" && key !== "ArrowLeft") return null;
|
|
582
|
+
return clamp(progress + (key === "ArrowRight" ? SEEK_STEP : -SEEK_STEP), 0, 0.999);
|
|
583
|
+
}
|
|
584
|
+
function pageWindow(shown, limit) {
|
|
585
|
+
const visible = new Set(shown.slice(0, limit));
|
|
586
|
+
return { visible, remaining: shown.length - visible.size };
|
|
587
|
+
}
|
|
588
|
+
function limitToReveal(limit, pos) {
|
|
589
|
+
return pos >= limit ? pos + 1 : limit;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
// src/js/render/strings.js
|
|
593
|
+
var DEFAULT_STRINGS = {
|
|
594
|
+
search: "Search sounds",
|
|
595
|
+
searchPlaceholder: "Search sounds\u2026",
|
|
596
|
+
all: "All",
|
|
597
|
+
types: "Type",
|
|
598
|
+
key: "Key",
|
|
599
|
+
anyKey: "Any key",
|
|
600
|
+
allTypes: "All types",
|
|
601
|
+
findType: "Find a type\u2026",
|
|
602
|
+
findKey: "Find a key\u2026",
|
|
603
|
+
noMatches: "No matches",
|
|
604
|
+
bpm: "BPM",
|
|
605
|
+
bpmMin: "Min BPM",
|
|
606
|
+
bpmMax: "Max BPM",
|
|
607
|
+
sort: "Sort",
|
|
608
|
+
sortBy: "Sort by",
|
|
609
|
+
sortDefault: "Default",
|
|
610
|
+
sortTitle: "Name",
|
|
611
|
+
sortBpm: "BPM",
|
|
612
|
+
sortKey: "Key",
|
|
613
|
+
sortDuration: "Length",
|
|
614
|
+
loop: "Loop",
|
|
615
|
+
play: "Play {title}",
|
|
616
|
+
pause: "Pause {title}",
|
|
617
|
+
seek: "Seek {title}",
|
|
618
|
+
download: "Download {title}",
|
|
619
|
+
count: "{count} sounds",
|
|
620
|
+
countOne: "1 sound",
|
|
621
|
+
countFiltered: "{count} of {total} sounds",
|
|
622
|
+
showMore: "Show {count} more",
|
|
623
|
+
empty: "No sounds match.",
|
|
624
|
+
clear: "Clear filters",
|
|
625
|
+
nowPlaying: "Playing {title}"
|
|
626
|
+
};
|
|
627
|
+
var SORT_LABEL_KEYS = {
|
|
628
|
+
default: "sortDefault",
|
|
629
|
+
title: "sortTitle",
|
|
630
|
+
bpm: "sortBpm",
|
|
631
|
+
key: "sortKey",
|
|
632
|
+
duration: "sortDuration"
|
|
633
|
+
};
|
|
634
|
+
function fill(template, vars = {}) {
|
|
635
|
+
return String(template).replace(/\{(\w+)\}/g, (match, name) => name in vars ? String(vars[name]) : match);
|
|
636
|
+
}
|
|
637
|
+
function countText(shown, total, strings = DEFAULT_STRINGS) {
|
|
638
|
+
if (shown !== total) return fill(strings.countFiltered, { count: shown, total });
|
|
639
|
+
return total === 1 ? strings.countOne : fill(strings.count, { count: total });
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
// src/js/render/options.js
|
|
643
|
+
var FILTERS = ["type", "key", "bpm"];
|
|
644
|
+
var COLUMNS = ["type", "bpm", "key", "duration"];
|
|
645
|
+
var RENDER_DEFAULTS = {
|
|
646
|
+
player: "inline",
|
|
647
|
+
search: true,
|
|
648
|
+
filters: [...FILTERS],
|
|
649
|
+
sorts: [...SORTS],
|
|
650
|
+
loopToggle: true,
|
|
651
|
+
showCount: true,
|
|
652
|
+
menuSearch: 8,
|
|
653
|
+
pageSize: 50,
|
|
654
|
+
columns: [...COLUMNS],
|
|
655
|
+
maxTypeChips: 10
|
|
656
|
+
};
|
|
657
|
+
function defined(obj) {
|
|
658
|
+
const out = {};
|
|
659
|
+
for (const k in obj ?? {}) if (obj[k] !== void 0) out[k] = obj[k];
|
|
660
|
+
return out;
|
|
661
|
+
}
|
|
662
|
+
function allowedList(values, allowed, fallback) {
|
|
663
|
+
return Array.isArray(values) ? values.filter((v) => allowed.includes(v)) : fallback;
|
|
664
|
+
}
|
|
665
|
+
function wholeNumber(value, fallback) {
|
|
666
|
+
const n = Number(value);
|
|
667
|
+
return Number.isFinite(n) && n >= 0 ? Math.floor(n) : fallback;
|
|
668
|
+
}
|
|
669
|
+
function resolveRenderOptions(options = {}) {
|
|
670
|
+
const o = { ...RENDER_DEFAULTS, ...defined(options) };
|
|
671
|
+
return {
|
|
672
|
+
...o,
|
|
673
|
+
player: o.player === "strip" ? "strip" : "inline",
|
|
674
|
+
filters: allowedList(o.filters, FILTERS, RENDER_DEFAULTS.filters),
|
|
675
|
+
sorts: allowedList(o.sorts, SORTS, RENDER_DEFAULTS.sorts),
|
|
676
|
+
columns: allowedList(o.columns, COLUMNS, RENDER_DEFAULTS.columns),
|
|
677
|
+
menuSearch: wholeNumber(o.menuSearch, RENDER_DEFAULTS.menuSearch),
|
|
678
|
+
maxTypeChips: wholeNumber(o.maxTypeChips, RENDER_DEFAULTS.maxTypeChips),
|
|
679
|
+
pageSize: wholeNumber(o.pageSize, RENDER_DEFAULTS.pageSize),
|
|
680
|
+
strings: { ...DEFAULT_STRINGS, ...defined(options.strings) }
|
|
681
|
+
};
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
// src/js/core/options.js
|
|
685
|
+
var DEFAULT_OPTIONS = {
|
|
686
|
+
...RENDER_DEFAULTS,
|
|
687
|
+
sounds: null,
|
|
688
|
+
manifest: null,
|
|
689
|
+
waveformStyle: "mirror",
|
|
690
|
+
waveformColor: null,
|
|
691
|
+
progressColor: null,
|
|
692
|
+
barWidth: 2,
|
|
693
|
+
barGap: 1,
|
|
694
|
+
loop: false,
|
|
695
|
+
autoAdvance: false,
|
|
696
|
+
arrowAudition: true,
|
|
697
|
+
idPrefix: null,
|
|
698
|
+
urlState: false,
|
|
699
|
+
playerOptions: null,
|
|
700
|
+
playerClass: null,
|
|
701
|
+
strings: null,
|
|
702
|
+
onReady: null,
|
|
703
|
+
onPlay: null,
|
|
704
|
+
onPause: null,
|
|
705
|
+
onEnd: null,
|
|
706
|
+
onFilter: null,
|
|
707
|
+
onError: null
|
|
708
|
+
};
|
|
709
|
+
function parseBool(value) {
|
|
710
|
+
if (value === "" || value === "true") return true;
|
|
711
|
+
if (value === "false") return false;
|
|
712
|
+
return void 0;
|
|
713
|
+
}
|
|
714
|
+
function parseList(value) {
|
|
715
|
+
if (value == null) return void 0;
|
|
716
|
+
return value.split(",").map((x) => x.trim()).filter(Boolean);
|
|
717
|
+
}
|
|
718
|
+
function parseNumber(value) {
|
|
719
|
+
return value === void 0 || value === "" ? void 0 : Number(value);
|
|
720
|
+
}
|
|
721
|
+
function parseUrlState(value) {
|
|
722
|
+
if (value === void 0) return void 0;
|
|
723
|
+
const b = parseBool(value);
|
|
724
|
+
return b === void 0 ? value : b;
|
|
725
|
+
}
|
|
726
|
+
function parseJson(value, name) {
|
|
727
|
+
if (!value) return void 0;
|
|
728
|
+
try {
|
|
729
|
+
return JSON.parse(value);
|
|
730
|
+
} catch {
|
|
731
|
+
console.warn(`${LOG} Ignoring invalid JSON in data-${name}`);
|
|
732
|
+
return void 0;
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
function readDataOptions(el) {
|
|
736
|
+
const d = el.dataset || {};
|
|
737
|
+
const out = {
|
|
738
|
+
player: d.player || void 0,
|
|
739
|
+
manifest: d.manifest || void 0,
|
|
740
|
+
search: parseBool(d.search),
|
|
741
|
+
filters: parseList(d.filters),
|
|
742
|
+
sorts: parseList(d.sorts),
|
|
743
|
+
showCount: parseBool(d.showCount),
|
|
744
|
+
menuSearch: parseNumber(d.menuSearch),
|
|
745
|
+
idPrefix: d.idPrefix || void 0,
|
|
746
|
+
urlState: parseUrlState(d.urlState),
|
|
747
|
+
loopToggle: parseBool(d.loopToggle),
|
|
748
|
+
pageSize: parseNumber(d.pageSize),
|
|
749
|
+
maxTypeChips: parseNumber(d.maxTypeChips),
|
|
750
|
+
columns: parseList(d.columns),
|
|
751
|
+
waveformStyle: d.waveformStyle || void 0,
|
|
752
|
+
waveformColor: d.waveformColor || void 0,
|
|
753
|
+
progressColor: d.progressColor || void 0,
|
|
754
|
+
barWidth: parseNumber(d.barWidth),
|
|
755
|
+
barGap: parseNumber(d.barGap),
|
|
756
|
+
loop: parseBool(d.loop),
|
|
757
|
+
autoAdvance: parseBool(d.autoAdvance),
|
|
758
|
+
arrowAudition: parseBool(d.arrowAudition),
|
|
759
|
+
strings: parseJson(d.strings, "strings"),
|
|
760
|
+
playerOptions: parseJson(d.playerOptions, "player-options")
|
|
761
|
+
};
|
|
762
|
+
for (const k of Object.keys(out)) if (out[k] === void 0) delete out[k];
|
|
763
|
+
return out;
|
|
764
|
+
}
|
|
765
|
+
function mergeOptions(...sources) {
|
|
766
|
+
const out = {};
|
|
767
|
+
for (const src of sources) {
|
|
768
|
+
if (!src) continue;
|
|
769
|
+
for (const k in src) if (src[k] !== null && src[k] !== void 0) out[k] = src[k];
|
|
770
|
+
}
|
|
771
|
+
return out;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
// src/js/render/html.js
|
|
775
|
+
var VOID = /* @__PURE__ */ new Set(["input", "br", "img"]);
|
|
776
|
+
function text(value) {
|
|
777
|
+
return escapeHtml(value ?? "");
|
|
778
|
+
}
|
|
779
|
+
function attrs(map = {}) {
|
|
780
|
+
let out = "";
|
|
781
|
+
for (const [name, value] of Object.entries(map)) {
|
|
782
|
+
if (value === true) out += ` ${name}`;
|
|
783
|
+
else if (value !== false && value != null) out += ` ${name}="${escapeHtml(value)}"`;
|
|
784
|
+
}
|
|
785
|
+
return out;
|
|
786
|
+
}
|
|
787
|
+
function h(tag, attributes = {}, ...children) {
|
|
788
|
+
const open = `<${tag}${attrs(attributes)}>`;
|
|
789
|
+
if (VOID.has(tag)) return open;
|
|
790
|
+
return open + children.flat(Infinity).filter((c) => c != null && c !== false && c !== "").join("") + `</${tag}>`;
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
// src/js/render/icons.js
|
|
794
|
+
function icon(path, extraClass = "") {
|
|
795
|
+
const cls = extraClass ? `ws-icon ${extraClass}` : "ws-icon";
|
|
796
|
+
return `<svg class="${cls}" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="${path}"/></svg>`;
|
|
797
|
+
}
|
|
798
|
+
var ICONS = {
|
|
799
|
+
play: icon("M8 5.5v13l11-6.5z", "ws-icon-play"),
|
|
800
|
+
pause: icon("M7 5h3.5v14H7zM13.5 5H17v14h-3.5z", "ws-icon-pause"),
|
|
801
|
+
search: icon("M10.5 4a6.5 6.5 0 1 0 4.03 11.6l4.43 4.43 1.41-1.41-4.43-4.43A6.5 6.5 0 0 0 10.5 4zm0 2a4.5 4.5 0 1 1 0 9 4.5 4.5 0 0 1 0-9z"),
|
|
802
|
+
chevron: icon("M6.4 8.6 12 14.2l5.6-5.6L19 10l-7 7-7-7z", "ws-menu-chevron"),
|
|
803
|
+
check: icon("M9.5 16.2 5.3 12l-1.4 1.4 5.6 5.6 11-11-1.4-1.4z", "ws-menu-check"),
|
|
804
|
+
download: icon("M11 4h2v8.6l3.3-3.3 1.4 1.4L12 16.4l-5.7-5.7 1.4-1.4 3.3 3.3zM5 18h14v2H5z"),
|
|
805
|
+
loop: icon("M17 4l3 3-3 3V8H8a3 3 0 0 0-3 3v1H3v-1a5 5 0 0 1 5-5h9V4zM7 20l-3-3 3-3v2h9a3 3 0 0 0 3-3v-1h2v1a5 5 0 0 1-5 5H7v2z")
|
|
806
|
+
};
|
|
807
|
+
|
|
808
|
+
// src/js/render/markup.js
|
|
809
|
+
function idBase(sounds) {
|
|
810
|
+
const signature = [sounds.length, ...sounds.map((s) => s.url)].join("|");
|
|
811
|
+
return `ws${hashString(signature).toString(36)}`;
|
|
812
|
+
}
|
|
813
|
+
function toolbarPlan(f, o) {
|
|
814
|
+
const typed = o.filters.includes("type") && f.types.length > 1;
|
|
815
|
+
const sorts = availableSorts(o.sorts, f);
|
|
816
|
+
return {
|
|
817
|
+
types: !typed ? null : f.types.length > o.maxTypeChips ? "menu" : "chips",
|
|
818
|
+
key: o.filters.includes("key") && f.keys.length > 1,
|
|
819
|
+
bpm: o.filters.includes("bpm") && f.bpm !== null && f.bpm.max > f.bpm.min,
|
|
820
|
+
sorts: sorts.length > 1 ? sorts : [],
|
|
821
|
+
search: !!o.search,
|
|
822
|
+
loop: !!o.loopToggle,
|
|
823
|
+
count: !!o.showCount
|
|
824
|
+
};
|
|
825
|
+
}
|
|
826
|
+
function renderSearch(s) {
|
|
827
|
+
return h(
|
|
828
|
+
"label",
|
|
829
|
+
{ class: "ws-search" },
|
|
830
|
+
ICONS.search,
|
|
831
|
+
h("span", { class: "ws-sr" }, text(s.search)),
|
|
832
|
+
h("input", { type: "search", class: "ws-search-input", "data-ws-search": true, placeholder: s.searchPlaceholder, autocomplete: "off", spellcheck: "false" })
|
|
833
|
+
);
|
|
834
|
+
}
|
|
835
|
+
function renderMenu(name, m) {
|
|
836
|
+
const listId = `${m.id}-${name}-list`;
|
|
837
|
+
const current = m.options.find((o) => o.value === m.value) ?? m.options[0];
|
|
838
|
+
const searchable = m.placeholder && m.options.length > m.searchFrom;
|
|
839
|
+
const button = h(
|
|
840
|
+
"button",
|
|
841
|
+
{ type: "button", class: "ws-menu-btn", "data-ws-menu-btn": true, "aria-haspopup": "listbox", "aria-expanded": "false", "aria-controls": listId },
|
|
842
|
+
m.prefix ? h("span", { class: "ws-menu-prefix" }, text(m.prefix)) : h("span", { class: "ws-sr" }, text(`${m.label}: `)),
|
|
843
|
+
h("span", { class: "ws-menu-value", "data-ws-menu-value": true }, text(current.label)),
|
|
844
|
+
ICONS.chevron
|
|
845
|
+
);
|
|
846
|
+
const search = searchable && h("input", {
|
|
847
|
+
type: "search",
|
|
848
|
+
class: "ws-menu-search",
|
|
849
|
+
"data-ws-menu-search": true,
|
|
850
|
+
role: "combobox",
|
|
851
|
+
"aria-expanded": "true",
|
|
852
|
+
"aria-controls": listId,
|
|
853
|
+
"aria-autocomplete": "list",
|
|
854
|
+
"aria-label": m.placeholder,
|
|
855
|
+
placeholder: m.placeholder,
|
|
856
|
+
autocomplete: "off",
|
|
857
|
+
spellcheck: "false"
|
|
858
|
+
});
|
|
859
|
+
const options = m.options.map((o, i) => h(
|
|
860
|
+
"li",
|
|
861
|
+
{ role: "option", id: `${m.id}-${name}-${i}`, class: "ws-menu-option", "data-value": o.value, "aria-selected": String(o === current) },
|
|
862
|
+
ICONS.check,
|
|
863
|
+
h("span", { class: "ws-menu-text" }, text(o.label)),
|
|
864
|
+
o.count != null && h("span", { class: "ws-menu-count" }, text(o.count))
|
|
865
|
+
));
|
|
866
|
+
return h(
|
|
867
|
+
"div",
|
|
868
|
+
{ class: "ws-menu", "data-ws-menu": name },
|
|
869
|
+
button,
|
|
870
|
+
h(
|
|
871
|
+
"div",
|
|
872
|
+
{ class: "ws-menu-pop", "data-ws-menu-pop": true, hidden: true },
|
|
873
|
+
search,
|
|
874
|
+
h("ul", { class: "ws-menu-list", role: "listbox", id: listId, "aria-label": m.label, tabindex: "-1", "data-ws-menu-list": true }, options),
|
|
875
|
+
h("p", { class: "ws-menu-none", "data-ws-menu-none": true, hidden: true }, text(m.noMatches))
|
|
876
|
+
)
|
|
877
|
+
);
|
|
878
|
+
}
|
|
879
|
+
function renderBpmRange(s, range) {
|
|
880
|
+
const field = (attr, label, placeholder) => h("input", { type: "number", inputmode: "numeric", [attr]: true, "aria-label": label, placeholder, min: "0", step: "1" });
|
|
881
|
+
return h(
|
|
882
|
+
"span",
|
|
883
|
+
{ class: "ws-bpm-range", role: "group", "aria-label": s.bpm },
|
|
884
|
+
field("data-ws-bpm-min", s.bpmMin, range.min),
|
|
885
|
+
h("span", { "aria-hidden": "true" }, "\u2013"),
|
|
886
|
+
field("data-ws-bpm-max", s.bpmMax, range.max),
|
|
887
|
+
h("span", { class: "ws-bpm-unit", "aria-hidden": "true" }, text(s.bpm))
|
|
888
|
+
);
|
|
889
|
+
}
|
|
890
|
+
function renderLoopToggle(s) {
|
|
891
|
+
return h("button", { type: "button", class: "ws-loop", "data-ws-loop": true, "aria-pressed": "false" }, ICONS.loop, h("span", {}, text(s.loop)));
|
|
892
|
+
}
|
|
893
|
+
function renderChip(value, label, count, pressed) {
|
|
894
|
+
return h(
|
|
895
|
+
"button",
|
|
896
|
+
{ type: "button", class: "ws-chip", "data-ws-type": value, "aria-pressed": String(pressed) },
|
|
897
|
+
h("span", { class: "ws-chip-label" }, text(label)),
|
|
898
|
+
" ",
|
|
899
|
+
h("span", { class: "ws-chip-count" }, text(count))
|
|
900
|
+
);
|
|
901
|
+
}
|
|
902
|
+
function renderToolbar(plan, { o, s, f, total, id }) {
|
|
903
|
+
const menu = (name, m) => renderMenu(name, { id, searchFrom: o.menuSearch, noMatches: s.noMatches, ...m });
|
|
904
|
+
const controls = [
|
|
905
|
+
plan.types === "menu" && menu("type", {
|
|
906
|
+
label: s.types,
|
|
907
|
+
value: "",
|
|
908
|
+
placeholder: s.findType,
|
|
909
|
+
options: [{ value: "", label: s.allTypes, count: total }, ...f.types.map((t) => ({ value: t.name, label: t.name, count: t.count }))]
|
|
910
|
+
}),
|
|
911
|
+
plan.key && menu("key", {
|
|
912
|
+
label: s.key,
|
|
913
|
+
value: "",
|
|
914
|
+
placeholder: s.findKey,
|
|
915
|
+
options: [{ value: "", label: s.anyKey }, ...f.keys.map((k) => ({ value: k, label: k }))]
|
|
916
|
+
}),
|
|
917
|
+
plan.bpm && renderBpmRange(s, f.bpm),
|
|
918
|
+
plan.sorts.length > 0 && menu("sort", {
|
|
919
|
+
label: s.sort,
|
|
920
|
+
prefix: s.sortBy,
|
|
921
|
+
value: plan.sorts[0],
|
|
922
|
+
options: plan.sorts.map((k) => ({ value: k, label: s[SORT_LABEL_KEYS[k]] }))
|
|
923
|
+
}),
|
|
924
|
+
plan.loop && renderLoopToggle(s)
|
|
925
|
+
].filter(Boolean);
|
|
926
|
+
const chips = plan.types === "chips" && h(
|
|
927
|
+
"div",
|
|
928
|
+
{ class: "ws-types", role: "group", "aria-label": s.types },
|
|
929
|
+
renderChip("", s.all, total, true),
|
|
930
|
+
f.types.map((t) => renderChip(t.name, t.name, t.count, false))
|
|
931
|
+
);
|
|
932
|
+
const count = plan.count && h("p", { class: "ws-count", "data-ws-count": true, "aria-live": "polite" }, text(countText(total, total, s)));
|
|
933
|
+
return h(
|
|
934
|
+
"div",
|
|
935
|
+
{ class: "ws-toolbar" },
|
|
936
|
+
plan.search && renderSearch(s),
|
|
937
|
+
controls.length > 0 && h("div", { class: "ws-controls" }, controls),
|
|
938
|
+
// The chips and the count share a row (the count alone without chips).
|
|
939
|
+
(chips || count) && h("div", { class: "ws-meta" }, chips, count)
|
|
940
|
+
);
|
|
941
|
+
}
|
|
942
|
+
var CELLS = {
|
|
943
|
+
type: (sound) => text(sound.type),
|
|
944
|
+
bpm: (sound) => text(sound.bpm ?? ""),
|
|
945
|
+
key: (sound) => text(sound.key),
|
|
946
|
+
duration: (sound) => text(formatDuration(sound.duration))
|
|
947
|
+
};
|
|
948
|
+
function renderRow(sound, index, o, hidden = false) {
|
|
949
|
+
const s = o.strings;
|
|
950
|
+
const vars = { title: sound.title };
|
|
951
|
+
const cells = o.columns.map((c) => h("span", { class: `ws-cell ws-${c}` }, CELLS[c](sound)));
|
|
952
|
+
return h(
|
|
953
|
+
"li",
|
|
954
|
+
{
|
|
955
|
+
class: "ws-row",
|
|
956
|
+
"data-ws-index": index,
|
|
957
|
+
"data-ws-id": sound.id,
|
|
958
|
+
"data-url": sound.url,
|
|
959
|
+
"data-title": sound.title,
|
|
960
|
+
"data-type": sound.type || null,
|
|
961
|
+
"data-bpm": sound.bpm,
|
|
962
|
+
"data-key": sound.key || null,
|
|
963
|
+
"data-duration": sound.duration,
|
|
964
|
+
"data-tags": sound.tags?.length ? sound.tags.join(",") : null,
|
|
965
|
+
"data-peaks": sound.peaks ? encodePeaks(sound.peaks) : null,
|
|
966
|
+
"data-waveform": sound.waveform,
|
|
967
|
+
"data-download": sound.download,
|
|
968
|
+
hidden
|
|
969
|
+
},
|
|
970
|
+
h("button", { type: "button", class: "ws-play", "aria-pressed": "false", "aria-label": fill(s.play, vars) }, ICONS.play, ICONS.pause),
|
|
971
|
+
h("span", { class: "ws-cell ws-title" }, text(sound.title)),
|
|
972
|
+
// Wide rows: `display: contents` makes each cell a column. Narrow
|
|
973
|
+
// rows: one line under the title.
|
|
974
|
+
cells.length > 0 && h("span", { class: "ws-cells" }, cells),
|
|
975
|
+
o.player === "inline" && h(
|
|
976
|
+
"span",
|
|
977
|
+
{ class: "ws-wave", role: "slider", "aria-label": fill(s.seek, vars), "aria-valuemin": "0", "aria-valuemax": "100", "aria-valuenow": "0", tabindex: "-1" },
|
|
978
|
+
h("canvas", { class: "ws-canvas", "aria-hidden": "true" })
|
|
979
|
+
),
|
|
980
|
+
// Optional, per sound: a plain link. Rows without one carry nothing.
|
|
981
|
+
sound.download && h("a", { class: "ws-download", href: sound.download, download: true, "aria-label": fill(s.download, vars) }, ICONS.download)
|
|
982
|
+
);
|
|
983
|
+
}
|
|
984
|
+
function renderFooter({ o, s, total }) {
|
|
985
|
+
const page = o.pageSize > 0 ? o.pageSize : total;
|
|
986
|
+
const more = Math.max(0, total - page);
|
|
987
|
+
const strip = o.player === "strip";
|
|
988
|
+
return [
|
|
989
|
+
h(
|
|
990
|
+
"p",
|
|
991
|
+
{ class: "ws-empty", "data-ws-empty": true, hidden: true },
|
|
992
|
+
text(s.empty),
|
|
993
|
+
" ",
|
|
994
|
+
h("button", { type: "button", class: "ws-clear", "data-ws-clear": true }, text(s.clear))
|
|
995
|
+
),
|
|
996
|
+
h("button", { type: "button", class: "ws-more", "data-ws-more": true, hidden: more === 0 }, text(fill(s.showMore, { count: Math.min(more, page) }))),
|
|
997
|
+
h("div", { class: strip ? "ws-engine ws-engine--strip" : "ws-engine", "data-ws-engine": true, hidden: !strip }),
|
|
998
|
+
h("p", { class: "ws-sr", "data-ws-status": true, "aria-live": "polite" })
|
|
999
|
+
].join("");
|
|
1000
|
+
}
|
|
1001
|
+
function renderSounds(sounds, options = {}) {
|
|
1002
|
+
const o = resolveRenderOptions(options);
|
|
1003
|
+
const list = normalizeSounds(sounds);
|
|
1004
|
+
const ctx = { o, s: o.strings, f: facets(list), total: list.length, id: o.idPrefix || idBase(list) };
|
|
1005
|
+
const page = o.pageSize > 0 ? o.pageSize : Infinity;
|
|
1006
|
+
return renderToolbar(toolbarPlan(ctx.f, o), ctx) + h(
|
|
1007
|
+
"ul",
|
|
1008
|
+
{ class: `ws-list ws-list--${o.player}`, role: "list", "data-ws-list": true },
|
|
1009
|
+
list.map((sound, i) => renderRow(sound, i, o, i >= page))
|
|
1010
|
+
) + renderFooter(ctx);
|
|
1011
|
+
}
|
|
1012
|
+
function renderSoundsElement(sounds, options = {}, className = "") {
|
|
1013
|
+
const o = resolveRenderOptions(options);
|
|
1014
|
+
const cls = ["waveform-sounds", `waveform-sounds--${o.player}`, className].filter(Boolean).join(" ");
|
|
1015
|
+
return h("div", { class: cls, "data-waveform-sounds": true, "data-player": o.player }, renderSounds(sounds, options));
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
// src/js/dom/rows.js
|
|
1019
|
+
var ROW = ":scope > [data-ws-index]";
|
|
1020
|
+
function readRows(list) {
|
|
1021
|
+
const rows = [...list.querySelectorAll(ROW)].sort((a, b) => Number(a.dataset.wsIndex) - Number(b.dataset.wsIndex));
|
|
1022
|
+
const sounds = [];
|
|
1023
|
+
for (const row of rows) {
|
|
1024
|
+
const d = row.dataset;
|
|
1025
|
+
const sound = normalizeSound({
|
|
1026
|
+
id: d.wsId,
|
|
1027
|
+
url: d.url,
|
|
1028
|
+
title: d.title,
|
|
1029
|
+
type: d.type,
|
|
1030
|
+
bpm: d.bpm,
|
|
1031
|
+
key: d.key,
|
|
1032
|
+
duration: d.duration,
|
|
1033
|
+
tags: d.tags,
|
|
1034
|
+
peaks: d.peaks,
|
|
1035
|
+
waveform: d.waveform,
|
|
1036
|
+
download: d.download
|
|
1037
|
+
}, sounds.length);
|
|
1038
|
+
if (!sound) {
|
|
1039
|
+
row.remove();
|
|
1040
|
+
continue;
|
|
1041
|
+
}
|
|
1042
|
+
row.dataset.wsIndex = String(sounds.length);
|
|
1043
|
+
sounds.push(sound);
|
|
1044
|
+
}
|
|
1045
|
+
return sounds;
|
|
1046
|
+
}
|
|
1047
|
+
function indexRows(list) {
|
|
1048
|
+
const rows = [];
|
|
1049
|
+
list.querySelectorAll(ROW).forEach((row) => {
|
|
1050
|
+
rows[Number(row.dataset.wsIndex)] = row;
|
|
1051
|
+
});
|
|
1052
|
+
return rows;
|
|
1053
|
+
}
|
|
1054
|
+
function visibleRows(list) {
|
|
1055
|
+
return [...list.querySelectorAll(ROW)].filter((r) => !r.hidden);
|
|
1056
|
+
}
|
|
1057
|
+
function orderRows(list, rows) {
|
|
1058
|
+
const frag = document.createDocumentFragment();
|
|
1059
|
+
for (const row of rows) if (row) frag.appendChild(row);
|
|
1060
|
+
list.appendChild(frag);
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
// src/js/dom/colors.js
|
|
1064
|
+
function parseAlpha(color) {
|
|
1065
|
+
const c = String(color ?? "").trim();
|
|
1066
|
+
if (!c || c === "transparent") return 0;
|
|
1067
|
+
const slash = c.match(/\/\s*([\d.]+)(%?)\s*\)$/);
|
|
1068
|
+
if (slash) return Number(slash[1]) / (slash[2] ? 100 : 1);
|
|
1069
|
+
const rgba = c.match(/^rgba\(\s*[^,]+,[^,]+,[^,]+,\s*([\d.]+)\s*\)$/);
|
|
1070
|
+
if (rgba) return Number(rgba[1]);
|
|
1071
|
+
return 1;
|
|
1072
|
+
}
|
|
1073
|
+
function pageSurface(el, minAlpha = 0.95) {
|
|
1074
|
+
for (let node = el; node && node.nodeType === 1; node = node.parentElement || node.getRootNode?.().host) {
|
|
1075
|
+
const bg = getComputedStyle(node).backgroundColor;
|
|
1076
|
+
if (parseAlpha(bg) > minAlpha) return bg;
|
|
1077
|
+
}
|
|
1078
|
+
return "#fff";
|
|
1079
|
+
}
|
|
1080
|
+
function resolveCssColor(container, value) {
|
|
1081
|
+
const probe = document.createElement("span");
|
|
1082
|
+
probe.style.cssText = "position:absolute;width:0;height:0;overflow:hidden;visibility:hidden";
|
|
1083
|
+
probe.style.color = value;
|
|
1084
|
+
container.appendChild(probe);
|
|
1085
|
+
const color = getComputedStyle(probe).color;
|
|
1086
|
+
probe.remove();
|
|
1087
|
+
return color;
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
// src/js/data/url-state.js
|
|
1091
|
+
function urlKeys(urlState) {
|
|
1092
|
+
if (!urlState) return null;
|
|
1093
|
+
const p = typeof urlState === "string" ? `${urlState}-` : "";
|
|
1094
|
+
return { q: `${p}q`, type: `${p}type`, key: `${p}key`, bpm: `${p}bpm`, sort: `${p}sort` };
|
|
1095
|
+
}
|
|
1096
|
+
function parseBpmRange(value) {
|
|
1097
|
+
const m = String(value ?? "").match(/^(\d*)-(\d*)$/);
|
|
1098
|
+
return m && (m[1] || m[2]) ? { bpmMin: m[1], bpmMax: m[2] } : null;
|
|
1099
|
+
}
|
|
1100
|
+
function formatBpmRange(min, max) {
|
|
1101
|
+
const lo = min ?? "", hi = max ?? "";
|
|
1102
|
+
return lo !== "" || hi !== "" ? `${lo}-${hi}` : "";
|
|
1103
|
+
}
|
|
1104
|
+
function readUrlState(search, keys, available, sorts) {
|
|
1105
|
+
const out = { filter: {}, sort: null };
|
|
1106
|
+
if (!keys) return out;
|
|
1107
|
+
const sp = new URLSearchParams(search);
|
|
1108
|
+
const q = sp.get(keys.q);
|
|
1109
|
+
if (q) out.filter.query = q;
|
|
1110
|
+
const type = sp.get(keys.type);
|
|
1111
|
+
if (type && available.types.some((t) => t.name === type)) out.filter.type = type;
|
|
1112
|
+
const key = normalizeKey(sp.get(keys.key));
|
|
1113
|
+
if (key && available.keys.includes(key)) out.filter.key = key;
|
|
1114
|
+
const bpm = parseBpmRange(sp.get(keys.bpm));
|
|
1115
|
+
if (bpm) Object.assign(out.filter, bpm);
|
|
1116
|
+
const sort = sp.get(keys.sort);
|
|
1117
|
+
if (sort && sorts.includes(sort)) out.sort = sort;
|
|
1118
|
+
return out;
|
|
1119
|
+
}
|
|
1120
|
+
function writeUrlState(href, keys, filter, sort, defaultSort) {
|
|
1121
|
+
if (!keys) return href;
|
|
1122
|
+
const url = new URL(href);
|
|
1123
|
+
const set = (name, v) => v ? url.searchParams.set(name, v) : url.searchParams.delete(name);
|
|
1124
|
+
set(keys.q, String(filter.query ?? "").trim());
|
|
1125
|
+
set(keys.type, filter.type);
|
|
1126
|
+
set(keys.key, filter.key);
|
|
1127
|
+
set(keys.bpm, formatBpmRange(filter.bpmMin, filter.bpmMax));
|
|
1128
|
+
set(keys.sort, sort !== defaultSort ? sort : "");
|
|
1129
|
+
return url.href;
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
// src/js/core/WaveformSounds.js
|
|
1133
|
+
var NO_FILTER = Object.freeze({ query: "", type: "", key: "", bpmMin: "", bpmMax: "" });
|
|
1134
|
+
var SEARCH_DELAY = 120;
|
|
1135
|
+
var BPM_DELAY = 200;
|
|
1136
|
+
var URL_DELAY = 250;
|
|
1137
|
+
var WaveformSounds = class _WaveformSounds {
|
|
1138
|
+
/** @type {Map<Element, WaveformSounds>} */
|
|
1139
|
+
static instances = /* @__PURE__ */ new Map();
|
|
1140
|
+
/**
|
|
1141
|
+
* @param {HTMLElement|string} container - The element (or a selector).
|
|
1142
|
+
* @param {import('../../../index').WaveformSoundsOptions} [options]
|
|
1143
|
+
*/
|
|
1144
|
+
constructor(container, options = {}) {
|
|
1145
|
+
const el = typeof container === "string" ? document.querySelector(container) : container;
|
|
1146
|
+
if (!el) throw new Error(`${LOG} Container not found: ${container}`);
|
|
1147
|
+
this.container = el;
|
|
1148
|
+
this.options = mergeOptions(DEFAULT_OPTIONS, options, readDataOptions(el));
|
|
1149
|
+
this.options.waveformStyle = this.options.waveformStyle === "bars" ? "bars" : "mirror";
|
|
1150
|
+
this.strings = { ...DEFAULT_STRINGS, ...this.options.strings || {} };
|
|
1151
|
+
this.render = { ...resolveRenderOptions(this.options), strings: this.strings };
|
|
1152
|
+
this.sounds = [];
|
|
1153
|
+
this.rows = [];
|
|
1154
|
+
this.filter = { ...NO_FILTER };
|
|
1155
|
+
this.sortBy = "default";
|
|
1156
|
+
this.limit = this._pageSize();
|
|
1157
|
+
this.currentIndex = null;
|
|
1158
|
+
this.playing = false;
|
|
1159
|
+
this.progress = 0;
|
|
1160
|
+
this.loop = !!this.options.loop;
|
|
1161
|
+
this.engine = null;
|
|
1162
|
+
this.menus = null;
|
|
1163
|
+
this.destroyed = false;
|
|
1164
|
+
this._ctl = new AbortController();
|
|
1165
|
+
this._originalHTML = null;
|
|
1166
|
+
this._pendingSeek = null;
|
|
1167
|
+
this._raf = 0;
|
|
1168
|
+
_WaveformSounds.instances.set(el, this);
|
|
1169
|
+
el.dataset.wsInitialized = "true";
|
|
1170
|
+
this.ready = Promise.resolve().then(() => this._init()).catch((err) => {
|
|
1171
|
+
console.error(`${LOG} Failed to initialise:`, err);
|
|
1172
|
+
this._emit("error", { error: err });
|
|
1173
|
+
this.options.onError?.(err, this);
|
|
1174
|
+
});
|
|
1175
|
+
}
|
|
1176
|
+
/* ── Setup ─────────────────────────────────────────────────────────── */
|
|
1177
|
+
/**
|
|
1178
|
+
* Adopt server-rendered markup or render it (from `sounds` or a fetched
|
|
1179
|
+
* manifest), then wire everything up.
|
|
1180
|
+
* @private
|
|
1181
|
+
*/
|
|
1182
|
+
async _init() {
|
|
1183
|
+
const el = this.container;
|
|
1184
|
+
const adopted = el.querySelector("[data-ws-list]");
|
|
1185
|
+
if (adopted) {
|
|
1186
|
+
this.sounds = readRows(adopted);
|
|
1187
|
+
} else {
|
|
1188
|
+
this._originalHTML = el.innerHTML;
|
|
1189
|
+
this.sounds = await this._loadSounds();
|
|
1190
|
+
if (this.destroyed) return;
|
|
1191
|
+
el.innerHTML = renderSounds(this.sounds, { ...this.render, idPrefix: this.options.idPrefix || el.id || void 0 });
|
|
1192
|
+
}
|
|
1193
|
+
if (this.destroyed) return;
|
|
1194
|
+
this._addedClasses = ["waveform-sounds", `waveform-sounds--${this.render.player}`].filter((c) => !el.classList.contains(c));
|
|
1195
|
+
el.classList.add(...this._addedClasses);
|
|
1196
|
+
this._cacheRefs();
|
|
1197
|
+
this._bind();
|
|
1198
|
+
this._observe();
|
|
1199
|
+
this._resolveColors();
|
|
1200
|
+
this._setLoop(this.loop);
|
|
1201
|
+
this._sorts = availableSorts(this.render.sorts, facets(this.sounds));
|
|
1202
|
+
if (!this._sortSet) this.sortBy = this._sorts[0] || "default";
|
|
1203
|
+
this._readUrl();
|
|
1204
|
+
this._syncControls();
|
|
1205
|
+
this._apply({ resort: this.sortBy !== "default" });
|
|
1206
|
+
if (this._playerClass()) this._ensureEngine();
|
|
1207
|
+
this._emit("ready", { sounds: this.sounds.length });
|
|
1208
|
+
this.options.onReady?.(this);
|
|
1209
|
+
}
|
|
1210
|
+
/**
|
|
1211
|
+
* The sounds from the `sounds` option, else the `manifest` URL.
|
|
1212
|
+
* @returns {Promise<import('../../../index').Sound[]>}
|
|
1213
|
+
* @private
|
|
1214
|
+
*/
|
|
1215
|
+
async _loadSounds() {
|
|
1216
|
+
if (this.options.sounds || !this.options.manifest) return normalizeSounds(this.options.sounds || []);
|
|
1217
|
+
const res = await fetch(this.options.manifest);
|
|
1218
|
+
if (!res.ok) throw new Error(`${LOG} Manifest ${this.options.manifest}: HTTP ${res.status}`);
|
|
1219
|
+
return parseManifest(await res.json());
|
|
1220
|
+
}
|
|
1221
|
+
/**
|
|
1222
|
+
* Look up the elements the runtime drives.
|
|
1223
|
+
* @private
|
|
1224
|
+
*/
|
|
1225
|
+
_cacheRefs() {
|
|
1226
|
+
const q = (sel) => this.container.querySelector(sel);
|
|
1227
|
+
this.$ = {
|
|
1228
|
+
list: q("[data-ws-list]"),
|
|
1229
|
+
search: q("[data-ws-search]"),
|
|
1230
|
+
bpmMin: q("[data-ws-bpm-min]"),
|
|
1231
|
+
bpmMax: q("[data-ws-bpm-max]"),
|
|
1232
|
+
loop: q("[data-ws-loop]"),
|
|
1233
|
+
count: q("[data-ws-count]"),
|
|
1234
|
+
empty: q("[data-ws-empty]"),
|
|
1235
|
+
more: q("[data-ws-more]"),
|
|
1236
|
+
engine: q("[data-ws-engine]"),
|
|
1237
|
+
status: q("[data-ws-status]"),
|
|
1238
|
+
chips: [...this.container.querySelectorAll("[data-ws-type]")]
|
|
1239
|
+
};
|
|
1240
|
+
this.rows = indexRows(this.$.list);
|
|
1241
|
+
}
|
|
1242
|
+
/**
|
|
1243
|
+
* Every listener. All are removed by `destroy()` through one
|
|
1244
|
+
* AbortController.
|
|
1245
|
+
* @private
|
|
1246
|
+
*/
|
|
1247
|
+
_bind() {
|
|
1248
|
+
const sig = { signal: this._ctl.signal };
|
|
1249
|
+
const $ = this.$;
|
|
1250
|
+
const root = this.container;
|
|
1251
|
+
root.addEventListener("click", (e) => this._onClick(e), sig);
|
|
1252
|
+
root.addEventListener("pointerdown", (e) => this._onPointerDown(e), sig);
|
|
1253
|
+
root.addEventListener("keydown", (e) => this._onKey(e), sig);
|
|
1254
|
+
let searchTimer = 0, bpmTimer = 0;
|
|
1255
|
+
$.search?.addEventListener("input", () => {
|
|
1256
|
+
clearTimeout(searchTimer);
|
|
1257
|
+
searchTimer = setTimeout(() => this.setFilter({ query: $.search.value }), SEARCH_DELAY);
|
|
1258
|
+
}, sig);
|
|
1259
|
+
$.search?.addEventListener("keydown", (e) => {
|
|
1260
|
+
if (e.key === "ArrowDown") {
|
|
1261
|
+
e.preventDefault();
|
|
1262
|
+
this._focusRow(visibleRows($.list)[0]);
|
|
1263
|
+
}
|
|
1264
|
+
if (e.key === "Escape" && $.search.value) {
|
|
1265
|
+
e.preventDefault();
|
|
1266
|
+
$.search.value = "";
|
|
1267
|
+
this.setFilter({ query: "" });
|
|
1268
|
+
}
|
|
1269
|
+
}, sig);
|
|
1270
|
+
const onBpm = () => {
|
|
1271
|
+
clearTimeout(bpmTimer);
|
|
1272
|
+
bpmTimer = setTimeout(() => this.setFilter({ bpmMin: $.bpmMin?.value ?? "", bpmMax: $.bpmMax?.value ?? "" }), BPM_DELAY);
|
|
1273
|
+
};
|
|
1274
|
+
$.bpmMin?.addEventListener("input", onBpm, sig);
|
|
1275
|
+
$.bpmMax?.addEventListener("input", onBpm, sig);
|
|
1276
|
+
this.menus = new Menus(root, {
|
|
1277
|
+
signal: this._ctl.signal,
|
|
1278
|
+
onPick: (name, value) => name === "sort" ? this.setSort(value) : this.setFilter({ [name]: value })
|
|
1279
|
+
});
|
|
1280
|
+
document.addEventListener("waveformplayer:play", (e) => {
|
|
1281
|
+
const player = e.detail?.player;
|
|
1282
|
+
if (player && player !== this.engine && this.playing) this.pause();
|
|
1283
|
+
}, sig);
|
|
1284
|
+
}
|
|
1285
|
+
/* ── Input ────────────────────────────────────────────────────────── */
|
|
1286
|
+
/**
|
|
1287
|
+
* Clicks: type chips, Show more, Clear, Loop, a touch tap on a waveform
|
|
1288
|
+
* (seek), and anywhere else on a row (play/pause).
|
|
1289
|
+
* @private
|
|
1290
|
+
*/
|
|
1291
|
+
_onClick(e) {
|
|
1292
|
+
const t = e.target;
|
|
1293
|
+
const chip = t.closest("[data-ws-type]");
|
|
1294
|
+
if (chip) {
|
|
1295
|
+
this.setFilter({ type: chip.dataset.wsType });
|
|
1296
|
+
return;
|
|
1297
|
+
}
|
|
1298
|
+
if (t.closest("[data-ws-more]")) {
|
|
1299
|
+
this.showMore();
|
|
1300
|
+
return;
|
|
1301
|
+
}
|
|
1302
|
+
if (t.closest("[data-ws-clear]")) {
|
|
1303
|
+
this.clearFilters();
|
|
1304
|
+
return;
|
|
1305
|
+
}
|
|
1306
|
+
if (t.closest("[data-ws-loop]")) {
|
|
1307
|
+
this.setLoop(!this.loop);
|
|
1308
|
+
return;
|
|
1309
|
+
}
|
|
1310
|
+
const wave = t.closest(".ws-wave");
|
|
1311
|
+
if (wave) {
|
|
1312
|
+
if (this._lastPointer === "touch") this._seekAt(wave, e.clientX);
|
|
1313
|
+
return;
|
|
1314
|
+
}
|
|
1315
|
+
const row = t.closest("[data-ws-index]");
|
|
1316
|
+
if (!row || t.closest(".ws-download")) return;
|
|
1317
|
+
this.toggle(Number(row.dataset.wsIndex));
|
|
1318
|
+
this._focusRowQuietly(row);
|
|
1319
|
+
}
|
|
1320
|
+
/**
|
|
1321
|
+
* Mouse and pen seek on PRESS, like every scrubber. Remembers the
|
|
1322
|
+
* pointer type for the click that follows.
|
|
1323
|
+
* @private
|
|
1324
|
+
*/
|
|
1325
|
+
_onPointerDown(e) {
|
|
1326
|
+
this._lastPointer = e.pointerType;
|
|
1327
|
+
const wave = e.target.closest(".ws-wave");
|
|
1328
|
+
if (!wave || e.button !== 0 || e.pointerType === "touch") return;
|
|
1329
|
+
e.preventDefault();
|
|
1330
|
+
this._seekAt(wave, e.clientX);
|
|
1331
|
+
}
|
|
1332
|
+
/**
|
|
1333
|
+
* Seek (or start) a row's sound where its waveform was pressed.
|
|
1334
|
+
* @private
|
|
1335
|
+
*/
|
|
1336
|
+
_seekAt(wave, clientX) {
|
|
1337
|
+
const row = wave.closest("[data-ws-index]");
|
|
1338
|
+
this._seekRow(Number(row.dataset.wsIndex), pointerFraction(clientX, wave.getBoundingClientRect()));
|
|
1339
|
+
this._focusRowQuietly(row);
|
|
1340
|
+
}
|
|
1341
|
+
/**
|
|
1342
|
+
* Keys on the list: `/` focuses search; ↑/↓/Home/End move between rows
|
|
1343
|
+
* (auditioning while something plays); ←/→ seek the playing row.
|
|
1344
|
+
* @private
|
|
1345
|
+
*/
|
|
1346
|
+
_onKey(e) {
|
|
1347
|
+
if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey) return;
|
|
1348
|
+
if (e.key === "/" && !isTyping(e.target) && this.$.search) {
|
|
1349
|
+
e.preventDefault();
|
|
1350
|
+
this.$.search.focus();
|
|
1351
|
+
return;
|
|
1352
|
+
}
|
|
1353
|
+
const row = e.target.closest?.("[data-ws-index]");
|
|
1354
|
+
if (!row) return;
|
|
1355
|
+
const index = Number(row.dataset.wsIndex);
|
|
1356
|
+
const seek = seekTarget(this.progress, e.key);
|
|
1357
|
+
if (seek !== null) {
|
|
1358
|
+
if (index !== this.currentIndex || !this.engine) return;
|
|
1359
|
+
e.preventDefault();
|
|
1360
|
+
this._seekRow(index, seek);
|
|
1361
|
+
return;
|
|
1362
|
+
}
|
|
1363
|
+
const rows = visibleRows(this.$.list);
|
|
1364
|
+
const target = rowTarget(e.key, rows.indexOf(row), rows.length);
|
|
1365
|
+
if (target === null) return;
|
|
1366
|
+
e.preventDefault();
|
|
1367
|
+
if (target === "search") {
|
|
1368
|
+
this.$.search?.focus();
|
|
1369
|
+
return;
|
|
1370
|
+
}
|
|
1371
|
+
this._focusRow(rows[target]);
|
|
1372
|
+
if (this.options.arrowAudition && this.playing) this.play(Number(rows[target].dataset.wsIndex));
|
|
1373
|
+
}
|
|
1374
|
+
/**
|
|
1375
|
+
* Focus a row's play button.
|
|
1376
|
+
* @private
|
|
1377
|
+
*/
|
|
1378
|
+
_focusRow(row) {
|
|
1379
|
+
row?.querySelector(".ws-play")?.focus();
|
|
1380
|
+
}
|
|
1381
|
+
/**
|
|
1382
|
+
* After a mouse or touch play, put focus on that row's play button so
|
|
1383
|
+
* the arrow keys drive the list instead of scrolling the page (a click
|
|
1384
|
+
* on the title or waveform left focus on <body>, and Safari never
|
|
1385
|
+
* focuses a clicked button). No scroll jump, and no focus ring: the
|
|
1386
|
+
* browser shows none for a focus that follows a pointer.
|
|
1387
|
+
* @private
|
|
1388
|
+
*/
|
|
1389
|
+
_focusRowQuietly(row) {
|
|
1390
|
+
const btn = row?.querySelector(".ws-play");
|
|
1391
|
+
if (btn && document.activeElement !== btn) btn.focus({ preventScroll: true });
|
|
1392
|
+
}
|
|
1393
|
+
/* ── Drawing & colours ────────────────────────────────────────────── */
|
|
1394
|
+
/**
|
|
1395
|
+
* Draw row canvases as they scroll into view; redraw on resize and on
|
|
1396
|
+
* theme flips (the canvas can't follow CSS by itself).
|
|
1397
|
+
* @private
|
|
1398
|
+
*/
|
|
1399
|
+
_observe() {
|
|
1400
|
+
if (this.render.player !== "inline" || typeof window === "undefined") return;
|
|
1401
|
+
this._drawn = /* @__PURE__ */ new Set();
|
|
1402
|
+
if ("IntersectionObserver" in window) {
|
|
1403
|
+
this._io = new IntersectionObserver((entries) => {
|
|
1404
|
+
for (const entry of entries) {
|
|
1405
|
+
if (!entry.isIntersecting) continue;
|
|
1406
|
+
const i = Number(entry.target.dataset.wsIndex);
|
|
1407
|
+
this._drawn.add(i);
|
|
1408
|
+
this._drawRow(i);
|
|
1409
|
+
}
|
|
1410
|
+
}, { rootMargin: "200px 0px" });
|
|
1411
|
+
this.rows.forEach((r) => r && this._io.observe(r));
|
|
1412
|
+
} else {
|
|
1413
|
+
this.rows.forEach((r, i) => r && this._drawn.add(i));
|
|
1414
|
+
}
|
|
1415
|
+
if ("ResizeObserver" in window) {
|
|
1416
|
+
let width = 0;
|
|
1417
|
+
this._ro = new ResizeObserver(([entry]) => {
|
|
1418
|
+
const w = Math.round(entry.contentRect.width);
|
|
1419
|
+
if (w === width) return;
|
|
1420
|
+
width = w;
|
|
1421
|
+
this._redrawAll();
|
|
1422
|
+
});
|
|
1423
|
+
this._ro.observe(this.$.list);
|
|
1424
|
+
}
|
|
1425
|
+
const refresh = () => requestAnimationFrame(() => {
|
|
1426
|
+
this._resolveColors();
|
|
1427
|
+
this._redrawAll();
|
|
1428
|
+
});
|
|
1429
|
+
this._mo = new MutationObserver(refresh);
|
|
1430
|
+
const watch = { attributes: true, attributeFilter: ["class", "data-theme", "data-color-scheme", "style"] };
|
|
1431
|
+
this._mo.observe(document.documentElement, watch);
|
|
1432
|
+
if (document.body) this._mo.observe(document.body, watch);
|
|
1433
|
+
try {
|
|
1434
|
+
window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", refresh, { signal: this._ctl.signal });
|
|
1435
|
+
} catch {
|
|
1436
|
+
}
|
|
1437
|
+
}
|
|
1438
|
+
/**
|
|
1439
|
+
* Resolve the canvas colours (options, else the CSS custom properties)
|
|
1440
|
+
* and keep `--ws-surface` current unless the site set it.
|
|
1441
|
+
* @private
|
|
1442
|
+
*/
|
|
1443
|
+
_resolveColors() {
|
|
1444
|
+
if (this._autoSurface || !getComputedStyle(this.container).getPropertyValue("--ws-surface").trim()) {
|
|
1445
|
+
this._autoSurface = true;
|
|
1446
|
+
this.container.style.removeProperty("--ws-surface");
|
|
1447
|
+
this.container.style.setProperty("--ws-surface", pageSurface(this.container));
|
|
1448
|
+
}
|
|
1449
|
+
this.colors = {
|
|
1450
|
+
wave: this.options.waveformColor || resolveCssColor(this.container, "var(--ws-wave-color)") || "rgba(128,128,128,.5)",
|
|
1451
|
+
progress: this.options.progressColor || resolveCssColor(this.container, "var(--ws-progress-color)") || "currentColor"
|
|
1452
|
+
};
|
|
1453
|
+
}
|
|
1454
|
+
/**
|
|
1455
|
+
* Draw one row's waveform (only once it has been on screen).
|
|
1456
|
+
* @private
|
|
1457
|
+
*/
|
|
1458
|
+
_drawRow(index) {
|
|
1459
|
+
if (this.render.player !== "inline" || index == null || !this._drawn?.has(index)) return;
|
|
1460
|
+
const row = this.rows[index];
|
|
1461
|
+
const canvas = row?.querySelector("canvas");
|
|
1462
|
+
if (!canvas || row.hidden) return;
|
|
1463
|
+
const gap = Number(this.options.barGap);
|
|
1464
|
+
drawRowWaveform(canvas, this.sounds[index].peaks, index === this.currentIndex ? this.progress : 0, {
|
|
1465
|
+
style: this.options.waveformStyle,
|
|
1466
|
+
color: this.colors?.wave || "rgba(128,128,128,.5)",
|
|
1467
|
+
progressColor: this.colors?.progress || "currentColor",
|
|
1468
|
+
barWidth: Math.max(1, Number(this.options.barWidth) || 2),
|
|
1469
|
+
barGap: Number.isFinite(gap) ? Math.max(0, gap) : 1
|
|
1470
|
+
});
|
|
1471
|
+
}
|
|
1472
|
+
/**
|
|
1473
|
+
* Redraw every row drawn so far.
|
|
1474
|
+
* @private
|
|
1475
|
+
*/
|
|
1476
|
+
_redrawAll() {
|
|
1477
|
+
this._drawn?.forEach((i) => this._drawRow(i));
|
|
1478
|
+
}
|
|
1479
|
+
/* ── Filters in the address ───────────────────────────────────────── */
|
|
1480
|
+
/**
|
|
1481
|
+
* Apply the filter and sort from the address (`urlState`).
|
|
1482
|
+
* @private
|
|
1483
|
+
*/
|
|
1484
|
+
_readUrl() {
|
|
1485
|
+
const keys = urlKeys(this.options.urlState);
|
|
1486
|
+
if (!keys || typeof location === "undefined") return;
|
|
1487
|
+
const { filter, sort } = readUrlState(location.search, keys, facets(this.sounds), this._sorts);
|
|
1488
|
+
this.filter = { ...this.filter, ...filter };
|
|
1489
|
+
if (sort) {
|
|
1490
|
+
this.sortBy = sort;
|
|
1491
|
+
this._sortSet = true;
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
/**
|
|
1495
|
+
* Rewrite the address shortly after a change (replaceState: no history
|
|
1496
|
+
* entries).
|
|
1497
|
+
* @private
|
|
1498
|
+
*/
|
|
1499
|
+
_queueUrl() {
|
|
1500
|
+
const keys = urlKeys(this.options.urlState);
|
|
1501
|
+
if (!keys || typeof location === "undefined") return;
|
|
1502
|
+
clearTimeout(this._urlTimer);
|
|
1503
|
+
this._urlTimer = setTimeout(() => {
|
|
1504
|
+
if (this.destroyed) return;
|
|
1505
|
+
const next = writeUrlState(location.href, keys, this.filter, this.sortBy, this._sorts?.[0] || "default");
|
|
1506
|
+
if (next !== location.href) history.replaceState(history.state, "", next);
|
|
1507
|
+
}, URL_DELAY);
|
|
1508
|
+
}
|
|
1509
|
+
/* ── Filtering, sorting, paging ───────────────────────────────────── */
|
|
1510
|
+
/** The sounds that pass the filter, in the current sort order. */
|
|
1511
|
+
get visible() {
|
|
1512
|
+
return sortSounds(this.sounds.filter((s) => matches(s, this.filter)), this.sortBy);
|
|
1513
|
+
}
|
|
1514
|
+
/**
|
|
1515
|
+
* Change the filter (merged into the current one) and re-apply. Back to
|
|
1516
|
+
* the first page.
|
|
1517
|
+
*
|
|
1518
|
+
* @param {Partial<import('../../../index').SoundsFilter>} patch
|
|
1519
|
+
*/
|
|
1520
|
+
setFilter(patch = {}) {
|
|
1521
|
+
this.filter = { ...this.filter, ...patch };
|
|
1522
|
+
this.limit = this._pageSize();
|
|
1523
|
+
this._syncControls();
|
|
1524
|
+
this._apply({ resort: false });
|
|
1525
|
+
}
|
|
1526
|
+
/** Reset every filter (the sort stays). */
|
|
1527
|
+
clearFilters() {
|
|
1528
|
+
this.setFilter(NO_FILTER);
|
|
1529
|
+
}
|
|
1530
|
+
/** @param {import('../../../index').SoundsSort} by */
|
|
1531
|
+
setSort(by) {
|
|
1532
|
+
this._sortSet = true;
|
|
1533
|
+
this.sortBy = SORTS.includes(by) ? by : "default";
|
|
1534
|
+
this.menus?.setValue("sort", this.sortBy);
|
|
1535
|
+
this._apply({ resort: true });
|
|
1536
|
+
}
|
|
1537
|
+
/** Reveal the next page of results. */
|
|
1538
|
+
showMore() {
|
|
1539
|
+
if (this.limit === Infinity) return;
|
|
1540
|
+
this.limit += this.render.pageSize;
|
|
1541
|
+
this._apply({ resort: false });
|
|
1542
|
+
}
|
|
1543
|
+
/**
|
|
1544
|
+
* Rows per page (Infinity when paging is off).
|
|
1545
|
+
* @private
|
|
1546
|
+
*/
|
|
1547
|
+
_pageSize() {
|
|
1548
|
+
return this.render.pageSize > 0 ? this.render.pageSize : Infinity;
|
|
1549
|
+
}
|
|
1550
|
+
/**
|
|
1551
|
+
* Show the current filter and sort in the controls (they can be set from
|
|
1552
|
+
* code or the address, not only by the controls themselves).
|
|
1553
|
+
* @private
|
|
1554
|
+
*/
|
|
1555
|
+
_syncControls() {
|
|
1556
|
+
const $ = this.$, f = this.filter;
|
|
1557
|
+
if (!$) return;
|
|
1558
|
+
if ($.search && $.search.value !== f.query) $.search.value = f.query;
|
|
1559
|
+
this.menus?.setValue("type", f.type || "");
|
|
1560
|
+
this.menus?.setValue("key", f.key || "");
|
|
1561
|
+
this.menus?.setValue("sort", this.sortBy);
|
|
1562
|
+
if ($.bpmMin && $.bpmMin.value !== String(f.bpmMin)) $.bpmMin.value = f.bpmMin;
|
|
1563
|
+
if ($.bpmMax && $.bpmMax.value !== String(f.bpmMax)) $.bpmMax.value = f.bpmMax;
|
|
1564
|
+
$.chips.forEach((c) => c.setAttribute("aria-pressed", String(c.dataset.wsType === (f.type || ""))));
|
|
1565
|
+
}
|
|
1566
|
+
/**
|
|
1567
|
+
* Lay the rows out for the current filter, sort and page: order, hide,
|
|
1568
|
+
* "Show more", the empty state and the count. Then report it.
|
|
1569
|
+
*
|
|
1570
|
+
* @param {{resort: boolean}} opts - Reorder the rows even if the sort
|
|
1571
|
+
* hasn't changed.
|
|
1572
|
+
* @private
|
|
1573
|
+
*/
|
|
1574
|
+
_apply({ resort }) {
|
|
1575
|
+
const $ = this.$;
|
|
1576
|
+
if (!$) return;
|
|
1577
|
+
if (resort || this.sortBy !== this._lastSort) {
|
|
1578
|
+
orderRows($.list, sortSounds(this.sounds, this.sortBy).map((s) => this.rows[this.sounds.indexOf(s)]));
|
|
1579
|
+
this._lastSort = this.sortBy;
|
|
1580
|
+
}
|
|
1581
|
+
const shown = this.visible;
|
|
1582
|
+
const { visible, remaining } = pageWindow(shown, this.limit);
|
|
1583
|
+
this.sounds.forEach((s, i) => {
|
|
1584
|
+
if (this.rows[i]) this.rows[i].hidden = !visible.has(s);
|
|
1585
|
+
});
|
|
1586
|
+
if ($.more) {
|
|
1587
|
+
$.more.hidden = remaining <= 0;
|
|
1588
|
+
$.more.textContent = fill(this.strings.showMore, { count: Math.min(remaining, this.render.pageSize || remaining) });
|
|
1589
|
+
}
|
|
1590
|
+
if ($.empty) $.empty.hidden = shown.length > 0;
|
|
1591
|
+
if ($.count) $.count.textContent = countText(shown.length, this.sounds.length, this.strings);
|
|
1592
|
+
this._queueUrl();
|
|
1593
|
+
this._emit("filter", { visible: shown.length, total: this.sounds.length, filter: { ...this.filter }, sort: this.sortBy });
|
|
1594
|
+
this.options.onFilter?.(shown, this);
|
|
1595
|
+
}
|
|
1596
|
+
/* ── Playback ─────────────────────────────────────────────────────── */
|
|
1597
|
+
/**
|
|
1598
|
+
* Resolve an index, id or sound to an index in `this.sounds`. No
|
|
1599
|
+
* target means the current sound, else the first visible one.
|
|
1600
|
+
*
|
|
1601
|
+
* @param {number|string|Object} [target]
|
|
1602
|
+
* @returns {number|null}
|
|
1603
|
+
* @private
|
|
1604
|
+
*/
|
|
1605
|
+
_indexOf(target) {
|
|
1606
|
+
if (target == null) return this.currentIndex ?? (this.visible[0] ? this.sounds.indexOf(this.visible[0]) : null);
|
|
1607
|
+
if (typeof target === "number") return this.sounds[target] ? target : null;
|
|
1608
|
+
const i = typeof target === "object" ? this.sounds.indexOf(target) : this.sounds.findIndex((s) => s.id === String(target));
|
|
1609
|
+
return i >= 0 ? i : null;
|
|
1610
|
+
}
|
|
1611
|
+
/**
|
|
1612
|
+
* The WaveformPlayer class: `playerClass`, else the page's global.
|
|
1613
|
+
* @returns {Function|null}
|
|
1614
|
+
* @private
|
|
1615
|
+
*/
|
|
1616
|
+
_playerClass() {
|
|
1617
|
+
return this.options.playerClass || (typeof window !== "undefined" ? window.WaveformPlayer : null) || null;
|
|
1618
|
+
}
|
|
1619
|
+
/**
|
|
1620
|
+
* Build the engine once (it holds no audio until a play).
|
|
1621
|
+
* @returns {Object|null} The engine, or null without a player class.
|
|
1622
|
+
* @private
|
|
1623
|
+
*/
|
|
1624
|
+
_ensureEngine() {
|
|
1625
|
+
if (this.engine) return this.engine;
|
|
1626
|
+
const Player = this._playerClass();
|
|
1627
|
+
if (!Player) {
|
|
1628
|
+
console.error(`${LOG} @arraypress/waveform-player is required: load it before playing (or pass playerClass).`);
|
|
1629
|
+
return null;
|
|
1630
|
+
}
|
|
1631
|
+
this.engine = new Player(this.$.engine, engineOptions(this.options.playerOptions, this.render.player, {
|
|
1632
|
+
onLoad: () => this._onEngineLoad(),
|
|
1633
|
+
onPlay: () => this._setPlaying(true),
|
|
1634
|
+
onPause: () => this._setPlaying(false),
|
|
1635
|
+
onEnd: () => this._onEnd(),
|
|
1636
|
+
onTimeUpdate: (time, duration) => this._onTime(time, duration),
|
|
1637
|
+
onError: (err) => this._onEngineError(err)
|
|
1638
|
+
}));
|
|
1639
|
+
return this.engine;
|
|
1640
|
+
}
|
|
1641
|
+
/**
|
|
1642
|
+
* Play a sound (by index, id or sound object), or resume the current
|
|
1643
|
+
* one. Before the list is built the call waits for it.
|
|
1644
|
+
*
|
|
1645
|
+
* @param {number|string|Object} [target]
|
|
1646
|
+
* @param {{at?: number}} [opts] - `at`: start position 0..1.
|
|
1647
|
+
*/
|
|
1648
|
+
play(target, opts = {}) {
|
|
1649
|
+
if (!this.$) {
|
|
1650
|
+
this.ready.then(() => {
|
|
1651
|
+
if (!this.destroyed) this.play(target, opts);
|
|
1652
|
+
});
|
|
1653
|
+
return;
|
|
1654
|
+
}
|
|
1655
|
+
const index = this._indexOf(target);
|
|
1656
|
+
if (index == null) return;
|
|
1657
|
+
const engine = this._ensureEngine();
|
|
1658
|
+
if (!engine) return;
|
|
1659
|
+
if (index === this.currentIndex && engine.audio?.src) {
|
|
1660
|
+
if (opts.at != null) this._seekRow(index, opts.at);
|
|
1661
|
+
if (!this.playing) engine.play();
|
|
1662
|
+
return;
|
|
1663
|
+
}
|
|
1664
|
+
const previous = this.currentIndex;
|
|
1665
|
+
this.currentIndex = index;
|
|
1666
|
+
this.progress = 0;
|
|
1667
|
+
this._pendingSeek = opts.at ?? null;
|
|
1668
|
+
if (previous != null) this._paintRow(previous);
|
|
1669
|
+
this._paintRow(index);
|
|
1670
|
+
const sound = this.sounds[index];
|
|
1671
|
+
engine.loadTrack(sound.url, sound.title, sound.type || null, { waveform: enginePeaks(sound, this.render.player), autoplay: true });
|
|
1672
|
+
}
|
|
1673
|
+
/** Pause the current sound. */
|
|
1674
|
+
pause() {
|
|
1675
|
+
if (this.engine && this.playing) this.engine.pause();
|
|
1676
|
+
}
|
|
1677
|
+
/**
|
|
1678
|
+
* The current sound plays/pauses; another sound starts.
|
|
1679
|
+
* @param {number|string|Object} [target]
|
|
1680
|
+
*/
|
|
1681
|
+
toggle(target) {
|
|
1682
|
+
const index = this._indexOf(target);
|
|
1683
|
+
if (index == null) return;
|
|
1684
|
+
if (index === this.currentIndex && this.playing) this.pause();
|
|
1685
|
+
else this.play(index);
|
|
1686
|
+
}
|
|
1687
|
+
/** Play the next visible sound (no wrap at the end). */
|
|
1688
|
+
next() {
|
|
1689
|
+
this._step(1);
|
|
1690
|
+
}
|
|
1691
|
+
/** Play the previous visible sound. */
|
|
1692
|
+
previous() {
|
|
1693
|
+
this._step(-1);
|
|
1694
|
+
}
|
|
1695
|
+
/**
|
|
1696
|
+
* Play the visible sound `dir` places away, revealing it if it's past
|
|
1697
|
+
* the current page.
|
|
1698
|
+
*
|
|
1699
|
+
* @param {1|-1} dir
|
|
1700
|
+
* @returns {boolean} Whether there was one.
|
|
1701
|
+
* @private
|
|
1702
|
+
*/
|
|
1703
|
+
_step(dir) {
|
|
1704
|
+
const shown = this.visible;
|
|
1705
|
+
const at = this.currentIndex == null ? -1 : shown.indexOf(this.sounds[this.currentIndex]);
|
|
1706
|
+
const target = shown[at + dir];
|
|
1707
|
+
if (!target) return false;
|
|
1708
|
+
const limit = limitToReveal(this.limit, at + dir);
|
|
1709
|
+
if (limit !== this.limit) {
|
|
1710
|
+
this.limit = limit;
|
|
1711
|
+
this._apply({ resort: false });
|
|
1712
|
+
}
|
|
1713
|
+
this.play(this.sounds.indexOf(target));
|
|
1714
|
+
return true;
|
|
1715
|
+
}
|
|
1716
|
+
/**
|
|
1717
|
+
* Loop the current sound (auditioning a loop is the common case).
|
|
1718
|
+
* @param {boolean} on
|
|
1719
|
+
*/
|
|
1720
|
+
setLoop(on) {
|
|
1721
|
+
this.loop = !!on;
|
|
1722
|
+
this._setLoop(this.loop);
|
|
1723
|
+
}
|
|
1724
|
+
/**
|
|
1725
|
+
* Apply the loop state to the toggle and the engine.
|
|
1726
|
+
* @private
|
|
1727
|
+
*/
|
|
1728
|
+
_setLoop(on) {
|
|
1729
|
+
this.$?.loop?.setAttribute("aria-pressed", String(on));
|
|
1730
|
+
if (this.engine?.audio) this.engine.audio.loop = on;
|
|
1731
|
+
}
|
|
1732
|
+
/**
|
|
1733
|
+
* Seek a row's sound to `fraction`; a row that isn't current starts
|
|
1734
|
+
* there. Before the duration is known the seek waits for it.
|
|
1735
|
+
* @private
|
|
1736
|
+
*/
|
|
1737
|
+
_seekRow(index, fraction) {
|
|
1738
|
+
if (index !== this.currentIndex || !this.engine) {
|
|
1739
|
+
this.play(index, { at: fraction });
|
|
1740
|
+
return;
|
|
1741
|
+
}
|
|
1742
|
+
const duration = this.engine.audio?.duration;
|
|
1743
|
+
if (!Number.isFinite(duration) || duration <= 0) {
|
|
1744
|
+
this._pendingSeek = fraction;
|
|
1745
|
+
return;
|
|
1746
|
+
}
|
|
1747
|
+
this.engine.seekTo(fraction * duration);
|
|
1748
|
+
this.progress = fraction;
|
|
1749
|
+
this._paintRow(index);
|
|
1750
|
+
if (!this.playing) this.engine.play();
|
|
1751
|
+
}
|
|
1752
|
+
/**
|
|
1753
|
+
* The engine loaded a sound: apply the loop, borrow decoded peaks for a
|
|
1754
|
+
* row that had none, and land a pending seek.
|
|
1755
|
+
* @private
|
|
1756
|
+
*/
|
|
1757
|
+
_onEngineLoad() {
|
|
1758
|
+
if (this.engine?.audio) this.engine.audio.loop = this.loop;
|
|
1759
|
+
const sound = this.sounds[this.currentIndex];
|
|
1760
|
+
if (sound && !sound.peaks && this.engine?.waveformData?.length) {
|
|
1761
|
+
sound.peaks = resample(this.engine.waveformData, 96);
|
|
1762
|
+
this._drawRow(this.currentIndex);
|
|
1763
|
+
}
|
|
1764
|
+
const duration = this.engine?.audio?.duration;
|
|
1765
|
+
if (this._pendingSeek != null && Number.isFinite(duration) && duration > 0) {
|
|
1766
|
+
this.engine.seekTo(this._pendingSeek * duration);
|
|
1767
|
+
this.progress = this._pendingSeek;
|
|
1768
|
+
this._pendingSeek = null;
|
|
1769
|
+
}
|
|
1770
|
+
}
|
|
1771
|
+
/**
|
|
1772
|
+
* Playback progress: repaint the current row, once per frame.
|
|
1773
|
+
* @private
|
|
1774
|
+
*/
|
|
1775
|
+
_onTime(time, duration) {
|
|
1776
|
+
if (this.currentIndex == null || !duration) return;
|
|
1777
|
+
if (this._pendingSeek != null) {
|
|
1778
|
+
const fraction = this._pendingSeek;
|
|
1779
|
+
this._pendingSeek = null;
|
|
1780
|
+
this.engine.seekTo(fraction * duration);
|
|
1781
|
+
return;
|
|
1782
|
+
}
|
|
1783
|
+
this.progress = Math.min(Math.max(time / duration, 0), 1);
|
|
1784
|
+
if (this._raf) return;
|
|
1785
|
+
this._raf = requestAnimationFrame(() => {
|
|
1786
|
+
this._raf = 0;
|
|
1787
|
+
this._drawRow(this.currentIndex);
|
|
1788
|
+
this.rows[this.currentIndex]?.querySelector(".ws-wave")?.setAttribute("aria-valuenow", String(Math.round(this.progress * 100)));
|
|
1789
|
+
});
|
|
1790
|
+
}
|
|
1791
|
+
/**
|
|
1792
|
+
* A sound finished: report it, then auto-advance or settle.
|
|
1793
|
+
* @private
|
|
1794
|
+
*/
|
|
1795
|
+
_onEnd() {
|
|
1796
|
+
const sound = this.sounds[this.currentIndex];
|
|
1797
|
+
this._emit("end", { sound, index: this.currentIndex });
|
|
1798
|
+
this.options.onEnd?.(sound, this);
|
|
1799
|
+
if (this.options.autoAdvance && this._step(1)) return;
|
|
1800
|
+
this.progress = 0;
|
|
1801
|
+
this._setPlaying(false);
|
|
1802
|
+
}
|
|
1803
|
+
/**
|
|
1804
|
+
* A sound failed to load or play: mark its row and report it.
|
|
1805
|
+
* @private
|
|
1806
|
+
*/
|
|
1807
|
+
_onEngineError(err) {
|
|
1808
|
+
this.rows[this.currentIndex]?.classList.add("is-error");
|
|
1809
|
+
this._emit("error", { error: err, sound: this.sounds[this.currentIndex], index: this.currentIndex });
|
|
1810
|
+
this.options.onError?.(err, this);
|
|
1811
|
+
}
|
|
1812
|
+
/**
|
|
1813
|
+
* Record play/pause and repaint. Events fire only on a real change: at a
|
|
1814
|
+
* natural end the browser fires `pause` then `ended`, and `_onEnd()`
|
|
1815
|
+
* also settles the state — one pause event, not two.
|
|
1816
|
+
* @private
|
|
1817
|
+
*/
|
|
1818
|
+
_setPlaying(on) {
|
|
1819
|
+
const changed = this.playing !== on;
|
|
1820
|
+
this.playing = on;
|
|
1821
|
+
const index = this.currentIndex;
|
|
1822
|
+
if (index == null) return;
|
|
1823
|
+
this._paintRow(index);
|
|
1824
|
+
if (!changed) return;
|
|
1825
|
+
const sound = this.sounds[index];
|
|
1826
|
+
if (on && this.$.status) this.$.status.textContent = fill(this.strings.nowPlaying, { title: sound.title });
|
|
1827
|
+
this._emit(on ? "play" : "pause", { sound, index });
|
|
1828
|
+
(on ? this.options.onPlay : this.options.onPause)?.(sound, this);
|
|
1829
|
+
}
|
|
1830
|
+
/* ── Row painting ─────────────────────────────────────────────────── */
|
|
1831
|
+
/**
|
|
1832
|
+
* A row's state classes, play-button label and waveform.
|
|
1833
|
+
* @private
|
|
1834
|
+
*/
|
|
1835
|
+
_paintRow(index) {
|
|
1836
|
+
const row = this.rows[index];
|
|
1837
|
+
if (!row) return;
|
|
1838
|
+
const current = index === this.currentIndex;
|
|
1839
|
+
const on = current && this.playing;
|
|
1840
|
+
row.classList.toggle("is-current", current);
|
|
1841
|
+
row.classList.toggle("is-playing", on);
|
|
1842
|
+
const btn = row.querySelector(".ws-play");
|
|
1843
|
+
if (btn) {
|
|
1844
|
+
btn.setAttribute("aria-pressed", String(on));
|
|
1845
|
+
btn.setAttribute("aria-label", fill(on ? this.strings.pause : this.strings.play, { title: this.sounds[index].title }));
|
|
1846
|
+
}
|
|
1847
|
+
const wave = row.querySelector(".ws-wave");
|
|
1848
|
+
if (wave) {
|
|
1849
|
+
wave.tabIndex = current ? 0 : -1;
|
|
1850
|
+
if (!current) wave.setAttribute("aria-valuenow", "0");
|
|
1851
|
+
}
|
|
1852
|
+
this._drawRow(index);
|
|
1853
|
+
}
|
|
1854
|
+
/* ── Events & lifecycle ──────────────────────────────────────────── */
|
|
1855
|
+
/**
|
|
1856
|
+
* Emit a `waveformsounds:<name>` event carrying this instance.
|
|
1857
|
+
* @private
|
|
1858
|
+
*/
|
|
1859
|
+
_emit(name, detail = {}) {
|
|
1860
|
+
emit(this.container, name, { ...detail, instance: this });
|
|
1861
|
+
}
|
|
1862
|
+
/** The sound playing (or paused) now, or null. */
|
|
1863
|
+
get current() {
|
|
1864
|
+
return this.currentIndex == null ? null : this.sounds[this.currentIndex];
|
|
1865
|
+
}
|
|
1866
|
+
/**
|
|
1867
|
+
* Tear down: listeners, observers, timers and the engine. Markup this
|
|
1868
|
+
* instance rendered is restored to what the container held before.
|
|
1869
|
+
* ADOPTED (server-rendered) markup is left as it is now — rows may be
|
|
1870
|
+
* re-sorted, hidden or marked current — so to start again, re-render it
|
|
1871
|
+
* rather than constructing a new instance over it.
|
|
1872
|
+
*/
|
|
1873
|
+
destroy() {
|
|
1874
|
+
if (this.destroyed) return;
|
|
1875
|
+
this.destroyed = true;
|
|
1876
|
+
this._ctl.abort();
|
|
1877
|
+
this._io?.disconnect();
|
|
1878
|
+
this._ro?.disconnect();
|
|
1879
|
+
this._mo?.disconnect();
|
|
1880
|
+
if (this._raf) cancelAnimationFrame(this._raf);
|
|
1881
|
+
clearTimeout(this._urlTimer);
|
|
1882
|
+
try {
|
|
1883
|
+
this.engine?.destroy();
|
|
1884
|
+
} catch {
|
|
1885
|
+
}
|
|
1886
|
+
this.engine = null;
|
|
1887
|
+
if (this._originalHTML != null) this.container.innerHTML = this._originalHTML;
|
|
1888
|
+
if (this._addedClasses?.length) this.container.classList.remove(...this._addedClasses);
|
|
1889
|
+
if (this._autoSurface) this.container.style.removeProperty("--ws-surface");
|
|
1890
|
+
delete this.container.dataset.wsInitialized;
|
|
1891
|
+
_WaveformSounds.instances.delete(this.container);
|
|
1892
|
+
}
|
|
1893
|
+
/**
|
|
1894
|
+
* Initialise every `[data-waveform-sounds]` under `root` that isn't yet.
|
|
1895
|
+
*
|
|
1896
|
+
* @param {ParentNode} [root=document]
|
|
1897
|
+
* @returns {WaveformSounds[]} The new instances.
|
|
1898
|
+
*/
|
|
1899
|
+
static init(root = document) {
|
|
1900
|
+
if (typeof document === "undefined") return [];
|
|
1901
|
+
const scope = root || document;
|
|
1902
|
+
const els = [...scope.matches?.("[data-waveform-sounds]") ? [scope] : [], ...scope.querySelectorAll("[data-waveform-sounds]")];
|
|
1903
|
+
const created = [];
|
|
1904
|
+
for (const el of els) {
|
|
1905
|
+
if (el.dataset.wsInitialized === "true" || _WaveformSounds.instances.has(el)) continue;
|
|
1906
|
+
try {
|
|
1907
|
+
created.push(new _WaveformSounds(el));
|
|
1908
|
+
} catch (err) {
|
|
1909
|
+
console.error(`${LOG} Failed to initialise:`, err, el);
|
|
1910
|
+
}
|
|
1911
|
+
}
|
|
1912
|
+
return created;
|
|
1913
|
+
}
|
|
1914
|
+
/**
|
|
1915
|
+
* The instance on an element (or selector), if any.
|
|
1916
|
+
* @param {Element|string} el
|
|
1917
|
+
* @returns {WaveformSounds|null}
|
|
1918
|
+
*/
|
|
1919
|
+
static getInstance(el) {
|
|
1920
|
+
const node = typeof el === "string" ? document.querySelector(el) : el;
|
|
1921
|
+
return node ? _WaveformSounds.instances.get(node) || null : null;
|
|
1922
|
+
}
|
|
1923
|
+
/** Destroy instances whose element has left the document (after a
|
|
1924
|
+
* client-side navigation). */
|
|
1925
|
+
static prune() {
|
|
1926
|
+
for (const [el, inst] of _WaveformSounds.instances) if (!el.isConnected) inst.destroy();
|
|
1927
|
+
}
|
|
1928
|
+
};
|
|
1929
|
+
|
|
1930
|
+
// src/js/entry.js
|
|
1931
|
+
WaveformSounds.utils = { encodePeaks, decodePeaks, normalizeKey, normalizeSounds, parseManifest, facets, matches, sortSounds, formatDuration, renderSounds };
|
|
1932
|
+
WaveformSounds.DEFAULT_OPTIONS = DEFAULT_OPTIONS;
|
|
1933
|
+
WaveformSounds.DEFAULT_STRINGS = DEFAULT_STRINGS;
|
|
1934
|
+
if (typeof window !== "undefined") window.WaveformSounds = WaveformSounds;
|
|
1935
|
+
var entry_default = WaveformSounds;
|
|
1936
|
+
|
|
1937
|
+
// src/js/index.js
|
|
1938
|
+
var index_default = entry_default;
|
|
1939
|
+
if (typeof document !== "undefined" && document.documentElement?.dataset?.waveformAutoinit !== "false") {
|
|
1940
|
+
if (document.readyState === "loading") {
|
|
1941
|
+
document.addEventListener("DOMContentLoaded", () => entry_default.init(), { once: true });
|
|
1942
|
+
} else {
|
|
1943
|
+
entry_default.init();
|
|
1944
|
+
}
|
|
1945
|
+
}
|
|
1946
|
+
/**
|
|
1947
|
+
* @arraypress/waveform-sounds
|
|
1948
|
+
* A searchable, filterable list of sounds for WaveformPlayer.
|
|
1949
|
+
*
|
|
1950
|
+
* Importing this entry initialises every `[data-waveform-sounds]` element
|
|
1951
|
+
* once the DOM is ready. Opt out page-wide with
|
|
1952
|
+
* `<html data-waveform-autoinit="false">` (the family's switch), or import
|
|
1953
|
+
* `@arraypress/waveform-sounds/no-autoinit`.
|
|
1954
|
+
*
|
|
1955
|
+
* @author ArrayPress
|
|
1956
|
+
* @license MIT
|
|
1957
|
+
*/
|