@waveform-playlist/engine 14.0.0-next.2 → 14.0.0-next.4

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
@@ -111,9 +111,9 @@ A `setTempo` places every clip that has a tick on the tick grid of the engine it
111
111
 
112
112
  A different tempo is not converted. A tick is the musical position, so an engine built at another tempo than the one the ticks were made under has clips whose `startSample` and `startTick` disagree until the next `setTempo`, which moves `startSample` to follow the tick. Clips added under the new engine get their ticks at its tempo and keep their place at that `setTempo`, while the older ones move.
113
113
 
114
- An arrangement plays through one engine at a time: building a second engine on it while the first has not been disposed logs a warning. Two engines alive on one arrangement is unsupported, in particular with different `ppqn`: the second engine's time base replaces the first's, so ticks the first engine gives later are computed with the second engine's. The engine's own `undoLimit` option is ignored, with a warning, when an arrangement is passed; set it on `createArrangement({ undoLimit })`. The `arrangement` option accepts only an arrangement made by `createArrangement()`. The engine recognises one by a versioned `Symbol.for` key and not by `instanceof`, so an arrangement made by another installed copy of this package (an app and a library that pin different versions) is accepted as long as both copies use the same key version. The key version changed with the mixer undo steps (`/v2`): an engine and an arrangement from copies on either side of that change refuse each other.
114
+ An arrangement plays through one engine at a time: building a second engine on it while the first has not been disposed logs a warning. Two engines alive on one arrangement is unsupported, in particular with different `ppqn`: the second engine's time base replaces the first's, so ticks the first engine gives later are computed with the second engine's. The engine's own `undoLimit` option is ignored, with a warning, when an arrangement is passed; set it on `createArrangement({ undoLimit })`. The `arrangement` option accepts only an arrangement made by `createArrangement()`. The engine recognises one by a versioned `Symbol.for` key and not by `instanceof`, so an arrangement made by another installed copy of this package (an app and a library that pin different versions) is accepted as long as both copies use the same key version. The key version changed with the mixer undo steps (`/v2`) and again with `addTrack`'s `index` (`/v3`): an engine and an arrangement from copies on either side of such a change refuse each other.
115
115
 
116
- The engine's track, clip, mixer, recording and history methods call the arrangement's, so a change made through either reaches the adapter and emits `statechange`. The arrangement's `removeTrack` also takes `{ undoable: false }` (no undo step, and the track is taken out of every undo and redo state, so no undo brings it back: for a dropped file that could not be decoded), and its `updateTrack` takes a function of the current track: `arrangement.updateTrack(id, (track) => ({ ...track, name: 'Bass' }))`.
116
+ The engine's track, clip, mixer, recording and history methods call the arrangement's, so a change made through either reaches the adapter and emits `statechange`. The arrangement's `removeTrack` also takes `{ undoable: false }` (no undo step, and the track is taken out of every undo and redo state, so no undo brings it back: for a dropped file that could not be decoded), `removeClip(trackId, clipId, options?)` removes a clip (an undo step; `{ undoable: false }` takes it out of every state in the same way), and its `updateTrack` takes a function of the current track: `arrangement.updateTrack(id, (track) => ({ ...track, name: 'Bass' }))`.
117
117
 
118
118
  ### Mixer moves are undo steps
119
119
 
