@toneflix/studio 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,20 +5,23 @@
5
5
  **The studio engine for the web.** Give any web app a real multitrack editor. Your users arrange, cut and shape audio as freely as in a desktop DAW, right in the browser.
6
6
 
7
7
  - **Edit without limits.** Split anything, drag clips anywhere, layer them and move them between tracks. Nothing snaps back unless you ask it to.
8
+ - **Hear every edit.** Playback follows the timeline as you work, with a mixer, effects, loops, a metronome and mixdown to WAV.
8
9
  - **Fast with big sessions.** Waveforms are drawn in the background and cached on the device, so long recordings open instantly the next time.
9
- - **Fits any stack.** No framework and no dependencies. Restyle it with CSS variables and drop in your own track controls.
10
+ - **Fits any stack.** No framework and no dependencies. Use the built-in toolbar and track controls, swap their icons for your own, or build your own UI on the same API.
10
11
  - **Open by design.** MIT licensed. Project exchange with the desktop DAWs musicians already use is on the roadmap.
11
12
 
12
13
  Read the docs and try the playground at **[toneflix.github.io/studio](https://toneflix.github.io/studio/)**.
13
14
 
14
- > Status: early. This release has the timeline and waveforms. Playback and recording come next.
15
+ > Status: early. The timeline, waveforms and playback are here. Recording comes next.
15
16
 
16
17
  ## Use
17
18
 
18
19
  ```ts
19
- import { StudioTimeline, Waveforms, makeClip, uid } from '@toneflix/studio';
20
+ import { AudioEngine, StudioTimeline, Waveforms, linkPlayback, makeClip, uid } from '@toneflix/studio';
20
21
 
21
- const timeline = new StudioTimeline(document.getElementById('editor')!, {
22
+ const engine = new AudioEngine();
23
+
24
+ const timeline = new StudioTimeline('#editor', {
22
25
  grid: { bpm: 120, meter: [4, 4], snap: 'beat' },
23
26
  createTrack: () => ({ id: uid('t'), name: 'New stem' }),
24
27
  });
@@ -30,8 +33,13 @@ timeline.load({
30
33
 
31
34
  // Peaks are worked out in a worker and kept in Cache Storage, so a stem is analysed once per device
32
35
  const waveforms = new Waveforms();
33
- const peaks = await waveforms.get('vox.wav:v1', () => audioContext.decodeAudioData(bytes));
34
- timeline.setSource({ id: 'vox.wav', duration: 12 }, peaks);
36
+ const audio = await engine.context.decodeAudioData(bytes);
37
+ const peaks = await waveforms.get('vox.wav:v1', () => audio);
38
+ timeline.setSource({ id: 'vox.wav', duration: audio.duration }, peaks);
39
+
40
+ // Play it: edits are heard at once, the playhead follows, Space plays and pauses
41
+ engine.setBuffer('vox.wav', audio);
42
+ linkPlayback(timeline, engine);
35
43
 
36
44
  timeline.on('change', ({ state, final }) => final && save(state));
37
45
  ```
@@ -53,12 +61,20 @@ timeline.on('change', ({ state, final }) => final && save(state));
53
61
 
54
62
  Where clips overlap on a lane, the one that starts later is on top and is the one heard. `audibleRanges(clips)` gives the heard part of each clip, for players and mix renderers.
55
63
 
56
- ## Pieces
64
+ ## Packages
65
+
66
+ Install `@toneflix/studio` for everything, or only the parts your app uses. Every package is released with the same version.
67
+
68
+ | Package | What it gives you |
69
+ | --- | --- |
70
+ | [`@toneflix/studio`](packages/studio) | Everything below, from one import |
71
+ | [`@toneflix/studio-core`](packages/core) | Tracks, clips, pure edits (`splitClips`, `moveClips`, `trimStart`, `setFades`…), snapping, `TimelineModel` and `History`. No DOM or audio, so it also runs on servers and in tests |
72
+ | [`@toneflix/studio-waveforms`](packages/waveforms) | `Waveforms`, `PeaksWorker`, `PeaksCache` and `drawWaveform`: peaks off the main thread, cached on the device |
73
+ | [`@toneflix/studio-audio`](packages/audio) | `AudioEngine`: playback with a mixer, effects, loops, a metronome and offline mixdown |
74
+ | [`@toneflix/studio-controls`](packages/controls) | `StudioToolbar` and `trackStrip`: playback and editing buttons and track mute, solo and volume, with Lucide icons you can replace |
75
+ | [`@toneflix/studio-timeline`](packages/timeline) | `StudioTimeline`, the editor view. Restyle it with the `--tfs-*` CSS variables or fill track headers with `renderHeader` |
57
76
 
58
- - `StudioTimeline`: the view. Tiles waveform canvases so only what is on screen is drawn. Restyle it with the `--tfs-*` CSS variables or fill track headers with `renderHeader`.
59
- - `TimelineModel` and `History`: tracks and clips as plain immutable data, and the undo list. Pass your own `History` to put your app's steps (mixer, effects) in the same list.
60
- - Pure edits (`splitClips`, `moveClips`, `trimStart`, `setFades`…): usable without the view, on the server or in tests.
61
- - `Waveforms`, `PeaksWorker`, `PeaksCache`: peaks off the main thread, cached on the device.
77
+ Recording will arrive as its own package.
62
78
 
63
79
  ## Develop
64
80
 
@@ -67,12 +83,12 @@ pnpm install
67
83
  pnpm test # node --test, no browser needed
68
84
  pnpm demo # the demo page with made-up audio
69
85
  pnpm docs:dev # the docs site with a live playground
70
- pnpm build # dist/ with type declarations
86
+ pnpm build # each package's dist/ with type declarations
71
87
  ```
72
88
 
73
89
  ## Release
74
90
 
75
- Publish a GitHub release tagged with the version, like `v0.2.0`. The Publish workflow takes the version from the tag, runs the checks, publishes to npm and saves the version in `package.json` on the default branch. A release marked as a pre-release goes out under the `next` tag.
91
+ Publish a GitHub release tagged with the version, like `v0.2.0`. The Publish workflow takes the version from the tag, runs the checks, publishes every package to npm and saves the version in each `package.json` on the default branch. A release marked as a pre-release goes out under the `next` tag.
76
92
 
77
93
  To publish without a release, run the Publish workflow from the Actions tab with a version and a dist-tag.
78
94
 
package/dist/index.d.ts CHANGED
@@ -1,14 +1,6 @@
1
- export * from './types.ts';
2
- export * from './edits.ts';
3
- export * from './overlap.ts';
4
- export * from './grid.ts';
5
- export * from './history.ts';
6
- export * from './emitter.ts';
7
- export * from './model.ts';
8
- export * from './peaks.ts';
9
- export * from './peaks-cache.ts';
10
- export * from './peaks-worker.ts';
11
- export * from './waveforms.ts';
12
- export * from './waveform.ts';
13
- export { StudioTimeline, type TimelineOptions, type TimelineEvents } from './view/timeline.ts';
14
- export { STYLES, injectStyles } from './view/styles.ts';
1
+ export * from '@toneflix/studio-core';
2
+ export * from '@toneflix/studio-waveforms';
3
+ export * from '@toneflix/studio-timeline';
4
+ export * from '@toneflix/studio-audio';
5
+ export * from '@toneflix/studio-controls';
6
+ export * from './playback.ts';
package/dist/index.js CHANGED
@@ -1,14 +1,6 @@
1
- export * from './types.js';
2
- export * from './edits.js';
3
- export * from './overlap.js';
4
- export * from './grid.js';
5
- export * from './history.js';
6
- export * from './emitter.js';
7
- export * from './model.js';
8
- export * from './peaks.js';
9
- export * from './peaks-cache.js';
10
- export * from './peaks-worker.js';
11
- export * from './waveforms.js';
12
- export * from './waveform.js';
13
- export { StudioTimeline } from './view/timeline.js';
14
- export { STYLES, injectStyles } from './view/styles.js';
1
+ export * from '@toneflix/studio-core';
2
+ export * from '@toneflix/studio-waveforms';
3
+ export * from '@toneflix/studio-timeline';
4
+ export * from '@toneflix/studio-audio';
5
+ export * from '@toneflix/studio-controls';
6
+ export * from './playback.js';
@@ -0,0 +1,11 @@
1
+ import type { AudioEngine } from '@toneflix/studio-audio';
2
+ import type { StudioTimeline } from '@toneflix/studio-timeline';
3
+ export interface LinkPlaybackOptions {
4
+ /** Space plays and pauses while the timeline has focus */
5
+ space?: boolean;
6
+ }
7
+ /**
8
+ * Keeps an engine and a timeline together: finished edits play at once, clicking the
9
+ * ruler seeks, and the playhead follows playback. Returns a function that unlinks them.
10
+ */
11
+ export declare const linkPlayback: (timeline: StudioTimeline, engine: AudioEngine, options?: LinkPlaybackOptions) => () => void;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Keeps an engine and a timeline together: finished edits play at once, clicking the
3
+ * ruler seeks, and the playhead follows playback. Returns a function that unlinks them.
4
+ */
5
+ export const linkPlayback = (timeline, engine, options = {}) => {
6
+ let frame = 0;
7
+ const follow = () => {
8
+ timeline.setTime(engine.time);
9
+ frame = engine.isPlaying ? requestAnimationFrame(follow) : 0;
10
+ };
11
+ const onKey = (e) => {
12
+ if (e.key !== ' ' || e.repeat || e.ctrlKey || e.metaKey || e.altKey)
13
+ return;
14
+ if (e.target instanceof HTMLElement && (e.target.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT', 'BUTTON'].includes(e.target.tagName)))
15
+ return;
16
+ e.preventDefault();
17
+ engine.toggle();
18
+ };
19
+ engine.load(timeline.state);
20
+ timeline.setLoop(engine.loop);
21
+ const unlink = [
22
+ timeline.on('change', ({ state, final }) => final && engine.load(state)),
23
+ timeline.on('seek', ({ time }) => engine.seek(time)),
24
+ engine.on('play', () => {
25
+ cancelAnimationFrame(frame);
26
+ follow();
27
+ }),
28
+ engine.on('pause', ({ time }) => timeline.setTime(time)),
29
+ engine.on('seek', ({ time }) => timeline.setTime(time)),
30
+ engine.on('end', ({ time }) => timeline.setTime(time)),
31
+ engine.on('loop', ({ loop }) => timeline.setLoop(loop)),
32
+ ];
33
+ if (options.space ?? true)
34
+ timeline.root.addEventListener('keydown', onKey);
35
+ return () => {
36
+ cancelAnimationFrame(frame);
37
+ for (const off of unlink)
38
+ off();
39
+ timeline.root.removeEventListener('keydown', onKey);
40
+ };
41
+ };
package/package.json CHANGED
@@ -1,12 +1,17 @@
1
1
  {
2
2
  "name": "@toneflix/studio",
3
- "version": "0.1.0",
4
- "description": "The studio engine for the web: multitrack audio editing that feels like a desktop DAW, in any browser app.",
3
+ "version": "0.3.0",
4
+ "description": "The studio engine for the web: multitrack audio editing that feels like a desktop DAW, in any browser app. Includes every Toneflix Studio package.",
5
5
  "license": "MIT",
6
6
  "author": "Toneflix <code@toneflix.com.ng>",
7
7
  "repository": {
8
8
  "type": "git",
9
- "url": "https://github.com/toneflix/studio.git"
9
+ "url": "https://github.com/toneflix/studio.git",
10
+ "directory": "packages/studio"
11
+ },
12
+ "homepage": "https://toneflix.github.io/studio/",
13
+ "bugs": {
14
+ "url": "https://github.com/toneflix/studio/issues"
10
15
  },
11
16
  "keywords": [
12
17
  "daw",
@@ -22,6 +27,7 @@
22
27
  "types": "./dist/index.d.ts",
23
28
  "exports": {
24
29
  ".": {
30
+ "@toneflix/source": "./src/index.ts",
25
31
  "types": "./dist/index.d.ts",
26
32
  "import": "./dist/index.js"
27
33
  }
@@ -31,37 +37,21 @@
31
37
  "README.md",
32
38
  "LICENSE"
33
39
  ],
34
- "scripts": {
35
- "build": "tsc -p tsconfig.build.json",
36
- "typecheck": "tsc -p tsconfig.json",
37
- "lint": "eslint .",
38
- "test": "node --test \"test/**/*.test.ts\"",
39
- "demo": "vite demo",
40
- "docs:dev": "vitepress dev docs",
41
- "docs:build": "vitepress build docs",
42
- "docs:preview": "vitepress preview docs"
43
- },
44
- "homepage": "https://github.com/toneflix/studio#readme",
45
- "bugs": {
46
- "url": "https://github.com/toneflix/studio/issues"
47
- },
48
- "devDependencies": {
49
- "@eslint/js": "^10.0.1",
50
- "@types/node": "^26.6.6",
51
- "@typescript/native": "npm:typescript@^7.0.2",
52
- "eslint": "^10.14.0",
53
- "globals": "^17.14.0",
54
- "typescript": "npm:@typescript/typescript6@^6.0.2",
55
- "typescript-eslint": "^8.72.1",
56
- "vite": "^8.3.5",
57
- "vitepress": "^1.6.4"
40
+ "dependencies": {
41
+ "@toneflix/studio-audio": "^0.3.0",
42
+ "@toneflix/studio-controls": "^0.3.0",
43
+ "@toneflix/studio-core": "^0.3.0",
44
+ "@toneflix/studio-timeline": "^0.3.0",
45
+ "@toneflix/studio-waveforms": "^0.3.0"
58
46
  },
59
47
  "engines": {
60
48
  "node": ">=22.18"
61
49
  },
62
- "packageManager": "pnpm@12.16.1",
63
50
  "publishConfig": {
64
51
  "access": "public",
65
52
  "provenance": true
53
+ },
54
+ "scripts": {
55
+ "build": "tsc -p tsconfig.build.json"
66
56
  }
67
- }
57
+ }
package/dist/edits.d.ts DELETED
@@ -1,47 +0,0 @@
1
- import { type Clip, type ClipInput, type Source, type TimelineState, type Track } from './types.ts';
2
- /** Shortest clip a trim or split may leave, in seconds. */
3
- export declare const MIN_CLIP = 0.01;
4
- /** A short id that is unique in this page. */
5
- export declare const uid: (prefix?: string) => string;
6
- type Sources = ReadonlyMap<string, Source>;
7
- export declare const makeClip: (input: ClipInput) => Clip;
8
- export declare const addClips: (state: TimelineState, clips: Clip[]) => TimelineState;
9
- export declare const removeClips: (state: TimelineState, ids: ReadonlySet<string>) => TimelineState;
10
- export declare const addTrack: (state: TimelineState, track: Track, index?: number) => TimelineState;
11
- /** Remove a track and its clips. */
12
- export declare const removeTrack: (state: TimelineState, id: string) => TimelineState;
13
- export declare const moveTrack: (state: TimelineState, id: string, index: number) => TimelineState;
14
- export declare const updateTrack: (state: TimelineState, id: string, patch: Partial<Omit<Track, 'id'>>) => TimelineState;
15
- /**
16
- * Move clips by a time shift and a number of lanes. Clips pass over and onto
17
- * other clips freely; only the timeline start and the outer lanes stop them.
18
- */
19
- export declare const moveClips: (state: TimelineState, ids: ReadonlySet<string>, shift: number, lanes?: number) => TimelineState;
20
- /** Move a clip's left edge to a timeline time, revealing or hiding the start of its audio. */
21
- export declare const trimStart: (state: TimelineState, sources: Sources, id: string, time: number) => TimelineState;
22
- /** Move a clip's right edge to a timeline time, up to the end of its audio. */
23
- export declare const trimEnd: (state: TimelineState, sources: Sources, id: string, time: number) => TimelineState;
24
- export declare const setFades: (state: TimelineState, id: string, fades: {
25
- fadeIn?: number;
26
- fadeOut?: number;
27
- }) => TimelineState;
28
- export declare const setGain: (state: TimelineState, ids: ReadonlySet<string>, gain: number) => TimelineState;
29
- /**
30
- * Split clips at a timeline time. The left piece keeps the clip's id and fade
31
- * in; the right piece gets a new id and the fade out. Returns the new ids too.
32
- */
33
- export declare const splitClips: (state: TimelineState, ids: ReadonlySet<string>, time: number) => {
34
- state: {
35
- tracks: readonly Track[];
36
- clips: Clip[];
37
- };
38
- created: string[];
39
- };
40
- /** Copy clips to just after the latest of them, on the same tracks. */
41
- export declare const duplicateClips: (state: TimelineState, ids: ReadonlySet<string>) => {
42
- state: TimelineState;
43
- created: string[];
44
- };
45
- /** Timeline length: the end of the last clip. */
46
- export declare const timelineEnd: (state: TimelineState) => number;
47
- export {};
package/dist/edits.js DELETED
@@ -1,140 +0,0 @@
1
- import { clipEnd } from './types.js';
2
- /** Shortest clip a trim or split may leave, in seconds. */
3
- export const MIN_CLIP = 0.01;
4
- let counter = 0;
5
- /** A short id that is unique in this page. */
6
- export const uid = (prefix = 'c') => `${prefix}${Date.now().toString(36)}${(counter++).toString(36)}`;
7
- const sourceLength = (sources, clip) => sources.get(clip.source)?.duration ?? Infinity;
8
- const replace = (state, ids, fn) => ({
9
- ...state,
10
- clips: state.clips.map((clip) => (ids.has(clip.id) ? fn(clip) : clip)),
11
- });
12
- export const makeClip = (input) => ({
13
- gain: 1,
14
- fadeIn: 0,
15
- fadeOut: 0,
16
- ...input,
17
- id: input.id ?? uid(),
18
- });
19
- export const addClips = (state, clips) => ({
20
- ...state,
21
- clips: [...state.clips, ...clips],
22
- });
23
- export const removeClips = (state, ids) => ({
24
- ...state,
25
- clips: state.clips.filter((clip) => !ids.has(clip.id)),
26
- });
27
- export const addTrack = (state, track, index = state.tracks.length) => {
28
- const tracks = [...state.tracks];
29
- tracks.splice(index, 0, track);
30
- return { ...state, tracks };
31
- };
32
- /** Remove a track and its clips. */
33
- export const removeTrack = (state, id) => ({
34
- tracks: state.tracks.filter((track) => track.id !== id),
35
- clips: state.clips.filter((clip) => clip.track !== id),
36
- });
37
- export const moveTrack = (state, id, index) => {
38
- const from = state.tracks.findIndex((track) => track.id === id);
39
- if (from < 0)
40
- return state;
41
- const tracks = [...state.tracks];
42
- const [track] = tracks.splice(from, 1);
43
- tracks.splice(Math.max(0, Math.min(index, tracks.length)), 0, track);
44
- return { ...state, tracks };
45
- };
46
- export const updateTrack = (state, id, patch) => ({
47
- ...state,
48
- tracks: state.tracks.map((track) => (track.id === id ? { ...track, ...patch } : track)),
49
- });
50
- /**
51
- * Move clips by a time shift and a number of lanes. Clips pass over and onto
52
- * other clips freely; only the timeline start and the outer lanes stop them.
53
- */
54
- export const moveClips = (state, ids, shift, lanes = 0) => {
55
- const moving = state.clips.filter((clip) => ids.has(clip.id));
56
- if (!moving.length)
57
- return state;
58
- const index = new Map(state.tracks.map((track, i) => [track.id, i]));
59
- const earliest = Math.min(...moving.map((clip) => clip.start));
60
- const lanesOf = moving.map((clip) => index.get(clip.track) ?? 0);
61
- const time = Math.max(shift, -earliest);
62
- const lane = Math.max(-Math.min(...lanesOf), Math.min(lanes, state.tracks.length - 1 - Math.max(...lanesOf)));
63
- return replace(state, ids, (clip) => ({
64
- ...clip,
65
- start: clip.start + time,
66
- track: lane ? state.tracks[(index.get(clip.track) ?? 0) + lane].id : clip.track,
67
- }));
68
- };
69
- /** Move a clip's left edge to a timeline time, revealing or hiding the start of its audio. */
70
- export const trimStart = (state, sources, id, time) => replace(state, new Set([id]), (clip) => {
71
- const earliest = Math.max(0, clip.start - clip.offset);
72
- const start = Math.min(Math.max(time, earliest), clipEnd(clip) - MIN_CLIP);
73
- const shift = start - clip.start;
74
- const duration = clip.duration - shift;
75
- return {
76
- ...clip,
77
- start,
78
- offset: clip.offset + shift,
79
- duration,
80
- fadeIn: Math.min(clip.fadeIn, duration),
81
- fadeOut: Math.min(clip.fadeOut, duration - Math.min(clip.fadeIn, duration)),
82
- };
83
- });
84
- /** Move a clip's right edge to a timeline time, up to the end of its audio. */
85
- export const trimEnd = (state, sources, id, time) => replace(state, new Set([id]), (clip) => {
86
- const latest = clip.start + sourceLength(sources, clip) - clip.offset;
87
- const end = Math.max(Math.min(time, latest), clip.start + MIN_CLIP);
88
- const duration = end - clip.start;
89
- return {
90
- ...clip,
91
- duration,
92
- fadeOut: Math.min(clip.fadeOut, duration),
93
- fadeIn: Math.min(clip.fadeIn, duration - Math.min(clip.fadeOut, duration)),
94
- };
95
- });
96
- export const setFades = (state, id, fades) => replace(state, new Set([id]), (clip) => {
97
- const fadeIn = Math.max(0, Math.min(fades.fadeIn ?? clip.fadeIn, clip.duration));
98
- const fadeOut = Math.max(0, Math.min(fades.fadeOut ?? clip.fadeOut, clip.duration - fadeIn));
99
- return { ...clip, fadeIn, fadeOut };
100
- });
101
- export const setGain = (state, ids, gain) => replace(state, ids, (clip) => ({ ...clip, gain: Math.max(0, gain) }));
102
- /**
103
- * Split clips at a timeline time. The left piece keeps the clip's id and fade
104
- * in; the right piece gets a new id and the fade out. Returns the new ids too.
105
- */
106
- export const splitClips = (state, ids, time) => {
107
- const created = [];
108
- const clips = [];
109
- for (const clip of state.clips) {
110
- const cut = time - clip.start;
111
- if (!ids.has(clip.id) || cut < MIN_CLIP || clip.duration - cut < MIN_CLIP) {
112
- clips.push(clip);
113
- continue;
114
- }
115
- const right = {
116
- ...clip,
117
- id: uid(),
118
- start: time,
119
- offset: clip.offset + cut,
120
- duration: clip.duration - cut,
121
- fadeIn: 0,
122
- fadeOut: Math.min(clip.fadeOut, clip.duration - cut),
123
- };
124
- created.push(right.id);
125
- clips.push({ ...clip, duration: cut, fadeIn: Math.min(clip.fadeIn, cut), fadeOut: 0 }, right);
126
- }
127
- return { state: { ...state, clips }, created };
128
- };
129
- /** Copy clips to just after the latest of them, on the same tracks. */
130
- export const duplicateClips = (state, ids) => {
131
- const picked = state.clips.filter((clip) => ids.has(clip.id));
132
- if (!picked.length)
133
- return { state, created: [] };
134
- const from = Math.min(...picked.map((clip) => clip.start));
135
- const to = Math.max(...picked.map(clipEnd));
136
- const copies = picked.map((clip) => ({ ...clip, id: uid(), start: clip.start + (to - from) }));
137
- return { state: addClips(state, copies), created: copies.map((clip) => clip.id) };
138
- };
139
- /** Timeline length: the end of the last clip. */
140
- export const timelineEnd = (state) => state.clips.reduce((end, clip) => Math.max(end, clipEnd(clip)), 0);
package/dist/emitter.d.ts DELETED
@@ -1,10 +0,0 @@
1
- type Listener<T> = (payload: T) => void;
2
- /** A small typed event emitter. */
3
- export declare class Emitter<Events extends Record<string, unknown>> {
4
- private listeners;
5
- on<K extends keyof Events>(event: K, listener: Listener<Events[K]>): () => void;
6
- off<K extends keyof Events>(event: K, listener: Listener<Events[K]>): void;
7
- protected emit<K extends keyof Events>(event: K, payload: Events[K]): void;
8
- removeAllListeners(): void;
9
- }
10
- export {};
package/dist/emitter.js DELETED
@@ -1,24 +0,0 @@
1
- /** A small typed event emitter. */
2
- export class Emitter {
3
- listeners = new Map();
4
- on(event, listener) {
5
- let set = this.listeners.get(event);
6
- if (!set) {
7
- set = new Set();
8
- this.listeners.set(event, set);
9
- }
10
- set.add(listener);
11
- return () => this.off(event, listener);
12
- }
13
- off(event, listener) {
14
- this.listeners.get(event)?.delete(listener);
15
- }
16
- emit(event, payload) {
17
- for (const listener of [...(this.listeners.get(event) ?? [])]) {
18
- listener(payload);
19
- }
20
- }
21
- removeAllListeners() {
22
- this.listeners.clear();
23
- }
24
- }
package/dist/grid.d.ts DELETED
@@ -1,33 +0,0 @@
1
- export type SnapTo = 'off' | 'bar' | 'beat' | '1/8' | '1/16' | '1/32';
2
- export interface GridOptions {
3
- /** Quarter notes per minute */
4
- bpm: number;
5
- /** Beats per bar and the note value of one beat, like [6, 8] */
6
- meter: [number, number];
7
- snap: SnapTo;
8
- }
9
- /** Bars and beats for a tempo and meter, and snapping times to them. */
10
- export declare class Grid {
11
- bpm: number;
12
- meter: [number, number];
13
- snap: SnapTo;
14
- constructor(options?: Partial<GridOptions>);
15
- set(options: Partial<GridOptions>): void;
16
- /** Seconds in one beat of the meter (an eighth note in 6/8). */
17
- get beat(): number;
18
- get bar(): number;
19
- /** Seconds between snap points, or 0 when snapping is off. */
20
- get step(): number;
21
- /** The nearest snap point to a time. */
22
- round(time: number): number;
23
- /** Bar and beat (both from 1) at a time. */
24
- position(time: number): {
25
- bar: number;
26
- beat: number;
27
- };
28
- }
29
- /**
30
- * Picks the closest of several candidate snap targets for a moving edge.
31
- * Returns the time shift to apply, or 0 when nothing is within reach.
32
- */
33
- export declare const nearestSnap: (edges: number[], targets: number[], reach: number) => number;
package/dist/grid.js DELETED
@@ -1,72 +0,0 @@
1
- /** Bars and beats for a tempo and meter, and snapping times to them. */
2
- export class Grid {
3
- bpm;
4
- meter;
5
- snap;
6
- constructor(options = {}) {
7
- this.bpm = options.bpm ?? 120;
8
- this.meter = options.meter ?? [4, 4];
9
- this.snap = options.snap ?? 'beat';
10
- }
11
- set(options) {
12
- if (options.bpm !== undefined)
13
- this.bpm = Math.min(999, Math.max(1, options.bpm));
14
- if (options.meter)
15
- this.meter = options.meter;
16
- if (options.snap)
17
- this.snap = options.snap;
18
- }
19
- /** Seconds in one beat of the meter (an eighth note in 6/8). */
20
- get beat() {
21
- return (60 / this.bpm) * (4 / this.meter[1]);
22
- }
23
- get bar() {
24
- return this.beat * this.meter[0];
25
- }
26
- /** Seconds between snap points, or 0 when snapping is off. */
27
- get step() {
28
- const quarter = 60 / this.bpm;
29
- switch (this.snap) {
30
- case 'bar':
31
- return this.bar;
32
- case 'beat':
33
- return this.beat;
34
- case '1/8':
35
- return quarter / 2;
36
- case '1/16':
37
- return quarter / 4;
38
- case '1/32':
39
- return quarter / 8;
40
- default:
41
- return 0;
42
- }
43
- }
44
- /** The nearest snap point to a time. */
45
- round(time) {
46
- const step = this.step;
47
- return step ? Math.round(time / step) * step : time;
48
- }
49
- /** Bar and beat (both from 1) at a time. */
50
- position(time) {
51
- const beats = Math.floor(time / this.beat + 1e-9);
52
- return { bar: Math.floor(beats / this.meter[0]) + 1, beat: (beats % this.meter[0]) + 1 };
53
- }
54
- }
55
- /**
56
- * Picks the closest of several candidate snap targets for a moving edge.
57
- * Returns the time shift to apply, or 0 when nothing is within reach.
58
- */
59
- export const nearestSnap = (edges, targets, reach) => {
60
- let best = 0;
61
- let bestDistance = reach;
62
- for (const edge of edges) {
63
- for (const target of targets) {
64
- const distance = Math.abs(target - edge);
65
- if (distance < bestDistance) {
66
- bestDistance = distance;
67
- best = target - edge;
68
- }
69
- }
70
- }
71
- return best;
72
- };
package/dist/history.d.ts DELETED
@@ -1,37 +0,0 @@
1
- import { Emitter } from './emitter.ts';
2
- /** One undoable step. */
3
- export interface HistoryEntry {
4
- label: string;
5
- undo(): void;
6
- redo(): void;
7
- }
8
- export interface HistoryInfo {
9
- canUndo: boolean;
10
- canRedo: boolean;
11
- undoLabel?: string;
12
- redoLabel?: string;
13
- }
14
- /**
15
- * The editor's single undo history. The timeline pushes its edits here, and the
16
- * host app can push its own steps (mixer, effects, tempo) into the same list.
17
- */
18
- export declare class History extends Emitter<{
19
- change: HistoryInfo;
20
- }> {
21
- private done;
22
- private undone;
23
- private busy;
24
- readonly limit: number;
25
- constructor(limit?: number);
26
- /** Record a step that has already been applied. */
27
- push(entry: HistoryEntry): void;
28
- undo(): boolean;
29
- redo(): boolean;
30
- clear(): void;
31
- get info(): HistoryInfo;
32
- get canUndo(): boolean;
33
- get canRedo(): boolean;
34
- /** Steps that undo and redo run don't record new entries. */
35
- private run;
36
- private changed;
37
- }