@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.mjs CHANGED
@@ -1,42 +1,58 @@
1
1
  // src/operations/clipOperations.ts
2
- import { createClip } from "@waveform-playlist/core";
2
+ import { createClip, isLoadingClip, loadingClipSpan } from "@waveform-playlist/core";
3
+ var spansMemo = /* @__PURE__ */ new WeakMap();
4
+ function trackClipSpans(clips, sampleRate) {
5
+ const memo = spansMemo.get(clips);
6
+ if (memo && memo.sampleRate === sampleRate) return memo.spans;
7
+ const spans = [];
8
+ for (const clip of clips) {
9
+ if (!isLoadingClip(clip)) {
10
+ spans.push(clip);
11
+ continue;
12
+ }
13
+ const span = loadingClipSpan(clip, sampleRate);
14
+ if (!span) continue;
15
+ const durationSamples = span.endSample === null ? 1 : span.endSample - span.startSample;
16
+ spans.push({ id: clip.id, startSample: span.startSample, durationSamples });
17
+ }
18
+ spans.sort((a, b) => a.startSample - b.startSample);
19
+ spansMemo.set(clips, { sampleRate, spans });
20
+ return spans;
21
+ }
22
+ function clampKeepingZero(delta, lower, upper) {
23
+ const clamped = Math.min(Math.max(delta, Math.min(lower, 0)), Math.max(upper, 0));
24
+ return clamped === 0 ? 0 : clamped;
25
+ }
3
26
  function constrainClipDrag(clip, deltaSamples, sortedClips, clipIndex) {
4
- let delta = deltaSamples;
5
- const minDelta = -clip.startSample;
6
- delta = Math.max(delta, minDelta);
27
+ let lower = -clip.startSample;
28
+ let upper = Number.POSITIVE_INFINITY;
7
29
  if (clipIndex > 0) {
8
30
  const prevClip = sortedClips[clipIndex - 1];
9
- const prevClipEnd = prevClip.startSample + prevClip.durationSamples;
10
- const minDeltaPrev = prevClipEnd - clip.startSample;
11
- delta = Math.max(delta, minDeltaPrev);
31
+ lower = Math.max(lower, prevClip.startSample + prevClip.durationSamples - clip.startSample);
12
32
  }
13
33
  if (clipIndex < sortedClips.length - 1) {
14
34
  const nextClip = sortedClips[clipIndex + 1];
15
- const maxDeltaNext = nextClip.startSample - (clip.startSample + clip.durationSamples);
16
- delta = Math.min(delta, maxDeltaNext);
35
+ upper = Math.min(upper, nextClip.startSample - (clip.startSample + clip.durationSamples));
17
36
  }
18
- return delta;
37
+ return clampKeepingZero(deltaSamples, lower, upper);
19
38
  }
20
39
  function constrainBoundaryTrim(clip, deltaSamples, boundary, sortedClips, clipIndex, minDurationSamples) {
21
- let delta = deltaSamples;
22
40
  if (boundary === "left") {
23
- delta = Math.max(delta, -clip.startSample);
24
- delta = Math.max(delta, -clip.offsetSamples);
41
+ let lower2 = Math.max(-clip.startSample, -clip.offsetSamples);
25
42
  if (clipIndex > 0) {
26
43
  const prevClip = sortedClips[clipIndex - 1];
27
- const prevClipEnd = prevClip.startSample + prevClip.durationSamples;
28
- delta = Math.max(delta, prevClipEnd - clip.startSample);
29
- }
30
- delta = Math.min(delta, clip.durationSamples - minDurationSamples);
31
- } else {
32
- delta = Math.max(delta, minDurationSamples - clip.durationSamples);
33
- delta = Math.min(delta, clip.sourceDurationSamples - clip.offsetSamples - clip.durationSamples);
34
- if (clipIndex < sortedClips.length - 1) {
35
- const nextClip = sortedClips[clipIndex + 1];
36
- delta = Math.min(delta, nextClip.startSample - clip.startSample - clip.durationSamples);
44
+ lower2 = Math.max(lower2, prevClip.startSample + prevClip.durationSamples - clip.startSample);
37
45
  }
46
+ const upper2 = clip.durationSamples - minDurationSamples;
47
+ return clampKeepingZero(deltaSamples, lower2, upper2);
48
+ }
49
+ const lower = minDurationSamples - clip.durationSamples;
50
+ let upper = clip.sourceDurationSamples - clip.offsetSamples - clip.durationSamples;
51
+ if (clipIndex < sortedClips.length - 1) {
52
+ const nextClip = sortedClips[clipIndex + 1];
53
+ upper = Math.min(upper, nextClip.startSample - clip.startSample - clip.durationSamples);
38
54
  }
39
- return delta;
55
+ return clampKeepingZero(deltaSamples, lower, upper);
40
56
  }