@@ -255,7 +255,7 @@ class PlaylistEngine {
255
255
 
256
256
  // Tracks
257
257
  setTracks(tracks: readonly ClipTrack[]): void; // replaces every track, clears the undo history
258
- addTrack(track: ClipTrack): void;
258
+ addTrack(track: ClipTrack, options?: AddTrackOptions): void; // { index }: where it enters (default: the end)
259
259
  removeTrack(trackId: string): void;
260
260
  updateTrack(trackId: string, track?: ClipTrack): void; // with a track: replace it; without: send the current one to the adapter again
261
261
  reorderTrack(trackId: string, toIndex: number): void;
@@ -308,7 +308,7 @@ class PlaylistEngine {
308
308
  on<K extends keyof EngineEvents>(event: K, listener: EngineEvents[K]): void;
309
309
  off<K extends keyof EngineEvents>(event: K, listener: EngineEvents[K]): void; // 'statechange' | 'play' | 'pause' | 'stop'
310
310
 
311
- dispose(): void;
311
+ dispose(options?: { keepAdapter?: boolean }): void; // keepAdapter: stop, leave the adapter undisposed
312
312
  }
313
313
  ```
314
314
 
@@ -333,8 +333,9 @@ interface Arrangement {
333
333
 
334
334
  // tracks
335
335
  setTracks(tracks: readonly ArrangementTrack[]): void;
336
- addTrack(track: ArrangementTrack): void;
336
+ addTrack(track: ArrangementTrack, options?: AddTrackOptions): void; // { index }: where it enters (default: the end)
337
337
  removeTrack(trackId: string, options?: RemoveTrackOptions): void;
338
+ removeClip(trackId: string, clipId: string, options?: RemoveClipOptions): void; // an undo step; undoable: false takes it out of every state
338
339
  updateTrack(
339
340
  trackId: string,
340
341
  next: ArrangementTrack | ((track: ArrangementTrack) => ArrangementTrack)
@@ -344,7 +345,7 @@ interface Arrangement {
344
345
  // clips (a clip that is still loading cannot be edited)
345
346
  moveClip(trackId: string, clipId: string, deltaSamples: number): number;
346
347
  trimClip(trackId: string, clipId: string, boundary: 'left' | 'right', deltaSamples: number): void;
347
- splitClip(trackId: string, clipId: string, atSample: number): void;
348
+ splitClip(trackId: string, clipId: string, atSample: number): void; // the left half keeps clipId
348
349
  getClipBounds(trackId: string, clipId: string): ClipBounds | null;
349
350
  constrainTrimDelta(trackId: string, clipId: string, boundary: 'left' | 'right', deltaSamples: number): number;
350
351
 
package/dist/index.d.mts CHANGED
@@ -49,6 +49,7 @@ declare function calculateSplitPoint(splitSample: number, samplesPerPixel: numbe
49
49
  *
50
50
  * The left clip retains the original fadeIn; the right clip retains the original fadeOut.
51
51
  * Both clips share the same waveformData reference and the same `src`.
52
+ * The left clip keeps the original's `id`; the right clip gets a new one.
52
53
  * If the clip has a name, suffixes " (1)" and " (2)" are appended.
53
54
  *
54
55
  * @param clip - The clip to split
@@ -245,6 +246,23 @@ interface RemoveTrackOptions {
245
246
  */
246
247
  undoable?: boolean;
247
248
  }
249
+ /** Options of `removeClip`. */
250
+ interface RemoveClipOptions {
251
+ /**
252
+ * `false`: the removal is not an undo step, and the clip is also taken out
253
+ * of every undo and redo state, so no undo or redo brings it back (a
254
+ * `<daw-clip>` the page removed while its track was detached, #848).
255
+ */
256
+ undoable?: boolean;
257
+ }
258
+ /** Options of `addTrack`. */
259
+ interface AddTrackOptions {
260
+ /**
261
+ * Where the track enters: its index in the new order (cut to a whole
262
+ * number, then held between 0 and the number of tracks). Left out: at the end.
263
+ */
264
+ index?: number;
265
+ }
248
266
  /** How a mixer setter's change goes into the undo history. */
249
267
  interface MixerChangeOptions {
250
268
  /** Changes with the same id, one after another, are one undo step. */
@@ -295,8 +313,14 @@ interface Arrangement {
295
313
  * transaction. An id that is in the tracks being replaced keeps its mix.
296
314
  */
297
315
  setTracks(tracks: readonly ArrangementTrack[]): void;
298
- addTrack(track: ArrangementTrack): void;
316
+ /** Add a track: an undo step. Throws for an `index` that is not a finite number. */
317
+ addTrack(track: ArrangementTrack, options?: AddTrackOptions): void;
299
318
  removeTrack(trackId: string, options?: RemoveTrackOptions): void;
319
+ /**
320
+ * Remove a clip from a track: an undo step. With `undoable: false` there is
321
+ * no step, and the clip is also taken out of every undo and redo state.
322
+ */
323
+ removeClip(trackId: string, clipId: string, options?: RemoveClipOptions): void;
300
324
  /**
301
325
  * Replace a track, with a track or with a function of the current one.
302
326
  * Changes nothing for an id no track has (a track object is still checked
@@ -399,9 +423,13 @@ interface CreateArrangementOptions {
399
423
  * v2 (#843): the mixer setters take options and are undo steps, the history
400
424
  * holds the mix (`'restoreMix'`), and the arrangement has the take's mute
401
425
  * (`setTrackRecording`, `recordingTrackIds`, `'recording'`).
426
+ *
427
+ * v3 (#848): `addTrack(track, { index })` puts the track at a place in the order.
402
428
  */
403
429
 
404
430
  type GetDecodeContext = () => Promise<BaseAudioContext>;
431
+ /** True for an arrangement made by `createArrangement()`, of this copy of the package or another. */
432
+ declare function isArrangement(value: unknown): boolean;
405
433
  /**
406
434
  * Give an arrangement the audio context its sources are decoded with.
407
435
  * Nothing is fetched before; the sources its clips name are pending
@@ -545,6 +573,16 @@ interface EngineState {
545
573
  /** Whether redo is available. */
546
574
  canRedo: boolean;
547
575
  }
576
+ /** Options of `PlaylistEngine.dispose()`. */
577
+ interface EngineDisposeOptions {
578
+ /**
579
+ * Leave the adapter undisposed (#848), for a host that plays another
580
+ * arrangement on the same adapter next: playback is stopped, the engine
581
+ * lets go of its arrangement and of the adapter's `onPlaybackEnded`, and a
582
+ * new engine can be built with the adapter.
583
+ */
584
+ keepAdapter?: boolean;
585
+ }
548
586
  /**
549
587
  * Configuration options for PlaylistEngine constructor.
550
588
  */
@@ -635,7 +673,7 @@ declare class PlaylistEngine {
635
673
  abortTransaction(): void;
636
674
  getState(): EngineState;
637
675
  setTracks(tracks: readonly ClipTrack[]): void;
638
- addTrack(track: ClipTrack): void;
676
+ addTrack(track: ClipTrack, options?: AddTrackOptions): void;
639
677
  removeTrack(trackId: string): void;
640
678
  /**
641
679
  * Move a track to a new position in the track order. Purely organizational —
@@ -723,7 +761,7 @@ declare class PlaylistEngine {
723
761
  setZoomLevel(samplesPerPixel: number): void;
724
762
  on<K extends EventName>(event: K, listener: EngineEvents[K]): void;
725
763
  off<K extends EventName>(event: K, listener: EngineEvents[K]): void;
726
- dispose(): void;
764
+ dispose(options?: EngineDisposeOptions): void;
727
765
  /** Runs a mixer setter on the arrangement. True when a value changed. */
728
766
  private _mixerChanged;
729
767
  /**
@@ -757,4 +795,4 @@ declare class PlaylistEngine {
757
795
  private _emitStateChange;
758
796
  }
759
797
 
760
- export { type Arrangement, type ArrangementSourceState, type ArrangementSourcesValue, type ClipBounds, type CreateArrangementOptions, type EngineEvents, type EngineState, type LoadSource, type MixerChangeOptions, PlaylistEngine, type PlaylistEngineOptions, type PlayoutAdapter, type RemoveTrackOptions, type TrackMixerValues, attachDecodeContext, calculateDuration, calculateSplitPoint, calculateViewportBounds, calculateZoomScrollPosition, canSplitAt, clampSeekPosition, constrainBoundaryTrim, constrainClipDrag, createArrangement, defaultLoadSource, findClosestZoomIndex, getVisibleChunkIndices, shouldUpdateViewport, splitClip };
798
+ export { type AddTrackOptions, type Arrangement, type ArrangementSourceState, type ArrangementSourcesValue, type ClipBounds, type CreateArrangementOptions, type EngineDisposeOptions, type EngineEvents, type EngineState, type LoadSource, type MixerChangeOptions, PlaylistEngine, type PlaylistEngineOptions, type PlayoutAdapter, type RemoveClipOptions, type RemoveTrackOptions, type TrackMixerValues, attachDecodeContext, calculateDuration, calculateSplitPoint, calculateViewportBounds, calculateZoomScrollPosition, canSplitAt, clampSeekPosition, constrainBoundaryTrim, constrainClipDrag, createArrangement, defaultLoadSource, findClosestZoomIndex, getVisibleChunkIndices, isArrangement, shouldUpdateViewport, splitClip };
package/dist/index.d.ts CHANGED
@@ -49,6 +49,7 @@ declare function calculateSplitPoint(splitSample: number, samplesPerPixel: numbe
49
49
  *
50
50
  * The left clip retains the original fadeIn; the right clip retains the original fadeOut.
51
51
  * Both clips share the same waveformData reference and the same `src`.
52
+ * The left clip keeps the original's `id`; the right clip gets a new one.
52
53
  * If the clip has a name, suffixes " (1)" and " (2)" are appended.
53
54
  *
54
55
  * @param clip - The clip to split
@@ -245,6 +246,23 @@ interface RemoveTrackOptions {
245
246
  */
246
247
  undoable?: boolean;
247
248
  }
249
+ /** Options of `removeClip`. */
250
+ interface RemoveClipOptions {
251
+ /**
252
+ * `false`: the removal is not an undo step, and the clip is also taken out
253
+ * of every undo and redo state, so no undo or redo brings it back (a
254
+ * `<daw-clip>` the page removed while its track was detached, #848).
255
+ */
256
+ undoable?: boolean;
257
+ }
258
+ /** Options of `addTrack`. */
259
+ interface AddTrackOptions {
260
+ /**
261
+ * Where the track enters: its index in the new order (cut to a whole
262
+ * number, then held between 0 and the number of tracks). Left out: at the end.
263
+ */
264
+ index?: number;
265
+ }
248
266
  /** How a mixer setter's change goes into the undo history. */
249
267
  interface MixerChangeOptions {
250
268
  /** Changes with the same id, one after another, are one undo step. */
@@ -295,8 +313,14 @@ interface Arrangement {
295
313
  * transaction. An id that is in the tracks being replaced keeps its mix.
296
314
  */
297
315
  setTracks(tracks: readonly ArrangementTrack[]): void;
298
- addTrack(track: ArrangementTrack): void;
316
+ /** Add a track: an undo step. Throws for an `index` that is not a finite number. */
317
+ addTrack(track: ArrangementTrack, options?: AddTrackOptions): void;
299
318
  removeTrack(trackId: string, options?: RemoveTrackOptions): void;
319
+ /**
320
+ * Remove a clip from a track: an undo step. With `undoable: false` there is
321
+ * no step, and the clip is also taken out of every undo and redo state.
322
+ */
323
+ removeClip(trackId: string, clipId: string, options?: RemoveClipOptions): void;
300
324
  /**
301
325
  * Replace a track, with a track or with a function of the current one.
302
326
  * Changes nothing for an id no track has (a track object is still checked
@@ -399,9 +423,13 @@ interface CreateArrangementOptions {
399
423
  * v2 (#843): the mixer setters take options and are undo steps, the history
400
424
  * holds the mix (`'restoreMix'`), and the arrangement has the take's mute
401
425
  * (`setTrackRecording`, `recordingTrackIds`, `'recording'`).
426
+ *
427
+ * v3 (#848): `addTrack(track, { index })` puts the track at a place in the order.
402
428
  */
403
429
 
404
430
  type GetDecodeContext = () => Promise<BaseAudioContext>;
431
+ /** True for an arrangement made by `createArrangement()`, of this copy of the package or another. */
432
+ declare function isArrangement(value: unknown): boolean;
405
433
  /**
406
434
  * Give an arrangement the audio context its sources are decoded with.
407
435
  * Nothing is fetched before; the sources its clips name are pending
@@ -545,6 +573,16 @@ interface EngineState {
545
573
  /** Whether redo is available. */
546
574
  canRedo: boolean;
547
575
  }
576
+ /** Options of `PlaylistEngine.dispose()`. */
577
+ interface EngineDisposeOptions {
578
+ /**
579
+ * Leave the adapter undisposed (#848), for a host that plays another
580
+ * arrangement on the same adapter next: playback is stopped, the engine
581
+ * lets go of its arrangement and of the adapter's `onPlaybackEnded`, and a
582
+ * new engine can be built with the adapter.
583
+ */
584
+ keepAdapter?: boolean;
585
+ }
548
586
  /**
549
587
  * Configuration options for PlaylistEngine constructor.
550
588
  */
@@ -635,7 +673,7 @@ declare class PlaylistEngine {
635
673
  abortTransaction(): void;
636
674
  getState(): EngineState;
637
675
  setTracks(tracks: readonly ClipTrack[]): void;
638
- addTrack(track: ClipTrack): void;
676
+ addTrack(track: ClipTrack, options?: AddTrackOptions): void;
639
677
  removeTrack(trackId: string): void;
640
678
  /**
641
679
  * Move a track to a new position in the track order. Purely organizational —
@@ -723,7 +761,7 @@ declare class PlaylistEngine {
723
761
  setZoomLevel(samplesPerPixel: number): void;
724
762
  on<K extends EventName>(event: K, listener: EngineEvents[K]): void;
725
763
  off<K extends EventName>(event: K, listener: EngineEvents[K]): void;
726
- dispose(): void;
764
+ dispose(options?: EngineDisposeOptions): void;
727
765
  /** Runs a mixer setter on the arrangement. True when a value changed. */
728
766
  private _mixerChanged;
729
767
  /**
@@ -757,4 +795,4 @@ declare class PlaylistEngine {
757
795
  private _emitStateChange;
758
796
  }
759
797
 
760
- export { type Arrangement, type ArrangementSourceState, type ArrangementSourcesValue, type ClipBounds, type CreateArrangementOptions, type EngineEvents, type EngineState, type LoadSource, type MixerChangeOptions, PlaylistEngine, type PlaylistEngineOptions, type PlayoutAdapter, type RemoveTrackOptions, type TrackMixerValues, attachDecodeContext, calculateDuration, calculateSplitPoint, calculateViewportBounds, calculateZoomScrollPosition, canSplitAt, clampSeekPosition, constrainBoundaryTrim, constrainClipDrag, createArrangement, defaultLoadSource, findClosestZoomIndex, getVisibleChunkIndices, shouldUpdateViewport, splitClip };
798
+ export { type AddTrackOptions, type Arrangement, type ArrangementSourceState, type ArrangementSourcesValue, type ClipBounds, type CreateArrangementOptions, type EngineDisposeOptions, type EngineEvents, type EngineState, type LoadSource, type MixerChangeOptions, PlaylistEngine, type PlaylistEngineOptions, type PlayoutAdapter, type RemoveClipOptions, type RemoveTrackOptions, type TrackMixerValues, attachDecodeContext, calculateDuration, calculateSplitPoint, calculateViewportBounds, calculateZoomScrollPosition, canSplitAt, clampSeekPosition, constrainBoundaryTrim, constrainClipDrag, createArrangement, defaultLoadSource, findClosestZoomIndex, getVisibleChunkIndices, isArrangement, shouldUpdateViewport, splitClip };
package/dist/index.js CHANGED
@@ -34,6 +34,7 @@ __export(index_exports, {
34
34
  defaultLoadSource: () => defaultLoadSource,
35
35
  findClosestZoomIndex: () => findClosestZoomIndex,
36
36
  getVisibleChunkIndices: () => getVisibleChunkIndices,
37
+ isArrangement: () => isArrangement,
37
38
  shouldUpdateViewport: () => shouldUpdateViewport,
38
39
  splitClip: () => splitClip
39
40
  });
@@ -87,20 +88,23 @@ function splitClip(clip, splitSample) {
87
88
  const rightDuration = clip.durationSamples - leftDuration;
88
89
  const leftName = clip.name ? `${clip.name} (1)` : void 0;
89
90
  const rightName = clip.name ? `${clip.name} (2)` : void 0;
90
- const left = (0, import_core.createClip)({
91
- startSample: clip.startSample,
92
- durationSamples: leftDuration,
93
- offsetSamples: clip.offsetSamples,
94
- sampleRate: clip.sampleRate,
95
- sourceDurationSamples: clip.sourceDurationSamples,
96
- gain: clip.gain,
97
- name: leftName,
98
- color: clip.color,
99
- fadeIn: clip.fadeIn,
100
- audioBuffer: clip.audioBuffer,
101
- waveformData: clip.waveformData,
102
- src: clip.src
103
- });
91
+ const left = {
92
+ ...(0, import_core.createClip)({
93
+ startSample: clip.startSample,
94
+ durationSamples: leftDuration,
95
+ offsetSamples: clip.offsetSamples,
96
+ sampleRate: clip.sampleRate,
97
+ sourceDurationSamples: clip.sourceDurationSamples,
98
+ gain: clip.gain,
99
+ name: leftName,
100
+ color: clip.color,
101
+ fadeIn: clip.fadeIn,
102
+ audioBuffer: clip.audioBuffer,
103
+ waveformData: clip.waveformData,
104
+ src: clip.src
105
+ }),
106
+ id: clip.id
107
+ };
104
108
  const right = (0, import_core.createClip)({
105
109
  startSample: splitSample,
106
110
  durationSamples: rightDuration,
@@ -194,10 +198,10 @@ var import_core7 = require("@waveform-playlist/core");
194
198
 
195
199
  // src/arrangement/attach.ts
196
200
  var ARRANGEMENT_ATTACH_DECODE = /* @__PURE__ */ Symbol.for(
197
- "@waveform-playlist/engine/arrangement/attach-decode/v2"
201
+ "@waveform-playlist/engine/arrangement/attach-decode/v3"
198
202
  );
199
203
  var ARRANGEMENT_ATTACH_TIME_BASE = /* @__PURE__ */ Symbol.for(
200
- "@waveform-playlist/engine/arrangement/time-base/v2"
204
+ "@waveform-playlist/engine/arrangement/time-base/v3"
201
205
  );
202
206
  function attachPoints(value) {
203
207
  return typeof value === "object" && value !== null ? value : {};
@@ -904,7 +908,56 @@ function mapHistoryStates(history, map) {
904
908
  return { undo: history.undo.map(map), redo: history.redo.map(map) };
905
909
  }
906
910
  function purgeTrack(history, current, trackId, base = null) {
907
- const strip = stateWithoutTrack(trackId);
911
+ return purgeStates(history, current, stateWithoutTrack(trackId), base);
912
+ }
913
+ function purgeClip(history, current, trackId, clipId, base = null) {
914
+ return purgeStates(
915
+ history,
916
+ current,
917
+ stateWithoutClip(history, current, trackId, clipId, base),
918
+ base
919
+ );
920
+ }
921
+ function stateWithoutClip(history, current, trackId, clipId, base = null) {
922
+ const inOrder = [
923
+ ...history.undo,
924
+ ...base ? [base] : [],
925
+ current,
926
+ ...[...history.redo].reverse()
927
+ ];
928
+ const mapped = /* @__PURE__ */ new Map();
929
+ let before;
930
+ let stripped = false;
931
+ for (const state of inOrder) {
932
+ const known = mapped.get(state);
933
+ if (known) {
934
+ before = known.tracks.find((t) => t.id === trackId);
935
+ continue;
936
+ }
937
+ const track = state.tracks.find((t) => t.id === trackId);
938
+ let next = track;
939
+ if (track?.clips.some((c) => c.id === clipId)) {
940
+ next = { ...track, clips: track.clips.filter((c) => c.id !== clipId) };
941
+ stripped = true;
942
+ }
943
+ if (stripped && next && before && next !== before && sameTrackFields(before, next))
944
+ next = before;
945
+ mapped.set(
946
+ state,
947
+ next === track ? state : { tracks: state.tracks.map((t) => t === track ? next : t), mixer: state.mixer }
948
+ );
949
+ before = next;
950
+ }
951
+ return (state) => mapped.get(state) ?? state;
952
+ }
953
+ function sameTrackFields(a, b) {
954
+ const keys = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)]);
955
+ for (const key of keys) {
956
+ if (key !== "clips" && a[key] !== b[key]) return false;
957
+ }
958
+ return a.clips.length === b.clips.length && a.clips.every((c, i) => c === b.clips[i]);
959
+ }
960
+ function purgeStates(history, current, strip, base) {
908
961
  const nextCurrent = strip(current);
909
962
  const nextBase = base && strip(base);
910
963
  const stripped = dropRepeats(mapHistoryStates(history, strip), nextBase ?? nextCurrent);
@@ -1019,6 +1072,15 @@ function duplicateTrackId(trackId) {
1019
1072
  var DEFAULT_MIN_DURATION_SECONDS = 0.1;
1020
1073
  var DEFAULT_UNDO_LIMIT = 100;
1021
1074
  var EMPTY_RECORDING = /* @__PURE__ */ new Set();
1075
+ function insertIndex(index, length) {
1076
+ if (index === void 0) return length;
1077
+ if (typeof index !== "number" || !Number.isFinite(index)) {
1078
+ throw new TypeError(
1079
+ `[waveform-playlist] addTrack: index must be a finite number, got ${String(index)}`
1080
+ );
1081
+ }
1082
+ return Math.max(0, Math.min(Math.trunc(index), length));
1083
+ }
1022
1084
  var ArrangementImpl = class {
1023
1085
  constructor(options = {}) {
1024
1086
  this._tracks = [];
@@ -1249,13 +1311,14 @@ var ArrangementImpl = class {
1249
1311
  this._tracksVersion++;
1250
1312
  this._emit({ type: "set" });
1251
1313
  }
1252
- addTrack(track) {
1314
+ addTrack(track, options) {
1315
+ const index = insertIndex(options?.index, this._tracks.length);
1253
1316
  assertClipsOfTrackKind(track);
1254
1317
  assertUniqueClipIds(track);
1255
1318
  if (this._tracks.some((t) => t.id === track.id)) throw duplicateTrackId(track.id);
1256
1319
  this._pushUndoSnapshot();
1257
1320
  const enriched = this._ingest(track);
1258
- this._tracks = [...this._tracks, enriched];
1321
+ this._tracks = [...this._tracks.slice(0, index), enriched, ...this._tracks.slice(index)];
1259
1322
  this._mixer = seedMixer(this._mixer, [enriched]);
1260
1323
  this._tracksVersion++;
1261
1324
  this._emit({ type: "add", trackId: track.id });
@@ -1277,6 +1340,21 @@ var ArrangementImpl = class {
1277
1340
  this._tracksVersion++;
1278
1341
  this._emit({ type: "remove", trackId });
1279
1342
  }
1343
+ /**
1344
+ * Remove a clip from a track: an undo step. With `undoable: false` there is
1345
+ * no step, and the clip is also taken out of every undo and redo state, so
1346
+ * that no undo or redo brings it back (#848: a `<daw-clip>` the page removed
1347
+ * while its track was detached).
1348
+ */
1349
+ removeClip(trackId, clipId, options) {
1350
+ if (options?.undoable === false) {
1351
+ this._removeClipEverywhere(trackId, clipId);
1352
+ return;
1353
+ }
1354
+ const current = this._tracks.find((t) => t.id === trackId);
1355
+ if (!current?.clips.some((c) => c.id === clipId)) return;
1356
+ this.updateTrack(trackId, (t) => ({ ...t, clips: t.clips.filter((c) => c.id !== clipId) }));
1357
+ }
1280
1358
  /**
1281
1359
  * Move a track to a new position in the track order. Purely organizational —
1282
1360
  * track order is not audible.
@@ -1558,6 +1636,29 @@ var ArrangementImpl = class {
1558
1636
  this._resyncSourcesQuietly();
1559
1637
  }
1560
1638
  }
1639
+ /** `removeClip` with `undoable: false`: out of the current tracks and out of every stored state. */
1640
+ _removeClipEverywhere(trackId, clipId) {
1641
+ const previous = this._tracks.find((t) => t.id === trackId);
1642
+ const base = this._transaction?.state ?? null;
1643
+ const purged = purgeClip(this._history, this._currentState(), trackId, clipId, base);
1644
+ const historyChanged = purged.history !== this._history;
1645
+ const baseChanged = purged.base !== base;
1646
+ this._history = purged.history;
1647
+ if (this._transaction && purged.base) {
1648
+ this._transaction = { ...this._transaction, state: purged.base };
1649
+ }
1650
+ if (purged.current.tracks !== this._tracks && previous) {
1651
+ this._gesture = null;
1652
+ this._tracks = purged.current.tracks;
1653
+ this._tracksVersion++;
1654
+ this._emit({ type: "update", trackId, previous });
1655
+ } else if (historyChanged) {
1656
+ this._gesture = null;
1657
+ this._emit({ type: "history" });
1658
+ } else if (baseChanged) {
1659
+ this._resyncSourcesQuietly();
1660
+ }
1661
+ }
1561
1662
  /** The state before a change: an undo step, or the mark that an open transaction changed. */
1562
1663
  _pushUndoSnapshot() {
1563
1664
  if (this._transaction) {
@@ -2112,8 +2213,8 @@ var PlaylistEngine = class {
2112
2213
  setTracks(tracks) {
2113
2214
  this._arrangement.setTracks(tracks);
2114
2215
  }
2115
- addTrack(track) {
2116
- this._arrangement.addTrack(track);
2216
+ addTrack(track, options) {
2217
+ this._arrangement.addTrack(track, options);
2117
2218
  }
2118
2219
  removeTrack(trackId) {
2119
2220
  this._arrangement.removeTrack(trackId);
@@ -2429,8 +2530,9 @@ var PlaylistEngine = class {
2429
2530
  // ---------------------------------------------------------------------------
2430
2531
  // Lifecycle
2431
2532
  // ---------------------------------------------------------------------------
2432
- dispose() {
2533
+ dispose(options = {}) {
2433
2534
  if (this._disposed) return;
2535
+ if (options.keepAdapter && this._isPlaying) this.stop();
2434
2536
  this._disposed = true;
2435
2537
  this._stopFollowingArrangement();
2436
2538
  this._detachFromArrangement();
@@ -2439,7 +2541,8 @@ var PlaylistEngine = class {
2439
2541
  this._isPlaying = false;
2440
2542
  this._adapter?.onPlaybackEnded?.(null);
2441
2543
  try {
2442
- this._adapter?.dispose();
2544
+ if (options.keepAdapter) this._adapter?.setTracks([]);
2545
+ else this._adapter?.dispose();
2443
2546
  } catch (err) {
2444
2547
  console.warn("[waveform-playlist/engine] Error disposing adapter:", err);
2445
2548
  }
@@ -2576,6 +2679,7 @@ function asArrangementImpl(arrangement) {
2576
2679
  defaultLoadSource,
2577
2680
  findClosestZoomIndex,
2578
2681
  getVisibleChunkIndices,
2682
+ isArrangement,
2579
2683
  shouldUpdateViewport,
2580
2684
  splitClip
2581
2685
  });