-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathindex.d.ts
More file actions
412 lines (379 loc) · 18.3 KB
/
Copy pathindex.d.ts
File metadata and controls
412 lines (379 loc) · 18.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
/**
* Type definitions for @arraypress/waveform-player
* Project: https://github.com/arraypress/waveform-player
*
* Hand-authored to mirror the runtime option surface and public API. This is
* the single source of truth for the library's types — the React and Astro
* wrappers re-export from here rather than re-declaring the option list.
*/
/**
* Visual style of the waveform.
*
* - `bars` — vertical bars from the baseline up
* - `mirror` — symmetrical bars mirrored around the centre line (default)
* - `line` — connected line graph
* - `blocks` — chunky square blocks
* - `dots` — dotted plot
* - `seekbar` — minimal seek bar with no peak detail
*/
export type WaveformStyle = 'bars' | 'mirror' | 'line' | 'blocks' | 'dots' | 'seekbar';
/** Forced colour scheme. `null` (default) auto-detects from the page theme and `prefers-color-scheme`. */
export type ColorPreset = 'dark' | 'light' | null;
/**
* How the player handles audio.
*
* - `self` — the player owns an `<audio>` element and plays the URL itself (default).
* - `external` — visualisation-only; `play()`/`pause()`/seek dispatch
* `waveformplayer:request-*` events for an external controller, which drives
* the visualisation back via {@link WaveformPlayer.setPlayingState} / {@link WaveformPlayer.setProgress}.
*/
export type AudioMode = 'self' | 'external';
/** Browser preload hint for the underlying `<audio>` element. */
export type AudioPreload = 'auto' | 'metadata' | 'none';
/** Vertical alignment of the play button relative to the waveform. */
export type ButtonAlign = 'auto' | 'top' | 'center' | 'bottom';
/** A clickable chapter marker rendered on top of the waveform. */
export interface WaveformMarker {
/** Time in seconds at which the marker appears. */
time: number;
/** Short label shown as a tooltip / accessible name. */
label: string;
/** Optional override colour (any CSS colour string). */
color?: string;
}
/**
* Pre-computed waveform peaks, OR a pointer to them.
*
* - `number[]` — inline array of peak amplitudes (0..1)
* - `string` (.json URL) — JSON file URL the library will `fetch()`
* - `string` (JSON array) — inline JSON string the library will parse
* - `null` / omitted — the library decodes the audio with the Web Audio API at load time
*/
export type WaveformPeaks = number[] | string | null;
/** `onTimeUpdate` fires with the same `(currentTime, duration, player)` order in both audio modes. */
export type WaveformTimeUpdateHandler = (currentTime: number, duration: number, player: WaveformPlayer) => void;
/** Lifecycle callback receiving the player instance. */
export type WaveformPlayerHandler = (player: WaveformPlayer) => void;
/** Error callback receiving the thrown error and the player instance. */
export type WaveformErrorHandler = (error: unknown, player: WaveformPlayer) => void;
/**
* Construction options for {@link WaveformPlayer}. Every field is optional; the
* library fills in defaults. The same keys can be supplied as `data-*`
* attributes on the host element for the zero-build drop-in.
*/
export interface WaveformPlayerOptions {
// ── Audio source ──────────────────────────────────────────────
/** Audio file URL. */
url?: string;
/** Shorthand alias for {@link url} (`data-src`). The canonical name wins if both are set. */
src?: string;
/** Waveform height in pixels. @default 64 */
height?: number;
/** Source peak resolution for live decode (ignored when `waveform` peaks are
* supplied); resampled to fit the visible bars. @default 1800 */
samples?: number;
/** `<audio>` preload hint. @default 'metadata' */
preload?: AudioPreload;
/** Whether the player owns its `<audio>` or delegates to an external controller. @default 'self' */
audioMode?: AudioMode;
/** Pre-computed peaks (array, .json URL, or JSON string). Skips Web Audio decoding when provided. */
waveform?: WaveformPeaks;
// ── Waveform visualisation ────────────────────────────────────
/** Visual style. @default 'mirror' */
waveformStyle?: WaveformStyle;
/** Shorthand alias for {@link waveformStyle} (`data-style`). The canonical name wins if both are set. */
style?: WaveformStyle;
/** Bar width in pixels (style-dependent default). */
barWidth?: number;
/** Gap between bars in pixels (style-dependent default). */
barSpacing?: number;
/** Rounded bar-cap radius in pixels (bars/mirror). `0` = square. @default 1 */
barRadius?: number;
/** Gradient axis when waveformColor/progressColor is an array of stops. @default 'vertical' */
waveformGradient?: 'vertical' | 'horizontal' | 'diagonal';
// ── Colours ───────────────────────────────────────────────────
/** Force a colour preset, or `null` to auto-detect. @default null */
colorPreset?: ColorPreset;
/**
* Unplayed waveform colour (each `null` = use the preset). Pass an array of
* CSS colour stops for a vertical gradient, e.g. `['#fafafa', '#71717a']`.
*/
waveformColor?: string | string[] | null;
/** Played-through colour. Also accepts an array of stops for a gradient. */
progressColor?: string | string[] | null;
// DOM chrome colours are CSS variables now (--wfp-button-color,
// --wfp-text-color, --wfp-text-secondary-color), not options.
// ── Playback ──────────────────────────────────────────────────
/** Initial playback rate. @default 1 */
playbackRate?: number;
/** Show the playback-speed control. @default false */
showPlaybackSpeed?: boolean;
/** Selectable playback rates. @default [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2] */
playbackRates?: number[];
// ── Layout / UI toggles ───────────────────────────────────────
/** Play-button alignment. @default 'auto' */
buttonAlign?: ButtonAlign;
/**
* Player layout. `'preview'` centers the title under the waveform and trims
* the meta row (time/speed/BPM) — ideal for sample-pack previews.
* @default 'default'
*/
layout?: 'default' | 'preview';
/**
* Play/pause button style. `'minimal'` renders a bare glyph with no circle —
* the look sample-pack and beat stores use in preview grids.
* @default 'circle'
*/
buttonStyle?: 'circle' | 'minimal';
/**
* Play/pause button size. A number is treated as px; a string (e.g. `'4rem'`)
* is used verbatim. Sets the `--wfp-btn-size` CSS variable, scaling both the
* `circle` and `minimal` styles — box and glyph — proportionally.
* @default null
*/
buttonSize?: number | string | null;
/**
* Play/pause button corner radius. A number is treated as px; a string (e.g.
* `'8px'`) is used verbatim. Set `0` for a square button. Sets the
* `--wfp-btn-radius` CSS variable, shaping the `circle` style's box — the
* bare `minimal` glyph has no box to round.
* @default null
*/
buttonRadius?: number | string | null;
/** Show transport controls. @default true */
showControls?: boolean;
/**
* Where the `artwork` image renders. `'info'` places it in the info row
* beside the title (requires `showInfo`); `'button'` makes the cover the
* play/pause button, which still works when the info row is hidden. Only one
* placement ever renders, so the cover cannot appear twice.
*
* `'button'` needs no other options: it drops the button's ring and uses
* cover-sized defaults (64px, 8px rounding) rather than the transport
* button's 36px circle. Set `buttonSize` / `buttonRadius` to override.
* @default 'info'
*/
artworkPosition?: 'info' | 'button';
/** Show the info (title/artist) block. @default true */
showInfo?: boolean;
/** Show current/total time. @default true */
showTime?: boolean;
/** Show a time tooltip on hover. @default false */
showHoverTime?: boolean;
/** Show a draggable circle handle + hover brightness on the seekbar style (hover/drag); the bar enables it. Drag-to-scrub works regardless. @default false */
seekHandle?: boolean;
/** Show detected BPM. @default false */
showBPM?: boolean;
/** Known BPM shown in the badge (with `showBPM`); wins over auto-detection. */
bpm?: number;
// ── Behaviour ─────────────────────────────────────────────────
/** Begin playback on load. @default false */
autoplay?: boolean;
/** Pause every other player instance when this one plays. @default true */
singlePlay?: boolean;
/** Start playing when the user seeks. @default true */
playOnSeek?: boolean;
/** Register system Media Session controls (self mode only). @default true */
enableMediaSession?: boolean;
// ── Markers ───────────────────────────────────────────────────
/** Chapter markers. @default [] */
markers?: WaveformMarker[];
/** Render markers. @default true */
showMarkers?: boolean;
// ── Accessibility ─────────────────────────────────────────────
/** Expose the waveform as a keyboard-operable ARIA slider. @default true */
accessibleSeek?: boolean;
/** Accessible name for the seek slider (falls back to the title, then `'Seek'`). @default null */
seekLabel?: string | null;
/**
* Template for the seek slider's spoken `aria-valuetext`. `%1$s` is the
* current time and `%2$s` the total duration (both formatted `M:SS`);
* sequential `%s` and reordered positional args are also supported. Lets
* consumers localize the connective text without reformatting the times.
* Falls back to `'%1$s of %2$s'`.
* @default null
*/
seekValueText?: string | null;
/** Accessible label (`aria-label`) for the play/pause button. Localize for non-English UIs. @default 'Play/Pause' */
playPauseLabel?: string;
/** Accessible label (`aria-label`) for the playback-speed button and menu. Localize for non-English UIs. @default 'Playback speed' */
speedLabel?: string;
// ── Content metadata ──────────────────────────────────────────
title?: string | null;
artist?: string | null;
artwork?: string | null;
album?: string;
/** Alt text for the artwork image. Localize for non-English UIs. @default 'Album artwork' */
artworkAlt?: string;
/** Media Session (lock-screen) title fallback used when no track `title` is set. Localize for non-English UIs. @default 'Unknown Track' */
unknownTrackText?: string;
/** Message shown when audio fails to load. @default 'Unable to load audio' */
errorText?: string;
// ── Icons (raw SVG markup) ────────────────────────────────────
playIcon?: string;
pauseIcon?: string;
// ── Callbacks ─────────────────────────────────────────────────
onLoad?: WaveformPlayerHandler | null;
onPlay?: WaveformPlayerHandler | null;
onPause?: WaveformPlayerHandler | null;
onEnd?: WaveformPlayerHandler | null;
onError?: WaveformErrorHandler | null;
onTimeUpdate?: WaveformTimeUpdateHandler | null;
/** Called when the Media Session "next track" control is used. Registering it shows the lock-screen skip-forward button. */
onNextTrack?: WaveformPlayerHandler | null;
/** Called when the Media Session "previous track" control is used. */
onPreviousTrack?: WaveformPlayerHandler | null;
}
/** `detail` of `waveformplayer:play | pause | ready | destroy`. */
export interface WaveformLifecycleEventDetail {
player: WaveformPlayer;
url: string;
}
/** `detail` of `waveformplayer:ended` — lifecycle plus the final time. */
export interface WaveformEndedEventDetail extends WaveformLifecycleEventDetail {
currentTime: number;
duration: number;
}
/** `detail` of `waveformplayer:timeupdate`. */
export interface WaveformTimeUpdateEventDetail {
player: WaveformPlayer;
currentTime: number;
duration: number;
/** Progress as a 0..1 fraction. */
progress: number;
url: string;
}
/** Track metadata carried by the external-mode `request-*` events. */
export interface WaveformTrackDetail {
url: string;
title: string | null;
artist: string | null;
artwork: string | null;
/** Chapter markers for the track (forwarded so controllers don't re-fetch). */
markers?: WaveformMarker[];
/** Pre-computed peaks for the track, if any. */
waveform?: WaveformPeaks;
id: string;
player: WaveformPlayer;
}
/** `detail` of `waveformplayer:request-play | request-pause`. */
export type WaveformRequestEventDetail = WaveformTrackDetail;
/** `detail` of `waveformplayer:request-seek` — adds the requested position. */
export interface WaveformRequestSeekEventDetail extends WaveformTrackDetail {
/** Requested position as a 0..1 fraction of total duration. */
percent: number;
}
/** Map of every custom event the player dispatches on its container (bubbling). */
export interface WaveformPlayerEventMap {
'waveformplayer:ready': CustomEvent<WaveformLifecycleEventDetail>;
'waveformplayer:play': CustomEvent<WaveformLifecycleEventDetail>;
'waveformplayer:pause': CustomEvent<WaveformLifecycleEventDetail>;
'waveformplayer:destroy': CustomEvent<WaveformLifecycleEventDetail>;
'waveformplayer:ended': CustomEvent<WaveformEndedEventDetail>;
'waveformplayer:timeupdate': CustomEvent<WaveformTimeUpdateEventDetail>;
'waveformplayer:request-play': CustomEvent<WaveformRequestEventDetail>;
'waveformplayer:request-pause': CustomEvent<WaveformRequestEventDetail>;
'waveformplayer:request-seek': CustomEvent<WaveformRequestSeekEventDetail>;
}
/**
* Modern audio player with waveform visualisation.
*
* @example
* ```ts
* import WaveformPlayer from '@arraypress/waveform-player';
* const player = new WaveformPlayer('#player', { url: '/track.mp3' });
* ```
*/
export declare class WaveformPlayer {
/**
* @param container Host element, or a CSS selector / element id resolving to one.
* @param options Player options (also readable from `data-*` attributes on the element).
*/
constructor(container: string | HTMLElement, options?: WaveformPlayerOptions);
/** Resolved options after merging defaults, data-attributes, and constructor options. */
readonly options: Required<WaveformPlayerOptions>;
/** Unique instance id (the host element id, or a generated one). */
readonly id: string;
/** Host element. */
readonly container: HTMLElement;
/** Current progress as a 0..1 fraction. */
progress: number;
/** Whether playback is active. */
isPlaying: boolean;
/**
* Start playback. In `self` mode returns the native `HTMLMediaElement.play()`
* promise; in `external` mode dispatches `waveformplayer:request-play` and returns `undefined`.
*/
play(): Promise<void> | undefined;
/** Pause playback (or dispatch `request-pause` in external mode). */
pause(): void;
/** Toggle play / pause. */
togglePlay(): void;
/** Load (or replace) the audio URL and regenerate the waveform. */
load(url: string): Promise<void>;
/** Load a new track without re-instantiating; updates metadata then plays. */
loadTrack(url: string, title?: string | null, artist?: string | null, options?: WaveformPlayerOptions): Promise<void>;
/** Seek to an absolute time in seconds (self mode). */
seekTo(seconds: number): void;
/** Seek to a fraction of total duration, 0..1 (self mode). */
seekToPercent(percent: number): void;
/** Set output volume, 0..1 (self mode). */
setVolume(volume: number): void;
/** Set the playback rate (self mode). */
setPlaybackRate(rate: number): void;
/** Provide pre-computed peaks directly. */
setWaveformData(data: WaveformPeaks): void;
/** Highlight the marker at `index` (clears the rest); pass `null` to clear all. */
setActiveMarker(index: number | null): void;
/** External mode: push play/pause state so the visualisation reflects your audio source. */
setPlayingState(playing: boolean): void;
/** External mode: push the current position so the progress overlay advances. */
setProgress(currentTime: number, duration: number): void;
/** Tear down the player: stops audio, removes all listeners, clears the container. */
destroy(): void;
/** Map of live instances keyed by id. */
static readonly instances: Map<string, WaveformPlayer>;
/** The instance currently playing, if any. */
static currentlyPlaying: WaveformPlayer | null;
/** Look up an instance by id, element, or element id. */
static getInstance(idOrElement: string | HTMLElement): WaveformPlayer | undefined;
/** All live instances. */
static getAllInstances(): WaveformPlayer[];
/** Destroy every live instance. */
static destroyAll(): void;
/** Decode an audio URL to peak data without constructing a player. */
static generateWaveformData(url: string, samples?: number): Promise<{ peaks: number[]; bpm: number | null }>;
/** Convention helper: derive the sibling `.json` peaks URL for an audio URL. */
static getPeaksUrl(audioUrl: string): string;
/** Scan the document for `[data-waveform-player]` elements and initialise them. */
static init(): void;
/**
* Pure helper functions exposed as a single source of truth so consumers
* (e.g. `@arraypress/waveform-bar`) can reuse them instead of shipping
* divergent copies.
*/
static readonly utils: {
/** Format seconds as `M:SS` (or `H:MM:SS` past an hour). */
formatTime(seconds: number): string;
/** Derive a display title from a URL's filename. */
extractTitleFromUrl(url: string): string;
/** Escape a value for safe interpolation into HTML. */
escapeHtml(str: unknown): string;
/** Whether a URL uses a safe (`http`/`https`/relative) scheme. */
isSafeHref(url: string): boolean;
/**
* Parse every recognised `data-*` attribute off an element into a
* sparse options object (the player's full declarative contract).
* Lets wrappers inherit the complete option surface without drifting.
*/
parseDataAttributes(element: HTMLElement): Partial<WaveformPlayerOptions>;
};
}
export default WaveformPlayer;
declare global {
interface Window {
/** Global constructor exposed by the IIFE/UMD build for `<script>` usage. */
WaveformPlayer: typeof WaveformPlayer;
}
interface HTMLElementEventMap extends WaveformPlayerEventMap {}
}