41
57
  function calculateSplitPoint(splitSample, samplesPerPixel) {
42
58
  return Math.floor(splitSample / samplesPerPixel) * samplesPerPixel;
@@ -44,22 +60,31 @@ function calculateSplitPoint(splitSample, samplesPerPixel) {
44
60
  function splitClip(clip, splitSample) {
45
61
  const leftDuration = splitSample - clip.startSample;
46
62
  const rightDuration = clip.durationSamples - leftDuration;
63
+ const midi = {
64
+ midiNotes: clip.midiNotes,
65
+ midiChannel: clip.midiChannel,
66
+ midiProgram: clip.midiProgram
67
+ };
47
68
  const leftName = clip.name ? `${clip.name} (1)` : void 0;
48
69
  const rightName = clip.name ? `${clip.name} (2)` : void 0;
49
- const left = createClip({
50
- startSample: clip.startSample,
51
- durationSamples: leftDuration,
52
- offsetSamples: clip.offsetSamples,
53
- sampleRate: clip.sampleRate,
54
- sourceDurationSamples: clip.sourceDurationSamples,
55
- gain: clip.gain,
56
- name: leftName,
57
- color: clip.color,
58
- fadeIn: clip.fadeIn,
59
- audioBuffer: clip.audioBuffer,
60
- waveformData: clip.waveformData,
61
- src: clip.src
62
- });
70
+ const left = {
71
+ ...createClip({
72
+ startSample: clip.startSample,
73
+ durationSamples: leftDuration,
74
+ offsetSamples: clip.offsetSamples,
75
+ sampleRate: clip.sampleRate,
76
+ sourceDurationSamples: clip.sourceDurationSamples,
77
+ gain: clip.gain,
78
+ name: leftName,
79
+ color: clip.color,
80
+ fadeIn: clip.fadeIn,
81
+ audioBuffer: clip.audioBuffer,
82
+ waveformData: clip.waveformData,
83
+ src: clip.src,
84
+ ...midi
85
+ }),
86
+ id: clip.id
87
+ };
63
88
  const right = createClip({
64
89
  startSample: splitSample,
65
90
  durationSamples: rightDuration,
@@ -72,7 +97,8 @@ function splitClip(clip, splitSample) {
72
97
  fadeOut: clip.fadeOut,
73
98
  audioBuffer: clip.audioBuffer,
74
99
  waveformData: clip.waveformData,
75
- src: clip.src
100
+ src: clip.src,
101
+ ...midi
76
102
  });
77
103
  return { left, right };
78
104
  }
@@ -149,14 +175,14 @@ function clampSeekPosition(time, duration) {
149
175
  }
150
176
 
151
177
  // src/arrangement/Arrangement.ts
152
- import { isLoadingClip as isLoadingClip5 } from "@waveform-playlist/core";
178
+ import { isDecidedPanLaw as isDecidedPanLaw2, isLoadingClip as isLoadingClip7, trackKind as trackKind2 } from "@waveform-playlist/core";
153
179
 
154
180
  // src/arrangement/attach.ts
155
181
  var ARRANGEMENT_ATTACH_DECODE = /* @__PURE__ */ Symbol.for(
156
- "@waveform-playlist/engine/arrangement/attach-decode/v1"
182
+ "@waveform-playlist/engine/arrangement/attach-decode/v3"
157
183
  );
158
184
  var ARRANGEMENT_ATTACH_TIME_BASE = /* @__PURE__ */ Symbol.for(
159
- "@waveform-playlist/engine/arrangement/time-base/v1"
185
+ "@waveform-playlist/engine/arrangement/time-base/v3"
160
186
  );
161
187
  function attachPoints(value) {
162
188
  return typeof value === "object" && value !== null ? value : {};
@@ -179,13 +205,14 @@ function attachTimeBase(arrangement, timeBase) {
179
205
  }
180
206
 
181
207
  // src/arrangement/clipEdits.ts
182
- import { isLoadingClip, sortClipsByTime } from "@waveform-playlist/core";
183
- function loadedClips(track) {
184
- return track.clips.filter((clip) => !isLoadingClip(clip));
208
+ import { isLoadingClip as isLoadingClip2 } from "@waveform-playlist/core";
209
+ function neighboursOf(track, clip) {
210
+ const sortedClips = trackClipSpans(track.clips, clip.sampleRate);
211
+ return { sortedClips, sortedIndex: sortedClips.indexOf(clip) };
185
212
  }
186
213
  function loadedClip(tracks, trackId, clipId) {
187
214
  const clip = tracks.find((t) => t.id === trackId)?.clips.find((c) => c.id === clipId);
188
- return clip && !isLoadingClip(clip) ? clip : void 0;
215
+ return clip && !isLoadingClip2(clip) ? clip : void 0;
189
216
  }
190
217
  function findClip(tracks, trackId, clipId, operation) {
191
218
  const track = tracks.find((t) => t.id === trackId);
@@ -201,7 +228,7 @@ function findClip(tracks, trackId, clipId, operation) {
201
228
  return null;
202
229
  }
203
230
  const clip = track.clips[clipIndex];
204
- if (isLoadingClip(clip)) {
231
+ if (isLoadingClip2(clip)) {
205
232
  console.warn(
206
233
  `[waveform-playlist/engine] ${operation}: clip "${clipId}" in track "${trackId}" is still loading and cannot be edited until its audio has loaded`
207
234
  );
@@ -226,8 +253,7 @@ function constrainTrim(tracks, trackId, clipId, boundary, deltaSamples, time) {
226
253
  const track = tracks.find((t) => t.id === trackId);
227
254
  const clip = loadedClip(tracks, trackId, clipId);
228
255
  if (!track || !clip) return 0;
229
- const sortedClips = sortClipsByTime(loadedClips(track));
230
- const sortedIndex = sortedClips.findIndex((c) => c.id === clipId);
256
+ const { sortedClips, sortedIndex } = neighboursOf(track, clip);
231
257
  return constrainBoundaryTrim(
232
258
  clip,
233
259
  deltaSamples,
@@ -241,8 +267,7 @@ function moveClip(tracks, trackId, clipId, deltaSamples, time) {
241
267
  const found = findClip(tracks, trackId, clipId, "moveClip");
242
268
  if (!found) return null;
243
269
  const { track, clip, clipIndex } = found;
244
- const sortedClips = sortClipsByTime(loadedClips(track));
245
- const sortedIndex = sortedClips.findIndex((c) => c.id === clipId);
270
+ const { sortedClips, sortedIndex } = neighboursOf(track, clip);
246
271
  const delta = constrainClipDrag(clip, deltaSamples, sortedClips, sortedIndex);
247
272
  if (delta === 0) return null;
248
273
  const startSample = Math.floor(clip.startSample + delta);
@@ -388,10 +413,11 @@ var defaultLoadSource = async (src, { signal, audioContext }) => {
388
413
  };
389
414
 
390
415
  // src/arrangement/sources.ts
391
- import { createSourceLoader, createValueSource, isLoadingClip as isLoadingClip2 } from "@waveform-playlist/core";
416
+ import { createSourceLoader, createValueSource, isLoadingClip as isLoadingClip3 } from "@waveform-playlist/core";
392
417
 
393
418
  // src/arrangement/resolveLoadingClip.ts
394
- import { createClip as createClip2 } from "@waveform-playlist/core";
419
+ import { createClip as createClip2, durationSamplesFromSeconds } from "@waveform-playlist/core";
420
+ var NOTHING_LEFT = /* @__PURE__ */ Symbol("nothing left");
395
421
  var warned = /* @__PURE__ */ new WeakMap();
396
422
  function label(loading) {
397
423
  return `clip "${loading.id}"`;
@@ -421,10 +447,10 @@ function fieldProblem(loading) {
421
447
  return null;
422
448
  }
423
449
  function fitDuration(loading, offsetSamples, total, rate) {
424
- if (!(offsetSamples < total)) return { problem: "offset is at or past the end of the audio" };
450
+ if (!(offsetSamples < total)) return NOTHING_LEFT;
425
451
  const rest = total - offsetSamples;
426
452
  const duration = givenDuration(loading);
427
- const wanted = duration === void 0 ? rest : Math.round(duration * rate);
453
+ const wanted = duration === void 0 ? rest : durationSamplesFromSeconds(loading.start ?? 0, duration, rate);
428
454
  if (!(wanted >= 1)) return { problem: "duration is shorter than one sample" };
429
455
  if (wanted > rest + 1) {
430
456
  warnOnce(loading, "duration runs past the end of the audio and was cut to it");
@@ -444,6 +470,7 @@ function convert(loading, buffer) {
444
470
  return "start or offset is too large";
445
471
  }
446
472
  const fitted = fitDuration(loading, offsetSamples, buffer.length, rate);
473
+ if (fitted === NOTHING_LEFT) return NOTHING_LEFT;
447
474
  if ("problem" in fitted) return fitted.problem;
448
475
  return {
449
476
  ...createClip2({
@@ -469,8 +496,33 @@ function resolveLoadingClip(loading, buffer) {
469
496
  } catch (error) {
470
497
  converted = error instanceof Error ? error.message : String(error);
471
498
  }
499
+ if (converted === NOTHING_LEFT) {
500
+ warnOnce(loading, "its offset is at or past the end of its audio; the clip is removed");
501
+ return { removed: `${label(loading)}: its offset is at or past the end of its audio` };
502
+ }
472
503
  return typeof converted === "string" ? { unusable: `${label(loading)}: ${converted}` } : { clip: converted };
473
504
  }
505
+ var cuts = /* @__PURE__ */ new WeakMap();
506
+ function fitArrivedClip(loading, clip, others) {
507
+ const start = clip.startSample;
508
+ const end = start + clip.durationSamples;
509
+ const covering = others.find(
510
+ (o) => o.startSample <= start && o.startSample + o.durationSamples > start
511
+ );
512
+ if (covering) {
513
+ return { unusable: `${label(loading)}: its start lies inside clip "${covering.id}"` };
514
+ }
515
+ const next = others.find((o) => o.startSample > start);
516
+ if (!next || next.startSample >= end) return { clip };
517
+ warnOnce(loading, `its audio ran into clip "${next.id}" and was cut where it starts`);
518
+ const byEnd = cuts.get(clip) ?? /* @__PURE__ */ new Map();
519
+ cuts.set(clip, byEnd);
520
+ const known = byEnd.get(next.startSample);
521
+ if (known) return { clip: known };
522
+ const cut = { ...clip, durationSamples: next.startSample - start };
523
+ byEnd.set(next.startSample, cut);
524
+ return { clip: cut };
525
+ }
474
526
 
475
527
  // src/arrangement/sources.ts
476
528
  var EMPTY_VALUE = {
@@ -601,20 +653,32 @@ var ArrangementSources = class {
601
653
  this._unusable = unusable;
602
654
  const seen = /* @__PURE__ */ new Map();
603
655
  let inCurrentTracks = false;
656
+ const removals = /* @__PURE__ */ new Map();
657
+ let trackIdNow = "";
658
+ const refuse = (clip, reason) => {
659
+ if (inCurrentTracks && !unusable.has(clip.src)) unusable.set(clip.src, reason);
660
+ return clip;
661
+ };
604
662
  const switched = (clip) => {
605
663
  const state = loaded.get(clip.src);
606
664
  if (state?.status !== "loaded") return clip;
607
665
  const result = this._resolve(clip, state.value, tickAt);
608
666
  if ("clip" in result) return result.clip;
609
- if (inCurrentTracks && !unusable.has(clip.src)) unusable.set(clip.src, result.unusable);
610
- return clip;
667
+ if ("removed" in result) {
668
+ const set = removals.get(trackIdNow) ?? /* @__PURE__ */ new Set();
669
+ removals.set(trackIdNow, set.add(clip));
670
+ return clip;
671
+ }
672
+ return refuse(clip, result.unusable);
611
673
  };
612
674
  const mapTrack = (track) => {
613
675
  const known = seen.get(track);
614
676
  if (known) return known;
615
677
  let next = track;
616
678
  if (this._sourcesOf(track).loading.length > 0) {
617
- const clips = track.clips.map((clip) => isLoadingClip2(clip) ? switched(clip) : clip);
679
+ trackIdNow = track.id;
680
+ const mapped = track.clips.map((clip) => isLoadingClip3(clip) ? switched(clip) : clip);
681
+ const clips = fitArrivals(track.clips, mapped, refuse, removals.get(track.id));
618
682
  if (clips.some((clip, i) => clip !== track.clips[i])) next = { ...track, clips };
619
683
  }
620
684
  seen.set(track, next);
@@ -633,7 +697,8 @@ var ArrangementSources = class {
633
697
  inCurrentTracks = false;
634
698
  }
635
699
  },
636
- stored: (tracks) => apply(tracks)
700
+ stored: (tracks) => apply(tracks),
701
+ removals: () => removals
637
702
  };
638
703
  }
639
704
  /** After a pass over every state: publish `value` if a status changed. */
@@ -658,7 +723,7 @@ var ArrangementSources = class {
658
723
  const loading = [];
659
724
  const carried = [];
660
725
  for (const clip of track.clips) {
661
- if (isLoadingClip2(clip)) loading.push(clip);
726
+ if (isLoadingClip3(clip)) loading.push(clip);
662
727
  else if (clip.src !== void 0 && clip.audioBuffer)
663
728
  carried.push([clip.src, clip.audioBuffer]);
664
729
  }
@@ -693,6 +758,22 @@ var ArrangementSources = class {
693
758
  return { sources, pendingCount, failedCount, isLoading: pendingCount > 0 };
694
759
  }
695
760
  };
761
+ function fitArrivals(before, after, refuse, removed = /* @__PURE__ */ new Set()) {
762
+ const arrived = after.map((_, i) => i).filter((i) => isLoadingClip3(before[i]) && !isLoadingClip3(after[i])).sort((i, j) => after[i].startSample - after[j].startSample);
763
+ if (arrived.length === 0) return after;
764
+ const result = [...after];
765
+ for (const i of arrived) {
766
+ const clip = result[i];
767
+ const others = trackClipSpans(
768
+ result.filter((c, j) => j !== i && !(isLoadingClip3(c) && removed.has(c))),
769
+ clip.sampleRate
770
+ );
771
+ const loading = before[i];
772
+ const fit = fitArrivedClip(loading, clip, others);
773
+ result[i] = "clip" in fit ? fit.clip : refuse(loading, "unusable" in fit ? fit.unusable : fit.removed);
774
+ }
775
+ return result;
776
+ }
696
777
  function sameValue(a, b) {
697
778
  if (a.sources.size !== b.sources.size) return false;
698
779
  for (const [src, state] of b.sources) {
@@ -702,30 +783,151 @@ function sameValue(a, b) {
702
783
  return true;
703
784
  }
704
785
 
786
+ // src/arrangement/mixer.ts
787
+ import {
788
+ DEFAULT_PAN_LAW,
789
+ audioPanLaw,
790
+ isDecidedPanLaw,
791
+ isLoadingClip as isLoadingClip4,
792
+ trackKind
793
+ } from "@waveform-playlist/core";
794
+ var EMPTY_MIXER = /* @__PURE__ */ new Map();
795
+ var DEFAULT_VOLUME = 1;
796
+ var DEFAULT_PAN = 0;
797
+ function mixerValuesOf(track) {
798
+ return {
799
+ volume: track.volume ?? DEFAULT_VOLUME,
800
+ muted: track.muted ?? false,
801
+ soloed: track.soloed ?? false,
802
+ pan: track.pan ?? DEFAULT_PAN,
803
+ panLaw: enteringPanLaw(track)
804
+ };
805
+ }
806
+ function decidedByAudio(track) {
807
+ if (trackKind(track) === "midi") return null;
808
+ return audioPanLaw({
809
+ clips: track.clips.filter((clip) => !isLoadingClip4(clip))
810
+ });
811
+ }
812
+ function enteringPanLaw(track) {
813
+ if (trackKind(track) === "midi") return DEFAULT_PAN_LAW;
814
+ if (isDecidedPanLaw(track.panLaw)) return track.panLaw;
815
+ return decidedByAudio(track) ?? DEFAULT_PAN_LAW;
816
+ }
817
+ function decidePanLaws(mixer, tracks) {
818
+ let next = null;
819
+ for (const track of tracks) {
820
+ const entry = mixer.get(track.id);
821
+ if (!entry || entry.panLaw !== DEFAULT_PAN_LAW) continue;
822
+ const panLaw = decidedByAudio(track);
823
+ if (!panLaw) continue;
824
+ if (!next) next = new Map(mixer);
825
+ next.set(track.id, { ...entry, panLaw });
826
+ }
827
+ return next ?? mixer;
828
+ }
829
+ function seedMixer(mixer, tracks) {
830
+ let next = null;
831
+ for (const track of tracks) {
832
+ if ((next ?? mixer).has(track.id)) continue;
833
+ if (!next) next = new Map(mixer);
834
+ next.set(track.id, mixerValuesOf(track));
835
+ }
836
+ return next ?? mixer;
837
+ }
838
+ function setMixerValues(mixer, trackId, patch) {
839
+ const entry = mixer.get(trackId);
840
+ if (!entry) return mixer;
841
+ const next = { ...entry, ...patch };
842
+ if (sameValues(entry, next)) return mixer;
843
+ return new Map(mixer).set(trackId, next);
844
+ }
845
+ function carryMixerEntry(mixer, fromId, toId) {
846
+ const entry = mixer.get(fromId);
847
+ if (!entry || fromId === toId) return mixer;
848
+ return new Map(
849
+ [...mixer].filter(([id]) => id !== toId).map(([id, values]) => [id === fromId ? toId : id, values])
850
+ );
851
+ }
852
+ function mixerOf(mixer, tracks) {
853
+ const ids = new Set(tracks.map((track) => track.id));
854
+ const seeded = seedMixer(mixer, tracks);
855
+ if (seeded.size === ids.size) return seeded;
856
+ return new Map([...seeded].filter(([id]) => ids.has(id)));
857
+ }
858
+ function withoutEntry(mixer, trackId) {
859
+ if (!mixer.has(trackId)) return mixer;
860
+ const next = new Map(mixer);
861
+ next.delete(trackId);
862
+ return next;
863
+ }
864
+ function sameValues(a, b) {
865
+ return a.volume === b.volume && a.muted === b.muted && a.soloed === b.soloed && a.pan === b.pan && a.panLaw === b.panLaw;
866
+ }
867
+ function sameMixerValues(a, b) {
868
+ if (a === b) return true;
869
+ if (a.size !== b.size) return false;
870
+ for (const [id, values] of a) {
871
+ const other = b.get(id);
872
+ if (!other || !sameValues(values, other)) return false;
873
+ }
874
+ return true;
875
+ }
876
+ function mixerChanges(before, after) {
877
+ if (before === after) return [];
878
+ const changes = [];
879
+ for (const [trackId, now] of after) {
880
+ const was = before.get(trackId);
881
+ if (!was || was === now) continue;
882
+ const values = {};
883
+ if (was.volume !== now.volume) values.volume = now.volume;
884
+ if (was.muted !== now.muted) values.muted = now.muted;
885
+ if (was.soloed !== now.soloed) values.soloed = now.soloed;
886
+ if (was.pan !== now.pan) values.pan = now.pan;
887
+ if (was.panLaw !== now.panLaw) values.panLaw = now.panLaw;
888
+ if (Object.keys(values).length > 0) changes.push({ trackId, values });
889
+ }
890
+ return changes;
891
+ }
892
+ function withMixerValues(track, values) {
893
+ 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.
894
+ (track.panLaw ?? DEFAULT_PAN_LAW) === values.panLaw) {
895
+ return track;
896
+ }
897
+ return { ...track, ...values };
898
+ }
899
+
705
900
  // src/arrangement/history.ts
706
901
  var EMPTY_HISTORY = { undo: [], redo: [] };
707
- function pushStep(history, tracks, limit) {
708
- const undo = [...history.undo, tracks];
902
+ function pushStep(history, state, limit) {
903
+ const undo = [...history.undo, state];
709
904
  return { undo: undo.length > limit ? undo.slice(undo.length - limit) : undo, redo: [] };
710
905
  }
711
906
  function undoStep(history, current) {
712
907
  if (history.undo.length === 0) return null;
713
- const tracks = history.undo[history.undo.length - 1];
908
+ const state = history.undo[history.undo.length - 1];
714
909
  return {
715
910
  history: { undo: history.undo.slice(0, -1), redo: [...history.redo, current] },
716
- tracks
911
+ state
717
912
  };
718
913
  }
719
914
  function redoStep(history, current) {
720
915
  if (history.redo.length === 0) return null;
721
- const tracks = history.redo[history.redo.length - 1];
916
+ const state = history.redo[history.redo.length - 1];
722
917
  return {
723
918
  history: { undo: [...history.undo, current], redo: history.redo.slice(0, -1) },
724
- tracks
919
+ state
725
920
  };
726
921
  }
727
- function beginBase(tracks) {
728
- return { tracks, changed: false };
922
+ function beginBase(state) {
923
+ return { state, changed: false };
924
+ }
925
+ function withStateTracks(state, tracks) {
926
+ return tracks === state.tracks ? state : { ...state, tracks };
927
+ }
928
+ function mapHistoryTracks(history, map) {
929
+ const each = (state) => withStateTracks(state, map(state.tracks));
930
+ return { undo: history.undo.map(each), redo: history.redo.map(each) };
729
931
  }
730
932
  function withoutTrack(tracks, trackId) {
731
933
  return tracks.some((track) => track.id === trackId) ? tracks.filter((track) => track.id !== trackId) : tracks;
@@ -733,75 +935,176 @@ function withoutTrack(tracks, trackId) {
733
935
  function sameTracks(a, b) {
734
936
  return a === b || a.length === b.length && a.every((track, i) => track === b[i]);
735
937
  }
736
- function purgeTrack(history, current, trackId) {
737
- const nextCurrent = withoutTrack(current, trackId);
938
+ function sameState(a, b) {
939
+ return a === b || sameTracks(a.tracks, b.tracks) && sameMixerValues(a.mixer, b.mixer);
940
+ }
941
+ function stateWithoutTrack(trackId) {
942
+ const mixers = /* @__PURE__ */ new Map();
943
+ const mixerWithout = (mixer) => {
944
+ const known = mixers.get(mixer);
945
+ if (known) return known;
946
+ const next = withoutEntry(mixer, trackId);
947
+ mixers.set(mixer, next);
948
+ return next;
949
+ };
950
+ return (state) => {
951
+ const tracks = withoutTrack(state.tracks, trackId);
952
+ const mixer = mixerWithout(state.mixer);
953
+ return tracks === state.tracks && mixer === state.mixer ? state : { tracks, mixer };
954
+ };
955
+ }
956
+ function dropRepeats(history, current) {
738
957
  const undo = [];
739
958
  for (const step of history.undo) {
740
- const stripped = withoutTrack(step, trackId);
741
- if (undo.length === 0 || !sameTracks(undo[undo.length - 1], stripped)) undo.push(stripped);
959
+ if (undo.length === 0 || !sameState(undo[undo.length - 1], step)) undo.push(step);
742
960
  }
743
- while (undo.length > 0 && sameTracks(undo[undo.length - 1], nextCurrent)) undo.pop();
961
+ while (undo.length > 0 && sameState(undo[undo.length - 1], current)) undo.pop();
744
962
  const redoFromCurrent = [];
745
963
  for (let i = history.redo.length - 1; i >= 0; i--) {
746
- const stripped = withoutTrack(history.redo[i], trackId);
747
- const before = redoFromCurrent.length > 0 ? redoFromCurrent[redoFromCurrent.length - 1] : nextCurrent;
748
- if (!sameTracks(before, stripped)) redoFromCurrent.push(stripped);
964
+ const step = history.redo[i];
965
+ const before = redoFromCurrent.length > 0 ? redoFromCurrent[redoFromCurrent.length - 1] : current;
966
+ if (!sameState(before, step)) redoFromCurrent.push(step);
967
+ }
968
+ if (undo.length === history.undo.length && redoFromCurrent.length === history.redo.length) {
969
+ return history;
749
970
  }
750
- const redo = redoFromCurrent.reverse();
751
- 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]);
752
- return { history: unchanged ? history : { undo, redo }, current: nextCurrent };
971
+ return { undo, redo: redoFromCurrent.reverse() };
753
972
  }
754
-
755
- // src/arrangement/mixer.ts
756
- var EMPTY_MIXER = /* @__PURE__ */ new Map();
757
- var DEFAULT_VOLUME = 1;
758
- var DEFAULT_PAN = 0;
759
- function mixerValuesOf(track) {
760
- return {
761
- volume: track.volume ?? DEFAULT_VOLUME,
762
- muted: track.muted ?? false,
763
- soloed: track.soloed ?? false,
764
- pan: track.pan ?? DEFAULT_PAN
973
+ function sameSteps(a, b) {
974
+ 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]);
975
+ }
976
+ function mapHistoryStates(history, map) {
977
+ return { undo: history.undo.map(map), redo: history.redo.map(map) };
978
+ }
979
+ function purgeTrack(history, current, trackId, base = null) {
980
+ return purgeStates(history, current, stateWithoutTrack(trackId), base);
981
+ }
982
+ function purgeClip(history, current, trackId, clipId, base = null) {
983
+ return purgeStates(
984
+ history,
985
+ current,
986
+ stateWithoutClip(history, current, trackId, (c) => c.id === clipId, base),
987
+ base
988
+ );
989
+ }
990
+ function purgeClipObjects(history, current, trackId, clips, base = null) {
991
+ const strip = stateWithoutClip(history, current, trackId, (c) => clips.has(c), base);
992
+ return { ...purgeStates(history, current, strip, base), strip };
993
+ }
994
+ function stateWithoutClip(history, current, trackId, isGone, base = null) {
995
+ const inOrder = [
996
+ ...history.undo,
997
+ ...base ? [base] : [],
998
+ current,
999
+ ...[...history.redo].reverse()
1000
+ ];
1001
+ const mapped = /* @__PURE__ */ new Map();
1002
+ let before;
1003
+ let stripped = false;
1004
+ for (const state of inOrder) {
1005
+ const known = mapped.get(state);
1006
+ if (known) {
1007
+ before = known.tracks.find((t) => t.id === trackId);
1008
+ continue;
1009
+ }
1010
+ const track = state.tracks.find((t) => t.id === trackId);
1011
+ let next = track;
1012
+ if (track?.clips.some(isGone)) {
1013
+ next = { ...track, clips: track.clips.filter((c) => !isGone(c)) };
1014
+ stripped = true;
1015
+ }
1016
+ if (stripped && next && before && next !== before && sameTrackFields(before, next))
1017
+ next = before;
1018
+ mapped.set(
1019
+ state,
1020
+ next === track ? state : { tracks: state.tracks.map((t) => t === track ? next : t), mixer: state.mixer }
1021
+ );
1022
+ before = next;
1023
+ }
1024
+ return (state) => mapped.get(state) ?? state;
1025
+ }
1026
+ function withCurrentTracks(history, current) {
1027
+ const byId = new Map(current.tracks.map((t) => [t.id, t]));
1028
+ const canon = (state) => {
1029
+ let changed = false;
1030
+ const tracks = state.tracks.map((t) => {
1031
+ const now = byId.get(t.id);
1032
+ if (now && now !== t && sameTrackFields(t, now)) {
1033
+ changed = true;
1034
+ return now;
1035
+ }
1036
+ return t;
1037
+ });
1038
+ return changed ? { tracks, mixer: state.mixer } : state;
765
1039
  };
1040
+ return mapHistoryStates(history, canon);
766
1041
  }
767
- function seedMixer(mixer, tracks) {
768
- let next = null;
769
- for (const track of tracks) {
770
- if ((next ?? mixer).has(track.id)) continue;
771
- if (!next) next = new Map(mixer);
772
- next.set(track.id, mixerValuesOf(track));
1042
+ function sameTrackFields(a, b) {
1043
+ const keys = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)]);
1044
+ for (const key of keys) {
1045
+ if (key !== "clips" && a[key] !== b[key]) return false;
773
1046
  }
774
- return next ?? mixer;
1047
+ return a.clips.length === b.clips.length && a.clips.every((c, i) => c === b.clips[i]);
775
1048
  }
776
- function setMixerValues(mixer, trackId, patch) {
777
- const entry = mixer.get(trackId);
778
- if (!entry) return mixer;
779
- return new Map(mixer).set(trackId, { ...entry, ...patch });
1049
+ function purgeStates(history, current, strip, base) {
1050
+ const nextCurrent = strip(current);
1051
+ const nextBase = base && strip(base);
1052
+ const stripped = dropRepeats(mapHistoryStates(history, strip), nextBase ?? nextCurrent);
1053
+ return {
1054
+ history: sameSteps(stripped, history) ? history : stripped,
1055
+ current: nextCurrent,
1056
+ base: nextBase
1057
+ };
780
1058
  }
781
- function carryMixerEntry(mixer, fromId, toId) {
782
- const entry = mixer.get(fromId);
783
- if (!entry || mixer.get(toId) === entry) return mixer;
784
- return new Map(mixer).set(toId, entry);
1059
+ function stateWithMixerValues(trackId, patch) {
1060
+ const mixers = /* @__PURE__ */ new Map();
1061
+ const states = /* @__PURE__ */ new Map();
1062
+ return (state) => {
1063
+ const known = states.get(state);
1064
+ if (known) return known;
1065
+ let mixer = mixers.get(state.mixer);
1066
+ if (!mixer) {
1067
+ mixer = setMixerValues(state.mixer, trackId, patch);
1068
+ mixers.set(state.mixer, mixer);
1069
+ }
1070
+ const next = mixer === state.mixer ? state : { ...state, mixer };
1071
+ states.set(state, next);
1072
+ return next;
1073
+ };
785
1074
  }
786
- function retainMixer(mixer, states) {
787
- const held = /* @__PURE__ */ new Set();
788
- for (const tracks of states) {
789
- for (const track of tracks) held.add(track.id);
790
- }
791
- if ([...mixer.keys()].every((id) => held.has(id))) return mixer;
792
- return new Map([...mixer].filter(([id]) => held.has(id)));
1075
+ function stateWithDecidedPanLaws() {
1076
+ const decided = /* @__PURE__ */ new Map();
1077
+ const states = /* @__PURE__ */ new Map();
1078
+ return (state) => {
1079
+ const known = states.get(state);
1080
+ if (known) return known;
1081
+ let byTracks = decided.get(state.mixer);
1082
+ if (!byTracks) {
1083
+ byTracks = /* @__PURE__ */ new Map();
1084
+ decided.set(state.mixer, byTracks);
1085
+ }
1086
+ let mixer = byTracks.get(state.tracks);
1087
+ if (!mixer) {
1088
+ mixer = decidePanLaws(state.mixer, state.tracks);
1089
+ byTracks.set(state.tracks, mixer);
1090
+ }
1091
+ const next = mixer === state.mixer ? state : { ...state, mixer };
1092
+ states.set(state, next);
1093
+ return next;
1094
+ };
793
1095
  }
794
- function withMixerValues(track, values) {
795
- if (!values || track.volume === values.volume && track.muted === values.muted && track.soloed === values.soloed && track.pan === values.pan) {
796
- return track;
797
- }
798
- return { ...track, ...values };
1096
+ function writeThrough(history, base, current, write) {
1097
+ const nextBase = base && { ...base, state: write(base.state) };
1098
+ return {
1099
+ history: dropRepeats(mapHistoryStates(history, write), nextBase?.state ?? current),
1100
+ base: nextBase
1101
+ };
799
1102
  }
800
1103
 
801
1104
  // src/arrangement/ticks.ts
802
- import { isLoadingClip as isLoadingClip3 } from "@waveform-playlist/core";
1105
+ import { isLoadingClip as isLoadingClip5 } from "@waveform-playlist/core";
803
1106
  function forLoadedClips(change) {
804
- return (clip) => isLoadingClip3(clip) ? clip : change(clip);
1107
+ return (clip) => isLoadingClip5(clip) ? clip : change(clip);
805
1108
  }
806
1109
  function withClips(track, change) {
807
1110
  let changed = false;
@@ -844,10 +1147,11 @@ function rescaleTick(tick, fromPpqn, toPpqn) {
844
1147
  }
845
1148
 
846
1149
  // src/arrangement/validate.ts
847
- import { assertTrackKind, isLoadingClip as isLoadingClip4 } from "@waveform-playlist/core";
1150
+ import { assertTrackKind, isLoadingClip as isLoadingClip6 } from "@waveform-playlist/core";
1151
+ var SPAN_RATE_WITHOUT_AUDIO = 48e3;
848
1152
  function assertClipsOfTrackKind(track) {
849
1153
  const clips = track.clips.map(
850
- (clip) => isLoadingClip4(clip) ? { id: clip.id, name: clip.name } : clip
1154
+ (clip) => isLoadingClip6(clip) ? { id: clip.id, name: clip.name } : clip
851
1155
  );
852
1156
  assertTrackKind({ ...track, clips });
853
1157
  }
@@ -862,6 +1166,26 @@ function assertUniqueClipIds(track) {
862
1166
  seen.add(clip.id);
863
1167
  }
864
1168
  }
1169
+ function findClipOverlap(clips) {
1170
+ const loaded = clips.find((clip) => !isLoadingClip6(clip));
1171
+ const spans = trackClipSpans(clips, loaded ? loaded.sampleRate : SPAN_RATE_WITHOUT_AUDIO);
1172
+ for (let i = 1; i < spans.length; i++) {
1173
+ const before = spans[i - 1];
1174
+ const after = spans[i];
1175
+ if (before.startSample + before.durationSamples > after.startSample) {
1176
+ return { first: before.id, second: after.id };
1177
+ }
1178
+ }
1179
+ return null;
1180
+ }
1181
+ function assertNoOverlappingClips(track) {
1182
+ const overlap = findClipOverlap(track.clips);
1183
+ if (overlap) {
1184
+ throw new Error(
1185
+ `[waveform-playlist] Track "${track.id}": clip "${overlap.first}" overlaps clip "${overlap.second}". Clips on a track cannot overlap.`
1186
+ );
1187
+ }
1188
+ }
865
1189
  function assertUniqueTrackIds(tracks) {
866
1190
  const seen = /* @__PURE__ */ new Set();
867
1191
  for (const track of tracks) {
@@ -878,17 +1202,46 @@ function duplicateTrackId(trackId) {
878
1202
  // src/arrangement/Arrangement.ts
879
1203
  var DEFAULT_MIN_DURATION_SECONDS = 0.1;
880
1204
  var DEFAULT_UNDO_LIMIT = 100;
1205
+ var EMPTY_RECORDING = /* @__PURE__ */ new Set();
1206
+ function insertIndex(index, length) {
1207
+ if (index === void 0) return length;
1208
+ if (typeof index !== "number" || !Number.isFinite(index)) {
1209
+ throw new TypeError(
1210
+ `[waveform-playlist] addTrack: index must be a finite number, got ${String(index)}`
1211
+ );
1212
+ }
1213
+ return Math.max(0, Math.min(Math.trunc(index), length));
1214
+ }
881
1215
  var ArrangementImpl = class {
882
1216
  constructor(options = {}) {
883
1217
  this._tracks = [];
884
1218
  this._tracksVersion = 0;
885
1219
  this._mixerVersion = 0;
886
1220
  this._mixer = EMPTY_MIXER;
1221
+ /**
1222
+ * The ids of the tracks a take is recording onto: outside the history and
1223
+ * every saved state (#843). Replaced on a change, never written to.
1224
+ */
1225
+ this._recordingTrackIds = EMPTY_RECORDING;
887
1226
  this._history = EMPTY_HISTORY;
888
1227
  this._transaction = null;
1228
+ /**
1229
+ * The gesture of the top undo step, while a change of that gesture may
1230
+ * still join it: its id, and the history from before its step was pushed
1231
+ * (put back when the gesture returns to where it began, with the redo
1232
+ * states and any step the undo limit evicted). Set when a gesture change
1233
+ * pushes the step, cleared by anything else that touches the history
1234
+ * (#843). `before` is kept in step with the history: the time base, the
1235
+ * switch to loaded clips and `undoable: false` reach it too.
1236
+ */
1237
+ this._gesture = null;
1238
+ /** Whether the last pass removed a clip with nothing of its audio left (#859). */
1239
+ this._purgedInPass = false;
889
1240
  this._subscribers = /* @__PURE__ */ new Set();
890
1241
  this._listeners = /* @__PURE__ */ new Set();
891
1242
  this._pending = [];
1243
+ /** The clips passes removed from the current tracks since the last announcement (#859). */
1244
+ this._removedNow = [];
892
1245
  this._delivering = false;
893
1246
  /** How the clip edits convert time: through the attached engine, or not at all. */
894
1247
  this._clipTime = {
@@ -949,7 +1302,7 @@ var ArrangementImpl = class {
949
1302
  }
950
1303
  /** Be told after every change. See `Arrangement.subscribe`. */
951
1304
  subscribe(listener) {
952
- const entry = () => listener();
1305
+ const entry = (change) => listener(change);
953
1306
  this._subscribers.add(entry);
954
1307
  return () => {
955
1308
  this._subscribers.delete(entry);
@@ -988,17 +1341,19 @@ var ArrangementImpl = class {
988
1341
  }
989
1342
  const prepare = tickPreparer(timeBase, this._tickPpqn);
990
1343
  const tracks = prepare(this._tracks);
991
- const history = {
992
- undo: this._history.undo.map(prepare),
993
- redo: this._history.redo.map(prepare)
1344
+ const history = mapHistoryTracks(this._history, prepare);
1345
+ const gesture = this._gesture && {
1346
+ ...this._gesture,
1347
+ before: mapHistoryTracks(this._gesture.before, prepare)
994
1348
  };
995
1349
  const transaction = this._transaction && {
996
1350
  ...this._transaction,
997
- tracks: prepare(this._transaction.tracks)
1351
+ state: withStateTracks(this._transaction.state, prepare(this._transaction.state.tracks))
998
1352
  };
999
1353
  this._timeBase = timeBase;
1000
1354
  this._tickPpqn = timeBase.ppqn;
1001
1355
  this._history = history;
1356
+ this._gesture = gesture;
1002
1357
  this._transaction = transaction;
1003
1358
  if (tracks !== this._tracks) {
1004
1359
  this._tracks = tracks;
@@ -1020,22 +1375,24 @@ var ArrangementImpl = class {
1020
1375
  }
1021
1376
  undo() {
1022
1377
  this._abortOpenTransaction();
1023
- const step = undoStep(this._history, this._tracks);
1378
+ this._gesture = null;
1379
+ const step = undoStep(this._history, this._currentState());
1024
1380
  if (!step) return;
1025
1381
  this._history = step.history;
1026
- this._restoreTracks(step.tracks);
1382
+ if (!this._restoreState(step.state)) this._emit({ type: "history" });
1027
1383
  }
1028
1384
  redo() {
1029
1385
  this._abortOpenTransaction();
1030
- const step = redoStep(this._history, this._tracks);
1386
+ this._gesture = null;
1387
+ const step = redoStep(this._history, this._currentState());
1031
1388
  if (!step) return;
1032
1389
  this._history = step.history;
1033
- this._restoreTracks(step.tracks);
1390
+ if (!this._restoreState(step.state)) this._emit({ type: "history" });
1034
1391
  }
1035
1392
  clearHistory() {
1036
1393
  const hadHistory = this.canUndo || this.canRedo;
1037
1394
  this._history = EMPTY_HISTORY;
1038
- this._mixer = retainMixer(this._mixer, this._heldStates());
1395
+ this._gesture = null;
1039
1396
  if (hadHistory) this._emit({ type: "history" });
1040
1397
  }
1041
1398
  beginTransaction() {
@@ -1045,7 +1402,8 @@ var ArrangementImpl = class {
1045
1402
  );
1046
1403
  }
1047
1404
  const replaced = this._transaction !== null;
1048
- this._transaction = beginBase(this._tracks);
1405
+ this._transaction = beginBase(this._currentState());
1406
+ this._gesture = null;
1049
1407
  if (replaced) this._resyncSourcesQuietly();
1050
1408
  }
1051
1409
  commitTransaction() {
@@ -1055,8 +1413,9 @@ var ArrangementImpl = class {
1055
1413
  return;
1056
1414
  }
1057
1415
  this._transaction = null;
1058
- if (transaction.changed && !sameTracks(transaction.tracks, this._tracks)) {
1059
- this._pushStep(transaction.tracks);
1416
+ this._gesture = null;
1417
+ if (transaction.changed && !sameState(transaction.state, this._currentState())) {
1418
+ this._pushStep(transaction.state);
1060
1419
  this._emit({ type: "history" });
1061
1420
  }
1062
1421
  }
@@ -1072,28 +1431,31 @@ var ArrangementImpl = class {
1072
1431
  // Track Management
1073
1432
  // ---------------------------------------------------------------------------
1074
1433
  // A track holds audio clips or MIDI clips, never both (#756); track ids are
1075
- // unique, and so are clip ids within a track. The three methods that take a
1434
+ // unique, and so are clip ids within a track; its clips do not overlap (#859). The three methods that take a
1076
1435
  // track check it before they change anything, so a throw leaves the tracks,
1077
1436
  // the undo history, the mixer and every subscriber untouched.
1078
1437
  setTracks(tracks) {
1079
1438
  tracks.forEach(assertClipsOfTrackKind);
1080
1439
  assertUniqueTrackIds(tracks);
1081
1440
  tracks.forEach(assertUniqueClipIds);
1441
+ tracks.forEach(assertNoOverlappingClips);
1082
1442
  this._transaction = null;
1083
1443
  this._history = EMPTY_HISTORY;
1084
- const kept = retainMixer(this._mixer, [this._tracks]);
1444
+ this._gesture = null;
1085
1445
  this._tracks = tracks.map((track) => this._ingest(track));
1086
- this._mixer = retainMixer(seedMixer(kept, this._tracks), [this._tracks]);
1446
+ this._mixer = mixerOf(this._mixer, this._tracks);
1087
1447
  this._tracksVersion++;
1088
1448
  this._emit({ type: "set" });
1089
1449
  }
1090
- addTrack(track) {
1450
+ addTrack(track, options) {
1451
+ const index = insertIndex(options?.index, this._tracks.length);
1091
1452
  assertClipsOfTrackKind(track);
1092
1453
  assertUniqueClipIds(track);
1454
+ assertNoOverlappingClips(track);
1093
1455
  if (this._tracks.some((t) => t.id === track.id)) throw duplicateTrackId(track.id);
1094
1456
  this._pushUndoSnapshot();
1095
1457
  const enriched = this._ingest(track);
1096
- this._tracks = [...this._tracks, enriched];
1458
+ this._tracks = [...this._tracks.slice(0, index), enriched, ...this._tracks.slice(index)];
1097
1459
  this._mixer = seedMixer(this._mixer, [enriched]);
1098
1460
  this._tracksVersion++;
1099
1461
  this._emit({ type: "add", trackId: track.id });
@@ -1111,9 +1473,25 @@ var ArrangementImpl = class {
1111
1473
  if (!this._tracks.some((t) => t.id === trackId)) return;
1112
1474
  this._pushUndoSnapshot();
1113
1475
  this._tracks = this._tracks.filter((t) => t.id !== trackId);
1476
+ this._mixer = withoutEntry(this._mixer, trackId);
1114
1477
  this._tracksVersion++;
1115
1478
  this._emit({ type: "remove", trackId });
1116
1479
  }
1480
+ /**
1481
+ * Remove a clip from a track: an undo step. With `undoable: false` there is
1482
+ * no step, and the clip is also taken out of every undo and redo state, so
1483
+ * that no undo or redo brings it back (#848: a `<daw-clip>` the page removed
1484
+ * while its track was detached).
1485
+ */
1486
+ removeClip(trackId, clipId, options) {
1487
+ if (options?.undoable === false) {
1488
+ this._removeClipEverywhere(trackId, clipId);
1489
+ return;
1490
+ }
1491
+ const current = this._tracks.find((t) => t.id === trackId);
1492
+ if (!current?.clips.some((c) => c.id === clipId)) return;
1493
+ this.updateTrack(trackId, (t) => ({ ...t, clips: t.clips.filter((c) => c.id !== clipId) }));
1494
+ }
1117
1495
  /**
1118
1496
  * Move a track to a new position in the track order. Purely organizational —
1119
1497
  * track order is not audible.
@@ -1149,6 +1527,7 @@ var ArrangementImpl = class {
1149
1527
  if (byFunction && track === current) return;
1150
1528
  assertClipsOfTrackKind(track);
1151
1529
  assertUniqueClipIds(track);
1530
+ assertNoOverlappingClips(track);
1152
1531
  if (track.id !== trackId && this._tracks.some((t) => t.id === track.id)) {
1153
1532
  throw duplicateTrackId(track.id);
1154
1533
  }
@@ -1157,7 +1536,6 @@ var ArrangementImpl = class {
1157
1536
  const enriched = this._ingest(track, new Set(current.clips));
1158
1537
  this._tracks = this._tracks.map((t) => t.id === trackId ? enriched : t);
1159
1538
  this._mixer = seedMixer(carryMixerEntry(this._mixer, trackId, enriched.id), [enriched]);
1160
- if (enriched.id !== trackId) this._mixer = retainMixer(this._mixer, this._heldStates());
1161
1539
  this._tracksVersion++;
1162
1540
  this._emit({ type: "update", trackId, previous: current });
1163
1541
  }
@@ -1194,19 +1572,63 @@ var ArrangementImpl = class {
1194
1572
  //
1195
1573
  // Each replaces the Map and one entry, bumps mixerVersion and announces
1196
1574
  // the change. NOT structural changes: no track object is replaced,
1197
- // tracksVersion stays (#501), and they are not undo steps. An id that is
1198
- // not in the current tracks does nothing.
1199
- setTrackVolume(trackId, volume) {
1200
- this._setMixerValues(trackId, { volume });
1575
+ // tracksVersion stays (#501). Each call is an undo step; inside an open
1576
+ // transaction it is part of it, like any other change. Calls with one
1577
+ // `gesture` id, one after another, are one step; `undoable: false` is no
1578
+ // step and is written into every saved state (#843). A value that does
1579
+ // not change, or an id that is not in the current tracks, does nothing.
1580
+ setTrackVolume(trackId, volume, options) {
1581
+ this._setMixerValues(trackId, { volume }, options);
1582
+ }
1583
+ setTrackMute(trackId, muted, options) {
1584
+ this._setMixerValues(trackId, { muted }, options);
1585
+ }
1586
+ setTrackSolo(trackId, soloed, options) {
1587
+ this._setMixerValues(trackId, { soloed }, options);
1201
1588
  }
1202
- setTrackMute(trackId, muted) {
1203
- this._setMixerValues(trackId, { muted });
1589
+ setTrackPan(trackId, pan, options) {
1590
+ this._setMixerValues(trackId, { pan }, options);
1591
+ }
1592
+ /**
1593
+ * Set a track's pan law (#684): a mixer value like the four above. It
1594
+ * takes a decided law; anything else, `'auto'` included, throws before
1595
+ * anything changes (a decided track does not go back to `'auto'`). May be
1596
+ * called before the track holds audio: the law is then decided, and the
1597
+ * first audio does not change it. A MIDI track has no law to set.
1598
+ */
1599
+ setTrackPanLaw(trackId, panLaw, options) {
1600
+ if (!isDecidedPanLaw2(panLaw)) {
1601
+ throw new TypeError(
1602
+ `setTrackPanLaw: panLaw must be 'mono' or 'stereo', got ${JSON.stringify(panLaw) ?? String(panLaw)}`
1603
+ );
1604
+ }
1605
+ const track = this._tracks.find((t) => t.id === trackId);
1606
+ if (!track || trackKind2(track) === "midi") return;
1607
+ this._setMixerValues(trackId, { panLaw }, options);
1204
1608
  }
1205
- setTrackSolo(trackId, soloed) {
1206
- this._setMixerValues(trackId, { soloed });
1609
+ // ---------------------------------------------------------------------------
1610
+ // Recording mute (the track a take is recording onto)
1611
+ // ---------------------------------------------------------------------------
1612
+ //
1613
+ // The track a take is recording onto plays muted: the engine's projection
1614
+ // and the adapter get `muted: stored || recording`, and the stored mute in
1615
+ // `getMixer()` is not touched. The set is outside the history: the take's
1616
+ // mute is no undo step, and undo, redo, abort, `setTracks` and
1617
+ // `clearHistory` leave it alone (#843).
1618
+ /** The ids of the tracks a take is recording onto. The same Set until it changes; never written to. */
1619
+ get recordingTrackIds() {
1620
+ return this._recordingTrackIds;
1207
1621
  }
1208
- setTrackPan(trackId, pan) {
1209
- this._setMixerValues(trackId, { pan });
1622
+ /**
1623
+ * Mark a track as the one a take is recording onto, or clear it. An id
1624
+ * that is not in the current tracks is recorded too, and mutes nothing
1625
+ * until a track of that id enters. The same value does nothing.
1626
+ */
1627
+ setTrackRecording(trackId, recording) {
1628
+ if (this._recordingTrackIds.has(trackId) === recording) return;
1629
+ this._recordingTrackIds = recording ? /* @__PURE__ */ new Set([...this._recordingTrackIds, trackId]) : new Set([...this._recordingTrackIds].filter((id) => id !== trackId));
1630
+ if (this._mixer.has(trackId)) this._mixerVersion++;
1631
+ this._emit({ type: "recording", trackId });
1210
1632
  }
1211
1633
  // ---------------------------------------------------------------------------
1212
1634
  // Tempo
@@ -1264,42 +1686,103 @@ var ArrangementImpl = class {
1264
1686
  ...track,
1265
1687
  clips: track.clips.map((clip) => {
1266
1688
  if (held?.has(clip)) return clip;
1267
- if (isLoadingClip5(clip)) return { ...clip };
1689
+ if (isLoadingClip7(clip)) return { ...clip };
1268
1690
  return { ...clip, startTick: clip.startTick ?? this._tickAt(clip.startSample) };
1269
1691
  })
1270
1692
  };
1271
1693
  }
1272
- _setMixerValues(trackId, values) {
1694
+ _setMixerValues(trackId, values, options = {}) {
1273
1695
  if (!this._tracks.some((t) => t.id === trackId)) return;
1274
1696
  const next = setMixerValues(this._mixer, trackId, values);
1275
1697
  if (next === this._mixer) return;
1276
- this._mixer = next;
1698
+ if (options.undoable === false) {
1699
+ this._writeMixerThrough(trackId, values, next);
1700
+ } else {
1701
+ this._recordMixerChange(options.gesture);
1702
+ this._mixer = next;
1703
+ this._dropReturnedGestureStep();
1704
+ }
1277
1705
  this._mixerVersion++;
1278
1706
  this._emit({ type: "mixer", trackId, values });
1279
1707
  }
1280
- /** Every tracks array the arrangement can still return to, and the current one. */
1708
+ /**
1709
+ * The undo step of a mixer change about to be made: part of an open
1710
+ * transaction, the top step when it was pushed by the same gesture and
1711
+ * nothing has touched the history since, or else a new step (which becomes
1712
+ * that gesture's).
1713
+ */
1714
+ _recordMixerChange(gesture) {
1715
+ if (this._transaction) {
1716
+ this._markTransactionChanged();
1717
+ return;
1718
+ }
1719
+ if (gesture !== void 0 && this._gesture?.id === gesture) return;
1720
+ const before = this._history;
1721
+ this._pushStep(this._currentState());
1722
+ if (gesture !== void 0 && this.canUndo) this._gesture = { id: gesture, before };
1723
+ }
1724
+ /**
1725
+ * A gesture that came back to the state its step holds leaves no step, and
1726
+ * the history is the one it found: the redo states its first change
1727
+ * cleared come back (as with a transaction that changes nothing).
1728
+ */
1729
+ _dropReturnedGestureStep() {
1730
+ const gesture = this._gesture;
1731
+ if (!gesture) return;
1732
+ const { undo } = this._history;
1733
+ if (!sameState(undo[undo.length - 1], this._currentState())) return;
1734
+ const current = this._currentState();
1735
+ this._history = dropRepeats(withCurrentTracks(gesture.before, current), current);
1736
+ this._gesture = null;
1737
+ }
1738
+ /**
1739
+ * `undoable: false`: the value in the current mix and in every saved state
1740
+ * that has an entry for the track, so that no undo, redo or abort brings
1741
+ * the old one back. A step that no longer differs from the state next to
1742
+ * it goes; when that was the step a gesture joins and no equal step is
1743
+ * left on top, the gesture's next change pushes a new one.
1744
+ */
1745
+ _writeMixerThrough(trackId, values, next) {
1746
+ this._mixer = next;
1747
+ const write = stateWithMixerValues(trackId, values);
1748
+ const { undo } = this._history;
1749
+ const top = undo.length > 0 ? write(undo[undo.length - 1]) : void 0;
1750
+ const written = writeThrough(this._history, this._transaction, this._currentState(), write);
1751
+ this._history = written.history;
1752
+ this._transaction = written.base;
1753
+ if (this._gesture) {
1754
+ const newTop = this._history.undo[this._history.undo.length - 1];
1755
+ this._gesture = newTop !== void 0 && top !== void 0 && sameState(newTop, top) ? { ...this._gesture, before: mapHistoryStates(this._gesture.before, write) } : null;
1756
+ }
1757
+ }
1758
+ /** The tracks and the mix as they are now: what an undo step or a transaction's base saves. */
1759
+ _currentState() {
1760
+ return { tracks: this._tracks, mixer: this._mixer };
1761
+ }
1762
+ /** Every tracks array the arrangement can still return to, and the current one (for the sources). */
1281
1763
  _heldStates() {
1282
1764
  return [
1283
1765
  this._tracks,
1284
- ...this._history.undo,
1285
- ...this._history.redo,
1286
- ...this._transaction ? [this._transaction.tracks] : []
1766
+ ...this._history.undo.map((state) => state.tracks),
1767
+ ...this._history.redo.map((state) => state.tracks),
1768
+ ...this._gesture ? this._gesture.before.undo.map((state) => state.tracks) : [],
1769
+ ...this._gesture ? this._gesture.before.redo.map((state) => state.tracks) : [],
1770
+ ...this._transaction ? [this._transaction.state.tracks] : []
1287
1771
  ];
1288
1772
  }
1289
1773
  /** `removeTrack` with `undoable: false`: out of the current tracks and out of every stored state. */
1290
1774
  _removeTrackEverywhere(trackId) {
1291
1775
  const wasThere = this._tracks.some((t) => t.id === trackId);
1292
- const purged = purgeTrack(this._history, this._tracks, trackId);
1776
+ const base = this._transaction?.state ?? null;
1777
+ const purged = purgeTrack(this._history, this._currentState(), trackId, base);
1293
1778
  const historyChanged = purged.history !== this._history;
1294
1779
  this._history = purged.history;
1295
- if (this._transaction) {
1296
- this._transaction = {
1297
- ...this._transaction,
1298
- tracks: withoutTrack(this._transaction.tracks, trackId)
1299
- };
1780
+ this._gesture = null;
1781
+ if (this._transaction && purged.base) {
1782
+ this._transaction = { ...this._transaction, state: purged.base };
1300
1783
  }
1301
- this._tracks = purged.current;
1302
- this._mixer = retainMixer(this._mixer, this._heldStates());
1784
+ this._tracks = purged.current.tracks;
1785
+ this._mixer = purged.current.mixer;
1303
1786
  if (wasThere) {
1304
1787
  this._tracksVersion++;
1305
1788
  this._emit({ type: "remove", trackId });
@@ -1309,41 +1792,89 @@ var ArrangementImpl = class {
1309
1792
  this._resyncSourcesQuietly();
1310
1793
  }
1311
1794
  }
1795
+ /** `removeClip` with `undoable: false`: out of the current tracks and out of every stored state. */
1796
+ _removeClipEverywhere(trackId, clipId) {
1797
+ const previous = this._tracks.find((t) => t.id === trackId);
1798
+ const base = this._transaction?.state ?? null;
1799
+ const purged = purgeClip(this._history, this._currentState(), trackId, clipId, base);
1800
+ const historyChanged = purged.history !== this._history;
1801
+ const baseChanged = purged.base !== base;
1802
+ this._history = purged.history;
1803
+ if (this._transaction && purged.base) {
1804
+ this._transaction = { ...this._transaction, state: purged.base };
1805
+ }
1806
+ if (purged.current.tracks !== this._tracks && previous) {
1807
+ this._gesture = null;
1808
+ this._tracks = purged.current.tracks;
1809
+ this._tracksVersion++;
1810
+ this._emit({ type: "update", trackId, previous });
1811
+ } else if (historyChanged) {
1812
+ this._gesture = null;
1813
+ this._emit({ type: "history" });
1814
+ } else if (baseChanged) {
1815
+ this._resyncSourcesQuietly();
1816
+ }
1817
+ }
1312
1818
  /** The state before a change: an undo step, or the mark that an open transaction changed. */
1313
1819
  _pushUndoSnapshot() {
1314
1820
  if (this._transaction) {
1315
- if (!this._transaction.changed) {
1316
- this._transaction = { ...this._transaction, changed: true };
1317
- }
1821
+ this._markTransactionChanged();
1318
1822
  return;
1319
1823
  }
1320
- this._pushStep(this._tracks);
1824
+ this._pushStep(this._currentState());
1321
1825
  }
1322
- /** Add an undo step. The history may let go of states with it (the redo stack, a step past the limit). */
1323
- _pushStep(tracks) {
1324
- const letsGo = this._history.redo.length > 0 || this._history.undo.length >= this.undoLimit;
1325
- this._history = pushStep(this._history, tracks, this.undoLimit);
1326
- if (letsGo) this._mixer = retainMixer(this._mixer, this._heldStates());
1826
+ /** An open transaction has changed something. */
1827
+ _markTransactionChanged() {
1828
+ if (this._transaction && !this._transaction.changed) {
1829
+ this._transaction = { ...this._transaction, changed: true };
1830
+ }
1327
1831
  }
1328
- _restoreTracks(snapshot) {
1832
+ /** Add an undo step. No gesture joins it (a gesture change that pushes sets its id after). */
1833
+ _pushStep(state) {
1834
+ this._history = pushStep(this._history, state, this.undoLimit);
1835
+ this._gesture = null;
1836
+ }
1837
+ /**
1838
+ * Make a saved state the current one (an undo, a redo, an abort) and
1839
+ * announce it: `'restore'` when the tracks array is another one (with the
1840
+ * mix from before, which may differ too), `'restoreMix'` when only mixer
1841
+ * values differ. `mixerVersion` counts it when a track that is in both
1842
+ * states has other values; an entry that comes or goes with its track is
1843
+ * not a mixer change. Returns false when nothing differed and nothing was
1844
+ * announced.
1845
+ */
1846
+ _restoreState(state) {
1329
1847
  const previous = this._tracks;
1330
- this._tracks = snapshot;
1331
- this._tracksVersion++;
1332
- this._emit({ type: "restore", previous });
1848
+ const previousMixer = this._mixer;
1849
+ const tracksChanged = state.tracks !== previous;
1850
+ const mixChanged = mixerChanges(previousMixer, state.mixer).length > 0;
1851
+ this._tracks = state.tracks;
1852
+ this._mixer = state.mixer;
1853
+ if (mixChanged) this._mixerVersion++;
1854
+ if (tracksChanged) {
1855
+ this._tracksVersion++;
1856
+ this._emit({ type: "restore", previous, previousMixer });
1857
+ } else if (mixChanged) {
1858
+ this._emit({ type: "restoreMix", previousMixer });
1859
+ }
1860
+ return tracksChanged || mixChanged;
1333
1861
  }
1334
- /** Ends an open transaction, restoring the tracks it began from if it changed them. */
1862
+ /** Ends an open transaction, restoring the state it began from if it changed anything. */
1335
1863
  _abortOpenTransaction() {
1336
1864
  const transaction = this._transaction;
1337
1865
  if (!transaction) return;
1338
1866
  this._transaction = null;
1867
+ this._gesture = null;
1339
1868
  if (transaction.changed) {
1340
- this._restoreTracks(transaction.tracks);
1869
+ this._restoreState(transaction.state);
1341
1870
  }
1342
1871
  }
1343
1872
  /** Declare the sources every state names, and switch the clips whose audio is there. */
1344
1873
  _syncSources() {
1345
1874
  this._sources.declare(this._heldStates());
1346
- return this._switchLoaded();
1875
+ const switched = this._switchLoaded();
1876
+ if (this._purgedInPass) this._sources.declare(this._heldStates());
1877
+ return switched;
1347
1878
  }
1348
1879
  /** The stored states changed with nothing to announce: the sources they name may have. */
1349
1880
  _resyncSourcesQuietly() {
@@ -1361,15 +1892,102 @@ var ArrangementImpl = class {
1361
1892
  const pass = this._sources.beginPass((startSample) => this._tickAt(startSample));
1362
1893
  const previous = this._tracks;
1363
1894
  this._tracks = pass.current(previous);
1364
- this._history = {
1365
- undo: this._history.undo.map(pass.stored),
1366
- redo: this._history.redo.map(pass.stored)
1367
- };
1895
+ this._history = mapHistoryTracks(this._history, pass.stored);
1896
+ if (this._gesture) {
1897
+ this._gesture = {
1898
+ ...this._gesture,
1899
+ before: mapHistoryTracks(this._gesture.before, pass.stored)
1900
+ };
1901
+ }
1368
1902
  if (this._transaction) {
1369
- this._transaction = { ...this._transaction, tracks: pass.stored(this._transaction.tracks) };
1903
+ const { state } = this._transaction;
1904
+ this._transaction = {
1905
+ ...this._transaction,
1906
+ state: withStateTracks(state, pass.stored(state.tracks))
1907
+ };
1370
1908
  }
1909
+ const removals = pass.removals();
1910
+ this._purgedInPass = removals.size > 0;
1911
+ for (const [trackId, clips] of removals) this._purgeClipObjects(trackId, clips);
1912
+ this._decidePanLaws();
1371
1913
  return this._tracks === previous ? null : previous;
1372
1914
  }
1915
+ /** These clip objects of a track out of every state, with no undo step and nothing announced. */
1916
+ _purgeClipObjects(trackId, clips) {
1917
+ const base = this._transaction?.state ?? null;
1918
+ const top = this._history.undo[this._history.undo.length - 1];
1919
+ const purged = purgeClipObjects(this._history, this._currentState(), trackId, clips, base);
1920
+ if (purged.history !== this._history && this._gesture) {
1921
+ const newTop = purged.history.undo[purged.history.undo.length - 1];
1922
+ if (!(top !== void 0 && newTop !== void 0 && sameState(newTop, purged.strip(top)))) {
1923
+ this._gesture = null;
1924
+ }
1925
+ }
1926
+ if (this._gesture) {
1927
+ const { before } = this._gesture;
1928
+ const strip = stateWithoutClip(before, this._currentState(), trackId, (c) => clips.has(c));
1929
+ this._gesture = { ...this._gesture, before: mapHistoryStates(before, strip) };
1930
+ }
1931
+ this._history = purged.history;
1932
+ if (this._transaction && purged.base) {
1933
+ this._transaction = { ...this._transaction, state: purged.base };
1934
+ }
1935
+ const track = this._tracks.find((t) => t.id === trackId);
1936
+ const gone = track ? track.clips.filter((c) => clips.has(c)) : [];
1937
+ if (gone.length > 0) {
1938
+ this._tracks = purged.current.tracks;
1939
+ for (const clip of gone) this._removedNow.push({ trackId, clipId: clip.id });
1940
+ }
1941
+ }
1942
+ /**
1943
+ * First audio decides a track's pan law (#684): in the current state and
1944
+ * in every state the arrangement can return to, a track whose law is
1945
+ * `'auto'` and that holds decoded audio gets the law of that audio, each
1946
+ * state from its own tracks. Part of the change that brought the audio:
1947
+ * not an undo step. `mixerVersion` counts it when the current mix changed.
1948
+ *
1949
+ * A saved step that no longer differs from the state next to it is
1950
+ * dropped, as `_writeMixerThrough` does (a law set on a track whose only
1951
+ * clip was loading, and the clip turns out to have that law): its undo, or
1952
+ * its redo, would do nothing. A gesture whose own step went has no step to
1953
+ * join, and its next change pushes a new one; a gesture whose step is still
1954
+ * the top one goes on.
1955
+ */
1956
+ _decidePanLaws() {
1957
+ const decide = stateWithDecidedPanLaws();
1958
+ const current = this._currentState();
1959
+ const decided = decide(current);
1960
+ if (decided !== current) {
1961
+ this._mixer = decided.mixer;
1962
+ this._mixerVersion++;
1963
+ }
1964
+ const changedIn = (before, after) => after.undo.some((state, i) => state !== before.undo[i]) || after.redo.some((state, i) => state !== before.redo[i]);
1965
+ let base = this._transaction?.state ?? null;
1966
+ if (this._transaction && base) {
1967
+ const decidedBase = decide(base);
1968
+ if (decidedBase !== base) {
1969
+ base = decidedBase;
1970
+ this._transaction = { ...this._transaction, state: decidedBase };
1971
+ }
1972
+ }
1973
+ const mapped = mapHistoryStates(this._history, decide);
1974
+ const savedChanged = changedIn(this._history, mapped);
1975
+ if (savedChanged || decided !== current) {
1976
+ const top = mapped.undo[mapped.undo.length - 1];
1977
+ const kept = dropRepeats(mapped, base ?? decided);
1978
+ if (savedChanged || kept !== mapped) this._history = kept;
1979
+ if (this._gesture && kept !== mapped) {
1980
+ const newTop = kept.undo[kept.undo.length - 1];
1981
+ if (!(newTop !== void 0 && top !== void 0 && sameState(newTop, top))) {
1982
+ this._gesture = null;
1983
+ }
1984
+ }
1985
+ }
1986
+ if (this._gesture) {
1987
+ const before = mapHistoryStates(this._gesture.before, decide);
1988
+ if (changedIn(this._gesture.before, before)) this._gesture = { ...this._gesture, before };
1989
+ }
1990
+ }
1373
1991
  /** A load finished or failed by itself (not inside one of this arrangement's methods). */
1374
1992
  _onSourceSettled() {
1375
1993
  const previous = this._switchLoaded();
@@ -1377,7 +1995,7 @@ var ArrangementImpl = class {
1377
1995
  this._tracksVersion++;
1378
1996
  this._emit({ type: "load", previous });
1379
1997
  } else {
1380
- this._sources.finishPass();
1998
+ this._resyncSourcesQuietly();
1381
1999
  }
1382
2000
  }
1383
2001
  /**
@@ -1392,17 +2010,17 @@ var ArrangementImpl = class {
1392
2010
  * always received that error).
1393
2011
  */
1394
2012
  _emit(change) {
1395
- const switched = change.type === "mixer" ? null : this._syncSources();
2013
+ const mixOnly = change.type === "mixer" || change.type === "restoreMix" || change.type === "recording";
2014
+ const switched = mixOnly ? null : this._syncSources();
1396
2015
  freezeTracksInDevelopment(this._tracks);
1397
- if (change.type === "remove" || change.type === "restore") {
1398
- this._mixer = retainMixer(this._mixer, this._heldStates());
1399
- }
1400
2016
  const at = {
1401
2017
  tracksVersion: this._tracksVersion,
1402
2018
  mixerVersion: this._mixerVersion
1403
2019
  };
1404
2020
  if (switched && (change.type === "add" || change.type === "update")) at.switched = switched;
1405
- this._pending.push({ change, at });
2021
+ const removed = this._removedNow;
2022
+ this._removedNow = [];
2023
+ this._pending.push({ change, at, removed: Object.freeze(removed) });
1406
2024
  if (this._delivering) return;
1407
2025
  this._delivering = true;
1408
2026
  let failed = false;
@@ -1419,9 +2037,12 @@ var ArrangementImpl = class {
1419
2037
  }
1420
2038
  }
1421
2039
  }
2040
+ const info = Object.freeze(
2041
+ next.removed.length > 0 ? { type: next.change.type, removedClips: next.removed } : { type: next.change.type }
2042
+ );
1422
2043
  for (const subscriber of [...this._subscribers]) {
1423
2044
  try {
1424
- subscriber();
2045
+ subscriber(info);
1425
2046
  } catch (error) {
1426
2047
  console.warn("[waveform-playlist] Error in an arrangement subscriber:", error);
1427
2048
  }
@@ -1441,7 +2062,7 @@ function createArrangement(options = {}) {
1441
2062
  }
1442
2063
 
1443
2064
  // src/adapterSync.ts
1444
- import { isLoadingClip as isLoadingClip6 } from "@waveform-playlist/core";
2065
+ import { isLoadingClip as isLoadingClip8, TRACK_VIEW_FIELDS } from "@waveform-playlist/core";
1445
2066
  var AdapterSync = class {
1446
2067
  constructor(_arrangement, _adapter) {
1447
2068
  this._arrangement = _arrangement;
@@ -1470,8 +2091,8 @@ var AdapterSync = class {
1470
2091
  }
1471
2092
  /**
1472
2093
  * The arrangement's tracks, each without its loading clips and with the
1473
- * current mixer values in its fields: what every adapter track call and
1474
- * `getState().tracks` use. The same
2094
+ * current mixer values in its fields (muted while a take records onto it): what every
2095
+ * adapter track call and `getState().tracks` use. The same
1475
2096
  * array until the tracks or the mix change, and the same track object
1476
2097
  * while neither that track nor its mix changed.
1477
2098
  */
@@ -1487,6 +2108,14 @@ var AdapterSync = class {
1487
2108
  this._projection = { tracksVersion, mixerVersion, tracks };
1488
2109
  return tracks;
1489
2110
  }
2111
+ /**
2112
+ * `tracks()` as the adapter is given them: without the view fields. Made
2113
+ * for each send; nothing depends on the adapter's tracks keeping their
2114
+ * identity between sends.
2115
+ */
2116
+ _playoutTracks() {
2117
+ return freezeTracksInDevelopment(this.tracks().map((track) => this._playout(track)));
2118
+ }
1490
2119
  /** When an engine attaches: send the tracks that are there. With none, the adapter is in step as it is. */
1491
2120
  sendInitialTracks() {
1492
2121
  if (this._arrangement.getTracks().length > 0) {
@@ -1498,7 +2127,7 @@ var AdapterSync = class {
1498
2127
  /** Send the adapter every track, and remember up to which change that covers. */
1499
2128
  sendAllTracks() {
1500
2129
  const version = this._arrangement.tracksVersion;
1501
- this._adapter?.setTracks(this.tracks());
2130
+ this._adapter?.setTracks(this._playoutTracks());
1502
2131
  this._syncedTracksVersion = version;
1503
2132
  }
1504
2133
  /** Send the arrangement's current track to the adapter. False when there is no such track. */
@@ -1506,18 +2135,42 @@ var AdapterSync = class {
1506
2135
  const track = this._arrangement.getTracks().find((t) => t.id === trackId);
1507
2136
  if (!track) return false;
1508
2137
  if (this._adapter?.updateTrack) {
1509
- this._adapter.updateTrack(trackId, this._project(track));
2138
+ this._adapter.updateTrack(trackId, this._playout(this._project(track)));
1510
2139
  } else {
1511
2140
  this.sendAllTracks();
1512
2141
  }
1513
2142
  return true;
1514
2143
  }
1515
- /** A mixer value changed: the adapter's setter for it. */
2144
+ /**
2145
+ * A mixer value changed: the adapter's setter for it. The mute sent is the
2146
+ * one the track plays with: muted while a take records onto the track,
2147
+ * whatever the value given.
2148
+ */
1516
2149
  sendMixerValues(trackId, values) {
1517
2150
  if (values.volume !== void 0) this._adapter?.setTrackVolume(trackId, values.volume);
1518
- if (values.muted !== void 0) this._adapter?.setTrackMute(trackId, values.muted);
2151
+ if (values.muted !== void 0) {
2152
+ this._adapter?.setTrackMute(trackId, values.muted || this._recordingNow(trackId));
2153
+ }
1519
2154
  if (values.soloed !== void 0) this._adapter?.setTrackSolo(trackId, values.soloed);
1520
2155
  if (values.pan !== void 0) this._adapter?.setTrackPan(trackId, values.pan);
2156
+ if (values.panLaw !== void 0) this._sendPanLaw(trackId, values.panLaw);
2157
+ }
2158
+ /** The adapter's setter for a pan law, or, for an adapter without one, the track again (#684). */
2159
+ _sendPanLaw(trackId, panLaw) {
2160
+ if (!this._adapter) return;
2161
+ if (this._adapter.setTrackPanLaw) this._adapter.setTrackPanLaw(trackId, panLaw);
2162
+ else this.sendTrack(trackId);
2163
+ }
2164
+ /**
2165
+ * After an undo, a redo or an abort brought back another mix: the setter
2166
+ * for each field that differs, of each current track that had an entry in
2167
+ * `previousMixer` too. A track that entered with the restore was sent
2168
+ * whole, with its mix in its fields.
2169
+ */
2170
+ sendMixerDiff(previousMixer) {
2171
+ for (const { trackId, values } of mixerChanges(previousMixer, this._arrangement.getMixer())) {
2172
+ this.sendMixerValues(trackId, values);
2173
+ }
1521
2174
  }
1522
2175
  /**
1523
2176
  * The adapter call for a change to the tracks.
@@ -1590,7 +2243,7 @@ var AdapterSync = class {
1590
2243
  _addTrack(trackId) {
1591
2244
  const track = this._arrangement.getTracks().find((t) => t.id === trackId);
1592
2245
  if (track && this._adapter?.addTrack) {
1593
- this._adapter.addTrack(this._project(track));
2246
+ this._adapter.addTrack(this._playout(this._project(track)));
1594
2247
  } else {
1595
2248
  this.sendAllTracks();
1596
2249
  }
@@ -1630,9 +2283,10 @@ var AdapterSync = class {
1630
2283
  if (before.clips.some((clip, i) => clip !== now.clips[i])) return false;
1631
2284
  const keys = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(now)]);
1632
2285
  keys.delete("clips");
2286
+ for (const field of TRACK_VIEW_FIELDS) keys.delete(field);
1633
2287
  return [...keys].every((key) => Object.is(before[key], now[key]));
1634
2288
  }
1635
- /** What an adapter and `getState()` are given for one of the arrangement's tracks. */
2289
+ /** What `getState()` is given for one of the arrangement's tracks (an adapter: `_playout` of it). */
1636
2290
  _project(track) {
1637
2291
  return this._withMix(this._loaded(track));
1638
2292
  }
@@ -1644,27 +2298,46 @@ var AdapterSync = class {
1644
2298
  _loaded(track) {
1645
2299
  const known = this._loadedMemo.get(track);
1646
2300
  if (known) return known;
1647
- const clips = track.clips.filter((clip) => !isLoadingClip6(clip));
2301
+ const clips = track.clips.filter((clip) => !isLoadingClip8(clip));
1648
2302
  const loaded = clips.length === track.clips.length ? track : { ...track, clips };
1649
2303
  this._loadedMemo.set(track, loaded);
1650
2304
  return loaded;
1651
2305
  }
1652
- /** One track with its current mixer values in its fields (memoized per track object). */
2306
+ /**
2307
+ * True when a take is recording onto the track and it is a current track
2308
+ * (it has an entry in the current mix): it plays muted. A recording id that
2309
+ * is not in the tracks mutes nothing until it enters.
2310
+ */
2311
+ _recordingNow(trackId) {
2312
+ return this._arrangement.recordingTrackIds.has(trackId) && this._arrangement.getMixer().has(trackId);
2313
+ }
2314
+ /** A projected track without its view fields: a copy that shares its clips. */
2315
+ _playout(track) {
2316
+ const copy = { ...track };
2317
+ for (const field of TRACK_VIEW_FIELDS) delete copy[field];
2318
+ return freezeTrackInDevelopment(copy);
2319
+ }
2320
+ /**
2321
+ * One track with its current mixer values in its fields, muted while a
2322
+ * take records onto it (memoized per track object).
2323
+ */
1653
2324
  _withMix(track) {
1654
2325
  const values = this._arrangement.getMixer().get(track.id);
2326
+ const recording = this._recordingNow(track.id);
1655
2327
  const memo = this._withMixMemo.get(track);
1656
- if (memo && memo.values === values) return memo.merged;
1657
- const merged = freezeTrackInDevelopment(withMixerValues(track, values));
1658
- this._withMixMemo.set(track, { values, merged });
2328
+ if (memo && memo.values === values && memo.recording === recording) return memo.merged;
2329
+ const playing = recording && values && !values.muted ? { ...values, muted: true } : values;
2330
+ const merged = freezeTrackInDevelopment(withMixerValues(track, playing));
2331
+ this._withMixMemo.set(track, { values, recording, merged });
1659
2332
  return merged;
1660
2333
  }
1661
2334
  };
1662
2335
 
1663
- // src/PlaylistEngine.ts
2336
+ // src/EditorEngine.ts
1664
2337
  var DEFAULT_SAMPLE_RATE = 48e3;
1665
2338
  var DEFAULT_SAMPLES_PER_PIXEL = 1024;
1666
2339
  var DEFAULT_ZOOM_LEVELS = [256, 512, 1024, 2048, 4096, 8192];
1667
- var PlaylistEngine = class {
2340
+ var EditorEngine = class {
1668
2341
  constructor(options = {}) {
1669
2342
  this._detachDecodeContext = null;
1670
2343
  this._currentTime = 0;
@@ -1691,13 +2364,13 @@ var PlaylistEngine = class {
1691
2364
  });
1692
2365
  });
1693
2366
  if (this._zoomLevels.length === 0) {
1694
- throw new Error("PlaylistEngine: zoomLevels must not be empty");
2367
+ throw new Error("EditorEngine: zoomLevels must not be empty");
1695
2368
  }
1696
2369
  const initialSpp = options.samplesPerPixel ?? DEFAULT_SAMPLES_PER_PIXEL;
1697
2370
  const zoomIndex = this._zoomLevels.indexOf(initialSpp);
1698
2371
  if (zoomIndex === -1) {
1699
2372
  throw new Error(
1700
- `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.`
2373
+ `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.`
1701
2374
  );
1702
2375
  }
1703
2376
  this._zoomIndex = zoomIndex;
@@ -1713,7 +2386,7 @@ var PlaylistEngine = class {
1713
2386
  this._arrangement = asArrangementImpl(options.arrangement);
1714
2387
  if (options.undoLimit !== void 0) {
1715
2388
  console.warn(
1716
- "[waveform-playlist] PlaylistEngine: undoLimit is ignored when an arrangement is passed. Set it on createArrangement({ undoLimit })."
2389
+ "[waveform-playlist] EditorEngine: undoLimit is ignored when an arrangement is passed. Set it on createArrangement({ undoLimit })."
1717
2390
  );
1718
2391
  }
1719
2392
  } else {
@@ -1805,8 +2478,8 @@ var PlaylistEngine = class {
1805
2478
  setTracks(tracks) {
1806
2479
  this._arrangement.setTracks(tracks);
1807
2480
  }
1808
- addTrack(track) {
1809
- this._arrangement.addTrack(track);
2481
+ addTrack(track, options) {
2482
+ this._arrangement.addTrack(track, options);
1810
2483
  }
1811
2484
  removeTrack(trackId) {
1812
2485
  this._arrangement.removeTrack(trackId);
@@ -2030,9 +2703,13 @@ var PlaylistEngine = class {
2030
2703
  //
2031
2704
  // Each setter writes the value into the arrangement's mixer part (so a later
2032
2705
  // adapter rebuild via setTracks keeps the value, and mixerVersion is bumped);
2033
- // the engine's listener then calls the adapter and emits statechange. For a
2034
- // track the arrangement does not hold nothing changes, and the adapter is
2035
- // still called from here (a consumer may target a track that has not been
2706
+ // the engine's listener then calls the adapter and emits statechange. Each
2707
+ // call is an undo step, unless `options` says otherwise: the same `gesture`
2708
+ // id joins one step, `undoable: false` is no step (`MixerChangeOptions`).
2709
+ //
2710
+ // When the arrangement changes nothing (a track it does not hold, or the
2711
+ // value the track already has), the adapter is still called from here,
2712
+ // with no statechange (a consumer may target a track that has not been
2036
2713
  // ingested yet). These are NOT structural
2037
2714
  // changes, so they deliberately do NOT bump tracksVersion — that would make
2038
2715
  // tracksVersion-gated consumers re-run expensive structural work (audio-graph
@@ -2040,22 +2717,58 @@ var PlaylistEngine = class {
2040
2717
  // cache a track snapshot (e.g. @dawcore/components' <daw-editor>) watch
2041
2718
  // mixerVersion to refresh that cache cheaply, so an unrelated setTracks
2042
2719
  // rebuild no longer reverts live mixer state (#501).
2043
- setTrackVolume(trackId, volume) {
2044
- const changed = this._mixerChanged(() => this._arrangement.setTrackVolume(trackId, volume));
2720
+ setTrackVolume(trackId, volume, options) {
2721
+ const changed = this._mixerChanged(
2722
+ () => this._arrangement.setTrackVolume(trackId, volume, options)
2723
+ );
2045
2724
  if (!changed && !this._disposed) this._adapter?.setTrackVolume(trackId, volume);
2046
2725
  }
2047
- setTrackMute(trackId, muted) {
2048
- const changed = this._mixerChanged(() => this._arrangement.setTrackMute(trackId, muted));
2049
- if (!changed && !this._disposed) this._adapter?.setTrackMute(trackId, muted);
2726
+ setTrackMute(trackId, muted, options) {
2727
+ const changed = this._mixerChanged(
2728
+ () => this._arrangement.setTrackMute(trackId, muted, options)
2729
+ );
2730
+ if (!changed && !this._disposed) this._adapterSync.sendMixerValues(trackId, { muted });
2050
2731
  }
2051
- setTrackSolo(trackId, soloed) {
2052
- const changed = this._mixerChanged(() => this._arrangement.setTrackSolo(trackId, soloed));
2732
+ setTrackSolo(trackId, soloed, options) {
2733
+ const changed = this._mixerChanged(
2734
+ () => this._arrangement.setTrackSolo(trackId, soloed, options)
2735
+ );
2053
2736
  if (!changed && !this._disposed) this._adapter?.setTrackSolo(trackId, soloed);
2054
2737
  }
2055
- setTrackPan(trackId, pan) {
2056
- const changed = this._mixerChanged(() => this._arrangement.setTrackPan(trackId, pan));
2738
+ setTrackPan(trackId, pan, options) {
2739
+ const changed = this._mixerChanged(() => this._arrangement.setTrackPan(trackId, pan, options));
2057
2740
  if (!changed && !this._disposed) this._adapter?.setTrackPan(trackId, pan);
2058
2741
  }
2742
+ /**
2743
+ * Set a track's pan law (#684): the arrangement's `setTrackPanLaw`.
2744
+ * Unlike the four setters above, nothing is sent to the adapter when the
2745
+ * arrangement changed nothing (a track it does not hold, the law the
2746
+ * track already has): for an adapter without `setTrackPanLaw` the call
2747
+ * would be a whole-track `updateTrack`.
2748
+ */
2749
+ setTrackPanLaw(trackId, panLaw, options) {
2750
+ this._arrangement.setTrackPanLaw(trackId, panLaw, options);
2751
+ }
2752
+ /**
2753
+ * Mark a track as the one a take is recording onto, or clear it when the
2754
+ * take ends: the arrangement's `setTrackRecording`. That track plays muted
2755
+ * (here and in the adapter) while its mute in the mix stays as it is; the
2756
+ * take's mute is not an undo step. The arrangement's `'recording'`
2757
+ * announcement brings the adapter in step, so there is no adapter call of
2758
+ * its own here; a disposed engine changes the arrangement only.
2759
+ */
2760
+ setTrackRecording(trackId, recording) {
2761
+ this._arrangement.setTrackRecording(trackId, recording);
2762
+ }
2763
+ /**
2764
+ * The tracks a take is recording onto, read from the arrangement (the
2765
+ * owner; no copy). The same set object until it changes; never write to
2766
+ * it, use `setTrackRecording`. Such a track plays muted, so a UI can
2767
+ * disable its mute control while the id is in the set.
2768
+ */
2769
+ get recordingTrackIds() {
2770
+ return this._arrangement.recordingTrackIds;
2771
+ }
2059
2772
  // ---------------------------------------------------------------------------
2060
2773
  // Zoom
2061
2774
  // ---------------------------------------------------------------------------
@@ -2092,8 +2805,9 @@ var PlaylistEngine = class {
2092
2805
  // ---------------------------------------------------------------------------
2093
2806
  // Lifecycle
2094
2807
  // ---------------------------------------------------------------------------
2095
- dispose() {
2808
+ dispose(options = {}) {
2096
2809
  if (this._disposed) return;
2810
+ if (options.keepAdapter && this._isPlaying) this.stop();
2097
2811
  this._disposed = true;
2098
2812
  this._stopFollowingArrangement();
2099
2813
  this._detachFromArrangement();
@@ -2102,7 +2816,8 @@ var PlaylistEngine = class {
2102
2816
  this._isPlaying = false;
2103
2817
  this._adapter?.onPlaybackEnded?.(null);
2104
2818
  try {
2105
- this._adapter?.dispose();
2819
+ if (options.keepAdapter) this._adapter?.setTracks([]);
2820
+ else this._adapter?.dispose();
2106
2821
  } catch (err) {
2107
2822
  console.warn("[waveform-playlist/engine] Error disposing adapter:", err);
2108
2823
  }
@@ -2128,6 +2843,14 @@ var PlaylistEngine = class {
2128
2843
  case "mixer":
2129
2844
  this._adapterSync.sendMixerValues(change.trackId, change.values);
2130
2845
  break;
2846
+ case "restoreMix":
2847
+ this._adapterSync.sendMixerDiff(change.previousMixer);
2848
+ break;
2849
+ case "recording": {
2850
+ const values = this._arrangement.getMixer().get(change.trackId);
2851
+ if (values) this._adapterSync.sendMixerValues(change.trackId, { muted: values.muted });
2852
+ break;
2853
+ }
2131
2854
  case "reorder":
2132
2855
  // not audible: adapter nodes are keyed by track id
2133
2856
  case "history":
@@ -2140,6 +2863,7 @@ var PlaylistEngine = class {
2140
2863
  this._followLoad(change, at);
2141
2864
  } else {
2142
2865
  this._adapterSync.follow(change, at);
2866
+ if (change.type === "restore") this._adapterSync.sendMixerDiff(change.previousMixer);
2143
2867
  }
2144
2868
  }
2145
2869
  this._emitStateChange();
@@ -2211,11 +2935,11 @@ var PlaylistEngine = class {
2211
2935
  function asArrangementImpl(arrangement) {
2212
2936
  if (isArrangement(arrangement)) return arrangement;
2213
2937
  throw new Error(
2214
- "[waveform-playlist] PlaylistEngine: the `arrangement` option must be an arrangement made by createArrangement()."
2938
+ "[waveform-playlist] EditorEngine: the `arrangement` option must be an arrangement made by createArrangement()."
2215
2939
  );
2216
2940
  }
2217
2941
  export {
2218
- PlaylistEngine,
2942
+ EditorEngine,
2219
2943
  attachDecodeContext,
2220
2944
  calculateDuration,
2221
2945
  calculateSplitPoint,
@@ -2227,9 +2951,12 @@ export {
2227
2951
  constrainClipDrag,
2228
2952
  createArrangement,
2229
2953
  defaultLoadSource,
2954
+ findClipOverlap,
2230
2955
  findClosestZoomIndex,
2231
2956
  getVisibleChunkIndices,
2957
+ isArrangement,
2232
2958
  shouldUpdateViewport,
2233
- splitClip
2959
+ splitClip,
2960
+ trackClipSpans
2234
2961
  };
2235
2962
  //# sourceMappingURL=index.mjs.map