@waveform-playlist/engine 14.0.0-next.1 → 14.0.0-next.10

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/dist/index.js CHANGED
@@ -20,7 +20,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
- PlaylistEngine: () => PlaylistEngine,
23
+ EditorEngine: () => EditorEngine,
24
24
  attachDecodeContext: () => attachDecodeContext,
25
25
  calculateDuration: () => calculateDuration,
26
26
  calculateSplitPoint: () => calculateSplitPoint,
@@ -32,52 +32,71 @@ __export(index_exports, {
32
32
  constrainClipDrag: () => constrainClipDrag,
33
33
  createArrangement: () => createArrangement,
34
34
  defaultLoadSource: () => defaultLoadSource,
35
+ findClipOverlap: () => findClipOverlap,
35
36
  findClosestZoomIndex: () => findClosestZoomIndex,
36
37
  getVisibleChunkIndices: () => getVisibleChunkIndices,
38
+ isArrangement: () => isArrangement,
37
39
  shouldUpdateViewport: () => shouldUpdateViewport,
38
- splitClip: () => splitClip
40
+ splitClip: () => splitClip,
41
+ trackClipSpans: () => trackClipSpans
39
42
  });
40
43
  module.exports = __toCommonJS(index_exports);
41
44
 
42
45
  // src/operations/clipOperations.ts
43
46
  var import_core = require("@waveform-playlist/core");
47
+ var spansMemo = /* @__PURE__ */ new WeakMap();
48
+ function trackClipSpans(clips, sampleRate) {
49
+ const memo = spansMemo.get(clips);
50
+ if (memo && memo.sampleRate === sampleRate) return memo.spans;
51
+ const spans = [];
52
+ for (const clip of clips) {
53
+ if (!(0, import_core.isLoadingClip)(clip)) {
54
+ spans.push(clip);
55
+ continue;
56
+ }
57
+ const span = (0, import_core.loadingClipSpan)(clip, sampleRate);
58
+ if (!span) continue;
59
+ const durationSamples = span.endSample === null ? 1 : span.endSample - span.startSample;
60
+ spans.push({ id: clip.id, startSample: span.startSample, durationSamples });
61
+ }
62
+ spans.sort((a, b) => a.startSample - b.startSample);
63
+ spansMemo.set(clips, { sampleRate, spans });
64
+ return spans;
65
+ }
66
+ function clampKeepingZero(delta, lower, upper) {
67
+ const clamped = Math.min(Math.max(delta, Math.min(lower, 0)), Math.max(upper, 0));
68
+ return clamped === 0 ? 0 : clamped;
69
+ }
44
70
  function constrainClipDrag(clip, deltaSamples, sortedClips, clipIndex) {
45
- let delta = deltaSamples;
46
- const minDelta = -clip.startSample;
47
- delta = Math.max(delta, minDelta);
71
+ let lower = -clip.startSample;
72
+ let upper = Number.POSITIVE_INFINITY;
48
73
  if (clipIndex > 0) {
49
74
  const prevClip = sortedClips[clipIndex - 1];
50
- const prevClipEnd = prevClip.startSample + prevClip.durationSamples;
51
- const minDeltaPrev = prevClipEnd - clip.startSample;
52
- delta = Math.max(delta, minDeltaPrev);
75
+ lower = Math.max(lower, prevClip.startSample + prevClip.durationSamples - clip.startSample);
53
76
  }
54
77
  if (clipIndex < sortedClips.length - 1) {
55
78
  const nextClip = sortedClips[clipIndex + 1];
56
- const maxDeltaNext = nextClip.startSample - (clip.startSample + clip.durationSamples);
57
- delta = Math.min(delta, maxDeltaNext);
79
+ upper = Math.min(upper, nextClip.startSample - (clip.startSample + clip.durationSamples));
58
80
  }
59
- return delta;
81
+ return clampKeepingZero(deltaSamples, lower, upper);
60
82
  }
61
83
  function constrainBoundaryTrim(clip, deltaSamples, boundary, sortedClips, clipIndex, minDurationSamples) {
62
- let delta = deltaSamples;
63
84
  if (boundary === "left") {
64
- delta = Math.max(delta, -clip.startSample);
65
- delta = Math.max(delta, -clip.offsetSamples);
85
+ let lower2 = Math.max(-clip.startSample, -clip.offsetSamples);
66
86
  if (clipIndex > 0) {
67
87
  const prevClip = sortedClips[clipIndex - 1];
68
- const prevClipEnd = prevClip.startSample + prevClip.durationSamples;
69
- delta = Math.max(delta, prevClipEnd - clip.startSample);
70
- }
71
- delta = Math.min(delta, clip.durationSamples - minDurationSamples);
72
- } else {
73
- delta = Math.max(delta, minDurationSamples - clip.durationSamples);
74
- delta = Math.min(delta, clip.sourceDurationSamples - clip.offsetSamples - clip.durationSamples);
75
- if (clipIndex < sortedClips.length - 1) {
76
- const nextClip = sortedClips[clipIndex + 1];
77
- delta = Math.min(delta, nextClip.startSample - clip.startSample - clip.durationSamples);
88
+ lower2 = Math.max(lower2, prevClip.startSample + prevClip.durationSamples - clip.startSample);
78
89
  }
90
+ const upper2 = clip.durationSamples - minDurationSamples;
91
+ return clampKeepingZero(deltaSamples, lower2, upper2);
92
+ }
93
+ const lower = minDurationSamples - clip.durationSamples;
94
+ let upper = clip.sourceDurationSamples - clip.offsetSamples - clip.durationSamples;
95
+ if (clipIndex < sortedClips.length - 1) {
96
+ const nextClip = sortedClips[clipIndex + 1];
97
+ upper = Math.min(upper, nextClip.startSample - clip.startSample - clip.durationSamples);
79
98
  }
80
- return delta;
99
+ return clampKeepingZero(deltaSamples, lower, upper);
81
100
  }
82
101
  function calculateSplitPoint(splitSample, samplesPerPixel) {
83
102
  return Math.floor(splitSample / samplesPerPixel) * samplesPerPixel;
@@ -85,22 +104,31 @@ function calculateSplitPoint(splitSample, samplesPerPixel) {
85
104
  function splitClip(clip, splitSample) {
86
105
  const leftDuration = splitSample - clip.startSample;
87
106
  const rightDuration = clip.durationSamples - leftDuration;
107
+ const midi = {
108
+ midiNotes: clip.midiNotes,
109
+ midiChannel: clip.midiChannel,
110
+ midiProgram: clip.midiProgram
111
+ };
88
112
  const leftName = clip.name ? `${clip.name} (1)` : void 0;
89
113
  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
- });
114
+ const left = {
115
+ ...(0, import_core.createClip)({
116
+ startSample: clip.startSample,
117
+ durationSamples: leftDuration,
118
+ offsetSamples: clip.offsetSamples,
119
+ sampleRate: clip.sampleRate,
120
+ sourceDurationSamples: clip.sourceDurationSamples,
121
+ gain: clip.gain,
122
+ name: leftName,
123
+ color: clip.color,
124
+ fadeIn: clip.fadeIn,
125
+ audioBuffer: clip.audioBuffer,
126
+ waveformData: clip.waveformData,
127
+ src: clip.src,
128
+ ...midi
129
+ }),
130
+ id: clip.id
131
+ };
104
132
  const right = (0, import_core.createClip)({
105
133
  startSample: splitSample,
106
134
  durationSamples: rightDuration,
@@ -113,7 +141,8 @@ function splitClip(clip, splitSample) {
113
141
  fadeOut: clip.fadeOut,
114
142
  audioBuffer: clip.audioBuffer,
115
143
  waveformData: clip.waveformData,
116
- src: clip.src
144
+ src: clip.src,
145
+ ...midi
117
146
  });
118
147
  return { left, right };
119
148
  }
@@ -190,14 +219,14 @@ function clampSeekPosition(time, duration) {
190
219
  }
191
220
 
192
221
  // src/arrangement/Arrangement.ts
193
- var import_core7 = require("@waveform-playlist/core");
222
+ var import_core8 = require("@waveform-playlist/core");
194
223
 
195
224
  // src/arrangement/attach.ts
196
225
  var ARRANGEMENT_ATTACH_DECODE = /* @__PURE__ */ Symbol.for(
197
- "@waveform-playlist/engine/arrangement/attach-decode/v1"
226
+ "@waveform-playlist/engine/arrangement/attach-decode/v3"
198
227
  );
199
228
  var ARRANGEMENT_ATTACH_TIME_BASE = /* @__PURE__ */ Symbol.for(
200
- "@waveform-playlist/engine/arrangement/time-base/v1"
229
+ "@waveform-playlist/engine/arrangement/time-base/v3"
201
230
  );
202
231
  function attachPoints(value) {
203
232
  return typeof value === "object" && value !== null ? value : {};
@@ -221,8 +250,9 @@ function attachTimeBase(arrangement, timeBase) {
221
250
 
222
251
  // src/arrangement/clipEdits.ts
223
252
  var import_core2 = require("@waveform-playlist/core");
224
- function loadedClips(track) {
225
- return track.clips.filter((clip) => !(0, import_core2.isLoadingClip)(clip));
253
+ function neighboursOf(track, clip) {
254
+ const sortedClips = trackClipSpans(track.clips, clip.sampleRate);
255
+ return { sortedClips, sortedIndex: sortedClips.indexOf(clip) };
226
256
  }
227
257
  function loadedClip(tracks, trackId, clipId) {
228
258
  const clip = tracks.find((t) => t.id === trackId)?.clips.find((c) => c.id === clipId);
@@ -267,8 +297,7 @@ function constrainTrim(tracks, trackId, clipId, boundary, deltaSamples, time) {
267
297
  const track = tracks.find((t) => t.id === trackId);
268
298
  const clip = loadedClip(tracks, trackId, clipId);
269
299
  if (!track || !clip) return 0;
270
- const sortedClips = (0, import_core2.sortClipsByTime)(loadedClips(track));
271
- const sortedIndex = sortedClips.findIndex((c) => c.id === clipId);
300
+ const { sortedClips, sortedIndex } = neighboursOf(track, clip);
272
301
  return constrainBoundaryTrim(
273
302
  clip,
274
303
  deltaSamples,
@@ -282,8 +311,7 @@ function moveClip(tracks, trackId, clipId, deltaSamples, time) {
282
311
  const found = findClip(tracks, trackId, clipId, "moveClip");
283
312
  if (!found) return null;
284
313
  const { track, clip, clipIndex } = found;
285
- const sortedClips = (0, import_core2.sortClipsByTime)(loadedClips(track));
286
- const sortedIndex = sortedClips.findIndex((c) => c.id === clipId);
314
+ const { sortedClips, sortedIndex } = neighboursOf(track, clip);
287
315
  const delta = constrainClipDrag(clip, deltaSamples, sortedClips, sortedIndex);
288
316
  if (delta === 0) return null;
289
317
  const startSample = Math.floor(clip.startSample + delta);
@@ -433,6 +461,7 @@ var import_core4 = require("@waveform-playlist/core");
433
461
 
434
462
  // src/arrangement/resolveLoadingClip.ts
435
463
  var import_core3 = require("@waveform-playlist/core");
464
+ var NOTHING_LEFT = /* @__PURE__ */ Symbol("nothing left");
436
465
  var warned = /* @__PURE__ */ new WeakMap();
437
466
  function label(loading) {
438
467
  return `clip "${loading.id}"`;
@@ -462,10 +491,10 @@ function fieldProblem(loading) {
462
491
  return null;
463
492
  }
464
493
  function fitDuration(loading, offsetSamples, total, rate) {
465
- if (!(offsetSamples < total)) return { problem: "offset is at or past the end of the audio" };
494
+ if (!(offsetSamples < total)) return NOTHING_LEFT;
466
495
  const rest = total - offsetSamples;
467
496
  const duration = givenDuration(loading);
468
- const wanted = duration === void 0 ? rest : Math.round(duration * rate);
497
+ const wanted = duration === void 0 ? rest : (0, import_core3.durationSamplesFromSeconds)(loading.start ?? 0, duration, rate);
469
498
  if (!(wanted >= 1)) return { problem: "duration is shorter than one sample" };
470
499
  if (wanted > rest + 1) {
471
500
  warnOnce(loading, "duration runs past the end of the audio and was cut to it");
@@ -485,6 +514,7 @@ function convert(loading, buffer) {
485
514
  return "start or offset is too large";
486
515
  }
487
516
  const fitted = fitDuration(loading, offsetSamples, buffer.length, rate);
517
+ if (fitted === NOTHING_LEFT) return NOTHING_LEFT;
488
518
  if ("problem" in fitted) return fitted.problem;
489
519
  return {
490
520
  ...(0, import_core3.createClip)({
@@ -510,8 +540,33 @@ function resolveLoadingClip(loading, buffer) {
510
540
  } catch (error) {
511
541
  converted = error instanceof Error ? error.message : String(error);
512
542
  }
543
+ if (converted === NOTHING_LEFT) {
544
+ warnOnce(loading, "its offset is at or past the end of its audio; the clip is removed");
545
+ return { removed: `${label(loading)}: its offset is at or past the end of its audio` };
546
+ }
513
547
  return typeof converted === "string" ? { unusable: `${label(loading)}: ${converted}` } : { clip: converted };
514
548
  }
549
+ var cuts = /* @__PURE__ */ new WeakMap();
550
+ function fitArrivedClip(loading, clip, others) {
551
+ const start = clip.startSample;
552
+ const end = start + clip.durationSamples;
553
+ const covering = others.find(
554
+ (o) => o.startSample <= start && o.startSample + o.durationSamples > start
555
+ );
556
+ if (covering) {
557
+ return { unusable: `${label(loading)}: its start lies inside clip "${covering.id}"` };
558
+ }
559
+ const next = others.find((o) => o.startSample > start);
560
+ if (!next || next.startSample >= end) return { clip };
561
+ warnOnce(loading, `its audio ran into clip "${next.id}" and was cut where it starts`);
562
+ const byEnd = cuts.get(clip) ?? /* @__PURE__ */ new Map();
563
+ cuts.set(clip, byEnd);
564
+ const known = byEnd.get(next.startSample);
565
+ if (known) return { clip: known };
566
+ const cut = { ...clip, durationSamples: next.startSample - start };
567
+ byEnd.set(next.startSample, cut);
568
+ return { clip: cut };
569
+ }
515
570
 
516
571
  // src/arrangement/sources.ts
517
572
  var EMPTY_VALUE = {
@@ -642,20 +697,32 @@ var ArrangementSources = class {
642
697
  this._unusable = unusable;
643
698
  const seen = /* @__PURE__ */ new Map();
644
699
  let inCurrentTracks = false;
700
+ const removals = /* @__PURE__ */ new Map();
701
+ let trackIdNow = "";
702
+ const refuse = (clip, reason) => {
703
+ if (inCurrentTracks && !unusable.has(clip.src)) unusable.set(clip.src, reason);
704
+ return clip;
705
+ };
645
706
  const switched = (clip) => {
646
707
  const state = loaded.get(clip.src);
647
708
  if (state?.status !== "loaded") return clip;
648
709
  const result = this._resolve(clip, state.value, tickAt);
649
710
  if ("clip" in result) return result.clip;
650
- if (inCurrentTracks && !unusable.has(clip.src)) unusable.set(clip.src, result.unusable);
651
- return clip;
711
+ if ("removed" in result) {
712
+ const set = removals.get(trackIdNow) ?? /* @__PURE__ */ new Set();
713
+ removals.set(trackIdNow, set.add(clip));
714
+ return clip;
715
+ }
716
+ return refuse(clip, result.unusable);
652
717
  };
653
718
  const mapTrack = (track) => {
654
719
  const known = seen.get(track);
655
720
  if (known) return known;
656
721
  let next = track;
657
722
  if (this._sourcesOf(track).loading.length > 0) {
658
- const clips = track.clips.map((clip) => (0, import_core4.isLoadingClip)(clip) ? switched(clip) : clip);
723
+ trackIdNow = track.id;
724
+ const mapped = track.clips.map((clip) => (0, import_core4.isLoadingClip)(clip) ? switched(clip) : clip);
725
+ const clips = fitArrivals(track.clips, mapped, refuse, removals.get(track.id));
659
726
  if (clips.some((clip, i) => clip !== track.clips[i])) next = { ...track, clips };
660
727
  }
661
728
  seen.set(track, next);
@@ -674,7 +741,8 @@ var ArrangementSources = class {
674
741
  inCurrentTracks = false;
675
742
  }
676
743
  },
677
- stored: (tracks) => apply(tracks)
744
+ stored: (tracks) => apply(tracks),
745
+ removals: () => removals
678
746
  };
679
747
  }
680
748
  /** After a pass over every state: publish `value` if a status changed. */
@@ -734,6 +802,22 @@ var ArrangementSources = class {
734
802
  return { sources, pendingCount, failedCount, isLoading: pendingCount > 0 };
735
803
  }
736
804
  };
805
+ function fitArrivals(before, after, refuse, removed = /* @__PURE__ */ new Set()) {
806
+ const arrived = after.map((_, i) => i).filter((i) => (0, import_core4.isLoadingClip)(before[i]) && !(0, import_core4.isLoadingClip)(after[i])).sort((i, j) => after[i].startSample - after[j].startSample);
807
+ if (arrived.length === 0) return after;
808
+ const result = [...after];
809
+ for (const i of arrived) {
810
+ const clip = result[i];
811
+ const others = trackClipSpans(
812
+ result.filter((c, j) => j !== i && !((0, import_core4.isLoadingClip)(c) && removed.has(c))),
813
+ clip.sampleRate
814
+ );
815
+ const loading = before[i];
816
+ const fit = fitArrivedClip(loading, clip, others);
817
+ result[i] = "clip" in fit ? fit.clip : refuse(loading, "unusable" in fit ? fit.unusable : fit.removed);
818
+ }
819
+ return result;
820
+ }
737
821
  function sameValue(a, b) {
738
822
  if (a.sources.size !== b.sources.size) return false;
739
823
  for (const [src, state] of b.sources) {
@@ -743,30 +827,145 @@ function sameValue(a, b) {
743
827
  return true;
744
828
  }
745
829
 
830
+ // src/arrangement/mixer.ts
831
+ var import_core5 = require("@waveform-playlist/core");
832
+ var EMPTY_MIXER = /* @__PURE__ */ new Map();
833
+ var DEFAULT_VOLUME = 1;
834
+ var DEFAULT_PAN = 0;
835
+ function mixerValuesOf(track) {
836
+ return {
837
+ volume: track.volume ?? DEFAULT_VOLUME,
838
+ muted: track.muted ?? false,
839
+ soloed: track.soloed ?? false,
840
+ pan: track.pan ?? DEFAULT_PAN,
841
+ panLaw: enteringPanLaw(track)
842
+ };
843
+ }
844
+ function decidedByAudio(track) {
845
+ if ((0, import_core5.trackKind)(track) === "midi") return null;
846
+ return (0, import_core5.audioPanLaw)({
847
+ clips: track.clips.filter((clip) => !(0, import_core5.isLoadingClip)(clip))
848
+ });
849
+ }
850
+ function enteringPanLaw(track) {
851
+ if ((0, import_core5.trackKind)(track) === "midi") return import_core5.DEFAULT_PAN_LAW;
852
+ if ((0, import_core5.isDecidedPanLaw)(track.panLaw)) return track.panLaw;
853
+ return decidedByAudio(track) ?? import_core5.DEFAULT_PAN_LAW;
854
+ }
855
+ function decidePanLaws(mixer, tracks) {
856
+ let next = null;
857
+ for (const track of tracks) {
858
+ const entry = mixer.get(track.id);
859
+ if (!entry || entry.panLaw !== import_core5.DEFAULT_PAN_LAW) continue;
860
+ const panLaw = decidedByAudio(track);
861
+ if (!panLaw) continue;
862
+ if (!next) next = new Map(mixer);
863
+ next.set(track.id, { ...entry, panLaw });
864
+ }
865
+ return next ?? mixer;
866
+ }
867
+ function seedMixer(mixer, tracks) {
868
+ let next = null;
869
+ for (const track of tracks) {
870
+ if ((next ?? mixer).has(track.id)) continue;
871
+ if (!next) next = new Map(mixer);
872
+ next.set(track.id, mixerValuesOf(track));
873
+ }
874
+ return next ?? mixer;
875
+ }
876
+ function setMixerValues(mixer, trackId, patch) {
877
+ const entry = mixer.get(trackId);
878
+ if (!entry) return mixer;
879
+ const next = { ...entry, ...patch };
880
+ if (sameValues(entry, next)) return mixer;
881
+ return new Map(mixer).set(trackId, next);
882
+ }
883
+ function carryMixerEntry(mixer, fromId, toId) {
884
+ const entry = mixer.get(fromId);
885
+ if (!entry || fromId === toId) return mixer;
886
+ return new Map(
887
+ [...mixer].filter(([id]) => id !== toId).map(([id, values]) => [id === fromId ? toId : id, values])
888
+ );
889
+ }
890
+ function mixerOf(mixer, tracks) {
891
+ const ids = new Set(tracks.map((track) => track.id));
892
+ const seeded = seedMixer(mixer, tracks);
893
+ if (seeded.size === ids.size) return seeded;
894
+ return new Map([...seeded].filter(([id]) => ids.has(id)));
895
+ }
896
+ function withoutEntry(mixer, trackId) {
897
+ if (!mixer.has(trackId)) return mixer;
898
+ const next = new Map(mixer);
899
+ next.delete(trackId);
900
+ return next;
901
+ }
902
+ function sameValues(a, b) {
903
+ return a.volume === b.volume && a.muted === b.muted && a.soloed === b.soloed && a.pan === b.pan && a.panLaw === b.panLaw;
904
+ }
905
+ function sameMixerValues(a, b) {
906
+ if (a === b) return true;
907
+ if (a.size !== b.size) return false;
908
+ for (const [id, values] of a) {
909
+ const other = b.get(id);
910
+ if (!other || !sameValues(values, other)) return false;
911
+ }
912
+ return true;
913
+ }
914
+ function mixerChanges(before, after) {
915
+ if (before === after) return [];
916
+ const changes = [];
917
+ for (const [trackId, now] of after) {
918
+ const was = before.get(trackId);
919
+ if (!was || was === now) continue;
920
+ const values = {};
921
+ if (was.volume !== now.volume) values.volume = now.volume;
922
+ if (was.muted !== now.muted) values.muted = now.muted;
923
+ if (was.soloed !== now.soloed) values.soloed = now.soloed;
924
+ if (was.pan !== now.pan) values.pan = now.pan;
925
+ if (was.panLaw !== now.panLaw) values.panLaw = now.panLaw;
926
+ if (Object.keys(values).length > 0) changes.push({ trackId, values });
927
+ }
928
+ return changes;
929
+ }
930
+ function withMixerValues(track, values) {
931
+ if (!values || track.volume === values.volume && track.muted === values.muted && track.soloed === values.soloed && track.pan === values.pan && // A track that carries no law is an 'auto' track: no copy for that alone.
932
+ (track.panLaw ?? import_core5.DEFAULT_PAN_LAW) === values.panLaw) {
933
+ return track;
934
+ }
935
+ return { ...track, ...values };
936
+ }
937
+
746
938
  // src/arrangement/history.ts
747
939
  var EMPTY_HISTORY = { undo: [], redo: [] };
748
- function pushStep(history, tracks, limit) {
749
- const undo = [...history.undo, tracks];
940
+ function pushStep(history, state, limit) {
941
+ const undo = [...history.undo, state];
750
942
  return { undo: undo.length > limit ? undo.slice(undo.length - limit) : undo, redo: [] };
751
943
  }
752
944
  function undoStep(history, current) {
753
945
  if (history.undo.length === 0) return null;
754
- const tracks = history.undo[history.undo.length - 1];
946
+ const state = history.undo[history.undo.length - 1];
755
947
  return {
756
948
  history: { undo: history.undo.slice(0, -1), redo: [...history.redo, current] },
757
- tracks
949
+ state
758
950
  };
759
951
  }
760
952
  function redoStep(history, current) {
761
953
  if (history.redo.length === 0) return null;
762
- const tracks = history.redo[history.redo.length - 1];
954
+ const state = history.redo[history.redo.length - 1];
763
955
  return {
764
956
  history: { undo: [...history.undo, current], redo: history.redo.slice(0, -1) },
765
- tracks
957
+ state
766
958
  };
767
959
  }
768
- function beginBase(tracks) {
769
- return { tracks, changed: false };
960
+ function beginBase(state) {
961
+ return { state, changed: false };
962
+ }
963
+ function withStateTracks(state, tracks) {
964
+ return tracks === state.tracks ? state : { ...state, tracks };
965
+ }
966
+ function mapHistoryTracks(history, map) {
967
+ const each = (state) => withStateTracks(state, map(state.tracks));
968
+ return { undo: history.undo.map(each), redo: history.redo.map(each) };
770
969
  }
771
970
  function withoutTrack(tracks, trackId) {
772
971
  return tracks.some((track) => track.id === trackId) ? tracks.filter((track) => track.id !== trackId) : tracks;
@@ -774,75 +973,176 @@ function withoutTrack(tracks, trackId) {
774
973
  function sameTracks(a, b) {
775
974
  return a === b || a.length === b.length && a.every((track, i) => track === b[i]);
776
975
  }
777
- function purgeTrack(history, current, trackId) {
778
- const nextCurrent = withoutTrack(current, trackId);
976
+ function sameState(a, b) {
977
+ return a === b || sameTracks(a.tracks, b.tracks) && sameMixerValues(a.mixer, b.mixer);
978
+ }
979
+ function stateWithoutTrack(trackId) {
980
+ const mixers = /* @__PURE__ */ new Map();
981
+ const mixerWithout = (mixer) => {
982
+ const known = mixers.get(mixer);
983
+ if (known) return known;
984
+ const next = withoutEntry(mixer, trackId);
985
+ mixers.set(mixer, next);
986
+ return next;
987
+ };
988
+ return (state) => {
989
+ const tracks = withoutTrack(state.tracks, trackId);
990
+ const mixer = mixerWithout(state.mixer);
991
+ return tracks === state.tracks && mixer === state.mixer ? state : { tracks, mixer };
992
+ };
993
+ }
994
+ function dropRepeats(history, current) {
779
995
  const undo = [];
780
996
  for (const step of history.undo) {
781
- const stripped = withoutTrack(step, trackId);
782
- if (undo.length === 0 || !sameTracks(undo[undo.length - 1], stripped)) undo.push(stripped);
997
+ if (undo.length === 0 || !sameState(undo[undo.length - 1], step)) undo.push(step);
783
998
  }
784
- while (undo.length > 0 && sameTracks(undo[undo.length - 1], nextCurrent)) undo.pop();
999
+ while (undo.length > 0 && sameState(undo[undo.length - 1], current)) undo.pop();
785
1000
  const redoFromCurrent = [];
786
1001
  for (let i = history.redo.length - 1; i >= 0; i--) {
787
- const stripped = withoutTrack(history.redo[i], trackId);
788
- const before = redoFromCurrent.length > 0 ? redoFromCurrent[redoFromCurrent.length - 1] : nextCurrent;
789
- if (!sameTracks(before, stripped)) redoFromCurrent.push(stripped);
1002
+ const step = history.redo[i];
1003
+ const before = redoFromCurrent.length > 0 ? redoFromCurrent[redoFromCurrent.length - 1] : current;
1004
+ if (!sameState(before, step)) redoFromCurrent.push(step);
1005
+ }
1006
+ if (undo.length === history.undo.length && redoFromCurrent.length === history.redo.length) {
1007
+ return history;
790
1008
  }
791
- const redo = redoFromCurrent.reverse();
792
- const unchanged = undo.length === history.undo.length && redo.length === history.redo.length && undo.every((step, i) => step === history.undo[i]) && redo.every((step, i) => step === history.redo[i]);
793
- return { history: unchanged ? history : { undo, redo }, current: nextCurrent };
1009
+ return { undo, redo: redoFromCurrent.reverse() };
794
1010
  }
795
-
796
- // src/arrangement/mixer.ts
797
- var EMPTY_MIXER = /* @__PURE__ */ new Map();
798
- var DEFAULT_VOLUME = 1;
799
- var DEFAULT_PAN = 0;
800
- function mixerValuesOf(track) {
801
- return {
802
- volume: track.volume ?? DEFAULT_VOLUME,
803
- muted: track.muted ?? false,
804
- soloed: track.soloed ?? false,
805
- pan: track.pan ?? DEFAULT_PAN
1011
+ function sameSteps(a, b) {
1012
+ return a === b || a.undo.length === b.undo.length && a.redo.length === b.redo.length && a.undo.every((step, i) => step === b.undo[i]) && a.redo.every((step, i) => step === b.redo[i]);
1013
+ }
1014
+ function mapHistoryStates(history, map) {
1015
+ return { undo: history.undo.map(map), redo: history.redo.map(map) };
1016
+ }
1017
+ function purgeTrack(history, current, trackId, base = null) {
1018
+ return purgeStates(history, current, stateWithoutTrack(trackId), base);
1019
+ }
1020
+ function purgeClip(history, current, trackId, clipId, base = null) {
1021
+ return purgeStates(
1022
+ history,
1023
+ current,
1024
+ stateWithoutClip(history, current, trackId, (c) => c.id === clipId, base),
1025
+ base
1026
+ );
1027
+ }
1028
+ function purgeClipObjects(history, current, trackId, clips, base = null) {
1029
+ const strip = stateWithoutClip(history, current, trackId, (c) => clips.has(c), base);
1030
+ return { ...purgeStates(history, current, strip, base), strip };
1031
+ }
1032
+ function stateWithoutClip(history, current, trackId, isGone, base = null) {
1033
+ const inOrder = [
1034
+ ...history.undo,
1035
+ ...base ? [base] : [],
1036
+ current,
1037
+ ...[...history.redo].reverse()
1038
+ ];
1039
+ const mapped = /* @__PURE__ */ new Map();
1040
+ let before;
1041
+ let stripped = false;
1042
+ for (const state of inOrder) {
1043
+ const known = mapped.get(state);
1044
+ if (known) {
1045
+ before = known.tracks.find((t) => t.id === trackId);
1046
+ continue;
1047
+ }
1048
+ const track = state.tracks.find((t) => t.id === trackId);
1049
+ let next = track;
1050
+ if (track?.clips.some(isGone)) {
1051
+ next = { ...track, clips: track.clips.filter((c) => !isGone(c)) };
1052
+ stripped = true;
1053
+ }
1054
+ if (stripped && next && before && next !== before && sameTrackFields(before, next))
1055
+ next = before;
1056
+ mapped.set(
1057
+ state,
1058
+ next === track ? state : { tracks: state.tracks.map((t) => t === track ? next : t), mixer: state.mixer }
1059
+ );
1060
+ before = next;
1061
+ }
1062
+ return (state) => mapped.get(state) ?? state;
1063
+ }
1064
+ function withCurrentTracks(history, current) {
1065
+ const byId = new Map(current.tracks.map((t) => [t.id, t]));
1066
+ const canon = (state) => {
1067
+ let changed = false;
1068
+ const tracks = state.tracks.map((t) => {
1069
+ const now = byId.get(t.id);
1070
+ if (now && now !== t && sameTrackFields(t, now)) {
1071
+ changed = true;
1072
+ return now;
1073
+ }
1074
+ return t;
1075
+ });
1076
+ return changed ? { tracks, mixer: state.mixer } : state;
806
1077
  };
1078
+ return mapHistoryStates(history, canon);
807
1079
  }
808
- function seedMixer(mixer, tracks) {
809
- let next = null;
810
- for (const track of tracks) {
811
- if ((next ?? mixer).has(track.id)) continue;
812
- if (!next) next = new Map(mixer);
813
- next.set(track.id, mixerValuesOf(track));
1080
+ function sameTrackFields(a, b) {
1081
+ const keys = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)]);
1082
+ for (const key of keys) {
1083
+ if (key !== "clips" && a[key] !== b[key]) return false;
814
1084
  }
815
- return next ?? mixer;
1085
+ return a.clips.length === b.clips.length && a.clips.every((c, i) => c === b.clips[i]);
816
1086
  }
817
- function setMixerValues(mixer, trackId, patch) {
818
- const entry = mixer.get(trackId);
819
- if (!entry) return mixer;
820
- return new Map(mixer).set(trackId, { ...entry, ...patch });
1087
+ function purgeStates(history, current, strip, base) {
1088
+ const nextCurrent = strip(current);
1089
+ const nextBase = base && strip(base);
1090
+ const stripped = dropRepeats(mapHistoryStates(history, strip), nextBase ?? nextCurrent);
1091
+ return {
1092
+ history: sameSteps(stripped, history) ? history : stripped,
1093
+ current: nextCurrent,
1094
+ base: nextBase
1095
+ };
821
1096
  }
822
- function carryMixerEntry(mixer, fromId, toId) {
823
- const entry = mixer.get(fromId);
824
- if (!entry || mixer.get(toId) === entry) return mixer;
825
- return new Map(mixer).set(toId, entry);
1097
+ function stateWithMixerValues(trackId, patch) {
1098
+ const mixers = /* @__PURE__ */ new Map();
1099
+ const states = /* @__PURE__ */ new Map();
1100
+ return (state) => {
1101
+ const known = states.get(state);
1102
+ if (known) return known;
1103
+ let mixer = mixers.get(state.mixer);
1104
+ if (!mixer) {
1105
+ mixer = setMixerValues(state.mixer, trackId, patch);
1106
+ mixers.set(state.mixer, mixer);
1107
+ }
1108
+ const next = mixer === state.mixer ? state : { ...state, mixer };
1109
+ states.set(state, next);
1110
+ return next;
1111
+ };
826
1112
  }
827
- function retainMixer(mixer, states) {
828
- const held = /* @__PURE__ */ new Set();
829
- for (const tracks of states) {
830
- for (const track of tracks) held.add(track.id);
831
- }
832
- if ([...mixer.keys()].every((id) => held.has(id))) return mixer;
833
- return new Map([...mixer].filter(([id]) => held.has(id)));
1113
+ function stateWithDecidedPanLaws() {
1114
+ const decided = /* @__PURE__ */ new Map();
1115
+ const states = /* @__PURE__ */ new Map();
1116
+ return (state) => {
1117
+ const known = states.get(state);
1118
+ if (known) return known;
1119
+ let byTracks = decided.get(state.mixer);
1120
+ if (!byTracks) {
1121
+ byTracks = /* @__PURE__ */ new Map();
1122
+ decided.set(state.mixer, byTracks);
1123
+ }
1124
+ let mixer = byTracks.get(state.tracks);
1125
+ if (!mixer) {
1126
+ mixer = decidePanLaws(state.mixer, state.tracks);
1127
+ byTracks.set(state.tracks, mixer);
1128
+ }
1129
+ const next = mixer === state.mixer ? state : { ...state, mixer };
1130
+ states.set(state, next);
1131
+ return next;
1132
+ };
834
1133
  }
835
- function withMixerValues(track, values) {
836
- if (!values || track.volume === values.volume && track.muted === values.muted && track.soloed === values.soloed && track.pan === values.pan) {
837
- return track;
838
- }
839
- return { ...track, ...values };
1134
+ function writeThrough(history, base, current, write) {
1135
+ const nextBase = base && { ...base, state: write(base.state) };
1136
+ return {
1137
+ history: dropRepeats(mapHistoryStates(history, write), nextBase?.state ?? current),
1138
+ base: nextBase
1139
+ };
840
1140
  }
841
1141
 
842
1142
  // src/arrangement/ticks.ts
843
- var import_core5 = require("@waveform-playlist/core");
1143
+ var import_core6 = require("@waveform-playlist/core");
844
1144
  function forLoadedClips(change) {
845
- return (clip) => (0, import_core5.isLoadingClip)(clip) ? clip : change(clip);
1145
+ return (clip) => (0, import_core6.isLoadingClip)(clip) ? clip : change(clip);
846
1146
  }
847
1147
  function withClips(track, change) {
848
1148
  let changed = false;
@@ -885,12 +1185,13 @@ function rescaleTick(tick, fromPpqn, toPpqn) {
885
1185
  }
886
1186
 
887
1187
  // src/arrangement/validate.ts
888
- var import_core6 = require("@waveform-playlist/core");
1188
+ var import_core7 = require("@waveform-playlist/core");
1189
+ var SPAN_RATE_WITHOUT_AUDIO = 48e3;
889
1190
  function assertClipsOfTrackKind(track) {
890
1191
  const clips = track.clips.map(
891
- (clip) => (0, import_core6.isLoadingClip)(clip) ? { id: clip.id, name: clip.name } : clip
1192
+ (clip) => (0, import_core7.isLoadingClip)(clip) ? { id: clip.id, name: clip.name } : clip
892
1193
  );
893
- (0, import_core6.assertTrackKind)({ ...track, clips });
1194
+ (0, import_core7.assertTrackKind)({ ...track, clips });
894
1195
  }
895
1196
  function assertUniqueClipIds(track) {
896
1197
  const seen = /* @__PURE__ */ new Set();
@@ -903,6 +1204,26 @@ function assertUniqueClipIds(track) {
903
1204
  seen.add(clip.id);
904
1205
  }
905
1206
  }
1207
+ function findClipOverlap(clips) {
1208
+ const loaded = clips.find((clip) => !(0, import_core7.isLoadingClip)(clip));
1209
+ const spans = trackClipSpans(clips, loaded ? loaded.sampleRate : SPAN_RATE_WITHOUT_AUDIO);
1210
+ for (let i = 1; i < spans.length; i++) {
1211
+ const before = spans[i - 1];
1212
+ const after = spans[i];
1213
+ if (before.startSample + before.durationSamples > after.startSample) {
1214
+ return { first: before.id, second: after.id };
1215
+ }
1216
+ }
1217
+ return null;
1218
+ }
1219
+ function assertNoOverlappingClips(track) {
1220
+ const overlap = findClipOverlap(track.clips);
1221
+ if (overlap) {
1222
+ throw new Error(
1223
+ `[waveform-playlist] Track "${track.id}": clip "${overlap.first}" overlaps clip "${overlap.second}". Clips on a track cannot overlap.`
1224
+ );
1225
+ }
1226
+ }
906
1227
  function assertUniqueTrackIds(tracks) {
907
1228
  const seen = /* @__PURE__ */ new Set();
908
1229
  for (const track of tracks) {
@@ -919,17 +1240,46 @@ function duplicateTrackId(trackId) {
919
1240
  // src/arrangement/Arrangement.ts
920
1241
  var DEFAULT_MIN_DURATION_SECONDS = 0.1;
921
1242
  var DEFAULT_UNDO_LIMIT = 100;
1243
+ var EMPTY_RECORDING = /* @__PURE__ */ new Set();
1244
+ function insertIndex(index, length) {
1245
+ if (index === void 0) return length;
1246
+ if (typeof index !== "number" || !Number.isFinite(index)) {
1247
+ throw new TypeError(
1248
+ `[waveform-playlist] addTrack: index must be a finite number, got ${String(index)}`
1249
+ );
1250
+ }
1251
+ return Math.max(0, Math.min(Math.trunc(index), length));
1252
+ }
922
1253
  var ArrangementImpl = class {
923
1254
  constructor(options = {}) {
924
1255
  this._tracks = [];
925
1256
  this._tracksVersion = 0;
926
1257
  this._mixerVersion = 0;
927
1258
  this._mixer = EMPTY_MIXER;
1259
+ /**
1260
+ * The ids of the tracks a take is recording onto: outside the history and
1261
+ * every saved state (#843). Replaced on a change, never written to.
1262
+ */
1263
+ this._recordingTrackIds = EMPTY_RECORDING;
928
1264
  this._history = EMPTY_HISTORY;
929
1265
  this._transaction = null;
1266
+ /**
1267
+ * The gesture of the top undo step, while a change of that gesture may
1268
+ * still join it: its id, and the history from before its step was pushed
1269
+ * (put back when the gesture returns to where it began, with the redo
1270
+ * states and any step the undo limit evicted). Set when a gesture change
1271
+ * pushes the step, cleared by anything else that touches the history
1272
+ * (#843). `before` is kept in step with the history: the time base, the
1273
+ * switch to loaded clips and `undoable: false` reach it too.
1274
+ */
1275
+ this._gesture = null;
1276
+ /** Whether the last pass removed a clip with nothing of its audio left (#859). */
1277
+ this._purgedInPass = false;
930
1278
  this._subscribers = /* @__PURE__ */ new Set();
931
1279
  this._listeners = /* @__PURE__ */ new Set();
932
1280
  this._pending = [];
1281
+ /** The clips passes removed from the current tracks since the last announcement (#859). */
1282
+ this._removedNow = [];
933
1283
  this._delivering = false;
934
1284
  /** How the clip edits convert time: through the attached engine, or not at all. */
935
1285
  this._clipTime = {
@@ -990,7 +1340,7 @@ var ArrangementImpl = class {
990
1340
  }
991
1341
  /** Be told after every change. See `Arrangement.subscribe`. */
992
1342
  subscribe(listener) {
993
- const entry = () => listener();
1343
+ const entry = (change) => listener(change);
994
1344
  this._subscribers.add(entry);
995
1345
  return () => {
996
1346
  this._subscribers.delete(entry);
@@ -1029,17 +1379,19 @@ var ArrangementImpl = class {
1029
1379
  }
1030
1380
  const prepare = tickPreparer(timeBase, this._tickPpqn);
1031
1381
  const tracks = prepare(this._tracks);
1032
- const history = {
1033
- undo: this._history.undo.map(prepare),
1034
- redo: this._history.redo.map(prepare)
1382
+ const history = mapHistoryTracks(this._history, prepare);
1383
+ const gesture = this._gesture && {
1384
+ ...this._gesture,
1385
+ before: mapHistoryTracks(this._gesture.before, prepare)
1035
1386
  };
1036
1387
  const transaction = this._transaction && {
1037
1388
  ...this._transaction,
1038
- tracks: prepare(this._transaction.tracks)
1389
+ state: withStateTracks(this._transaction.state, prepare(this._transaction.state.tracks))
1039
1390
  };
1040
1391
  this._timeBase = timeBase;
1041
1392
  this._tickPpqn = timeBase.ppqn;
1042
1393
  this._history = history;
1394
+ this._gesture = gesture;
1043
1395
  this._transaction = transaction;
1044
1396
  if (tracks !== this._tracks) {
1045
1397
  this._tracks = tracks;
@@ -1061,22 +1413,24 @@ var ArrangementImpl = class {
1061
1413
  }
1062
1414
  undo() {
1063
1415
  this._abortOpenTransaction();
1064
- const step = undoStep(this._history, this._tracks);
1416
+ this._gesture = null;
1417
+ const step = undoStep(this._history, this._currentState());
1065
1418
  if (!step) return;
1066
1419
  this._history = step.history;
1067
- this._restoreTracks(step.tracks);
1420
+ if (!this._restoreState(step.state)) this._emit({ type: "history" });
1068
1421
  }
1069
1422
  redo() {
1070
1423
  this._abortOpenTransaction();
1071
- const step = redoStep(this._history, this._tracks);
1424
+ this._gesture = null;
1425
+ const step = redoStep(this._history, this._currentState());
1072
1426
  if (!step) return;
1073
1427
  this._history = step.history;
1074
- this._restoreTracks(step.tracks);
1428
+ if (!this._restoreState(step.state)) this._emit({ type: "history" });
1075
1429
  }
1076
1430
  clearHistory() {
1077
1431
  const hadHistory = this.canUndo || this.canRedo;
1078
1432
  this._history = EMPTY_HISTORY;
1079
- this._mixer = retainMixer(this._mixer, this._heldStates());
1433
+ this._gesture = null;
1080
1434
  if (hadHistory) this._emit({ type: "history" });
1081
1435
  }
1082
1436
  beginTransaction() {
@@ -1086,7 +1440,8 @@ var ArrangementImpl = class {
1086
1440
  );
1087
1441
  }
1088
1442
  const replaced = this._transaction !== null;
1089
- this._transaction = beginBase(this._tracks);
1443
+ this._transaction = beginBase(this._currentState());
1444
+ this._gesture = null;
1090
1445
  if (replaced) this._resyncSourcesQuietly();
1091
1446
  }
1092
1447
  commitTransaction() {
@@ -1096,8 +1451,9 @@ var ArrangementImpl = class {
1096
1451
  return;
1097
1452
  }
1098
1453
  this._transaction = null;
1099
- if (transaction.changed && !sameTracks(transaction.tracks, this._tracks)) {
1100
- this._pushStep(transaction.tracks);
1454
+ this._gesture = null;
1455
+ if (transaction.changed && !sameState(transaction.state, this._currentState())) {
1456
+ this._pushStep(transaction.state);
1101
1457
  this._emit({ type: "history" });
1102
1458
  }
1103
1459
  }
@@ -1113,28 +1469,31 @@ var ArrangementImpl = class {
1113
1469
  // Track Management
1114
1470
  // ---------------------------------------------------------------------------
1115
1471
  // A track holds audio clips or MIDI clips, never both (#756); track ids are
1116
- // unique, and so are clip ids within a track. The three methods that take a
1472
+ // unique, and so are clip ids within a track; its clips do not overlap (#859). The three methods that take a
1117
1473
  // track check it before they change anything, so a throw leaves the tracks,
1118
1474
  // the undo history, the mixer and every subscriber untouched.
1119
1475
  setTracks(tracks) {
1120
1476
  tracks.forEach(assertClipsOfTrackKind);
1121
1477
  assertUniqueTrackIds(tracks);
1122
1478
  tracks.forEach(assertUniqueClipIds);
1479
+ tracks.forEach(assertNoOverlappingClips);
1123
1480
  this._transaction = null;
1124
1481
  this._history = EMPTY_HISTORY;
1125
- const kept = retainMixer(this._mixer, [this._tracks]);
1482
+ this._gesture = null;
1126
1483
  this._tracks = tracks.map((track) => this._ingest(track));
1127
- this._mixer = retainMixer(seedMixer(kept, this._tracks), [this._tracks]);
1484
+ this._mixer = mixerOf(this._mixer, this._tracks);
1128
1485
  this._tracksVersion++;
1129
1486
  this._emit({ type: "set" });
1130
1487
  }
1131
- addTrack(track) {
1488
+ addTrack(track, options) {
1489
+ const index = insertIndex(options?.index, this._tracks.length);
1132
1490
  assertClipsOfTrackKind(track);
1133
1491
  assertUniqueClipIds(track);
1492
+ assertNoOverlappingClips(track);
1134
1493
  if (this._tracks.some((t) => t.id === track.id)) throw duplicateTrackId(track.id);
1135
1494
  this._pushUndoSnapshot();
1136
1495
  const enriched = this._ingest(track);
1137
- this._tracks = [...this._tracks, enriched];
1496
+ this._tracks = [...this._tracks.slice(0, index), enriched, ...this._tracks.slice(index)];
1138
1497
  this._mixer = seedMixer(this._mixer, [enriched]);
1139
1498
  this._tracksVersion++;
1140
1499
  this._emit({ type: "add", trackId: track.id });
@@ -1152,9 +1511,25 @@ var ArrangementImpl = class {
1152
1511
  if (!this._tracks.some((t) => t.id === trackId)) return;
1153
1512
  this._pushUndoSnapshot();
1154
1513
  this._tracks = this._tracks.filter((t) => t.id !== trackId);
1514
+ this._mixer = withoutEntry(this._mixer, trackId);
1155
1515
  this._tracksVersion++;
1156
1516
  this._emit({ type: "remove", trackId });
1157
1517
  }
1518
+ /**
1519
+ * Remove a clip from a track: an undo step. With `undoable: false` there is
1520
+ * no step, and the clip is also taken out of every undo and redo state, so
1521
+ * that no undo or redo brings it back (#848: a `<daw-clip>` the page removed
1522
+ * while its track was detached).
1523
+ */
1524
+ removeClip(trackId, clipId, options) {
1525
+ if (options?.undoable === false) {
1526
+ this._removeClipEverywhere(trackId, clipId);
1527
+ return;
1528
+ }
1529
+ const current = this._tracks.find((t) => t.id === trackId);
1530
+ if (!current?.clips.some((c) => c.id === clipId)) return;
1531
+ this.updateTrack(trackId, (t) => ({ ...t, clips: t.clips.filter((c) => c.id !== clipId) }));
1532
+ }
1158
1533
  /**
1159
1534
  * Move a track to a new position in the track order. Purely organizational —
1160
1535
  * track order is not audible.
@@ -1190,6 +1565,7 @@ var ArrangementImpl = class {
1190
1565
  if (byFunction && track === current) return;
1191
1566
  assertClipsOfTrackKind(track);
1192
1567
  assertUniqueClipIds(track);
1568
+ assertNoOverlappingClips(track);
1193
1569
  if (track.id !== trackId && this._tracks.some((t) => t.id === track.id)) {
1194
1570
  throw duplicateTrackId(track.id);
1195
1571
  }
@@ -1198,7 +1574,6 @@ var ArrangementImpl = class {
1198
1574
  const enriched = this._ingest(track, new Set(current.clips));
1199
1575
  this._tracks = this._tracks.map((t) => t.id === trackId ? enriched : t);
1200
1576
  this._mixer = seedMixer(carryMixerEntry(this._mixer, trackId, enriched.id), [enriched]);
1201
- if (enriched.id !== trackId) this._mixer = retainMixer(this._mixer, this._heldStates());
1202
1577
  this._tracksVersion++;
1203
1578
  this._emit({ type: "update", trackId, previous: current });
1204
1579
  }
@@ -1235,19 +1610,63 @@ var ArrangementImpl = class {
1235
1610
  //
1236
1611
  // Each replaces the Map and one entry, bumps mixerVersion and announces
1237
1612
  // the change. NOT structural changes: no track object is replaced,
1238
- // tracksVersion stays (#501), and they are not undo steps. An id that is
1239
- // not in the current tracks does nothing.
1240
- setTrackVolume(trackId, volume) {
1241
- this._setMixerValues(trackId, { volume });
1613
+ // tracksVersion stays (#501). Each call is an undo step; inside an open
1614
+ // transaction it is part of it, like any other change. Calls with one
1615
+ // `gesture` id, one after another, are one step; `undoable: false` is no
1616
+ // step and is written into every saved state (#843). A value that does
1617
+ // not change, or an id that is not in the current tracks, does nothing.
1618
+ setTrackVolume(trackId, volume, options) {
1619
+ this._setMixerValues(trackId, { volume }, options);
1620
+ }
1621
+ setTrackMute(trackId, muted, options) {
1622
+ this._setMixerValues(trackId, { muted }, options);
1242
1623
  }
1243
- setTrackMute(trackId, muted) {
1244
- this._setMixerValues(trackId, { muted });
1624
+ setTrackSolo(trackId, soloed, options) {
1625
+ this._setMixerValues(trackId, { soloed }, options);
1626
+ }
1627
+ setTrackPan(trackId, pan, options) {
1628
+ this._setMixerValues(trackId, { pan }, options);
1629
+ }
1630
+ /**
1631
+ * Set a track's pan law (#684): a mixer value like the four above. It
1632
+ * takes a decided law; anything else, `'auto'` included, throws before
1633
+ * anything changes (a decided track does not go back to `'auto'`). May be
1634
+ * called before the track holds audio: the law is then decided, and the
1635
+ * first audio does not change it. A MIDI track has no law to set.
1636
+ */
1637
+ setTrackPanLaw(trackId, panLaw, options) {
1638
+ if (!(0, import_core8.isDecidedPanLaw)(panLaw)) {
1639
+ throw new TypeError(
1640
+ `setTrackPanLaw: panLaw must be 'mono' or 'stereo', got ${JSON.stringify(panLaw) ?? String(panLaw)}`
1641
+ );
1642
+ }
1643
+ const track = this._tracks.find((t) => t.id === trackId);
1644
+ if (!track || (0, import_core8.trackKind)(track) === "midi") return;
1645
+ this._setMixerValues(trackId, { panLaw }, options);
1245
1646
  }
1246
- setTrackSolo(trackId, soloed) {
1247
- this._setMixerValues(trackId, { soloed });
1647
+ // ---------------------------------------------------------------------------
1648
+ // Recording mute (the track a take is recording onto)
1649
+ // ---------------------------------------------------------------------------
1650
+ //
1651
+ // The track a take is recording onto plays muted: the engine's projection
1652
+ // and the adapter get `muted: stored || recording`, and the stored mute in
1653
+ // `getMixer()` is not touched. The set is outside the history: the take's
1654
+ // mute is no undo step, and undo, redo, abort, `setTracks` and
1655
+ // `clearHistory` leave it alone (#843).
1656
+ /** The ids of the tracks a take is recording onto. The same Set until it changes; never written to. */
1657
+ get recordingTrackIds() {
1658
+ return this._recordingTrackIds;
1248
1659
  }
1249
- setTrackPan(trackId, pan) {
1250
- this._setMixerValues(trackId, { pan });
1660
+ /**
1661
+ * Mark a track as the one a take is recording onto, or clear it. An id
1662
+ * that is not in the current tracks is recorded too, and mutes nothing
1663
+ * until a track of that id enters. The same value does nothing.
1664
+ */
1665
+ setTrackRecording(trackId, recording) {
1666
+ if (this._recordingTrackIds.has(trackId) === recording) return;
1667
+ this._recordingTrackIds = recording ? /* @__PURE__ */ new Set([...this._recordingTrackIds, trackId]) : new Set([...this._recordingTrackIds].filter((id) => id !== trackId));
1668
+ if (this._mixer.has(trackId)) this._mixerVersion++;
1669
+ this._emit({ type: "recording", trackId });
1251
1670
  }
1252
1671
  // ---------------------------------------------------------------------------
1253
1672
  // Tempo
@@ -1305,42 +1724,103 @@ var ArrangementImpl = class {
1305
1724
  ...track,
1306
1725
  clips: track.clips.map((clip) => {
1307
1726
  if (held?.has(clip)) return clip;
1308
- if ((0, import_core7.isLoadingClip)(clip)) return { ...clip };
1727
+ if ((0, import_core8.isLoadingClip)(clip)) return { ...clip };
1309
1728
  return { ...clip, startTick: clip.startTick ?? this._tickAt(clip.startSample) };
1310
1729
  })
1311
1730
  };
1312
1731
  }
1313
- _setMixerValues(trackId, values) {
1732
+ _setMixerValues(trackId, values, options = {}) {
1314
1733
  if (!this._tracks.some((t) => t.id === trackId)) return;
1315
1734
  const next = setMixerValues(this._mixer, trackId, values);
1316
1735
  if (next === this._mixer) return;
1317
- this._mixer = next;
1736
+ if (options.undoable === false) {
1737
+ this._writeMixerThrough(trackId, values, next);
1738
+ } else {
1739
+ this._recordMixerChange(options.gesture);
1740
+ this._mixer = next;
1741
+ this._dropReturnedGestureStep();
1742
+ }
1318
1743
  this._mixerVersion++;
1319
1744
  this._emit({ type: "mixer", trackId, values });
1320
1745
  }
1321
- /** Every tracks array the arrangement can still return to, and the current one. */
1746
+ /**
1747
+ * The undo step of a mixer change about to be made: part of an open
1748
+ * transaction, the top step when it was pushed by the same gesture and
1749
+ * nothing has touched the history since, or else a new step (which becomes
1750
+ * that gesture's).
1751
+ */
1752
+ _recordMixerChange(gesture) {
1753
+ if (this._transaction) {
1754
+ this._markTransactionChanged();
1755
+ return;
1756
+ }
1757
+ if (gesture !== void 0 && this._gesture?.id === gesture) return;
1758
+ const before = this._history;
1759
+ this._pushStep(this._currentState());
1760
+ if (gesture !== void 0 && this.canUndo) this._gesture = { id: gesture, before };
1761
+ }
1762
+ /**
1763
+ * A gesture that came back to the state its step holds leaves no step, and
1764
+ * the history is the one it found: the redo states its first change
1765
+ * cleared come back (as with a transaction that changes nothing).
1766
+ */
1767
+ _dropReturnedGestureStep() {
1768
+ const gesture = this._gesture;
1769
+ if (!gesture) return;
1770
+ const { undo } = this._history;
1771
+ if (!sameState(undo[undo.length - 1], this._currentState())) return;
1772
+ const current = this._currentState();
1773
+ this._history = dropRepeats(withCurrentTracks(gesture.before, current), current);
1774
+ this._gesture = null;
1775
+ }
1776
+ /**
1777
+ * `undoable: false`: the value in the current mix and in every saved state
1778
+ * that has an entry for the track, so that no undo, redo or abort brings
1779
+ * the old one back. A step that no longer differs from the state next to
1780
+ * it goes; when that was the step a gesture joins and no equal step is
1781
+ * left on top, the gesture's next change pushes a new one.
1782
+ */
1783
+ _writeMixerThrough(trackId, values, next) {
1784
+ this._mixer = next;
1785
+ const write = stateWithMixerValues(trackId, values);
1786
+ const { undo } = this._history;
1787
+ const top = undo.length > 0 ? write(undo[undo.length - 1]) : void 0;
1788
+ const written = writeThrough(this._history, this._transaction, this._currentState(), write);
1789
+ this._history = written.history;
1790
+ this._transaction = written.base;
1791
+ if (this._gesture) {
1792
+ const newTop = this._history.undo[this._history.undo.length - 1];
1793
+ this._gesture = newTop !== void 0 && top !== void 0 && sameState(newTop, top) ? { ...this._gesture, before: mapHistoryStates(this._gesture.before, write) } : null;
1794
+ }
1795
+ }
1796
+ /** The tracks and the mix as they are now: what an undo step or a transaction's base saves. */
1797
+ _currentState() {
1798
+ return { tracks: this._tracks, mixer: this._mixer };
1799
+ }
1800
+ /** Every tracks array the arrangement can still return to, and the current one (for the sources). */
1322
1801
  _heldStates() {
1323
1802
  return [
1324
1803
  this._tracks,
1325
- ...this._history.undo,
1326
- ...this._history.redo,
1327
- ...this._transaction ? [this._transaction.tracks] : []
1804
+ ...this._history.undo.map((state) => state.tracks),
1805
+ ...this._history.redo.map((state) => state.tracks),
1806
+ ...this._gesture ? this._gesture.before.undo.map((state) => state.tracks) : [],
1807
+ ...this._gesture ? this._gesture.before.redo.map((state) => state.tracks) : [],
1808
+ ...this._transaction ? [this._transaction.state.tracks] : []
1328
1809
  ];
1329
1810
  }
1330
1811
  /** `removeTrack` with `undoable: false`: out of the current tracks and out of every stored state. */
1331
1812
  _removeTrackEverywhere(trackId) {
1332
1813
  const wasThere = this._tracks.some((t) => t.id === trackId);
1333
- const purged = purgeTrack(this._history, this._tracks, trackId);
1814
+ const base = this._transaction?.state ?? null;
1815
+ const purged = purgeTrack(this._history, this._currentState(), trackId, base);
1334
1816
  const historyChanged = purged.history !== this._history;
1335
1817
  this._history = purged.history;
1336
- if (this._transaction) {
1337
- this._transaction = {
1338
- ...this._transaction,
1339
- tracks: withoutTrack(this._transaction.tracks, trackId)
1340
- };
1818
+ this._gesture = null;
1819
+ if (this._transaction && purged.base) {
1820
+ this._transaction = { ...this._transaction, state: purged.base };
1341
1821
  }
1342
- this._tracks = purged.current;
1343
- this._mixer = retainMixer(this._mixer, this._heldStates());
1822
+ this._tracks = purged.current.tracks;
1823
+ this._mixer = purged.current.mixer;
1344
1824
  if (wasThere) {
1345
1825
  this._tracksVersion++;
1346
1826
  this._emit({ type: "remove", trackId });
@@ -1350,41 +1830,89 @@ var ArrangementImpl = class {
1350
1830
  this._resyncSourcesQuietly();
1351
1831
  }
1352
1832
  }
1833
+ /** `removeClip` with `undoable: false`: out of the current tracks and out of every stored state. */
1834
+ _removeClipEverywhere(trackId, clipId) {
1835
+ const previous = this._tracks.find((t) => t.id === trackId);
1836
+ const base = this._transaction?.state ?? null;
1837
+ const purged = purgeClip(this._history, this._currentState(), trackId, clipId, base);
1838
+ const historyChanged = purged.history !== this._history;
1839
+ const baseChanged = purged.base !== base;
1840
+ this._history = purged.history;
1841
+ if (this._transaction && purged.base) {
1842
+ this._transaction = { ...this._transaction, state: purged.base };
1843
+ }
1844
+ if (purged.current.tracks !== this._tracks && previous) {
1845
+ this._gesture = null;
1846
+ this._tracks = purged.current.tracks;
1847
+ this._tracksVersion++;
1848
+ this._emit({ type: "update", trackId, previous });
1849
+ } else if (historyChanged) {
1850
+ this._gesture = null;
1851
+ this._emit({ type: "history" });
1852
+ } else if (baseChanged) {
1853
+ this._resyncSourcesQuietly();
1854
+ }
1855
+ }
1353
1856
  /** The state before a change: an undo step, or the mark that an open transaction changed. */
1354
1857
  _pushUndoSnapshot() {
1355
1858
  if (this._transaction) {
1356
- if (!this._transaction.changed) {
1357
- this._transaction = { ...this._transaction, changed: true };
1358
- }
1859
+ this._markTransactionChanged();
1359
1860
  return;
1360
1861
  }
1361
- this._pushStep(this._tracks);
1862
+ this._pushStep(this._currentState());
1362
1863
  }
1363
- /** Add an undo step. The history may let go of states with it (the redo stack, a step past the limit). */
1364
- _pushStep(tracks) {
1365
- const letsGo = this._history.redo.length > 0 || this._history.undo.length >= this.undoLimit;
1366
- this._history = pushStep(this._history, tracks, this.undoLimit);
1367
- if (letsGo) this._mixer = retainMixer(this._mixer, this._heldStates());
1864
+ /** An open transaction has changed something. */
1865
+ _markTransactionChanged() {
1866
+ if (this._transaction && !this._transaction.changed) {
1867
+ this._transaction = { ...this._transaction, changed: true };
1868
+ }
1368
1869
  }
1369
- _restoreTracks(snapshot) {
1870
+ /** Add an undo step. No gesture joins it (a gesture change that pushes sets its id after). */
1871
+ _pushStep(state) {
1872
+ this._history = pushStep(this._history, state, this.undoLimit);
1873
+ this._gesture = null;
1874
+ }
1875
+ /**
1876
+ * Make a saved state the current one (an undo, a redo, an abort) and
1877
+ * announce it: `'restore'` when the tracks array is another one (with the
1878
+ * mix from before, which may differ too), `'restoreMix'` when only mixer
1879
+ * values differ. `mixerVersion` counts it when a track that is in both
1880
+ * states has other values; an entry that comes or goes with its track is
1881
+ * not a mixer change. Returns false when nothing differed and nothing was
1882
+ * announced.
1883
+ */
1884
+ _restoreState(state) {
1370
1885
  const previous = this._tracks;
1371
- this._tracks = snapshot;
1372
- this._tracksVersion++;
1373
- this._emit({ type: "restore", previous });
1886
+ const previousMixer = this._mixer;
1887
+ const tracksChanged = state.tracks !== previous;
1888
+ const mixChanged = mixerChanges(previousMixer, state.mixer).length > 0;
1889
+ this._tracks = state.tracks;
1890
+ this._mixer = state.mixer;
1891
+ if (mixChanged) this._mixerVersion++;
1892
+ if (tracksChanged) {
1893
+ this._tracksVersion++;
1894
+ this._emit({ type: "restore", previous, previousMixer });
1895
+ } else if (mixChanged) {
1896
+ this._emit({ type: "restoreMix", previousMixer });
1897
+ }
1898
+ return tracksChanged || mixChanged;
1374
1899
  }
1375
- /** Ends an open transaction, restoring the tracks it began from if it changed them. */
1900
+ /** Ends an open transaction, restoring the state it began from if it changed anything. */
1376
1901
  _abortOpenTransaction() {
1377
1902
  const transaction = this._transaction;
1378
1903
  if (!transaction) return;
1379
1904
  this._transaction = null;
1905
+ this._gesture = null;
1380
1906
  if (transaction.changed) {
1381
- this._restoreTracks(transaction.tracks);
1907
+ this._restoreState(transaction.state);
1382
1908
  }
1383
1909
  }
1384
1910
  /** Declare the sources every state names, and switch the clips whose audio is there. */
1385
1911
  _syncSources() {
1386
1912
  this._sources.declare(this._heldStates());
1387
- return this._switchLoaded();
1913
+ const switched = this._switchLoaded();
1914
+ if (this._purgedInPass) this._sources.declare(this._heldStates());
1915
+ return switched;
1388
1916
  }
1389
1917
  /** The stored states changed with nothing to announce: the sources they name may have. */
1390
1918
  _resyncSourcesQuietly() {
@@ -1402,15 +1930,102 @@ var ArrangementImpl = class {
1402
1930
  const pass = this._sources.beginPass((startSample) => this._tickAt(startSample));
1403
1931
  const previous = this._tracks;
1404
1932
  this._tracks = pass.current(previous);
1405
- this._history = {
1406
- undo: this._history.undo.map(pass.stored),
1407
- redo: this._history.redo.map(pass.stored)
1408
- };
1933
+ this._history = mapHistoryTracks(this._history, pass.stored);
1934
+ if (this._gesture) {
1935
+ this._gesture = {
1936
+ ...this._gesture,
1937
+ before: mapHistoryTracks(this._gesture.before, pass.stored)
1938
+ };
1939
+ }
1409
1940
  if (this._transaction) {
1410
- this._transaction = { ...this._transaction, tracks: pass.stored(this._transaction.tracks) };
1941
+ const { state } = this._transaction;
1942
+ this._transaction = {
1943
+ ...this._transaction,
1944
+ state: withStateTracks(state, pass.stored(state.tracks))
1945
+ };
1411
1946
  }
1947
+ const removals = pass.removals();
1948
+ this._purgedInPass = removals.size > 0;
1949
+ for (const [trackId, clips] of removals) this._purgeClipObjects(trackId, clips);
1950
+ this._decidePanLaws();
1412
1951
  return this._tracks === previous ? null : previous;
1413
1952
  }
1953
+ /** These clip objects of a track out of every state, with no undo step and nothing announced. */
1954
+ _purgeClipObjects(trackId, clips) {
1955
+ const base = this._transaction?.state ?? null;
1956
+ const top = this._history.undo[this._history.undo.length - 1];
1957
+ const purged = purgeClipObjects(this._history, this._currentState(), trackId, clips, base);
1958
+ if (purged.history !== this._history && this._gesture) {
1959
+ const newTop = purged.history.undo[purged.history.undo.length - 1];
1960
+ if (!(top !== void 0 && newTop !== void 0 && sameState(newTop, purged.strip(top)))) {
1961
+ this._gesture = null;
1962
+ }
1963
+ }
1964
+ if (this._gesture) {
1965
+ const { before } = this._gesture;
1966
+ const strip = stateWithoutClip(before, this._currentState(), trackId, (c) => clips.has(c));
1967
+ this._gesture = { ...this._gesture, before: mapHistoryStates(before, strip) };
1968
+ }
1969
+ this._history = purged.history;
1970
+ if (this._transaction && purged.base) {
1971
+ this._transaction = { ...this._transaction, state: purged.base };
1972
+ }
1973
+ const track = this._tracks.find((t) => t.id === trackId);
1974
+ const gone = track ? track.clips.filter((c) => clips.has(c)) : [];
1975
+ if (gone.length > 0) {
1976
+ this._tracks = purged.current.tracks;
1977
+ for (const clip of gone) this._removedNow.push({ trackId, clipId: clip.id });
1978
+ }
1979
+ }
1980
+ /**
1981
+ * First audio decides a track's pan law (#684): in the current state and
1982
+ * in every state the arrangement can return to, a track whose law is
1983
+ * `'auto'` and that holds decoded audio gets the law of that audio, each
1984
+ * state from its own tracks. Part of the change that brought the audio:
1985
+ * not an undo step. `mixerVersion` counts it when the current mix changed.
1986
+ *
1987
+ * A saved step that no longer differs from the state next to it is
1988
+ * dropped, as `_writeMixerThrough` does (a law set on a track whose only
1989
+ * clip was loading, and the clip turns out to have that law): its undo, or
1990
+ * its redo, would do nothing. A gesture whose own step went has no step to
1991
+ * join, and its next change pushes a new one; a gesture whose step is still
1992
+ * the top one goes on.
1993
+ */
1994
+ _decidePanLaws() {
1995
+ const decide = stateWithDecidedPanLaws();
1996
+ const current = this._currentState();
1997
+ const decided = decide(current);
1998
+ if (decided !== current) {
1999
+ this._mixer = decided.mixer;
2000
+ this._mixerVersion++;
2001
+ }
2002
+ const changedIn = (before, after) => after.undo.some((state, i) => state !== before.undo[i]) || after.redo.some((state, i) => state !== before.redo[i]);
2003
+ let base = this._transaction?.state ?? null;
2004
+ if (this._transaction && base) {
2005
+ const decidedBase = decide(base);
2006
+ if (decidedBase !== base) {
2007
+ base = decidedBase;
2008
+ this._transaction = { ...this._transaction, state: decidedBase };
2009
+ }
2010
+ }
2011
+ const mapped = mapHistoryStates(this._history, decide);
2012
+ const savedChanged = changedIn(this._history, mapped);
2013
+ if (savedChanged || decided !== current) {
2014
+ const top = mapped.undo[mapped.undo.length - 1];
2015
+ const kept = dropRepeats(mapped, base ?? decided);
2016
+ if (savedChanged || kept !== mapped) this._history = kept;
2017
+ if (this._gesture && kept !== mapped) {
2018
+ const newTop = kept.undo[kept.undo.length - 1];
2019
+ if (!(newTop !== void 0 && top !== void 0 && sameState(newTop, top))) {
2020
+ this._gesture = null;
2021
+ }
2022
+ }
2023
+ }
2024
+ if (this._gesture) {
2025
+ const before = mapHistoryStates(this._gesture.before, decide);
2026
+ if (changedIn(this._gesture.before, before)) this._gesture = { ...this._gesture, before };
2027
+ }
2028
+ }
1414
2029
  /** A load finished or failed by itself (not inside one of this arrangement's methods). */
1415
2030
  _onSourceSettled() {
1416
2031
  const previous = this._switchLoaded();
@@ -1418,7 +2033,7 @@ var ArrangementImpl = class {
1418
2033
  this._tracksVersion++;
1419
2034
  this._emit({ type: "load", previous });
1420
2035
  } else {
1421
- this._sources.finishPass();
2036
+ this._resyncSourcesQuietly();
1422
2037
  }
1423
2038
  }
1424
2039
  /**
@@ -1433,17 +2048,17 @@ var ArrangementImpl = class {
1433
2048
  * always received that error).
1434
2049
  */
1435
2050
  _emit(change) {
1436
- const switched = change.type === "mixer" ? null : this._syncSources();
2051
+ const mixOnly = change.type === "mixer" || change.type === "restoreMix" || change.type === "recording";
2052
+ const switched = mixOnly ? null : this._syncSources();
1437
2053
  freezeTracksInDevelopment(this._tracks);
1438
- if (change.type === "remove" || change.type === "restore") {
1439
- this._mixer = retainMixer(this._mixer, this._heldStates());
1440
- }
1441
2054
  const at = {
1442
2055
  tracksVersion: this._tracksVersion,
1443
2056
  mixerVersion: this._mixerVersion
1444
2057
  };
1445
2058
  if (switched && (change.type === "add" || change.type === "update")) at.switched = switched;
1446
- this._pending.push({ change, at });
2059
+ const removed = this._removedNow;
2060
+ this._removedNow = [];
2061
+ this._pending.push({ change, at, removed: Object.freeze(removed) });
1447
2062
  if (this._delivering) return;
1448
2063
  this._delivering = true;
1449
2064
  let failed = false;
@@ -1460,9 +2075,12 @@ var ArrangementImpl = class {
1460
2075
  }
1461
2076
  }
1462
2077
  }
2078
+ const info = Object.freeze(
2079
+ next.removed.length > 0 ? { type: next.change.type, removedClips: next.removed } : { type: next.change.type }
2080
+ );
1463
2081
  for (const subscriber of [...this._subscribers]) {
1464
2082
  try {
1465
- subscriber();
2083
+ subscriber(info);
1466
2084
  } catch (error) {
1467
2085
  console.warn("[waveform-playlist] Error in an arrangement subscriber:", error);
1468
2086
  }
@@ -1482,7 +2100,7 @@ function createArrangement(options = {}) {
1482
2100
  }
1483
2101
 
1484
2102
  // src/adapterSync.ts
1485
- var import_core8 = require("@waveform-playlist/core");
2103
+ var import_core9 = require("@waveform-playlist/core");
1486
2104
  var AdapterSync = class {
1487
2105
  constructor(_arrangement, _adapter) {
1488
2106
  this._arrangement = _arrangement;
@@ -1511,8 +2129,8 @@ var AdapterSync = class {
1511
2129
  }
1512
2130
  /**
1513
2131
  * The arrangement's tracks, each without its loading clips and with the
1514
- * current mixer values in its fields: what every adapter track call and
1515
- * `getState().tracks` use. The same
2132
+ * current mixer values in its fields (muted while a take records onto it): what every
2133
+ * adapter track call and `getState().tracks` use. The same
1516
2134
  * array until the tracks or the mix change, and the same track object
1517
2135
  * while neither that track nor its mix changed.
1518
2136
  */
@@ -1528,6 +2146,14 @@ var AdapterSync = class {
1528
2146
  this._projection = { tracksVersion, mixerVersion, tracks };
1529
2147
  return tracks;
1530
2148
  }
2149
+ /**
2150
+ * `tracks()` as the adapter is given them: without the view fields. Made
2151
+ * for each send; nothing depends on the adapter's tracks keeping their
2152
+ * identity between sends.
2153
+ */
2154
+ _playoutTracks() {
2155
+ return freezeTracksInDevelopment(this.tracks().map((track) => this._playout(track)));
2156
+ }
1531
2157
  /** When an engine attaches: send the tracks that are there. With none, the adapter is in step as it is. */
1532
2158
  sendInitialTracks() {
1533
2159
  if (this._arrangement.getTracks().length > 0) {
@@ -1539,7 +2165,7 @@ var AdapterSync = class {
1539
2165
  /** Send the adapter every track, and remember up to which change that covers. */
1540
2166
  sendAllTracks() {
1541
2167
  const version = this._arrangement.tracksVersion;
1542
- this._adapter?.setTracks(this.tracks());
2168
+ this._adapter?.setTracks(this._playoutTracks());
1543
2169
  this._syncedTracksVersion = version;
1544
2170
  }
1545
2171
  /** Send the arrangement's current track to the adapter. False when there is no such track. */
@@ -1547,18 +2173,42 @@ var AdapterSync = class {
1547
2173
  const track = this._arrangement.getTracks().find((t) => t.id === trackId);
1548
2174
  if (!track) return false;
1549
2175
  if (this._adapter?.updateTrack) {
1550
- this._adapter.updateTrack(trackId, this._project(track));
2176
+ this._adapter.updateTrack(trackId, this._playout(this._project(track)));
1551
2177
  } else {
1552
2178
  this.sendAllTracks();
1553
2179
  }
1554
2180
  return true;
1555
2181
  }
1556
- /** A mixer value changed: the adapter's setter for it. */
2182
+ /**
2183
+ * A mixer value changed: the adapter's setter for it. The mute sent is the
2184
+ * one the track plays with: muted while a take records onto the track,
2185
+ * whatever the value given.
2186
+ */
1557
2187
  sendMixerValues(trackId, values) {
1558
2188
  if (values.volume !== void 0) this._adapter?.setTrackVolume(trackId, values.volume);
1559
- if (values.muted !== void 0) this._adapter?.setTrackMute(trackId, values.muted);
2189
+ if (values.muted !== void 0) {
2190
+ this._adapter?.setTrackMute(trackId, values.muted || this._recordingNow(trackId));
2191
+ }
1560
2192
  if (values.soloed !== void 0) this._adapter?.setTrackSolo(trackId, values.soloed);
1561
2193
  if (values.pan !== void 0) this._adapter?.setTrackPan(trackId, values.pan);
2194
+ if (values.panLaw !== void 0) this._sendPanLaw(trackId, values.panLaw);
2195
+ }
2196
+ /** The adapter's setter for a pan law, or, for an adapter without one, the track again (#684). */
2197
+ _sendPanLaw(trackId, panLaw) {
2198
+ if (!this._adapter) return;
2199
+ if (this._adapter.setTrackPanLaw) this._adapter.setTrackPanLaw(trackId, panLaw);
2200
+ else this.sendTrack(trackId);
2201
+ }
2202
+ /**
2203
+ * After an undo, a redo or an abort brought back another mix: the setter
2204
+ * for each field that differs, of each current track that had an entry in
2205
+ * `previousMixer` too. A track that entered with the restore was sent
2206
+ * whole, with its mix in its fields.
2207
+ */
2208
+ sendMixerDiff(previousMixer) {
2209
+ for (const { trackId, values } of mixerChanges(previousMixer, this._arrangement.getMixer())) {
2210
+ this.sendMixerValues(trackId, values);
2211
+ }
1562
2212
  }
1563
2213
  /**
1564
2214
  * The adapter call for a change to the tracks.
@@ -1631,7 +2281,7 @@ var AdapterSync = class {
1631
2281
  _addTrack(trackId) {
1632
2282
  const track = this._arrangement.getTracks().find((t) => t.id === trackId);
1633
2283
  if (track && this._adapter?.addTrack) {
1634
- this._adapter.addTrack(this._project(track));
2284
+ this._adapter.addTrack(this._playout(this._project(track)));
1635
2285
  } else {
1636
2286
  this.sendAllTracks();
1637
2287
  }
@@ -1671,9 +2321,10 @@ var AdapterSync = class {
1671
2321
  if (before.clips.some((clip, i) => clip !== now.clips[i])) return false;
1672
2322
  const keys = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(now)]);
1673
2323
  keys.delete("clips");
2324
+ for (const field of import_core9.TRACK_VIEW_FIELDS) keys.delete(field);
1674
2325
  return [...keys].every((key) => Object.is(before[key], now[key]));
1675
2326
  }
1676
- /** What an adapter and `getState()` are given for one of the arrangement's tracks. */
2327
+ /** What `getState()` is given for one of the arrangement's tracks (an adapter: `_playout` of it). */
1677
2328
  _project(track) {
1678
2329
  return this._withMix(this._loaded(track));
1679
2330
  }
@@ -1685,27 +2336,46 @@ var AdapterSync = class {
1685
2336
  _loaded(track) {
1686
2337
  const known = this._loadedMemo.get(track);
1687
2338
  if (known) return known;
1688
- const clips = track.clips.filter((clip) => !(0, import_core8.isLoadingClip)(clip));
2339
+ const clips = track.clips.filter((clip) => !(0, import_core9.isLoadingClip)(clip));
1689
2340
  const loaded = clips.length === track.clips.length ? track : { ...track, clips };
1690
2341
  this._loadedMemo.set(track, loaded);
1691
2342
  return loaded;
1692
2343
  }
1693
- /** One track with its current mixer values in its fields (memoized per track object). */
2344
+ /**
2345
+ * True when a take is recording onto the track and it is a current track
2346
+ * (it has an entry in the current mix): it plays muted. A recording id that
2347
+ * is not in the tracks mutes nothing until it enters.
2348
+ */
2349
+ _recordingNow(trackId) {
2350
+ return this._arrangement.recordingTrackIds.has(trackId) && this._arrangement.getMixer().has(trackId);
2351
+ }
2352
+ /** A projected track without its view fields: a copy that shares its clips. */
2353
+ _playout(track) {
2354
+ const copy = { ...track };
2355
+ for (const field of import_core9.TRACK_VIEW_FIELDS) delete copy[field];
2356
+ return freezeTrackInDevelopment(copy);
2357
+ }
2358
+ /**
2359
+ * One track with its current mixer values in its fields, muted while a
2360
+ * take records onto it (memoized per track object).
2361
+ */
1694
2362
  _withMix(track) {
1695
2363
  const values = this._arrangement.getMixer().get(track.id);
2364
+ const recording = this._recordingNow(track.id);
1696
2365
  const memo = this._withMixMemo.get(track);
1697
- if (memo && memo.values === values) return memo.merged;
1698
- const merged = freezeTrackInDevelopment(withMixerValues(track, values));
1699
- this._withMixMemo.set(track, { values, merged });
2366
+ if (memo && memo.values === values && memo.recording === recording) return memo.merged;
2367
+ const playing = recording && values && !values.muted ? { ...values, muted: true } : values;
2368
+ const merged = freezeTrackInDevelopment(withMixerValues(track, playing));
2369
+ this._withMixMemo.set(track, { values, recording, merged });
1700
2370
  return merged;
1701
2371
  }
1702
2372
  };
1703
2373
 
1704
- // src/PlaylistEngine.ts
2374
+ // src/EditorEngine.ts
1705
2375
  var DEFAULT_SAMPLE_RATE = 48e3;
1706
2376
  var DEFAULT_SAMPLES_PER_PIXEL = 1024;
1707
2377
  var DEFAULT_ZOOM_LEVELS = [256, 512, 1024, 2048, 4096, 8192];
1708
- var PlaylistEngine = class {
2378
+ var EditorEngine = class {
1709
2379
  constructor(options = {}) {
1710
2380
  this._detachDecodeContext = null;
1711
2381
  this._currentTime = 0;
@@ -1732,13 +2402,13 @@ var PlaylistEngine = class {
1732
2402
  });
1733
2403
  });
1734
2404
  if (this._zoomLevels.length === 0) {
1735
- throw new Error("PlaylistEngine: zoomLevels must not be empty");
2405
+ throw new Error("EditorEngine: zoomLevels must not be empty");
1736
2406
  }
1737
2407
  const initialSpp = options.samplesPerPixel ?? DEFAULT_SAMPLES_PER_PIXEL;
1738
2408
  const zoomIndex = this._zoomLevels.indexOf(initialSpp);
1739
2409
  if (zoomIndex === -1) {
1740
2410
  throw new Error(
1741
- `PlaylistEngine: samplesPerPixel ${initialSpp} is not in zoomLevels [${this._zoomLevels.join(", ")}]. Either pass a samplesPerPixel value that exists in zoomLevels, or include ${initialSpp} in your zoomLevels array.`
2411
+ `EditorEngine: samplesPerPixel ${initialSpp} is not in zoomLevels [${this._zoomLevels.join(", ")}]. Either pass a samplesPerPixel value that exists in zoomLevels, or include ${initialSpp} in your zoomLevels array.`
1742
2412
  );
1743
2413
  }
1744
2414
  this._zoomIndex = zoomIndex;
@@ -1754,7 +2424,7 @@ var PlaylistEngine = class {
1754
2424
  this._arrangement = asArrangementImpl(options.arrangement);
1755
2425
  if (options.undoLimit !== void 0) {
1756
2426
  console.warn(
1757
- "[waveform-playlist] PlaylistEngine: undoLimit is ignored when an arrangement is passed. Set it on createArrangement({ undoLimit })."
2427
+ "[waveform-playlist] EditorEngine: undoLimit is ignored when an arrangement is passed. Set it on createArrangement({ undoLimit })."
1758
2428
  );
1759
2429
  }
1760
2430
  } else {
@@ -1846,8 +2516,8 @@ var PlaylistEngine = class {
1846
2516
  setTracks(tracks) {
1847
2517
  this._arrangement.setTracks(tracks);
1848
2518
  }
1849
- addTrack(track) {
1850
- this._arrangement.addTrack(track);
2519
+ addTrack(track, options) {
2520
+ this._arrangement.addTrack(track, options);
1851
2521
  }
1852
2522
  removeTrack(trackId) {
1853
2523
  this._arrangement.removeTrack(trackId);
@@ -2071,9 +2741,13 @@ var PlaylistEngine = class {
2071
2741
  //
2072
2742
  // Each setter writes the value into the arrangement's mixer part (so a later
2073
2743
  // adapter rebuild via setTracks keeps the value, and mixerVersion is bumped);
2074
- // the engine's listener then calls the adapter and emits statechange. For a
2075
- // track the arrangement does not hold nothing changes, and the adapter is
2076
- // still called from here (a consumer may target a track that has not been
2744
+ // the engine's listener then calls the adapter and emits statechange. Each
2745
+ // call is an undo step, unless `options` says otherwise: the same `gesture`
2746
+ // id joins one step, `undoable: false` is no step (`MixerChangeOptions`).
2747
+ //
2748
+ // When the arrangement changes nothing (a track it does not hold, or the
2749
+ // value the track already has), the adapter is still called from here,
2750
+ // with no statechange (a consumer may target a track that has not been
2077
2751
  // ingested yet). These are NOT structural
2078
2752
  // changes, so they deliberately do NOT bump tracksVersion — that would make
2079
2753
  // tracksVersion-gated consumers re-run expensive structural work (audio-graph
@@ -2081,22 +2755,58 @@ var PlaylistEngine = class {
2081
2755
  // cache a track snapshot (e.g. @dawcore/components' <daw-editor>) watch
2082
2756
  // mixerVersion to refresh that cache cheaply, so an unrelated setTracks
2083
2757
  // rebuild no longer reverts live mixer state (#501).
2084
- setTrackVolume(trackId, volume) {
2085
- const changed = this._mixerChanged(() => this._arrangement.setTrackVolume(trackId, volume));
2758
+ setTrackVolume(trackId, volume, options) {
2759
+ const changed = this._mixerChanged(
2760
+ () => this._arrangement.setTrackVolume(trackId, volume, options)
2761
+ );
2086
2762
  if (!changed && !this._disposed) this._adapter?.setTrackVolume(trackId, volume);
2087
2763
  }
2088
- setTrackMute(trackId, muted) {
2089
- const changed = this._mixerChanged(() => this._arrangement.setTrackMute(trackId, muted));
2090
- if (!changed && !this._disposed) this._adapter?.setTrackMute(trackId, muted);
2764
+ setTrackMute(trackId, muted, options) {
2765
+ const changed = this._mixerChanged(
2766
+ () => this._arrangement.setTrackMute(trackId, muted, options)
2767
+ );
2768
+ if (!changed && !this._disposed) this._adapterSync.sendMixerValues(trackId, { muted });
2091
2769
  }
2092
- setTrackSolo(trackId, soloed) {
2093
- const changed = this._mixerChanged(() => this._arrangement.setTrackSolo(trackId, soloed));
2770
+ setTrackSolo(trackId, soloed, options) {
2771
+ const changed = this._mixerChanged(
2772
+ () => this._arrangement.setTrackSolo(trackId, soloed, options)
2773
+ );
2094
2774
  if (!changed && !this._disposed) this._adapter?.setTrackSolo(trackId, soloed);
2095
2775
  }
2096
- setTrackPan(trackId, pan) {
2097
- const changed = this._mixerChanged(() => this._arrangement.setTrackPan(trackId, pan));
2776
+ setTrackPan(trackId, pan, options) {
2777
+ const changed = this._mixerChanged(() => this._arrangement.setTrackPan(trackId, pan, options));
2098
2778
  if (!changed && !this._disposed) this._adapter?.setTrackPan(trackId, pan);
2099
2779
  }
2780
+ /**
2781
+ * Set a track's pan law (#684): the arrangement's `setTrackPanLaw`.
2782
+ * Unlike the four setters above, nothing is sent to the adapter when the
2783
+ * arrangement changed nothing (a track it does not hold, the law the
2784
+ * track already has): for an adapter without `setTrackPanLaw` the call
2785
+ * would be a whole-track `updateTrack`.
2786
+ */
2787
+ setTrackPanLaw(trackId, panLaw, options) {
2788
+ this._arrangement.setTrackPanLaw(trackId, panLaw, options);
2789
+ }
2790
+ /**
2791
+ * Mark a track as the one a take is recording onto, or clear it when the
2792
+ * take ends: the arrangement's `setTrackRecording`. That track plays muted
2793
+ * (here and in the adapter) while its mute in the mix stays as it is; the
2794
+ * take's mute is not an undo step. The arrangement's `'recording'`
2795
+ * announcement brings the adapter in step, so there is no adapter call of
2796
+ * its own here; a disposed engine changes the arrangement only.
2797
+ */
2798
+ setTrackRecording(trackId, recording) {
2799
+ this._arrangement.setTrackRecording(trackId, recording);
2800
+ }
2801
+ /**
2802
+ * The tracks a take is recording onto, read from the arrangement (the
2803
+ * owner; no copy). The same set object until it changes; never write to
2804
+ * it, use `setTrackRecording`. Such a track plays muted, so a UI can
2805
+ * disable its mute control while the id is in the set.
2806
+ */
2807
+ get recordingTrackIds() {
2808
+ return this._arrangement.recordingTrackIds;
2809
+ }
2100
2810
  // ---------------------------------------------------------------------------
2101
2811
  // Zoom
2102
2812
  // ---------------------------------------------------------------------------
@@ -2133,8 +2843,9 @@ var PlaylistEngine = class {
2133
2843
  // ---------------------------------------------------------------------------
2134
2844
  // Lifecycle
2135
2845
  // ---------------------------------------------------------------------------
2136
- dispose() {
2846
+ dispose(options = {}) {
2137
2847
  if (this._disposed) return;
2848
+ if (options.keepAdapter && this._isPlaying) this.stop();
2138
2849
  this._disposed = true;
2139
2850
  this._stopFollowingArrangement();
2140
2851
  this._detachFromArrangement();
@@ -2143,7 +2854,8 @@ var PlaylistEngine = class {
2143
2854
  this._isPlaying = false;
2144
2855
  this._adapter?.onPlaybackEnded?.(null);
2145
2856
  try {
2146
- this._adapter?.dispose();
2857
+ if (options.keepAdapter) this._adapter?.setTracks([]);
2858
+ else this._adapter?.dispose();
2147
2859
  } catch (err) {
2148
2860
  console.warn("[waveform-playlist/engine] Error disposing adapter:", err);
2149
2861
  }
@@ -2169,6 +2881,14 @@ var PlaylistEngine = class {
2169
2881
  case "mixer":
2170
2882
  this._adapterSync.sendMixerValues(change.trackId, change.values);
2171
2883
  break;
2884
+ case "restoreMix":
2885
+ this._adapterSync.sendMixerDiff(change.previousMixer);
2886
+ break;
2887
+ case "recording": {
2888
+ const values = this._arrangement.getMixer().get(change.trackId);
2889
+ if (values) this._adapterSync.sendMixerValues(change.trackId, { muted: values.muted });
2890
+ break;
2891
+ }
2172
2892
  case "reorder":
2173
2893
  // not audible: adapter nodes are keyed by track id
2174
2894
  case "history":
@@ -2181,6 +2901,7 @@ var PlaylistEngine = class {
2181
2901
  this._followLoad(change, at);
2182
2902
  } else {
2183
2903
  this._adapterSync.follow(change, at);
2904
+ if (change.type === "restore") this._adapterSync.sendMixerDiff(change.previousMixer);
2184
2905
  }
2185
2906
  }
2186
2907
  this._emitStateChange();
@@ -2252,12 +2973,12 @@ var PlaylistEngine = class {
2252
2973
  function asArrangementImpl(arrangement) {
2253
2974
  if (isArrangement(arrangement)) return arrangement;
2254
2975
  throw new Error(
2255
- "[waveform-playlist] PlaylistEngine: the `arrangement` option must be an arrangement made by createArrangement()."
2976
+ "[waveform-playlist] EditorEngine: the `arrangement` option must be an arrangement made by createArrangement()."
2256
2977
  );
2257
2978
  }
2258
2979
  // Annotate the CommonJS export names for ESM import in node:
2259
2980
  0 && (module.exports = {
2260
- PlaylistEngine,
2981
+ EditorEngine,
2261
2982
  attachDecodeContext,
2262
2983
  calculateDuration,
2263
2984
  calculateSplitPoint,
@@ -2269,9 +2990,12 @@ function asArrangementImpl(arrangement) {
2269
2990
  constrainClipDrag,
2270
2991
  createArrangement,
2271
2992
  defaultLoadSource,
2993
+ findClipOverlap,
2272
2994
  findClosestZoomIndex,
2273
2995
  getVisibleChunkIndices,
2996
+ isArrangement,
2274
2997
  shouldUpdateViewport,
2275
- splitClip
2998
+ splitClip,
2999
+ trackClipSpans
2276
3000
  });
2277
3001
  //# sourceMappingURL=index.js.map