@dawcore/components 0.0.39-next.6 → 0.0.39-next.7

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
@@ -10,7 +10,7 @@ var __decorateClass = (decorators, target, key, kind) => {
10
10
  };
11
11
 
12
12
  // <define:__INSTALL_SPECS__>
13
- var define_INSTALL_SPECS_default = { "@dawcore/faust": "@dawcore/faust@^0.0.2-next.1", "@dawcore/midi": "@dawcore/midi@^0.0.6-next.4", "@dawcore/transport": "@dawcore/transport@^0.0.16-next.4", "@dawcore/wam": "@dawcore/wam@^0.0.5-next.0", "@waveform-playlist/core": "@waveform-playlist/core@^13.0.0-next.4", "@waveform-playlist/engine": "@waveform-playlist/engine@^14.0.0-next.3", "@waveform-playlist/worklets": "@waveform-playlist/worklets@^13.0.1-next.0", "@waveform-playlist/playout": "@waveform-playlist/playout@^13.0.0-next.4" };
13
+ var define_INSTALL_SPECS_default = { "@dawcore/faust": "@dawcore/faust@^0.0.2-next.1", "@dawcore/midi": "@dawcore/midi@^0.0.6-next.5", "@dawcore/transport": "@dawcore/transport@^0.0.16-next.4", "@dawcore/wam": "@dawcore/wam@^0.0.5-next.0", "@waveform-playlist/core": "@waveform-playlist/core@^13.0.0-next.4", "@waveform-playlist/engine": "@waveform-playlist/engine@^14.0.0-next.4", "@waveform-playlist/worklets": "@waveform-playlist/worklets@^13.0.1-next.0", "@waveform-playlist/playout": "@waveform-playlist/playout@^13.0.0-next.4" };
14
14
 
15
15
  // src/elements/daw-annotation.ts
16
16
  import { LitElement } from "lit";
@@ -268,6 +268,8 @@ var DawAnnotationTrackElement = class extends LitElement2 {
268
268
  };
269
269
  // --- Lifecycle ---
270
270
  this._childObserver = null;
271
+ /** The listeners of this connection, aborted in disconnectedCallback. */
272
+ this._listeners = null;
271
273
  }
272
274
  get activeAnnotationId() {
273
275
  return this._activeAnnotationId;
@@ -468,7 +470,13 @@ var DawAnnotationTrackElement = class extends LitElement2 {
468
470
  delete this["annotationShortcuts"];
469
471
  this.annotationShortcuts = value;
470
472
  }
471
- document.addEventListener("keydown", this._onKeyDownCapture, true);
473
+ this._listeners?.abort();
474
+ this._listeners = new AbortController();
475
+ document.addEventListener("keydown", this._onKeyDownCapture, {
476
+ capture: true,
477
+ // capture phase
478
+ signal: this._listeners.signal
479
+ });
472
480
  setTimeout(() => {
473
481
  this.dispatchEvent(
474
482
  new CustomEvent("daw-annotation-track-connected", {
@@ -487,7 +495,8 @@ var DawAnnotationTrackElement = class extends LitElement2 {
487
495
  }
488
496
  disconnectedCallback() {
489
497
  super.disconnectedCallback();
490
- document.removeEventListener("keydown", this._onKeyDownCapture, true);
498
+ this._listeners?.abort();
499
+ this._listeners = null;
491
500
  this._childObserver?.disconnect();
492
501
  this._childObserver = null;
493
502
  }
@@ -561,6 +570,8 @@ var DawAnnotationListElement = class extends LitElement3 {
561
570
  * blur event doesn't re-enter `_commitEdit` (cancel already restores the
562
571
  * text and clears `_editingId` itself). */
563
572
  this._cancelling = false;
573
+ /** The listeners of this connection, aborted in disconnectedCallback. */
574
+ this._listeners = null;
564
575
  this._onSelect = (e) => {
565
576
  if (e.target !== this.track) return;
566
577
  this._activeId = e.detail.annotation?.id ?? null;
@@ -618,15 +629,17 @@ var DawAnnotationListElement = class extends LitElement3 {
618
629
  }
619
630
  connectedCallback() {
620
631
  super.connectedCallback();
621
- document.addEventListener("daw-annotation-select", this._onSelect);
622
- document.addEventListener("daw-timeupdate", this._onTimeUpdate);
623
- document.addEventListener("daw-stop", this._onStop);
632
+ this._listeners?.abort();
633
+ this._listeners = new AbortController();
634
+ const { signal } = this._listeners;
635
+ document.addEventListener("daw-annotation-select", this._onSelect, { signal });
636
+ document.addEventListener("daw-timeupdate", this._onTimeUpdate, { signal });
637
+ document.addEventListener("daw-stop", this._onStop, { signal });
624
638
  }
625
639
  disconnectedCallback() {
626
640
  super.disconnectedCallback();
627
- document.removeEventListener("daw-annotation-select", this._onSelect);
628
- document.removeEventListener("daw-timeupdate", this._onTimeUpdate);
629
- document.removeEventListener("daw-stop", this._onStop);
641
+ this._listeners?.abort();
642
+ this._listeners = null;
630
643
  this._observer?.disconnect();
631
644
  this._observer = null;
632
645
  this._observedTrack = null;
@@ -768,6 +781,10 @@ var DawAnnotationListElement = class extends LitElement3 {
768
781
  }
769
782
  };
770
783
  DawAnnotationListElement.styles = css`
784
+ /* The hidden attribute hides the element: :host sets display (modern-web-guidance custom-elements). */
785
+ :host([hidden]) {
786
+ display: none;
787
+ }
771
788
  :host {
772
789
  display: block;
773
790
  max-height: var(--daw-annotation-list-max-height, 240px);
@@ -827,68 +844,174 @@ DawAnnotationListElement = __decorateClass([
827
844
  // src/elements/daw-clip.ts
828
845
  import { LitElement as LitElement4 } from "lit";
829
846
  import { customElement as customElement4, property as property4 } from "lit/decorators.js";
847
+
848
+ // src/interactions/element-links.ts
849
+ function linkHostOf(el) {
850
+ const editor = el.closest("daw-editor");
851
+ return editor && typeof editor._trackLinkState === "function" ? editor : null;
852
+ }
853
+ function refreshLinkStates(host, trackEls) {
854
+ for (const [trackId, trackEl] of trackEls) {
855
+ trackEl._setDetached(host._trackLinkState(trackId) === "detached");
856
+ for (const clipEl of trackEl.querySelectorAll("daw-clip")) {
857
+ const clip = clipEl;
858
+ clip._setDetached(host._clipLinkState(trackId, clip.clipId) === "detached");
859
+ }
860
+ }
861
+ }
862
+ function detachedWarning(element, change, reason) {
863
+ return "[dawcore] " + element + " is detached (" + reason + "): " + change + " changes nothing. Remove the element and insert it again to declare a new one.";
864
+ }
865
+ function setCustomState(internals, name, on) {
866
+ const states = internals?.states;
867
+ if (!states) return;
868
+ if (on) states.add(name);
869
+ else states.delete(name);
870
+ }
871
+
872
+ // src/elements/daw-clip.ts
830
873
  var DawClipElement = class extends LitElement4 {
831
874
  constructor() {
832
875
  super(...arguments);
833
876
  this.src = "";
834
877
  this.peaksSrc = "";
835
- this.start = 0;
836
- this.duration = 0;
837
- this.offset = 0;
838
- this.gain = 1;
839
- this.name = "";
840
878
  this.color = "";
841
879
  this.fadeIn = 0;
842
880
  this.fadeOut = 0;
843
881
  this.fadeType = "linear";
844
- this.midiNotes = null;
845
- this._midiChannel = null;
846
- this._midiProgram = null;
882
+ /** What the page declared: the attributes, and a property set before the clip entered. */
883
+ this._declared = {
884
+ start: 0,
885
+ duration: 0,
886
+ offset: 0,
887
+ gain: 1,
888
+ name: "",
889
+ midiNotes: null,
890
+ midiChannel: null,
891
+ midiProgram: null
892
+ };
893
+ this._fromAttribute = false;
894
+ this._internals = this.attachInternals?.() ?? null;
847
895
  this.clipId = crypto.randomUUID();
848
896
  // Removal is detected by the editor's MutationObserver — detached elements
849
897
  // cannot bubble events to ancestors.
850
898
  this._hasRendered = false;
851
899
  }
900
+ get start() {
901
+ return this._linked("start");
902
+ }
903
+ set start(value) {
904
+ this._request("start", value);
905
+ }
906
+ get duration() {
907
+ return this._linked("duration");
908
+ }
909
+ set duration(value) {
910
+ this._request("duration", value);
911
+ }
912
+ get offset() {
913
+ return this._linked("offset");
914
+ }
915
+ set offset(value) {
916
+ this._request("offset", value);
917
+ }
918
+ get gain() {
919
+ return this._linked("gain");
920
+ }
921
+ set gain(value) {
922
+ this._request("gain", value);
923
+ }
924
+ get name() {
925
+ return this._linked("name");
926
+ }
927
+ set name(value) {
928
+ this._request("name", value ?? "");
929
+ }
930
+ get midiNotes() {
931
+ return this._linked("midiNotes");
932
+ }
933
+ set midiNotes(value) {
934
+ this._request("midiNotes", value ?? null);
935
+ }
852
936
  get midiChannel() {
853
- return this._midiChannel;
937
+ return this._linked("midiChannel");
854
938
  }
855
939
  set midiChannel(value) {
856
- const old = this._midiChannel;
857
- if (value === null) {
858
- this._midiChannel = null;
859
- this.requestUpdate("midiChannel", old);
860
- return;
861
- }
862
- if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0 || value > 15) {
940
+ if (value !== null && (!Number.isFinite(value) || !Number.isInteger(value) || value < 0 || value > 15)) {
863
941
  console.warn("[dawcore] daw-clip midi-channel " + value + " is out of range 0-15 \u2014 ignored");
864
942
  return;
865
943
  }
866
- this._midiChannel = value;
867
- this.requestUpdate("midiChannel", old);
944
+ this._request("midiChannel", value);
868
945
  }
869
946
  get midiProgram() {
870
- return this._midiProgram;
947
+ return this._linked("midiProgram");
871
948
  }
872
949
  set midiProgram(value) {
873
- const old = this._midiProgram;
874
- if (value === null) {
875
- this._midiProgram = null;
876
- this.requestUpdate("midiProgram", old);
877
- return;
878
- }
879
- if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0 || value > 127) {
950
+ if (value !== null && (!Number.isFinite(value) || !Number.isInteger(value) || value < 0 || value > 127)) {
880
951
  console.warn("[dawcore] daw-clip midi-program " + value + " is out of range 0-127 \u2014 ignored");
881
952
  return;
882
953
  }
883
- this._midiProgram = value;
884
- this.requestUpdate("midiProgram", old);
954
+ this._request("midiProgram", value);
955
+ }
956
+ attributeChangedCallback(name, old, value) {
957
+ this._fromAttribute = true;
958
+ try {
959
+ super.attributeChangedCallback(name, old, value);
960
+ } finally {
961
+ this._fromAttribute = false;
962
+ }
963
+ }
964
+ get _trackId() {
965
+ return this.closest("daw-track")?.trackId ?? "";
966
+ }
967
+ _linked(key) {
968
+ const host = linkHostOf(this);
969
+ const trackId = this._trackId;
970
+ const live = host && trackId && host._clipLinkState(trackId, this.clipId) === "live" ? host._clipValues(trackId, this.clipId) : null;
971
+ return live ? live[key] : this._declared[key];
972
+ }
973
+ _request(key, value) {
974
+ const old = this._linked(key);
975
+ const host = linkHostOf(this);
976
+ const trackId = this._trackId;
977
+ const state9 = host && trackId ? host._clipLinkState(trackId, this.clipId) : "pending";
978
+ if (this._fromAttribute || state9 === "pending") {
979
+ this._declared = { ...this._declared, [key]: value };
980
+ }
981
+ if (state9 === "live") {
982
+ host._requestClipChange(trackId, this.clipId, { [key]: value });
983
+ } else if (state9 === "detached") {
984
+ const label = '<daw-clip> of track "' + trackId + '"';
985
+ console.warn(detachedWarning(label, key + " = " + String(value), host._detachedReason()));
986
+ }
987
+ this.requestUpdate(key, old);
988
+ }
989
+ /** @internal Shown as `:state(detached)` (#848). */
990
+ _setDetached(detached) {
991
+ setCustomState(this._internals, "detached", detached);
885
992
  }
886
993
  // Light DOM — no visual rendering, just a data container
887
994
  createRenderRoot() {
888
995
  return this;
889
996
  }
997
+ /**
998
+ * A move with `Node.moveBefore()` (#848; modern-web-guidance
999
+ * `custom-elements`): the browser calls this instead of
1000
+ * `disconnectedCallback` → `connectedCallback`, so the element stays
1001
+ * connected, and Lit's disconnect and connect do not run. It announces
1002
+ * itself again, as a connect does, so the editor sees its new place: a
1003
+ * clip in another track, a track back in an editor (#848; a real-Chromium
1004
+ * check found both missed with an empty hook).
1005
+ */
1006
+ connectedMoveCallback() {
1007
+ this._announceConnected();
1008
+ }
890
1009
  connectedCallback() {
891
1010
  super.connectedCallback();
1011
+ this._announceConnected();
1012
+ }
1013
+ /** Tell the editor this element is here (a connect or a moveBefore() move). */
1014
+ _announceConnected() {
892
1015
  setTimeout(() => {
893
1016
  this.dispatchEvent(
894
1017
  new CustomEvent("daw-clip-connected", {
@@ -938,20 +1061,20 @@ __decorateClass([
938
1061
  property4({ attribute: "peaks-src" })
939
1062
  ], DawClipElement.prototype, "peaksSrc", 2);
940
1063
  __decorateClass([
941
- property4({ type: Number })
942
- ], DawClipElement.prototype, "start", 2);
1064
+ property4({ type: Number, noAccessor: true })
1065
+ ], DawClipElement.prototype, "start", 1);
943
1066
  __decorateClass([
944
- property4({ type: Number })
945
- ], DawClipElement.prototype, "duration", 2);
1067
+ property4({ type: Number, noAccessor: true })
1068
+ ], DawClipElement.prototype, "duration", 1);
946
1069
  __decorateClass([
947
- property4({ type: Number })
948
- ], DawClipElement.prototype, "offset", 2);
1070
+ property4({ type: Number, noAccessor: true })
1071
+ ], DawClipElement.prototype, "offset", 1);
949
1072
  __decorateClass([
950
- property4({ type: Number })
951
- ], DawClipElement.prototype, "gain", 2);
1073
+ property4({ type: Number, noAccessor: true })
1074
+ ], DawClipElement.prototype, "gain", 1);
952
1075
  __decorateClass([
953
- property4()
954
- ], DawClipElement.prototype, "name", 2);
1076
+ property4({ noAccessor: true })
1077
+ ], DawClipElement.prototype, "name", 1);
955
1078
  __decorateClass([
956
1079
  property4()
957
1080
  ], DawClipElement.prototype, "color", 2);
@@ -965,8 +1088,8 @@ __decorateClass([
965
1088
  property4({ attribute: "fade-type" })
966
1089
  ], DawClipElement.prototype, "fadeType", 2);
967
1090
  __decorateClass([
968
- property4({ attribute: false })
969
- ], DawClipElement.prototype, "midiNotes", 2);
1091
+ property4({ attribute: false, noAccessor: true })
1092
+ ], DawClipElement.prototype, "midiNotes", 1);
970
1093
  __decorateClass([
971
1094
  property4({ type: Number, attribute: "midi-channel", noAccessor: true })
972
1095
  ], DawClipElement.prototype, "midiChannel", 1);
@@ -1013,11 +1136,10 @@ var DawTrackElement = class extends LitElement5 {
1013
1136
  constructor() {
1014
1137
  super(...arguments);
1015
1138
  this.src = "";
1016
- this.name = "";
1017
- this.volume = 1;
1018
- this.pan = 0;
1019
- this.muted = false;
1020
- this.soloed = false;
1139
+ /** What the page declared: the attributes, and a property set before the track entered. */
1140
+ this._declared = { name: "", volume: 1, pan: 0, muted: false, soloed: false };
1141
+ this._fromAttribute = false;
1142
+ this._internals = this.attachInternals?.() ?? null;
1021
1143
  this._kind = "audio";
1022
1144
  this._renderMode = "waveform";
1023
1145
  this.spectrogramConfig = null;
@@ -1027,10 +1149,86 @@ var DawTrackElement = class extends LitElement5 {
1027
1149
  // cannot bubble events to ancestors).
1028
1150
  this._hasRendered = false;
1029
1151
  }
1152
+ get name() {
1153
+ return this._linked("name");
1154
+ }
1155
+ set name(value) {
1156
+ this._request("name", value ?? "");
1157
+ }
1158
+ get volume() {
1159
+ return this._linked("volume");
1160
+ }
1161
+ set volume(value) {
1162
+ this._request("volume", value);
1163
+ }
1164
+ get pan() {
1165
+ return this._linked("pan");
1166
+ }
1167
+ set pan(value) {
1168
+ this._request("pan", value);
1169
+ }
1170
+ get muted() {
1171
+ return this._linked("muted");
1172
+ }
1173
+ set muted(value) {
1174
+ this._request("muted", Boolean(value));
1175
+ }
1176
+ get soloed() {
1177
+ return this._linked("soloed");
1178
+ }
1179
+ set soloed(value) {
1180
+ this._request("soloed", Boolean(value));
1181
+ }
1182
+ /** The track's position in the arrangement the editor plays; -1 when it is not there. */
1183
+ get index() {
1184
+ return linkHostOf(this)?._trackIndex(this.trackId) ?? -1;
1185
+ }
1186
+ attributeChangedCallback(name, old, value) {
1187
+ this._fromAttribute = true;
1188
+ try {
1189
+ super.attributeChangedCallback(name, old, value);
1190
+ } finally {
1191
+ this._fromAttribute = false;
1192
+ }
1193
+ }
1194
+ _linked(key) {
1195
+ const host = linkHostOf(this);
1196
+ const live = host?._trackLinkState(this.trackId) === "live" ? host._trackValues(this.trackId) : null;
1197
+ return live ? live[key] : this._declared[key];
1198
+ }
1199
+ _request(key, value) {
1200
+ const old = this._linked(key);
1201
+ const host = linkHostOf(this);
1202
+ const state9 = host?._trackLinkState(this.trackId) ?? "pending";
1203
+ if (this._fromAttribute || state9 === "pending") {
1204
+ this._declared = { ...this._declared, [key]: value };
1205
+ }
1206
+ if (state9 === "live") {
1207
+ host._requestTrackChange(this.trackId, { [key]: value });
1208
+ } else if (state9 === "detached") {
1209
+ const label = '<daw-track name="' + this._declared.name + '">';
1210
+ console.warn(detachedWarning(label, key + " = " + String(value), host._detachedReason()));
1211
+ }
1212
+ this.requestUpdate(key, old);
1213
+ }
1214
+ /** @internal Shown as `:state(detached)` (#848). */
1215
+ _setDetached(detached) {
1216
+ setCustomState(this._internals, "detached", detached);
1217
+ }
1030
1218
  get kind() {
1031
- return this._kind;
1219
+ const host = linkHostOf(this);
1220
+ const live = host?._trackLinkState(this.trackId) === "live" ? host._trackKind(this.trackId) : null;
1221
+ return live ?? this._kind;
1032
1222
  }
1033
1223
  set kind(value) {
1224
+ const host = linkHostOf(this);
1225
+ const live = host?._trackLinkState(this.trackId) === "live" ? host._trackKind(this.trackId) : null;
1226
+ if (live && value !== live) {
1227
+ console.warn(
1228
+ '[dawcore] <daw-track> "' + (this._declared.name || "Untitled") + '": kind cannot change after the track has loaded (still "' + live + '"). Remove the track and add one of the other kind.'
1229
+ );
1230
+ if (!this._fromAttribute) return;
1231
+ }
1034
1232
  if (value !== "audio" && value !== "midi") {
1035
1233
  console.warn(
1036
1234
  '[dawcore] <daw-track kind="' + String(value) + `"> is not a track kind ('audio' or 'midi'); keeping "` + this._kind + '"'
@@ -1122,8 +1320,24 @@ var DawTrackElement = class extends LitElement5 {
1122
1320
  }
1123
1321
  return editor;
1124
1322
  }
1323
+ /**
1324
+ * A move with `Node.moveBefore()` (#848; modern-web-guidance
1325
+ * `custom-elements`): the browser calls this instead of
1326
+ * `disconnectedCallback` → `connectedCallback`, so the element stays
1327
+ * connected, and Lit's disconnect and connect do not run. It announces
1328
+ * itself again, as a connect does, so the editor sees its new place: a
1329
+ * clip in another track, a track back in an editor (#848; a real-Chromium
1330
+ * check found both missed with an empty hook).
1331
+ */
1332
+ connectedMoveCallback() {
1333
+ this._announceConnected();
1334
+ }
1125
1335
  connectedCallback() {
1126
1336
  super.connectedCallback();
1337
+ this._announceConnected();
1338
+ }
1339
+ /** Tell the editor this element is here (a connect or a moveBefore() move). */
1340
+ _announceConnected() {
1127
1341
  setTimeout(() => {
1128
1342
  this.dispatchEvent(
1129
1343
  new CustomEvent("daw-track-connected", {
@@ -1156,20 +1370,20 @@ __decorateClass([
1156
1370
  property5()
1157
1371
  ], DawTrackElement.prototype, "src", 2);
1158
1372
  __decorateClass([
1159
- property5()
1160
- ], DawTrackElement.prototype, "name", 2);
1373
+ property5({ noAccessor: true })
1374
+ ], DawTrackElement.prototype, "name", 1);
1161
1375
  __decorateClass([
1162
- property5({ type: Number })
1163
- ], DawTrackElement.prototype, "volume", 2);
1376
+ property5({ type: Number, noAccessor: true })
1377
+ ], DawTrackElement.prototype, "volume", 1);
1164
1378
  __decorateClass([
1165
- property5({ type: Number })
1166
- ], DawTrackElement.prototype, "pan", 2);
1379
+ property5({ type: Number, noAccessor: true })
1380
+ ], DawTrackElement.prototype, "pan", 1);
1167
1381
  __decorateClass([
1168
- property5({ type: Boolean })
1169
- ], DawTrackElement.prototype, "muted", 2);
1382
+ property5({ type: Boolean, noAccessor: true })
1383
+ ], DawTrackElement.prototype, "muted", 1);
1170
1384
  __decorateClass([
1171
- property5({ type: Boolean })
1172
- ], DawTrackElement.prototype, "soloed", 2);
1385
+ property5({ type: Boolean, noAccessor: true })
1386
+ ], DawTrackElement.prototype, "soloed", 1);
1173
1387
  __decorateClass([
1174
1388
  property5({ reflect: true, noAccessor: true })
1175
1389
  ], DawTrackElement.prototype, "kind", 1);
@@ -1923,6 +2137,8 @@ function warnUnsupportedOnce(element, methods) {
1923
2137
  var DawTransportButton = class extends LitElement10 {
1924
2138
  constructor() {
1925
2139
  super(...arguments);
2140
+ /** The host's capability listeners, one controller per connection. */
2141
+ this._capabilityListeners = null;
1926
2142
  this._onCapabilityPointerEnter = () => {
1927
2143
  this.requestUpdate();
1928
2144
  };
@@ -1960,8 +2176,11 @@ var DawTransportButton = class extends LitElement10 {
1960
2176
  }
1961
2177
  connectedCallback() {
1962
2178
  super.connectedCallback();
1963
- this.addEventListener("pointerdown", this._onCapabilityPointerDown);
1964
- this.addEventListener("pointerenter", this._onCapabilityPointerEnter);
2179
+ this._capabilityListeners?.abort();
2180
+ this._capabilityListeners = new AbortController();
2181
+ const { signal } = this._capabilityListeners;
2182
+ this.addEventListener("pointerdown", this._onCapabilityPointerDown, { signal });
2183
+ this.addEventListener("pointerenter", this._onCapabilityPointerEnter, { signal });
1965
2184
  requestAnimationFrame(() => {
1966
2185
  if (!this.isConnected) return;
1967
2186
  this.requestUpdate();
@@ -1969,8 +2188,8 @@ var DawTransportButton = class extends LitElement10 {
1969
2188
  }
1970
2189
  disconnectedCallback() {
1971
2190
  super.disconnectedCallback();
1972
- this.removeEventListener("pointerdown", this._onCapabilityPointerDown);
1973
- this.removeEventListener("pointerenter", this._onCapabilityPointerEnter);
2191
+ this._capabilityListeners?.abort();
2192
+ this._capabilityListeners = null;
1974
2193
  }
1975
2194
  };
1976
2195
  /** Methods the transport target must implement for this control to be
@@ -2000,6 +2219,8 @@ var DawPlayButtonElement = class extends DawTransportButton {
2000
2219
  super(...arguments);
2001
2220
  this._isRecording = false;
2002
2221
  this._targetRef = null;
2222
+ /** The listeners on `_targetRef`, aborted when the target changes or the button disconnects. */
2223
+ this._targetListeners = null;
2003
2224
  this._onRecStart = () => {
2004
2225
  this._isRecording = true;
2005
2226
  };
@@ -2030,15 +2251,16 @@ var DawPlayButtonElement = class extends DawTransportButton {
2030
2251
  this._cleanupListeners();
2031
2252
  if (!target) return;
2032
2253
  this._targetRef = target;
2033
- target.addEventListener("daw-recording-start", this._onRecStart);
2034
- target.addEventListener("daw-recording-complete", this._onRecEnd);
2035
- target.addEventListener("daw-recording-error", this._onRecEnd);
2254
+ this._targetListeners = new AbortController();
2255
+ const { signal } = this._targetListeners;
2256
+ target.addEventListener("daw-recording-start", this._onRecStart, { signal });
2257
+ target.addEventListener("daw-recording-complete", this._onRecEnd, { signal });
2258
+ target.addEventListener("daw-recording-error", this._onRecEnd, { signal });
2036
2259
  }
2037
2260
  _cleanupListeners() {
2038
2261
  if (this._targetRef) {
2039
- this._targetRef.removeEventListener("daw-recording-start", this._onRecStart);
2040
- this._targetRef.removeEventListener("daw-recording-complete", this._onRecEnd);
2041
- this._targetRef.removeEventListener("daw-recording-error", this._onRecEnd);
2262
+ this._targetListeners?.abort();
2263
+ this._targetListeners = null;
2042
2264
  this._targetRef = null;
2043
2265
  }
2044
2266
  }
@@ -2076,6 +2298,8 @@ var DawPauseButtonElement = class extends DawTransportButton {
2076
2298
  this._isPaused = false;
2077
2299
  this._isRecording = false;
2078
2300
  this._targetRef = null;
2301
+ /** The listeners on `_targetRef`, aborted when the target changes or the button disconnects. */
2302
+ this._targetListeners = null;
2079
2303
  this._onRecStart = () => {
2080
2304
  this._isRecording = true;
2081
2305
  };
@@ -2114,19 +2338,18 @@ var DawPauseButtonElement = class extends DawTransportButton {
2114
2338
  this._cleanupListeners();
2115
2339
  if (!target) return;
2116
2340
  this._targetRef = target;
2117
- target.addEventListener("daw-recording-start", this._onRecStart);
2118
- target.addEventListener("daw-recording-complete", this._onRecEnd);
2119
- target.addEventListener("daw-recording-error", this._onRecEnd);
2120
- target.addEventListener("daw-recording-pause", this._onRecPause);
2121
- target.addEventListener("daw-recording-resume", this._onRecResume);
2341
+ this._targetListeners = new AbortController();
2342
+ const { signal } = this._targetListeners;
2343
+ target.addEventListener("daw-recording-start", this._onRecStart, { signal });
2344
+ target.addEventListener("daw-recording-complete", this._onRecEnd, { signal });
2345
+ target.addEventListener("daw-recording-error", this._onRecEnd, { signal });
2346
+ target.addEventListener("daw-recording-pause", this._onRecPause, { signal });
2347
+ target.addEventListener("daw-recording-resume", this._onRecResume, { signal });
2122
2348
  }
2123
2349
  _cleanupListeners() {
2124
2350
  if (this._targetRef) {
2125
- this._targetRef.removeEventListener("daw-recording-start", this._onRecStart);
2126
- this._targetRef.removeEventListener("daw-recording-complete", this._onRecEnd);
2127
- this._targetRef.removeEventListener("daw-recording-error", this._onRecEnd);
2128
- this._targetRef.removeEventListener("daw-recording-pause", this._onRecPause);
2129
- this._targetRef.removeEventListener("daw-recording-resume", this._onRecResume);
2351
+ this._targetListeners?.abort();
2352
+ this._targetListeners = null;
2130
2353
  this._targetRef = null;
2131
2354
  }
2132
2355
  }
@@ -2216,10 +2439,11 @@ DawStopButtonElement = __decorateClass([
2216
2439
  // src/elements/daw-editor.ts
2217
2440
  import { LitElement as LitElement14, html as html12, css as css11 } from "lit";
2218
2441
  import { customElement as customElement16, property as property12, state as state4 } from "lit/decorators.js";
2442
+ import { repeat } from "lit/directives/repeat.js";
2219
2443
  import {
2220
2444
  createMixerGesture as createMixerGesture2,
2221
2445
  clipPixelWidth,
2222
- isLoadingClip as isLoadingClip3,
2446
+ isLoadingClip as isLoadingClip5,
2223
2447
  trackKind
2224
2448
  } from "@waveform-playlist/core";
2225
2449
 
@@ -2981,15 +3205,6 @@ function mixOfTrack(track) {
2981
3205
  function mixOfElement(el) {
2982
3206
  return { volume: el.volume, pan: el.pan, muted: el.muted, soloed: el.soloed };
2983
3207
  }
2984
- function pickMix(mix, names) {
2985
- const named = new Set(names);
2986
- return {
2987
- ...named.has("volume") && { volume: mix.volume },
2988
- ...named.has("pan") && { pan: mix.pan },
2989
- ...named.has("muted") && { muted: mix.muted },
2990
- ...named.has("soloed") && { soloed: mix.soloed }
2991
- };
2992
- }
2993
3208
  function clampNumber(value, min, max) {
2994
3209
  return Math.max(min, Math.min(max, Number(value)));
2995
3210
  }
@@ -3200,6 +3415,10 @@ var DawTrackControlsElement = class extends LitElement12 {
3200
3415
  }
3201
3416
  };
3202
3417
  DawTrackControlsElement.styles = css8`
3418
+ /* The hidden attribute hides the element: :host sets display (modern-web-guidance custom-elements). */
3419
+ :host([hidden]) {
3420
+ display: none;
3421
+ }
3203
3422
  :host {
3204
3423
  display: flex;
3205
3424
  flex-direction: column;
@@ -3661,6 +3880,8 @@ var ViewportController = class {
3661
3880
  this._scrollContainer = null;
3662
3881
  this._lastScrollLeft = 0;
3663
3882
  this._resizeObserver = null;
3883
+ /** The scroll listener on `_scrollContainer`, aborted when it is replaced or the host disconnects. */
3884
+ this._scrollListener = null;
3664
3885
  // Permissive defaults: render everything until scroll container is attached
3665
3886
  this.visibleStart = -Infinity;
3666
3887
  this.visibleEnd = Infinity;
@@ -3692,16 +3913,21 @@ var ViewportController = class {
3692
3913
  });
3693
3914
  }
3694
3915
  hostDisconnected() {
3695
- this._scrollContainer?.removeEventListener("scroll", this._onScroll);
3916
+ this._scrollListener?.abort();
3917
+ this._scrollListener = null;
3696
3918
  this._resizeObserver?.disconnect();
3697
3919
  this._resizeObserver = null;
3698
3920
  this._scrollContainer = null;
3699
3921
  }
3700
3922
  _attachScrollContainer(container) {
3701
- this._scrollContainer?.removeEventListener("scroll", this._onScroll);
3923
+ this._scrollListener?.abort();
3702
3924
  this._resizeObserver?.disconnect();
3703
3925
  this._scrollContainer = container;
3704
- container.addEventListener("scroll", this._onScroll, { passive: true });
3926
+ this._scrollListener = new AbortController();
3927
+ container.addEventListener("scroll", this._onScroll, {
3928
+ passive: true,
3929
+ signal: this._scrollListener.signal
3930
+ });
3705
3931
  this._update(container.scrollLeft, container.clientWidth);
3706
3932
  if (typeof ResizeObserver !== "undefined") {
3707
3933
  this._resizeObserver = new ResizeObserver(() => {
@@ -3728,9 +3954,11 @@ var ViewportController = class {
3728
3954
  var AudioResumeController = class {
3729
3955
  constructor(host) {
3730
3956
  this._target = null;
3957
+ /** The gesture listeners on `_target`: one controller per attach. */
3958
+ this._listeners = null;
3731
3959
  this._attached = false;
3732
3960
  this._generation = 0;
3733
- this._onGesture = (e) => {
3961
+ this._onGesture = () => {
3734
3962
  let ctx;
3735
3963
  try {
3736
3964
  ctx = this._host.audioContext;
@@ -3754,11 +3982,7 @@ var AudioResumeController = class {
3754
3982
  );
3755
3983
  });
3756
3984
  }
3757
- const otherType = e.type === "pointerdown" ? "keydown" : "pointerdown";
3758
- this._target?.removeEventListener(otherType, this._onGesture, {
3759
- capture: true
3760
- });
3761
- this._target = null;
3985
+ this._removeListeners();
3762
3986
  };
3763
3987
  this._host = host;
3764
3988
  host.addController(this);
@@ -3780,13 +4004,17 @@ var AudioResumeController = class {
3780
4004
  if (!resolvedTarget) return;
3781
4005
  this._target = resolvedTarget;
3782
4006
  this._attached = true;
4007
+ this._listeners = new AbortController();
4008
+ const { signal } = this._listeners;
3783
4009
  resolvedTarget.addEventListener("pointerdown", this._onGesture, {
3784
4010
  once: true,
3785
- capture: true
4011
+ capture: true,
4012
+ signal
3786
4013
  });
3787
4014
  resolvedTarget.addEventListener("keydown", this._onGesture, {
3788
4015
  once: true,
3789
- capture: true
4016
+ capture: true,
4017
+ signal
3790
4018
  });
3791
4019
  });
3792
4020
  }
@@ -3810,12 +4038,8 @@ var AudioResumeController = class {
3810
4038
  }
3811
4039
  _removeListeners() {
3812
4040
  if (!this._target) return;
3813
- this._target.removeEventListener("pointerdown", this._onGesture, {
3814
- capture: true
3815
- });
3816
- this._target.removeEventListener("keydown", this._onGesture, {
3817
- capture: true
3818
- });
4041
+ this._listeners?.abort();
4042
+ this._listeners = null;
3819
4043
  this._target = null;
3820
4044
  }
3821
4045
  };
@@ -3839,6 +4063,8 @@ import {
3839
4063
  var RecordingController = class {
3840
4064
  constructor(host) {
3841
4065
  this._sessions = /* @__PURE__ */ new Map();
4066
+ /** Each session's mic-unplug listener, aborted when the session ends. */
4067
+ this._trackEndedListeners = /* @__PURE__ */ new WeakMap();
3842
4068
  /** Track IDs with a startRecording in flight (session not yet in _sessions).
3843
4069
  * The session is only set after several awaits — without this, two rapid
3844
4070
  * start calls both pass the _sessions guard and build two capture
@@ -3967,8 +4193,6 @@ var RecordingController = class {
3967
4193
  latencySamples,
3968
4194
  clipName: options.clipName,
3969
4195
  wasOverdub: options.overdub ?? false,
3970
- _onTrackEnded: onTrackEnded,
3971
- _audioTrack: audioTrack,
3972
4196
  stopAckResolve: null,
3973
4197
  stopPromise: null,
3974
4198
  stopping: false
@@ -3980,7 +4204,9 @@ var RecordingController = class {
3980
4204
  source.connect(workletNode);
3981
4205
  workletNode.port.postMessage({ command: "start", channelCount });
3982
4206
  if (audioTrack && onTrackEnded) {
3983
- audioTrack.addEventListener("ended", onTrackEnded);
4207
+ const listener = new AbortController();
4208
+ this._trackEndedListeners.set(session, listener);
4209
+ audioTrack.addEventListener("ended", onTrackEnded, { signal: listener.signal });
3984
4210
  }
3985
4211
  this._host._engine?.setTrackRecording(trackId, true);
3986
4212
  this._host.dispatchEvent(
@@ -4242,9 +4468,8 @@ var RecordingController = class {
4242
4468
  }
4243
4469
  }
4244
4470
  _removeTrackEndedListener(session) {
4245
- if (session._audioTrack && session._onTrackEnded) {
4246
- session._audioTrack.removeEventListener("ended", session._onTrackEnded);
4247
- }
4471
+ this._trackEndedListeners.get(session)?.abort();
4472
+ this._trackEndedListeners.delete(session);
4248
4473
  }
4249
4474
  _dispatchRecordingError(trackId, error) {
4250
4475
  this._host.dispatchEvent(
@@ -4316,6 +4541,8 @@ var AnnotationController = class {
4316
4541
  * Driven by daw-timeupdate, cleared on daw-stop, retained on pause.
4317
4542
  * Replaced immutably (a fresh Map) on every change. */
4318
4543
  this._playingIds = /* @__PURE__ */ new Map();
4544
+ /** The host listeners of this connection, aborted in hostDisconnected. */
4545
+ this._listeners = null;
4319
4546
  this._onDataChange = () => {
4320
4547
  this.deriveSecondsCaches();
4321
4548
  this._host.requestUpdate();
@@ -4367,11 +4594,14 @@ var AnnotationController = class {
4367
4594
  );
4368
4595
  }
4369
4596
  hostConnected() {
4370
- this._host.addEventListener("daw-annotation-update", this._onDataChange);
4371
- this._host.addEventListener("daw-annotation-select", this._onDataChange);
4372
- this._host.addEventListener("daw-annotation-connected", this._onDataChange);
4373
- this._host.addEventListener("daw-timeupdate", this._onTimeUpdate);
4374
- this._host.addEventListener("daw-stop", this._onStop);
4597
+ this._listeners?.abort();
4598
+ this._listeners = new AbortController();
4599
+ const { signal } = this._listeners;
4600
+ this._host.addEventListener("daw-annotation-update", this._onDataChange, { signal });
4601
+ this._host.addEventListener("daw-annotation-select", this._onDataChange, { signal });
4602
+ this._host.addEventListener("daw-annotation-connected", this._onDataChange, { signal });
4603
+ this._host.addEventListener("daw-timeupdate", this._onTimeUpdate, { signal });
4604
+ this._host.addEventListener("daw-stop", this._onStop, { signal });
4375
4605
  this._removalObserver = new MutationObserver((mutations) => {
4376
4606
  let changed = false;
4377
4607
  for (const m of mutations) {
@@ -4401,11 +4631,8 @@ var AnnotationController = class {
4401
4631
  this._removalObserver.observe(this._host, { childList: true, subtree: true });
4402
4632
  }
4403
4633
  hostDisconnected() {
4404
- this._host.removeEventListener("daw-annotation-update", this._onDataChange);
4405
- this._host.removeEventListener("daw-annotation-select", this._onDataChange);
4406
- this._host.removeEventListener("daw-annotation-connected", this._onDataChange);
4407
- this._host.removeEventListener("daw-timeupdate", this._onTimeUpdate);
4408
- this._host.removeEventListener("daw-stop", this._onStop);
4634
+ this._listeners?.abort();
4635
+ this._listeners = null;
4409
4636
  this._removalObserver?.disconnect();
4410
4637
  this._removalObserver = null;
4411
4638
  this._tracks = [];
@@ -4635,6 +4862,8 @@ var PointerHandler = class {
4635
4862
  // still holds; zeroing only the host would desync the two).
4636
4863
  this._preDragSelectionStart = 0;
4637
4864
  this._preDragSelectionEnd = 0;
4865
+ /** The timeline's listeners of the seek / selection press in progress. */
4866
+ this._seekGesture = null;
4638
4867
  /** Cancels the armed clip drag; set while one is armed (#848). */
4639
4868
  this._cancelArmedClipDrag = null;
4640
4869
  this.onPointerDown = (e) => {
@@ -4651,11 +4880,10 @@ var PointerHandler = class {
4651
4880
  console.warn("[dawcore] setPointerCapture failed: " + String(err));
4652
4881
  }
4653
4882
  const onMove = (me) => clipHandler.onPointerMove(me);
4883
+ const gesture = new AbortController();
4654
4884
  const detach = (pointerId) => {
4655
4885
  this._cancelArmedClipDrag = null;
4656
- this._timeline?.removeEventListener("pointermove", onMove);
4657
- this._timeline?.removeEventListener("pointerup", onUp);
4658
- this._timeline?.removeEventListener("pointercancel", onCancel);
4886
+ gesture.abort();
4659
4887
  try {
4660
4888
  this._timeline?.releasePointerCapture(pointerId);
4661
4889
  } catch (err) {
@@ -4681,9 +4909,10 @@ var PointerHandler = class {
4681
4909
  );
4682
4910
  detach(downPointerId);
4683
4911
  };
4684
- this._timeline.addEventListener("pointermove", onMove);
4685
- this._timeline.addEventListener("pointerup", onUp);
4686
- this._timeline.addEventListener("pointercancel", onCancel);
4912
+ const { signal: signal2 } = gesture;
4913
+ this._timeline.addEventListener("pointermove", onMove, { signal: signal2 });
4914
+ this._timeline.addEventListener("pointerup", onUp, { signal: signal2 });
4915
+ this._timeline.addEventListener("pointercancel", onCancel, { signal: signal2 });
4687
4916
  }
4688
4917
  return;
4689
4918
  }
@@ -4706,9 +4935,12 @@ var PointerHandler = class {
4706
4935
  } catch (err) {
4707
4936
  console.warn("[dawcore] setPointerCapture failed: " + String(err));
4708
4937
  }
4709
- this._timeline.addEventListener("pointermove", this._onPointerMove);
4710
- this._timeline.addEventListener("pointerup", this._onPointerUp);
4711
- this._timeline.addEventListener("pointercancel", this._onPointerCancel);
4938
+ this._seekGesture?.abort();
4939
+ this._seekGesture = new AbortController();
4940
+ const { signal } = this._seekGesture;
4941
+ this._timeline.addEventListener("pointermove", this._onPointerMove, { signal });
4942
+ this._timeline.addEventListener("pointerup", this._onPointerUp, { signal });
4943
+ this._timeline.addEventListener("pointercancel", this._onPointerCancel, { signal });
4712
4944
  };
4713
4945
  this._onPointerMove = (e) => {
4714
4946
  if (!this._timeline) return;
@@ -4815,9 +5047,8 @@ var PointerHandler = class {
4815
5047
  "[dawcore] releasePointerCapture failed (may already be released): " + String(err)
4816
5048
  );
4817
5049
  }
4818
- this._timeline.removeEventListener("pointermove", this._onPointerMove);
4819
- this._timeline.removeEventListener("pointerup", this._onPointerUp);
4820
- this._timeline.removeEventListener("pointercancel", this._onPointerCancel);
5050
+ this._seekGesture?.abort();
5051
+ this._seekGesture = null;
4821
5052
  }
4822
5053
  _resetInteractionState() {
4823
5054
  this._isDragging = false;
@@ -4913,6 +5144,7 @@ var PointerHandler = class {
4913
5144
 
4914
5145
  // src/interactions/clip-pointer-handler.ts
4915
5146
  import { snapTickToGrid as snapTickToGrid2 } from "@waveform-playlist/core";
5147
+ import { constrainClipDrag } from "@waveform-playlist/engine";
4916
5148
  var ClipPointerHandler = class {
4917
5149
  constructor(host) {
4918
5150
  this._mode = null;
@@ -4929,6 +5161,10 @@ var ClipPointerHandler = class {
4929
5161
  this._originalOffsetSamples = 0;
4930
5162
  this._originalDurationSamples = 0;
4931
5163
  this._originalStartSample = 0;
5164
+ // Move: the dragged clip and the track's loaded clips, sorted, at drag start
5165
+ this._moveClip = null;
5166
+ this._moveSorted = [];
5167
+ this._committing = false;
4932
5168
  this._host = host;
4933
5169
  }
4934
5170
  /**
@@ -4953,6 +5189,18 @@ var ClipPointerHandler = class {
4953
5189
  }
4954
5190
  return Math.round(totalDeltaPx * h.renderSamplesPerPixel);
4955
5191
  }
5192
+ /** A sample delta from `anchorSample` in pixels: in tick space in beats mode,
5193
+ * so the drawn position does not drift from the sample round-trip. */
5194
+ _samplesToPx(anchorSample, deltaSamples) {
5195
+ const h = this._host;
5196
+ if (h.scaleMode === "beats") {
5197
+ const anchorSec = anchorSample / h.effectiveSampleRate;
5198
+ const anchorTick = h._secondsToTicks(anchorSec);
5199
+ const newTick = h._secondsToTicks(anchorSec + deltaSamples / h.effectiveSampleRate);
5200
+ return Math.round((newTick - anchorTick) / h.ticksPerPixel);
5201
+ }
5202
+ return Math.round(deltaSamples / h.renderSamplesPerPixel);
5203
+ }
4956
5204
  /** Returns true if a drag interaction is currently in progress. */
4957
5205
  get isActive() {
4958
5206
  return this._mode !== null;
@@ -4962,6 +5210,21 @@ var ClipPointerHandler = class {
4962
5210
  get isDragging() {
4963
5211
  return this._isDragging;
4964
5212
  }
5213
+ /**
5214
+ * The clip being dragged (past the threshold) with its bounds at the drag's
5215
+ * start, or null; null too while the release makes its one arrangement
5216
+ * call, so that call is not taken for an outside change (#848).
5217
+ */
5218
+ get draggedClip() {
5219
+ if (!this._isDragging || this._committing) return null;
5220
+ return {
5221
+ trackId: this._trackId,
5222
+ clipId: this._clipId,
5223
+ startSample: this._originalStartSample,
5224
+ durationSamples: this._originalDurationSamples,
5225
+ offsetSamples: this._originalOffsetSamples
5226
+ };
5227
+ }
4965
5228
  /**
4966
5229
  * Attempts to handle a pointerdown event on the given target element.
4967
5230
  * Returns true if the target is a recognized clip interaction element.
@@ -4999,11 +5262,10 @@ var ClipPointerHandler = class {
4999
5262
  }
5000
5263
  /**
5001
5264
  * The press has become a drag (the pointer passed the threshold): take the
5002
- * clip's bounds and open the transaction now, not at the press. An undo
5003
- * made during the press (it is not a drag, so undo works) then has no
5004
- * transaction to abort, and the drag that follows starts from the clip as
5005
- * the undo left it, one undo step (#848, review of #915). Returns false
5006
- * when the clip is gone (the undo removed it): the press is dropped.
5265
+ * clip's bounds now, not at the press, so a drag after an undo made during
5266
+ * the press starts from the clip as the undo left it (#848, review of
5267
+ * #915). Returns false when the clip is gone (the undo removed it): the
5268
+ * press is dropped.
5007
5269
  */
5008
5270
  _startDrag() {
5009
5271
  const engine = this._host.engine;
@@ -5015,13 +5277,17 @@ var ClipPointerHandler = class {
5015
5277
  this._originalStartSample = bounds.startSample;
5016
5278
  this._originalOffsetSamples = bounds.offsetSamples;
5017
5279
  this._originalDurationSamples = bounds.durationSamples;
5018
- engine.beginTransaction();
5280
+ if (this._mode === "move") {
5281
+ const track = engine.getState().tracks.find((t) => t.id === trackId);
5282
+ const clip = track?.clips.find((c) => c.id === clipId) ?? null;
5283
+ if (!track || !clip) return false;
5284
+ this._moveClip = clip;
5285
+ this._moveSorted = [...track.clips].sort((a, b) => a.startSample - b.startSample);
5286
+ }
5019
5287
  } else {
5020
- console.warn(
5021
- "[dawcore] drag start: engine unavailable, drag mutations will not be grouped for undo"
5022
- );
5288
+ console.warn("[dawcore] drag start: engine unavailable, the drag will not be applied");
5023
5289
  }
5024
- if (this._mode === "trim-left" || this._mode === "trim-right") {
5290
+ {
5025
5291
  const container = this._host.shadowRoot?.querySelector(
5026
5292
  `.clip-container[data-clip-id="${clipId}"]`
5027
5293
  );
@@ -5030,7 +5296,7 @@ var ClipPointerHandler = class {
5030
5296
  this._originalLeft = parseFloat(container.style.left) || 0;
5031
5297
  this._originalWidth = parseFloat(container.style.width) || 0;
5032
5298
  } else {
5033
- console.warn("[dawcore] clip container not found for trim visual feedback: " + clipId);
5299
+ console.warn("[dawcore] clip container not found for drag visual feedback: " + clipId);
5034
5300
  }
5035
5301
  }
5036
5302
  return true;
@@ -5054,10 +5320,13 @@ var ClipPointerHandler = class {
5054
5320
  if (!engine) return;
5055
5321
  if (this._mode === "move") {
5056
5322
  const totalSnappedDelta = this._snapDeltaToSamples(totalDeltaPx, this._originalStartSample);
5057
- const incrementalDeltaSamples = totalSnappedDelta - this._cumulativeDeltaSamples;
5058
- if (incrementalDeltaSamples !== 0) {
5059
- const applied = engine.moveClip(this._trackId, this._clipId, incrementalDeltaSamples, true);
5060
- this._cumulativeDeltaSamples += applied;
5323
+ const clip = this._moveClip;
5324
+ const index = clip ? this._moveSorted.indexOf(clip) : -1;
5325
+ const delta = clip && index !== -1 ? constrainClipDrag(clip, totalSnappedDelta, this._moveSorted, index) : totalSnappedDelta;
5326
+ this._cumulativeDeltaSamples = delta;
5327
+ if (this._clipContainer) {
5328
+ const deltaPx = this._samplesToPx(this._originalStartSample, delta);
5329
+ this._clipContainer.style.left = this._originalLeft + deltaPx + "px";
5061
5330
  }
5062
5331
  } else {
5063
5332
  const boundary = this._mode === "trim-left" ? "left" : "right";
@@ -5069,17 +5338,7 @@ var ClipPointerHandler = class {
5069
5338
  boundary,
5070
5339
  rawDeltaSamples
5071
5340
  );
5072
- let deltaPx;
5073
- if (this._host.scaleMode === "beats") {
5074
- const h = this._host;
5075
- const anchorSec = anchor / h.effectiveSampleRate;
5076
- const anchorTick = h._secondsToTicks(anchorSec);
5077
- const newSec = anchorSec + deltaSamples / h.effectiveSampleRate;
5078
- const newTick = h._secondsToTicks(newSec);
5079
- deltaPx = Math.round((newTick - anchorTick) / h.ticksPerPixel);
5080
- } else {
5081
- deltaPx = Math.round(deltaSamples / this._host.renderSamplesPerPixel);
5082
- }
5341
+ const deltaPx = this._samplesToPx(anchor, deltaSamples);
5083
5342
  this._cumulativeDeltaSamples = deltaSamples;
5084
5343
  if (this._clipContainer) {
5085
5344
  if (this._mode === "trim-left") {
@@ -5118,31 +5377,39 @@ var ClipPointerHandler = class {
5118
5377
  if (this._mode === null) return;
5119
5378
  try {
5120
5379
  if (!this._isDragging || this._cumulativeDeltaSamples === 0) {
5121
- this._restoreTrimVisual();
5380
+ this._restoreVisual();
5122
5381
  return;
5123
5382
  }
5124
5383
  const engine = this._host.engine;
5384
+ this._committing = true;
5125
5385
  if (this._mode === "move") {
5386
+ this._restoreVisual();
5126
5387
  if (engine) {
5127
- engine.updateTrack(this._trackId);
5128
- this._host.dispatchEvent(
5129
- new CustomEvent("daw-clip-move", {
5130
- bubbles: true,
5131
- composed: true,
5132
- detail: {
5133
- trackId: this._trackId,
5134
- clipId: this._clipId,
5135
- deltaSamples: this._cumulativeDeltaSamples
5136
- }
5137
- })
5388
+ const applied = engine.moveClip(
5389
+ this._trackId,
5390
+ this._clipId,
5391
+ this._cumulativeDeltaSamples
5138
5392
  );
5393
+ if (applied !== 0) {
5394
+ this._host.dispatchEvent(
5395
+ new CustomEvent("daw-clip-move", {
5396
+ bubbles: true,
5397
+ composed: true,
5398
+ detail: {
5399
+ trackId: this._trackId,
5400
+ clipId: this._clipId,
5401
+ deltaSamples: applied
5402
+ }
5403
+ })
5404
+ );
5405
+ }
5139
5406
  } else {
5140
5407
  console.warn(
5141
- "[dawcore] engine unavailable at move drop \u2014 audio may be out of sync for track " + this._trackId
5408
+ "[dawcore] engine unavailable at move drop \u2014 move not applied for clip " + this._clipId
5142
5409
  );
5143
5410
  }
5144
5411
  } else {
5145
- this._restoreTrimVisual();
5412
+ this._restoreVisual();
5146
5413
  const boundary = this._mode === "trim-left" ? "left" : "right";
5147
5414
  if (engine) {
5148
5415
  engine.trimClip(this._trackId, this._clipId, boundary, this._cumulativeDeltaSamples);
@@ -5165,13 +5432,7 @@ var ClipPointerHandler = class {
5165
5432
  }
5166
5433
  }
5167
5434
  } finally {
5168
- if (this._isDragging) {
5169
- if (this._cumulativeDeltaSamples !== 0) {
5170
- this._host.engine?.commitTransaction();
5171
- } else {
5172
- this._host.engine?.abortTransaction();
5173
- }
5174
- }
5435
+ this._committing = false;
5175
5436
  this._reset();
5176
5437
  }
5177
5438
  }
@@ -5179,16 +5440,13 @@ var ClipPointerHandler = class {
5179
5440
  *
5180
5441
  * pointercancel fires INSTEAD of pointerup on touch interruption, pen
5181
5442
  * leaving hover range, or OS gestures. Without this handler the drag stays
5182
- * armed (hover keeps moving the clip), the engine transaction stays open
5183
- * (every later edit becomes un-undoable until some drag commits), and the
5184
- * per-frame skipAdapter moveClip mutations are never synced or rolled back
5185
- * (waveform and audio permanently disagree). */
5443
+ * armed (hover keeps moving the clip). The drag wrote nothing to the
5444
+ * arrangement, so reverting is putting the view back. */
5186
5445
  onPointerCancel(_e) {
5187
5446
  if (this._mode === null) return;
5188
5447
  try {
5189
- this._restoreTrimVisual();
5448
+ this._restoreVisual();
5190
5449
  } finally {
5191
- if (this._isDragging) this._host.engine?.abortTransaction();
5192
5450
  this._reset();
5193
5451
  }
5194
5452
  }
@@ -5210,11 +5468,11 @@ var ClipPointerHandler = class {
5210
5468
  return true;
5211
5469
  }
5212
5470
  /** Restore clip container CSS AND waveform peaks to original values after
5213
- * a trim visual preview. Peaks matter: the drag wrote re-extracted peak
5471
+ * a drag's visual preview. Peaks matter: a trim wrote re-extracted peak
5214
5472
  * arrays imperatively onto the <daw-waveform> elements (bypassing Lit), and
5215
- * a cancelled/zero-delta trim makes no engine mutation — so no statechange
5473
+ * a cancelled/zero-delta drag makes no engine mutation — so no statechange
5216
5474
  * re-render will ever repair them. */
5217
- _restoreTrimVisual() {
5475
+ _restoreVisual() {
5218
5476
  if (this._clipContainer) {
5219
5477
  this._clipContainer.style.left = this._originalLeft + "px";
5220
5478
  this._clipContainer.style.width = this._originalWidth + "px";
@@ -5242,6 +5500,8 @@ var ClipPointerHandler = class {
5242
5500
  this._originalOffsetSamples = 0;
5243
5501
  this._originalDurationSamples = 0;
5244
5502
  this._originalStartSample = 0;
5503
+ this._moveClip = null;
5504
+ this._moveSorted = [];
5245
5505
  }
5246
5506
  };
5247
5507
 
@@ -5275,9 +5535,12 @@ var AnnotationDragHandler = class {
5275
5535
  if (index === -1) return;
5276
5536
  const edge = isBoundary ? boundary.getAttribute("data-edge") : null;
5277
5537
  const captureEl = isBoundary ? boundary : box;
5538
+ this._drag?.listeners.abort();
5539
+ const listeners = new AbortController();
5278
5540
  this._drag = {
5279
5541
  track,
5280
5542
  captureEl,
5543
+ listeners,
5281
5544
  pointerId: e.pointerId,
5282
5545
  startClientX: e.clientX,
5283
5546
  moved: false,
@@ -5292,9 +5555,10 @@ var AnnotationDragHandler = class {
5292
5555
  captureEl.setPointerCapture(e.pointerId);
5293
5556
  } catch {
5294
5557
  }
5295
- captureEl.addEventListener("pointermove", this._onPointerMove);
5296
- captureEl.addEventListener("pointerup", this._onPointerUp);
5297
- captureEl.addEventListener("pointercancel", this._onPointerCancel);
5558
+ const { signal } = listeners;
5559
+ captureEl.addEventListener("pointermove", this._onPointerMove, { signal });
5560
+ captureEl.addEventListener("pointerup", this._onPointerUp, { signal });
5561
+ captureEl.addEventListener("pointercancel", this._onPointerCancel, { signal });
5298
5562
  };
5299
5563
  /** Non-private (underscore convention) so tests can drive moves directly. */
5300
5564
  this._onPointerMove = (e) => {
@@ -5399,9 +5663,7 @@ var AnnotationDragHandler = class {
5399
5663
  drag.captureEl.releasePointerCapture(drag.pointerId);
5400
5664
  } catch {
5401
5665
  }
5402
- drag.captureEl.removeEventListener("pointermove", this._onPointerMove);
5403
- drag.captureEl.removeEventListener("pointerup", this._onPointerUp);
5404
- drag.captureEl.removeEventListener("pointercancel", this._onPointerCancel);
5666
+ drag.listeners.abort();
5405
5667
  this._drag = null;
5406
5668
  }
5407
5669
  };
@@ -5418,6 +5680,8 @@ var TrackReorderHandler = class _TrackReorderHandler {
5418
5680
  this._fromIndex = 0;
5419
5681
  this._targetIndex = 0;
5420
5682
  this._gripEl = null;
5683
+ /** The grip's listeners of the drag in progress: one controller per drag. */
5684
+ this._gesture = null;
5421
5685
  this.onGrab = (trackId, e, gripEl) => {
5422
5686
  if (this._trackId !== null) return;
5423
5687
  const column = this._host.shadowRoot?.querySelector(".controls-column");
@@ -5467,9 +5731,11 @@ var TrackReorderHandler = class _TrackReorderHandler {
5467
5731
  gripEl.setPointerCapture(e.pointerId);
5468
5732
  } catch {
5469
5733
  }
5470
- gripEl.addEventListener("pointermove", this._onPointerMove);
5471
- gripEl.addEventListener("pointerup", this._onPointerUp);
5472
- gripEl.addEventListener("pointercancel", this._onPointerCancel);
5734
+ this._gesture = new AbortController();
5735
+ const { signal } = this._gesture;
5736
+ gripEl.addEventListener("pointermove", this._onPointerMove, { signal });
5737
+ gripEl.addEventListener("pointerup", this._onPointerUp, { signal });
5738
+ gripEl.addEventListener("pointercancel", this._onPointerCancel, { signal });
5473
5739
  };
5474
5740
  this._onPointerMove = (e) => {
5475
5741
  if (e.pointerId !== this._pointerId || this._trackId === null) return;
@@ -5539,6 +5805,11 @@ var TrackReorderHandler = class _TrackReorderHandler {
5539
5805
  static _reducedMotion() {
5540
5806
  return typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
5541
5807
  }
5808
+ /** The dragged track and the order of the rows at the grab (#848), or null. */
5809
+ get draggedTrack() {
5810
+ if (this._trackId === null) return null;
5811
+ return { trackId: this._trackId, order: this._rows.map((r) => r.trackId) };
5812
+ }
5542
5813
  /** True from the grab until the drag ends or is cancelled. */
5543
5814
  get isActive() {
5544
5815
  return this._trackId !== null;
@@ -5568,9 +5839,8 @@ var TrackReorderHandler = class _TrackReorderHandler {
5568
5839
  this._lanes = [];
5569
5840
  const grip = this._gripEl;
5570
5841
  if (grip) {
5571
- grip.removeEventListener("pointermove", this._onPointerMove);
5572
- grip.removeEventListener("pointerup", this._onPointerUp);
5573
- grip.removeEventListener("pointercancel", this._onPointerCancel);
5842
+ this._gesture?.abort();
5843
+ this._gesture = null;
5574
5844
  try {
5575
5845
  grip.releasePointerCapture(this._pointerId);
5576
5846
  } catch {
@@ -5634,13 +5904,66 @@ function parseDisplayTime(value, format) {
5634
5904
  return Math.max(0, seconds);
5635
5905
  }
5636
5906
 
5907
+ // src/interactions/abort.ts
5908
+ function abortError(message) {
5909
+ return new DOMException(message, "AbortError");
5910
+ }
5911
+ function isAbortError(error) {
5912
+ return error?.name === "AbortError";
5913
+ }
5914
+ function reasonOf(signal) {
5915
+ return signal.reason;
5916
+ }
5917
+ var PlaySignals = class {
5918
+ constructor() {
5919
+ this._controllers = /* @__PURE__ */ new WeakMap();
5920
+ }
5921
+ /** The signal of an arrangement: aborted when it is next swapped out. */
5922
+ signalOf(arrangement) {
5923
+ let controller = this._controllers.get(arrangement);
5924
+ if (!controller) {
5925
+ controller = new AbortController();
5926
+ this._controllers.set(arrangement, controller);
5927
+ }
5928
+ return controller.signal;
5929
+ }
5930
+ /** The arrangement leaves play: its waits end with `reason`; a later play gets a new signal. */
5931
+ swappedOut(arrangement, reason) {
5932
+ const controller = this._controllers.get(arrangement);
5933
+ this._controllers.delete(arrangement);
5934
+ controller?.abort(reason);
5935
+ }
5936
+ };
5937
+ function untilAborted(promise, signal) {
5938
+ if (!signal) return promise;
5939
+ if (signal.aborted) return Promise.reject(reasonOf(signal));
5940
+ return new Promise((resolve, reject) => {
5941
+ const done = new AbortController();
5942
+ signal.addEventListener("abort", () => reject(reasonOf(signal)), { signal: done.signal });
5943
+ promise.then(
5944
+ (value) => {
5945
+ done.abort();
5946
+ resolve(value);
5947
+ },
5948
+ (error) => {
5949
+ done.abort();
5950
+ reject(error);
5951
+ }
5952
+ );
5953
+ });
5954
+ }
5955
+
5637
5956
  // src/interactions/file-loader.ts
5638
- async function loadFiles(host, files) {
5957
+ async function loadFiles(host, files, options = {}) {
5958
+ const signal = options.signal;
5959
+ if (signal?.aborted) throw reasonOf(signal);
5639
5960
  if (!files) {
5640
5961
  console.warn("[dawcore] loadFiles called with null/undefined");
5641
5962
  return { loaded: [], failed: [] };
5642
5963
  }
5643
5964
  const fileArray = Array.from(files);
5965
+ const target = host.arrangement;
5966
+ const played = host._operationSignal();
5644
5967
  const loaded = [];
5645
5968
  const failed = [];
5646
5969
  const dispatchLoadError = (file, error) => {
@@ -5660,6 +5983,10 @@ async function loadFiles(host, files) {
5660
5983
  dispatchLoadError(file, new Error("<daw-editor> was disconnected"));
5661
5984
  continue;
5662
5985
  }
5986
+ if (played.aborted) {
5987
+ dispatchLoadError(file, reasonOf(played));
5988
+ continue;
5989
+ }
5663
5990
  if (file.type && !file.type.startsWith("audio/")) {
5664
5991
  const error = new Error("Non-audio MIME type: " + file.type);
5665
5992
  console.warn("[dawcore] Skipping non-audio file: " + file.name + " (" + file.type + ")");
@@ -5668,12 +5995,26 @@ async function loadFiles(host, files) {
5668
5995
  }
5669
5996
  let trackId = null;
5670
5997
  try {
5671
- trackId = await host._addDroppedFile(file);
5672
- await host._whenTrackLoaded(trackId);
5998
+ const adding = host._addDroppedFile(file);
5999
+ trackId = await untilAborted(adding, signal).catch((err) => {
6000
+ if (signal?.aborted)
6001
+ void adding.then(
6002
+ (id) => host._discardTrack(id, target),
6003
+ () => {
6004
+ }
6005
+ );
6006
+ throw err;
6007
+ });
6008
+ await untilAborted(host._whenTrackLoaded(trackId), signal);
5673
6009
  loaded.push(trackId);
5674
6010
  } catch (err) {
6011
+ if (signal?.aborted) {
6012
+ for (const id of [...loaded, ...trackId !== null ? [trackId] : []])
6013
+ host._discardTrack(id, target);
6014
+ throw reasonOf(signal);
6015
+ }
5675
6016
  console.warn("[dawcore] Failed to load file: " + file.name + " \u2014 " + String(err));
5676
- if (trackId !== null) host._discardTrack(trackId);
6017
+ if (trackId !== null) host._discardTrack(trackId, target);
5677
6018
  dispatchLoadError(file, err);
5678
6019
  }
5679
6020
  }
@@ -5689,6 +6030,9 @@ async function loadMidiImpl(host, source, options = {}) {
5689
6030
  "loadMidi: startTime must be a non-negative finite number (got " + String(options.startTime) + ")"
5690
6031
  );
5691
6032
  }
6033
+ const signal = host._operationSignal(options.signal);
6034
+ const target = host.arrangement;
6035
+ if (signal.aborted) throw reasonOf(signal);
5692
6036
  let midiModule;
5693
6037
  try {
5694
6038
  midiModule = await import("@dawcore/midi");
@@ -5699,7 +6043,7 @@ async function loadMidiImpl(host, source, options = {}) {
5699
6043
  const { parseMidiUrl, parseMidiFile } = midiModule;
5700
6044
  let parsed;
5701
6045
  if (typeof source === "string") {
5702
- parsed = await parseMidiUrl(source, void 0, options.signal);
6046
+ parsed = await parseMidiUrl(source, void 0, signal);
5703
6047
  } else {
5704
6048
  let buffer;
5705
6049
  try {
@@ -5711,21 +6055,24 @@ async function loadMidiImpl(host, source, options = {}) {
5711
6055
  }
5712
6056
  parsed = parseMidiFile(buffer);
5713
6057
  }
5714
- const childrenBefore = new Set(host.querySelectorAll("daw-track"));
6058
+ if (signal.aborted) throw reasonOf(signal);
5715
6059
  const settlements = await Promise.allSettled(
5716
6060
  parsed.tracks.map(
5717
- (t) => host.addTrack({
5718
- name: t.name,
5719
- kind: "midi",
5720
- clips: [
5721
- {
5722
- midiNotes: t.notes,
5723
- midiChannel: t.channel,
5724
- midiProgram: t.programNumber,
5725
- start: startTime
5726
- }
5727
- ]
5728
- })
6061
+ (t) => host.addTrack(
6062
+ {
6063
+ name: t.name,
6064
+ kind: "midi",
6065
+ clips: [
6066
+ {
6067
+ midiNotes: t.notes,
6068
+ midiChannel: t.channel,
6069
+ midiProgram: t.programNumber,
6070
+ start: startTime
6071
+ }
6072
+ ]
6073
+ },
6074
+ { signal }
6075
+ )
5729
6076
  )
5730
6077
  );
5731
6078
  const succeeded = [];
@@ -5738,17 +6085,14 @@ async function loadMidiImpl(host, source, options = {}) {
5738
6085
  }
5739
6086
  }
5740
6087
  if (rejections.length > 0) {
5741
- const appendedTracks = Array.from(host.querySelectorAll("daw-track")).filter(
5742
- (el) => !childrenBefore.has(el)
5743
- );
5744
- for (const el of appendedTracks) {
6088
+ for (const trackId of succeeded) {
5745
6089
  try {
5746
- el.remove();
6090
+ host._discardTrack(trackId, target);
5747
6091
  } catch (cleanupErr) {
5748
6092
  console.warn("[dawcore] loadMidi cleanup failed for a track: " + String(cleanupErr));
5749
6093
  }
5750
6094
  }
5751
- await Promise.resolve();
6095
+ if (signal.aborted) throw reasonOf(signal);
5752
6096
  for (let i = 1; i < rejections.length; i++) {
5753
6097
  console.warn(
5754
6098
  "[dawcore] loadMidi: additional track failure (" + i + "): " + stringifyReason(rejections[i])
@@ -5828,33 +6172,6 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
5828
6172
  clip
5829
6173
  ]
5830
6174
  }));
5831
- const desc = host._tracks.get(trackId);
5832
- if (desc) {
5833
- const sr = host.effectiveSampleRate;
5834
- const clipDesc = {
5835
- kind: "drop",
5836
- // The take has no <daw-clip> element — the engine id is the only
5837
- // handle updateClip()/removeClip() can address it by (#659).
5838
- clipId: clip.id,
5839
- src: "",
5840
- peaksSrc: "",
5841
- start: startSample / sr,
5842
- duration: durSamples / sr,
5843
- offset: 0,
5844
- gain: 1,
5845
- name: clipName ?? "Recording",
5846
- fadeIn: 0,
5847
- fadeOut: 0,
5848
- fadeType: "linear",
5849
- midiNotes: null,
5850
- midiChannel: null,
5851
- midiProgram: null
5852
- };
5853
- host._tracks = new Map(host._tracks).set(trackId, {
5854
- ...desc,
5855
- clips: [...desc.clips, clipDesc]
5856
- });
5857
- }
5858
6175
  if (host.isConnected) {
5859
6176
  host.dispatchEvent(
5860
6177
  new CustomEvent("daw-recording-clip-add", {
@@ -5937,18 +6254,18 @@ function performSplit(host, time) {
5937
6254
  );
5938
6255
  return false;
5939
6256
  }
6257
+ const leftClip = trackAfter.clips.find((c) => c.id === originalClipId);
5940
6258
  const newClips = trackAfter.clips.filter((c) => !clipIdsBefore.has(c.id));
5941
- if (newClips.length !== 2) {
6259
+ if (!leftClip || newClips.length !== 1) {
5942
6260
  if (newClips.length > 0) {
5943
6261
  console.warn(
5944
- "[dawcore] splitAtPlayhead: expected 2 new clips after split but got " + newClips.length
6262
+ "[dawcore] splitAtPlayhead: expected the original clip and 1 new clip after split but got " + newClips.length + " new"
5945
6263
  );
5946
6264
  }
5947
6265
  return false;
5948
6266
  }
5949
- const sorted = [...newClips].sort((a, b) => a.startSample - b.startSample);
5950
- const leftClipId = sorted[0].id;
5951
- const rightClipId = sorted[1].id;
6267
+ const leftClipId = leftClip.id;
6268
+ const rightClipId = newClips[0].id;
5952
6269
  host.dispatchEvent(
5953
6270
  new CustomEvent("daw-clip-split", {
5954
6271
  bubbles: true,
@@ -6248,6 +6565,113 @@ var LoadAnnouncer = class {
6248
6565
  }
6249
6566
  };
6250
6567
 
6568
+ // src/interactions/arrangement-view.ts
6569
+ import { isLoadingClip as isLoadingClip3 } from "@waveform-playlist/core";
6570
+ var views = /* @__PURE__ */ new WeakMap();
6571
+ function sameMix(a, b) {
6572
+ return a.volume === b.volume && a.pan === b.pan && a.muted === b.muted && a.soloed === b.soloed;
6573
+ }
6574
+ function loadedTrack(track, mix, recording) {
6575
+ const cached = views.get(track);
6576
+ if (cached && cached.recording === recording && sameMix(cached.mix, mix)) return cached.view;
6577
+ const view = {
6578
+ ...track,
6579
+ clips: track.clips.filter((c) => !isLoadingClip3(c)),
6580
+ volume: mix.volume,
6581
+ pan: mix.pan,
6582
+ muted: mix.muted || recording,
6583
+ soloed: mix.soloed
6584
+ };
6585
+ views.set(track, { mix: { ...mix }, recording, view });
6586
+ return view;
6587
+ }
6588
+ function mixOf(arrangement, trackId) {
6589
+ const mix = arrangement.getMixer().get(trackId);
6590
+ if (!mix) return null;
6591
+ return arrangement.recordingTrackIds.has(trackId) ? { ...mix, muted: true } : mix;
6592
+ }
6593
+ function clipSeconds(clip, fallbackSampleRate) {
6594
+ if (isLoadingClip3(clip)) {
6595
+ return { start: clip.start ?? 0, duration: clip.duration ?? 0, offset: clip.offset ?? 0 };
6596
+ }
6597
+ const sr = clip.sampleRate ?? fallbackSampleRate;
6598
+ return {
6599
+ start: clip.startSample / sr,
6600
+ duration: clip.durationSamples / sr,
6601
+ offset: clip.offsetSamples / sr
6602
+ };
6603
+ }
6604
+
6605
+ // src/interactions/arrangement-swap.ts
6606
+ import { isArrangement } from "@waveform-playlist/engine";
6607
+ function normalizeHandedIn(value, own) {
6608
+ if (value === null || value === void 0 || value === own) return null;
6609
+ if (!isArrangement(value)) {
6610
+ throw new TypeError(
6611
+ "[dawcore] editor.arrangement must be an arrangement made by createArrangement() (@waveform-playlist/engine), or null for the editor's own."
6612
+ );
6613
+ }
6614
+ return value;
6615
+ }
6616
+ function swapArrangement(host, next) {
6617
+ if (next === host._handedIn) return;
6618
+ if (host.isRecording) {
6619
+ console.warn(
6620
+ "[dawcore] editor.arrangement was not changed: a take is recording. Set it after stopRecording() resolves."
6621
+ );
6622
+ return;
6623
+ }
6624
+ host._cancelDrags();
6625
+ if (host.isPlaying) host.stop();
6626
+ const before = host._arrangement.getTracks().map((t) => t.id);
6627
+ host._releaseEngine();
6628
+ host._playArrangement(next);
6629
+ const kept = new Set(host._arrangement.getTracks().map((t) => t.id));
6630
+ for (const id of before) if (!kept.has(id)) host._disposeTrackChain(id);
6631
+ host._buildEngineIfReady();
6632
+ }
6633
+
6634
+ // src/interactions/drag-watch.ts
6635
+ import { isLoadingClip as isLoadingClip4 } from "@waveform-playlist/core";
6636
+ function clipDragChanged(arrangement, drag) {
6637
+ const clip = arrangement.getTracks().find((t) => t.id === drag.trackId)?.clips.find((c) => c.id === drag.clipId);
6638
+ if (!clip || isLoadingClip4(clip)) return true;
6639
+ return clip.startSample !== drag.startSample || clip.durationSamples !== drag.durationSamples || clip.offsetSamples !== drag.offsetSamples;
6640
+ }
6641
+ function trackDragChanged(arrangement, drag) {
6642
+ const ids = arrangement.getTracks().map((t) => t.id);
6643
+ if (!ids.includes(drag.trackId) || ids.length !== drag.order.length) return true;
6644
+ return ids.some((id, i) => id !== drag.order[i]);
6645
+ }
6646
+
6647
+ // src/interactions/clip-rehome.ts
6648
+ function trackHoldingClip(arrangement, clipId, exceptTrackId) {
6649
+ const track = arrangement.getTracks().find((t) => t.id !== exceptTrackId && t.clips.some((c) => c.id === clipId));
6650
+ return track?.id ?? null;
6651
+ }
6652
+ function moveClipToTrack(arrangement, fromTrackId, toTrackId, clipId, toKind) {
6653
+ const tracks = arrangement.getTracks();
6654
+ const clip = tracks.find((t) => t.id === fromTrackId)?.clips.find((c) => c.id === clipId);
6655
+ const to = tracks.find((t) => t.id === toTrackId);
6656
+ if (!clip || !to) return new Error('clip "' + clipId + '" or track "' + toTrackId + '" is gone');
6657
+ const isMidi = "midiNotes" in clip && clip.midiNotes != null;
6658
+ const kindError = clipKindError(to.name ?? "", toKind, isMidi, clip.name || clipId);
6659
+ if (kindError) return kindError;
6660
+ arrangement.beginTransaction();
6661
+ try {
6662
+ arrangement.updateTrack(fromTrackId, (t) => ({
6663
+ ...t,
6664
+ clips: t.clips.filter((c) => c.id !== clipId)
6665
+ }));
6666
+ arrangement.updateTrack(toTrackId, (t) => ({ ...t, clips: [...t.clips, clip] }));
6667
+ } catch (err) {
6668
+ arrangement.abortTransaction();
6669
+ return err instanceof Error ? err : new Error(String(err));
6670
+ }
6671
+ arrangement.commitTransaction();
6672
+ return null;
6673
+ }
6674
+
6251
6675
  // src/effects/effects-chain-controller.ts
6252
6676
  var idCounter = 0;
6253
6677
  var EffectsChainController = class {
@@ -7487,8 +7911,8 @@ async function buildOfflineChain(ctx, entries) {
7487
7911
 
7488
7912
  // src/interactions/peaks-loader.ts
7489
7913
  import WaveformData2 from "waveform-data";
7490
- async function loadWaveformDataFromUrl(src) {
7491
- const response = await fetch(src);
7914
+ async function loadWaveformDataFromUrl(src, signal) {
7915
+ const response = await fetch(src, signal ? { signal } : void 0);
7492
7916
  if (!response.ok) {
7493
7917
  throw new Error("[dawcore] Failed to fetch peaks data: " + response.statusText);
7494
7918
  }
@@ -7508,7 +7932,10 @@ var LINE_HEIGHT_PX = 16;
7508
7932
  var ScrollSyncController = class {
7509
7933
  constructor(host) {
7510
7934
  this._scrollContainer = null;
7511
- this._wheelTargets = /* @__PURE__ */ new Set();
7935
+ /** The scroll listener on `_scrollContainer`, aborted when it is replaced or detached. */
7936
+ this._scrollListener = null;
7937
+ /** Each wheel target and the controller of its listener. */
7938
+ this._wheelTargets = /* @__PURE__ */ new Map();
7512
7939
  this._warnedX = false;
7513
7940
  this._warnedY = false;
7514
7941
  /** Selector (in host shadow DOM) for the scroll container. */
@@ -7553,11 +7980,14 @@ var ScrollSyncController = class {
7553
7980
  });
7554
7981
  }
7555
7982
  hostDisconnected() {
7556
- this._scrollContainer?.removeEventListener("scroll", this._onScroll);
7983
+ this._detachAll();
7984
+ }
7985
+ /** Remove the scroll and every wheel listener. */
7986
+ _detachAll() {
7987
+ this._scrollListener?.abort();
7988
+ this._scrollListener = null;
7557
7989
  this._scrollContainer = null;
7558
- for (const target of this._wheelTargets) {
7559
- target.removeEventListener("wheel", this._onWheel);
7560
- }
7990
+ for (const listener of this._wheelTargets.values()) listener.abort();
7561
7991
  this._wheelTargets.clear();
7562
7992
  }
7563
7993
  /**
@@ -7583,29 +8013,31 @@ var ScrollSyncController = class {
7583
8013
  console.warn(
7584
8014
  '[dawcore] ScrollSyncController: scroll container "' + this.scrollSelector + '" was removed from the DOM \u2014 detaching listeners until it reappears.'
7585
8015
  );
7586
- this._scrollContainer.removeEventListener("scroll", this._onScroll);
7587
- this._scrollContainer = null;
7588
- for (const t of this._wheelTargets) t.removeEventListener("wheel", this._onWheel);
7589
- this._wheelTargets.clear();
8016
+ this._detachAll();
7590
8017
  }
7591
8018
  return;
7592
8019
  }
7593
8020
  if (container !== this._scrollContainer) {
7594
- this._scrollContainer?.removeEventListener("scroll", this._onScroll);
8021
+ this._scrollListener?.abort();
7595
8022
  this._scrollContainer = container;
7596
- container.addEventListener("scroll", this._onScroll, { passive: true });
8023
+ this._scrollListener = new AbortController();
8024
+ container.addEventListener("scroll", this._onScroll, {
8025
+ passive: true,
8026
+ signal: this._scrollListener.signal
8027
+ });
7597
8028
  }
7598
8029
  const nextTargets = new Set(this._queryAll(this.wheelForwardSelector));
7599
- for (const old of this._wheelTargets) {
8030
+ for (const [old, listener] of [...this._wheelTargets]) {
7600
8031
  if (!nextTargets.has(old)) {
7601
- old.removeEventListener("wheel", this._onWheel);
8032
+ listener.abort();
7602
8033
  this._wheelTargets.delete(old);
7603
8034
  }
7604
8035
  }
7605
8036
  for (const next of nextTargets) {
7606
8037
  if (!this._wheelTargets.has(next)) {
7607
- next.addEventListener("wheel", this._onWheel, { passive: false });
7608
- this._wheelTargets.add(next);
8038
+ const listener = new AbortController();
8039
+ next.addEventListener("wheel", this._onWheel, { passive: false, signal: listener.signal });
8040
+ this._wheelTargets.set(next, listener);
7609
8041
  }
7610
8042
  }
7611
8043
  this._apply();
@@ -7710,7 +8142,38 @@ var PlaybackAnimationController = class {
7710
8142
 
7711
8143
  // src/elements/daw-editor.ts
7712
8144
  var RULER_HEIGHT = 30;
8145
+ function clipDescriptorOf(config) {
8146
+ return {
8147
+ kind: "drop",
8148
+ clipId: crypto.randomUUID(),
8149
+ src: config.src ?? "",
8150
+ peaksSrc: config.peaksSrc ?? "",
8151
+ start: config.start ?? 0,
8152
+ duration: config.duration ?? 0,
8153
+ offset: config.offset ?? 0,
8154
+ gain: config.gain ?? 1,
8155
+ name: config.name ?? "",
8156
+ fadeIn: config.fadeIn ?? 0,
8157
+ fadeOut: config.fadeOut ?? 0,
8158
+ fadeType: config.fadeType ?? "linear",
8159
+ midiNotes: config.midiNotes ?? null,
8160
+ midiChannel: config.midiChannel ?? null,
8161
+ midiProgram: config.midiProgram ?? null
8162
+ };
8163
+ }
8164
+ function extrasOf(descriptor) {
8165
+ return {
8166
+ kind: descriptor.kind,
8167
+ renderMode: descriptor.renderMode,
8168
+ spectrogramConfig: descriptor.spectrogramConfig,
8169
+ src: descriptor.src,
8170
+ peaksSrc: new Map(
8171
+ descriptor.clips.flatMap((c) => c.clipId ? [[c.clipId, c.peaksSrc]] : [])
8172
+ )
8173
+ };
8174
+ }
7713
8175
  var noAdapterError = () => "No PlayoutAdapter set on <daw-editor>. Set editor.adapter before use.\n\n // Option 1: Native Web Audio (no Tone.js)\n " + installCommand("@dawcore/transport") + "\n import { NativePlayoutAdapter } from '@dawcore/transport';\n editor.adapter = new NativePlayoutAdapter(new AudioContext());\n\n // Option 2: Tone.js (effects, MIDI synths)\n " + installCommand("@waveform-playlist/playout") + "\n import { createToneAdapter } from '@waveform-playlist/playout';\n editor.adapter = createToneAdapter();";
8176
+ var ENTERED = /* @__PURE__ */ Symbol("entered");
7714
8177
  var DawEditorElement = class extends LitElement14 {
7715
8178
  constructor() {
7716
8179
  super();
@@ -7739,13 +8202,18 @@ var DawEditorElement = class extends LitElement14 {
7739
8202
  this._ppqn = 960;
7740
8203
  this.snapTo = "off";
7741
8204
  /**
7742
- * The one owner of the tracks, the clips, the mix, the undo history and
7743
- * loading (#848). Made with the editor, kept across a disconnect; the
7744
- * engine plays it once there is an adapter.
8205
+ * The editor's own arrangement (#848): the one owner of the tracks, the
8206
+ * clips, the mix, the undo history and loading of what the `<daw-track>`
8207
+ * children declare. Made with the editor, kept across a disconnect.
7745
8208
  */
7746
- this._arrangement = createArrangement();
7747
- /** Sends the load events, read from the arrangement (#848). */
8209
+ this._ownArrangement = createArrangement();
8210
+ /** An arrangement the app handed in (`editor.arrangement`), played alone; null: the own one. */
8211
+ this._handedIn = null;
8212
+ /** Sends the load events, read from the arrangement played (#848; a new one per swap). */
7748
8213
  this._announcer = new LoadAnnouncer((event) => this.dispatchEvent(event));
8214
+ /** Stops following the arrangement played (its sources and its tracks). */
8215
+ this._unfollow = () => {
8216
+ };
7749
8217
  /**
7750
8218
  * Ids of tracks registered (a `<daw-track>` connected, a file dropped) and
7751
8219
  * not yet in the arrangement: they enter at the next flush, once there is
@@ -7759,13 +8227,17 @@ var DawEditorElement = class extends LitElement14 {
7759
8227
  * loads settles it here, without a public event (#917).
7760
8228
  */
7761
8229
  this._awaitedClips = /* @__PURE__ */ new Map();
7762
- /** `<daw-track>` elements `addTrack()` made: every other one is the page's (the history rule). */
7763
- this._editorMadeTracks = /* @__PURE__ */ new WeakSet();
7764
8230
  this._previewPeaks = /* @__PURE__ */ new Map();
7765
8231
  /** The `.dat` data of those clips, handed to the peak pipeline when the audio arrives. */
7766
8232
  this._previewWaveforms = /* @__PURE__ */ new Map();
7767
- this._tracks = /* @__PURE__ */ new Map();
7768
- this._engineTracks = /* @__PURE__ */ new Map();
8233
+ /**
8234
+ * Tracks registered and not in the arrangement yet, with their declaration
8235
+ * (#848): a `<daw-track>` is read when it enters (its clips and attributes
8236
+ * as they are then); a dropped file carries its descriptor. The one place a
8237
+ * track's state lives until it enters.
8238
+ */
8239
+ this._pending = /* @__PURE__ */ new Map();
8240
+ this._extras = /* @__PURE__ */ new Map();
7769
8241
  this._peaksData = /* @__PURE__ */ new Map();
7770
8242
  this._isPlaying = false;
7771
8243
  this._duration = 0;
@@ -7839,6 +8311,8 @@ var DawEditorElement = class extends LitElement14 {
7839
8311
  s.scrollSelector = ".scroll-area";
7840
8312
  return s;
7841
8313
  })();
8314
+ /** One gesture id per track for the rest of this task: mix sets made together are one step (#843). */
8315
+ this._taskGestures = /* @__PURE__ */ new Map();
7842
8316
  /**
7843
8317
  * Cache of the last ViewportState forwarded to the spectrogram controller.
7844
8318
  * Lit's `updated()` fires on every reactive state change (`_isPlaying`,
@@ -7871,12 +8345,14 @@ var DawEditorElement = class extends LitElement14 {
7871
8345
  console.warn("[dawcore] Invalid daw-track-connected event detail: " + String(e.detail));
7872
8346
  return;
7873
8347
  }
7874
- if (this._tracks.has(trackId)) {
8348
+ if (this._pending.has(trackId) || this._extras.has(trackId) || this._isEntered(trackId)) {
7875
8349
  this._trackElements.set(trackId, trackEl);
7876
8350
  return;
7877
8351
  }
7878
- const descriptor = this._readTrackDescriptor(trackEl);
7879
- this._tracks = new Map(this._tracks).set(trackId, descriptor);
8352
+ this._pending = new Map(this._pending).set(trackId, {
8353
+ element: trackEl,
8354
+ extraClips: []
8355
+ });
7880
8356
  this._trackElements.set(trackId, trackEl);
7881
8357
  this._queueEntry(trackId);
7882
8358
  };
@@ -7885,50 +8361,33 @@ var DawEditorElement = class extends LitElement14 {
7885
8361
  if (!trackId) return;
7886
8362
  const trackEl = e.target.closest("daw-track");
7887
8363
  if (!trackEl) return;
7888
- const oldDescriptor = this._tracks.get(trackId);
7889
- let descriptor = this._readTrackDescriptor(trackEl);
7890
- if (oldDescriptor && oldDescriptor.kind !== descriptor.kind) {
7891
- console.warn(
7892
- '[dawcore] <daw-track> "' + descriptor.name + '": kind cannot change after the track has loaded (still "' + oldDescriptor.kind + '"). Remove the track and add one of the other kind.'
7893
- );
7894
- descriptor = {
7895
- ...descriptor,
7896
- kind: oldDescriptor.kind,
7897
- renderMode: trackDescriptorRenderMode(oldDescriptor.kind, trackEl.renderMode)
7898
- };
7899
- const keptKind = oldDescriptor.kind;
7900
- queueMicrotask(() => {
7901
- trackEl.kind = keptKind;
7902
- });
7903
- }
7904
- if (oldDescriptor && oldDescriptor.src === descriptor.src && !descriptor.clips.some(isDomClip) && !oldDescriptor.clips.some(isDomClip)) {
7905
- descriptor = { ...descriptor, clips: oldDescriptor.clips };
7906
- }
7907
- this._tracks = new Map(this._tracks).set(trackId, descriptor);
8364
+ const old = this._extras.get(trackId);
8365
+ if (!old || !this._isEntered(trackId)) return;
7908
8366
  const changed = Array.isArray(e.detail.changed) ? e.detail.changed : [];
7909
- this._writeMixFields(trackId, pickMix(mixOfElement(trackEl), changed));
7910
- if (oldDescriptor && oldDescriptor.src !== descriptor.src) {
7911
- this._replaceShorthandClips(trackId, descriptor);
7912
- }
7913
- if (descriptor.renderMode === "spectrogram" && oldDescriptor?.renderMode !== "spectrogram") {
7914
- const engineTrack = this._engineTracks.get(trackId);
7915
- if (engineTrack) {
7916
- for (const clip of engineTrack.clips) {
7917
- this._maybeRegisterSpectrogramClipAudio(trackId, clip);
7918
- }
7919
- }
7920
- }
7921
- if (descriptor.renderMode !== "spectrogram" && oldDescriptor?.renderMode === "spectrogram") {
7922
- const engineTrack = this._engineTracks.get(trackId);
7923
- if (engineTrack && this._spectrogramController) {
7924
- for (const clip of engineTrack.clips) {
7925
- this._spectrogramController.unregisterClipAudio(clip.id);
7926
- }
8367
+ const next = {
8368
+ ...old,
8369
+ ...changed.includes("renderMode") && {
8370
+ renderMode: trackDescriptorRenderMode(old.kind, trackEl.renderMode)
8371
+ },
8372
+ ...changed.includes("spectrogramConfig") && {
8373
+ spectrogramConfig: trackEl.spectrogramConfig
8374
+ },
8375
+ ...changed.includes("src") && { src: trackEl.src }
8376
+ };
8377
+ this._extras = new Map(this._extras).set(trackId, next);
8378
+ if (old.src !== next.src) this._replaceShorthandClips(trackId, trackEl);
8379
+ const loaded = this._loadedTracks().find((t) => t.id === trackId)?.clips ?? [];
8380
+ if (next.renderMode === "spectrogram" && old.renderMode !== "spectrogram") {
8381
+ for (const clip of loaded) this._maybeRegisterSpectrogramClipAudio(trackId, clip);
8382
+ }
8383
+ if (next.renderMode !== "spectrogram" && old.renderMode === "spectrogram") {
8384
+ if (this._spectrogramController) {
8385
+ for (const clip of loaded) this._spectrogramController.unregisterClipAudio(clip.id);
7927
8386
  }
7928
8387
  this._disposeSpectrogramControllerIfEmpty();
7929
8388
  }
7930
- if (descriptor.spectrogramConfig !== oldDescriptor?.spectrogramConfig) {
7931
- this._spectrogramController?.setTrackConfig(trackId, descriptor.spectrogramConfig ?? null);
8389
+ if (next.spectrogramConfig !== old.spectrogramConfig) {
8390
+ this._spectrogramController?.setTrackConfig(trackId, next.spectrogramConfig ?? null);
7932
8391
  }
7933
8392
  };
7934
8393
  this._onTrackControl = (e) => {
@@ -7947,7 +8406,7 @@ var DawEditorElement = class extends LitElement14 {
7947
8406
  })
7948
8407
  );
7949
8408
  }
7950
- if (this._tracks.has(trackId)) {
8409
+ if (this._isEntered(trackId)) {
7951
8410
  const options = typeof gesture === "string" ? { gesture } : void 0;
7952
8411
  if (prop === "volume") this._writeMix(trackId, "volume", clampNumber(value, 0, 1), options);
7953
8412
  if (prop === "pan") this._writeMix(trackId, "pan", clampNumber(value, -1, 1), options);
@@ -7973,56 +8432,42 @@ var DawEditorElement = class extends LitElement14 {
7973
8432
  const trackEl = clipEl.closest("daw-track");
7974
8433
  if (!trackEl) return;
7975
8434
  const trackId = trackEl.trackId;
7976
- if (!this._isEntered(trackId)) {
8435
+ if (this._rehomeClip(trackId, clipEl)) return;
8436
+ const entered = this._arrangementOf(trackId).getTracks().some((t) => t.id === trackId);
8437
+ if (!entered && !this._pending.has(trackId) && this._trackLinkState(trackId) === "detached") {
8438
+ this._takeClip(trackId, clipEl.clipId, clipEl.peaksSrc || "");
8439
+ console.warn(
8440
+ detachedWarning(
8441
+ '<daw-track> "' + (trackEl.name || "Untitled") + '"',
8442
+ "a <daw-clip> added to it",
8443
+ this._detachedReason()
8444
+ )
8445
+ );
8446
+ this._rejectAwaitedClips(
8447
+ (id) => id === clipEl.clipId,
8448
+ 'addClip: track "' + trackId + '" is detached'
8449
+ );
8450
+ this._refreshLinkStates();
8451
+ return;
8452
+ }
8453
+ if (!entered) {
7977
8454
  if (!this._entryQueue.includes(trackId)) {
7978
8455
  this._rejectAwaitedClips(
7979
8456
  (id) => id === clipEl.clipId,
7980
8457
  'addClip: track "' + trackId + '" is not in the editor (an Undo took it out)'
7981
8458
  );
7982
- return;
7983
8459
  }
7984
- const desc = this._tracks.get(trackId);
7985
- if (desc && !desc.clips.some((c) => isDomClip(c) && c.clipId === clipEl.clipId)) {
7986
- this._tracks = new Map(this._tracks).set(trackId, {
7987
- ...desc,
7988
- clips: [...desc.clips, this._readClipDescriptor(clipEl)]
7989
- });
7990
- }
7991
- return;
7992
- }
7993
- const loadedDesc = this._tracks.get(trackId);
7994
- if (loadedDesc && loadedDesc.clips.some((c) => isDomClip(c) && c.clipId === clipEl.clipId)) {
7995
8460
  return;
7996
8461
  }
8462
+ if (this._extras.get(trackId)?.peaksSrc.has(clipEl.clipId)) return;
7997
8463
  this._loadAndAppendClip(trackId, this._readClipDescriptor(clipEl));
7998
8464
  };
7999
- this._onClipUpdate = (e) => {
8000
- const clipEl = e.target;
8001
- if (!(clipEl instanceof HTMLElement) || clipEl.tagName !== "DAW-CLIP") return;
8002
- const detail = e.detail;
8003
- if (!detail.trackId) {
8004
- console.warn(
8005
- "[dawcore] daw-clip-update fired from a <daw-clip> not nested in a <daw-track> \u2014 ignored"
8006
- );
8007
- return;
8008
- }
8009
- const desc = this._tracks.get(detail.trackId);
8010
- if (desc && !this._isEntered(detail.trackId)) {
8011
- this._tracks = new Map(this._tracks).set(detail.trackId, {
8012
- ...desc,
8013
- clips: desc.clips.map(
8014
- (c) => isDomClip(c) && c.clipId === clipEl.clipId ? this._readClipDescriptor(clipEl) : c
8015
- )
8016
- });
8017
- return;
8018
- }
8019
- this._applyClipUpdate(detail.trackId, detail.clipId, clipEl);
8020
- };
8021
- this._waitingForDragEnd = false;
8022
8465
  /** Who waits for a track to enter (addTrack, a dropped file). */
8023
8466
  this._entryWaiters = /* @__PURE__ */ new Map();
8024
- /** Ends the waits of `_whenTrackLoaded` (as loaded) when the editor is disconnected. */
8025
- this._loadWaitEnds = /* @__PURE__ */ new Set();
8467
+ /** One AbortController per arrangement while it is played (D2, interactions/abort.ts). */
8468
+ this._playSignals = new PlaySignals();
8469
+ /** One AbortController per connection: aborted in disconnectedCallback (D8). */
8470
+ this._connection = new AbortController();
8026
8471
  /** Last versions the statechange handler worked from; reset for each engine. */
8027
8472
  this._lastTracksVersion = -1;
8028
8473
  this._lastMixerVersion = -1;
@@ -8089,15 +8534,7 @@ var DawEditorElement = class extends LitElement14 {
8089
8534
  }
8090
8535
  return time * this.effectiveSampleRate / this.samplesPerPixel;
8091
8536
  };
8092
- /** Guards the statechange handler's engine→DOM sync (Task: reorder #612)
8093
- * while the observer is pushing DOM order INTO the engine — the intermediate
8094
- * statechange emissions during the transaction would otherwise bounce
8095
- * half-applied orders back into the DOM. */
8096
- this._inOrderSync = false;
8097
- this._arrangement.sources.subscribe(() => {
8098
- this._announceLoading();
8099
- this.requestUpdate();
8100
- });
8537
+ this._follow(this._ownArrangement);
8101
8538
  }
8102
8539
  get samplesPerPixel() {
8103
8540
  return this._samplesPerPixel;
@@ -8219,8 +8656,7 @@ var DawEditorElement = class extends LitElement14 {
8219
8656
  * render — even if no canvases have been registered yet.
8220
8657
  */
8221
8658
  _maybeRegisterSpectrogramClipAudio(trackId, clip) {
8222
- const descriptor = this._tracks.get(trackId);
8223
- if (descriptor?.renderMode !== "spectrogram") return;
8659
+ if (this._renderModeOf(trackId) !== "spectrogram") return;
8224
8660
  const buffer = clip.audioBuffer ?? this._clipBuffers.get(clip.id);
8225
8661
  if (!buffer) return;
8226
8662
  const channelData = [];
@@ -8292,9 +8728,100 @@ var DawEditorElement = class extends LitElement14 {
8292
8728
  }
8293
8729
  return null;
8294
8730
  }
8295
- /** Reject the `addClip()` calls waiting for clips that match `which`. */
8296
- _rejectAwaitedClips(which, message) {
8297
- for (const [clipId, awaited] of [...this._awaitedClips]) {
8731
+ /** The arrangement played now: a handed-in one, else the editor's own. */
8732
+ get _arrangement() {
8733
+ return this._handedIn ?? this._ownArrangement;
8734
+ }
8735
+ /**
8736
+ * The arrangement the editor plays (#848 PR 3): one handed in by the app,
8737
+ * or else the editor's own, whose content the `<daw-track>` children
8738
+ * declare. Setting one plays it alone, like `video.srcObject`: the
8739
+ * children are not added to it and show `:state(detached)` while it is
8740
+ * set; `null` (or the editor's own) goes back to the own arrangement with
8741
+ * what it held. A swap keeps the adapter: playback stops, a new engine is
8742
+ * built on the new arrangement. Refused (with a warning) during a take.
8743
+ * The editor never disposes or clears an arrangement it was handed.
8744
+ * Throws a `TypeError` for a value that is not an arrangement.
8745
+ */
8746
+ get arrangement() {
8747
+ return this._arrangement;
8748
+ }
8749
+ set arrangement(value) {
8750
+ swapArrangement(this, normalizeHandedIn(value, this._ownArrangement));
8751
+ }
8752
+ /**
8753
+ * Follow the arrangement played: a source that fails changes no track,
8754
+ * only `sources` tells of it (the events, the failed look); the elements'
8755
+ * link states follow its tracks (a structural change only, not every
8756
+ * mixer frame).
8757
+ */
8758
+ _follow(arrangement) {
8759
+ this._unfollow();
8760
+ const stopSources = arrangement.sources.subscribe(() => {
8761
+ this._announceLoading();
8762
+ this.requestUpdate();
8763
+ });
8764
+ let tracksVersion = arrangement.tracksVersion;
8765
+ const stopTracks = arrangement.subscribe(() => {
8766
+ this._watchDrags();
8767
+ if (arrangement.tracksVersion === tracksVersion) return;
8768
+ tracksVersion = arrangement.tracksVersion;
8769
+ this._refreshLinkStates();
8770
+ });
8771
+ this._unfollow = () => {
8772
+ stopSources();
8773
+ stopTracks();
8774
+ };
8775
+ }
8776
+ /**
8777
+ * A change to the arrangement while a drag is in progress came from
8778
+ * elsewhere (a drag writes nothing until its release): cancel the drag
8779
+ * when it changed what is dragged (#848 P2, interactions/drag-watch.ts).
8780
+ */
8781
+ _watchDrags() {
8782
+ const clip = this._clipPointer.draggedClip;
8783
+ if (clip && clipDragChanged(this._arrangement, clip)) this._pointer.cancelClipDrag();
8784
+ const track = this._trackReorderDrag.draggedTrack;
8785
+ if (track && trackDragChanged(this._arrangement, track)) this._trackReorderDrag.cancel();
8786
+ }
8787
+ // --- The swap (interactions/arrangement-swap.ts) ---
8788
+ /** @internal */
8789
+ _releaseEngine() {
8790
+ if (!this._engine) return;
8791
+ try {
8792
+ this._engine.dispose({ keepAdapter: true });
8793
+ } catch (err) {
8794
+ console.warn("[dawcore] Error releasing the engine: " + String(err));
8795
+ }
8796
+ this._engine = null;
8797
+ }
8798
+ /** @internal */
8799
+ _disposeTrackChain(trackId) {
8800
+ this._effectsManager?.disposeTrackChain(trackId);
8801
+ }
8802
+ /** @internal */
8803
+ _playArrangement(next) {
8804
+ this._playSignals.swappedOut(
8805
+ this._arrangement,
8806
+ abortError("the arrangement was swapped out (editor.arrangement) before it finished")
8807
+ );
8808
+ this._handedIn = next;
8809
+ this._announcer = new LoadAnnouncer((event) => this.dispatchEvent(event));
8810
+ this._follow(this._arrangement);
8811
+ this._currentTime = 0;
8812
+ this._stopPlayhead();
8813
+ this._recomputeDuration();
8814
+ this._refreshLinkStates();
8815
+ this._announceLoading();
8816
+ this.requestUpdate();
8817
+ }
8818
+ /** @internal */
8819
+ _buildEngineIfReady() {
8820
+ if (this._externalAdapter && this.isConnected && !this._engine) this._buildEngineReporting();
8821
+ }
8822
+ /** Reject the `addClip()` calls waiting for clips that match `which`. */
8823
+ _rejectAwaitedClips(which, message) {
8824
+ for (const [clipId, awaited] of [...this._awaitedClips]) {
8298
8825
  if (which(clipId, awaited.trackId)) awaited.reject(new Error(message));
8299
8826
  }
8300
8827
  }
@@ -8400,7 +8927,7 @@ var DawEditorElement = class extends LitElement14 {
8400
8927
  {
8401
8928
  effectiveSampleRate: this.effectiveSampleRate,
8402
8929
  duration: this._duration,
8403
- tracks: [...this._engineTracks.values()],
8930
+ tracks: this._loadedTracks(),
8404
8931
  masterVolume: this._engine?.getState().masterVolume ?? 1,
8405
8932
  getMasterEffectsState: () => this.getEffectsState(),
8406
8933
  getTrackEffectsState: (trackId) => this.getTrackEffectsState(trackId)
@@ -8525,11 +9052,26 @@ var DawEditorElement = class extends LitElement14 {
8525
9052
  * Returns false for unknown track/clip IDs (defensive).
8526
9053
  */
8527
9054
  isMidiClip(trackId, clipId) {
8528
- const track = this._engineTracks.get(trackId);
8529
- if (!track) return false;
8530
- const clip = track.clips.find((c) => c.id === clipId);
9055
+ const clip = this._loadedClip(trackId, clipId);
8531
9056
  return clip?.midiNotes != null;
8532
9057
  }
9058
+ /** The arrangement's tracks as they are played: loaded clips, the current mix (#848). */
9059
+ _loadedTracks() {
9060
+ const arrangement = this._arrangement;
9061
+ return arrangement.getTracks().map(
9062
+ (t) => loadedTrack(
9063
+ t,
9064
+ arrangement.getMixer().get(t.id) ?? mixOfTrack(t),
9065
+ arrangement.recordingTrackIds.has(t.id)
9066
+ )
9067
+ );
9068
+ }
9069
+ /** A loaded clip of a track of the arrangement, or undefined. */
9070
+ _loadedClip(trackId, clipId) {
9071
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9072
+ const clip = track?.clips.find((c) => c.id === clipId);
9073
+ return clip && !isLoadingClip5(clip) ? clip : void 0;
9074
+ }
8533
9075
  get effectiveSampleRate() {
8534
9076
  return this.sampleRate;
8535
9077
  }
@@ -8608,11 +9150,80 @@ var DawEditorElement = class extends LitElement14 {
8608
9150
  * the arrangement is not listed (its descriptor stays for a Redo).
8609
9151
  */
8610
9152
  get tracks() {
8611
- const ids = [...this._arrangement.getTracks().map((t) => t.id), ...this._entryQueue];
8612
- return ids.flatMap((trackId) => {
8613
- const descriptor = this._tracks.get(trackId);
9153
+ const listed = this._arrangement.getTracks().map((track) => this._listTrack(track));
9154
+ const queue = this._handedIn ? this._entryQueue.filter((id) => !this._trackElements.has(id)) : this._entryQueue;
9155
+ const waiting = queue.flatMap((trackId) => {
9156
+ const descriptor = this._pendingDescriptor(trackId);
8614
9157
  return descriptor ? [{ trackId, ...descriptor, ...this._mixOf(trackId) }] : [];
8615
9158
  });
9159
+ return [...listed, ...waiting];
9160
+ }
9161
+ /** A track of the arrangement as `editor.tracks` lists it: everything read from the arrangement. */
9162
+ _listTrack(track) {
9163
+ const extras = this._extras.get(track.id);
9164
+ const clipEls = new Map(
9165
+ [...this.querySelectorAll("daw-clip")].map((el) => [
9166
+ el.clipId,
9167
+ el
9168
+ ])
9169
+ );
9170
+ const sr = this.effectiveSampleRate;
9171
+ const clips = track.clips.map((clip) => {
9172
+ const el = clipEls.get(clip.id);
9173
+ const times = clipSeconds(clip, sr);
9174
+ const midi = isLoadingClip5(clip) ? null : clip;
9175
+ const base = {
9176
+ src: typeof clip.src === "string" ? clip.src : "",
9177
+ peaksSrc: extras?.peaksSrc.get(clip.id) ?? this._takenPeaksSrc(clip.id) ?? "",
9178
+ ...times,
9179
+ gain: clip.gain ?? 1,
9180
+ name: clip.name ?? "",
9181
+ fadeIn: el?.fadeIn ?? 0,
9182
+ fadeOut: el?.fadeOut ?? 0,
9183
+ fadeType: el?.fadeType ?? "linear",
9184
+ midiNotes: midi?.midiNotes ?? null,
9185
+ midiChannel: midi?.midiChannel ?? null,
9186
+ midiProgram: midi?.midiProgram ?? null
9187
+ };
9188
+ return el ? { kind: "dom", clipId: clip.id, ...base } : { kind: "drop", clipId: clip.id, ...base };
9189
+ });
9190
+ return {
9191
+ trackId: track.id,
9192
+ name: track.name ?? "",
9193
+ src: extras?.src ?? "",
9194
+ kind: trackKind(track),
9195
+ renderMode: this._renderModeOf(track.id),
9196
+ spectrogramConfig: extras?.spectrogramConfig ?? null,
9197
+ clips,
9198
+ ...this._mixOf(track.id)
9199
+ };
9200
+ }
9201
+ /** A pending track's declaration: its element's attributes and clips now, or its descriptor. */
9202
+ _pendingDescriptor(trackId) {
9203
+ const pending = this._pending.get(trackId);
9204
+ if (!pending) return null;
9205
+ if (!("element" in pending)) return pending.descriptor;
9206
+ const read = this._readTrackDescriptor(pending.element);
9207
+ return pending.extraClips.length > 0 ? { ...read, clips: [...read.clips, ...pending.extraClips] } : read;
9208
+ }
9209
+ /** The extras a track of the arrangement takes when the editor has none for it. */
9210
+ _defaultExtras(trackId) {
9211
+ const track = this._arrangementOf(trackId).getTracks().find((t) => t.id === trackId);
9212
+ if (!track) return null;
9213
+ const kind = trackKind(track);
9214
+ return {
9215
+ kind,
9216
+ renderMode: trackDescriptorRenderMode(kind, "waveform"),
9217
+ src: "",
9218
+ peaksSrc: /* @__PURE__ */ new Map()
9219
+ };
9220
+ }
9221
+ /** How a track is drawn: its extras, else from its kind (an undo-restored track has none). */
9222
+ _renderModeOf(trackId) {
9223
+ const extras = this._extras.get(trackId);
9224
+ if (extras) return extras.renderMode;
9225
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9226
+ return trackDescriptorRenderMode(track ? trackKind(track) : "audio", "waveform");
8616
9227
  }
8617
9228
  /**
8618
9229
  * A track's mix, from its one owner, the arrangement (#843), as the engine
@@ -8621,13 +9232,162 @@ var DawEditorElement = class extends LitElement14 {
8621
9232
  * waiting to enter shows what its element declares.
8622
9233
  */
8623
9234
  _mixOf(trackId) {
8624
- const played = this._engineTracks.get(trackId);
8625
- if (played) return mixOfTrack(played);
8626
- const mix = this._arrangement.getMixer().get(trackId);
9235
+ const mix = mixOf(this._arrangement, trackId);
8627
9236
  if (mix) return mix;
9237
+ const pending = this._pending.get(trackId);
9238
+ if (pending && "mix" in pending) return pending.mix;
8628
9239
  const el = this._trackElements.get(trackId);
8629
9240
  return el ? mixOfElement(el) : DEFAULT_TRACK_MIX;
8630
9241
  }
9242
+ // --- Element links (#848, interactions/element-links.ts) ---
9243
+ /** @internal */
9244
+ _trackLinkState(trackId) {
9245
+ if (this._handedIn && this._trackElements.has(trackId)) return "detached";
9246
+ if (this._isEntered(trackId)) return "live";
9247
+ return this._extras.has(trackId) && !this._pending.has(trackId) ? "detached" : "pending";
9248
+ }
9249
+ /** @internal */
9250
+ _clipLinkState(trackId, clipId) {
9251
+ const track = this._trackLinkState(trackId);
9252
+ if (track !== "live") return track;
9253
+ const held = this._arrangement.getTracks().some((t) => t.clips.some((c) => c.id === clipId));
9254
+ if (held) return "live";
9255
+ return this._extras.get(trackId)?.peaksSrc.has(clipId) ? "detached" : "pending";
9256
+ }
9257
+ /** @internal The stored mix (not a take's mute) and the name. */
9258
+ _trackValues(trackId) {
9259
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9260
+ const mix = this._arrangement.getMixer().get(trackId);
9261
+ if (!track || !mix) return null;
9262
+ return { ...mix, name: track.name ?? "" };
9263
+ }
9264
+ /** @internal */
9265
+ _clipValues(trackId, clipId) {
9266
+ const clip = this._arrangement.getTracks().find((t) => t.id === this._clipHolderId(trackId, clipId))?.clips.find((c) => c.id === clipId);
9267
+ if (!clip) return null;
9268
+ const midi = isLoadingClip5(clip) ? null : clip;
9269
+ return {
9270
+ ...clipSeconds(clip, this.effectiveSampleRate),
9271
+ gain: clip.gain ?? 1,
9272
+ name: clip.name ?? "",
9273
+ midiNotes: midi?.midiNotes ?? null,
9274
+ midiChannel: midi?.midiChannel ?? null,
9275
+ midiProgram: midi?.midiProgram ?? null
9276
+ };
9277
+ }
9278
+ /** @internal A property or attribute set on a live `<daw-track>`: one undo step per field kind. */
9279
+ _requestTrackChange(trackId, partial) {
9280
+ const { name, ...mix } = partial;
9281
+ if (Object.keys(mix).length > 0) this._writeMixFields(trackId, mix, this._taskGesture(trackId));
9282
+ if (name !== void 0) this._renameTrack(trackId, name || "Untitled");
9283
+ }
9284
+ _taskGesture(trackId) {
9285
+ let id = this._taskGestures.get(trackId);
9286
+ if (!id) {
9287
+ id = createMixerGesture2().id;
9288
+ this._taskGestures.set(trackId, id);
9289
+ if (this._taskGestures.size === 1) queueMicrotask(() => this._taskGestures.clear());
9290
+ }
9291
+ return id;
9292
+ }
9293
+ /** @internal A property or attribute set on a live `<daw-clip>`: one undo step. */
9294
+ _requestClipChange(trackId, clipId, partial) {
9295
+ const current = this._clipValues(trackId, clipId);
9296
+ if (!current) return;
9297
+ const holderId = this._clipHolderId(trackId, clipId);
9298
+ const clip = this._arrangement.getTracks().find((t) => t.id === holderId)?.clips.find((c) => c.id === clipId);
9299
+ const src = clip && typeof clip.src === "string" ? clip.src : "";
9300
+ this._applyClipUpdate(holderId, clipId, { ...current, ...partial, src });
9301
+ }
9302
+ /**
9303
+ * The clips of an entering track that another track of the arrangement
9304
+ * holds (the page moved their `<daw-clip>` here while the track waited):
9305
+ * the track takes the held clip as it is, and `from` names what leaves
9306
+ * where. A held clip of the other kind is refused and stays.
9307
+ */
9308
+ _takeOverMovedClips(trackId, track) {
9309
+ const from = /* @__PURE__ */ new Map();
9310
+ const movedIds = /* @__PURE__ */ new Set();
9311
+ const refused = [];
9312
+ const others = this._arrangement.getTracks().filter((t) => t.id !== trackId);
9313
+ const kind = trackKind(track);
9314
+ const clips = [];
9315
+ for (const clip of track.clips) {
9316
+ const holder = others.find((t) => t.clips.some((c) => c.id === clip.id));
9317
+ const held = holder?.clips.find((c) => c.id === clip.id);
9318
+ if (!holder || !held) {
9319
+ clips.push(clip);
9320
+ continue;
9321
+ }
9322
+ const isMidi = "midiNotes" in held && held.midiNotes != null;
9323
+ const error = clipKindError(track.name ?? "", kind, isMidi, held.name || held.id);
9324
+ if (error) {
9325
+ refused.push({ clipId: clip.id, error });
9326
+ continue;
9327
+ }
9328
+ clips.push(held);
9329
+ movedIds.add(clip.id);
9330
+ const ids = from.get(holder.id) ?? /* @__PURE__ */ new Set();
9331
+ from.set(holder.id, ids.add(clip.id));
9332
+ }
9333
+ return {
9334
+ track: movedIds.size || refused.length ? { ...track, clips } : track,
9335
+ from,
9336
+ movedIds,
9337
+ refused
9338
+ };
9339
+ }
9340
+ /** Run `fn` as one undo step of each arrangement it changes. */
9341
+ _inOneStep(arrangements, fn) {
9342
+ for (const a of arrangements) a.beginTransaction();
9343
+ try {
9344
+ fn();
9345
+ } finally {
9346
+ for (const a of arrangements) a.commitTransaction();
9347
+ }
9348
+ }
9349
+ /** The `peaks-src` some track took for a clip element, if any. */
9350
+ _takenPeaksSrc(clipId) {
9351
+ for (const extras of this._extras.values()) {
9352
+ const peaksSrc = extras.peaksSrc.get(clipId);
9353
+ if (peaksSrc !== void 0) return peaksSrc;
9354
+ }
9355
+ return void 0;
9356
+ }
9357
+ /**
9358
+ * The arrangement whose history holds a track: the one that holds it now,
9359
+ * or else, for a page track, the own one (an Undo took it out there; a
9360
+ * handed-in arrangement may be played meanwhile), or else the one played.
9361
+ */
9362
+ _historyOf(trackId, isPageTrack = this._trackElements.has(trackId)) {
9363
+ const holder = this._arrangementOf(trackId);
9364
+ if (holder.getTracks().some((t) => t.id === trackId)) return holder;
9365
+ return isPageTrack ? this._ownArrangement : holder;
9366
+ }
9367
+ /** The track of the arrangement played that holds a clip: `trackId` when it does, or else the one that does. */
9368
+ _clipHolderId(trackId, clipId) {
9369
+ const tracks = this._arrangement.getTracks();
9370
+ if (tracks.some((t) => t.id === trackId && t.clips.some((c) => c.id === clipId)))
9371
+ return trackId;
9372
+ return tracks.find((t) => t.clips.some((c) => c.id === clipId))?.id ?? trackId;
9373
+ }
9374
+ /** @internal */
9375
+ _trackKind(trackId) {
9376
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9377
+ return track ? trackKind(track) : null;
9378
+ }
9379
+ /** @internal */
9380
+ _trackIndex(trackId) {
9381
+ return this._arrangement.getTracks().findIndex((t) => t.id === trackId);
9382
+ }
9383
+ /** @internal */
9384
+ _detachedReason() {
9385
+ return this._handedIn ? "a handed-in arrangement is set (editor.arrangement)" : "its track or clip is not in the arrangement the editor plays";
9386
+ }
9387
+ /** Set or clear `:state(detached)` on every registered element (#848). */
9388
+ _refreshLinkStates() {
9389
+ refreshLinkStates(this, this._trackElements);
9390
+ }
8631
9391
  /**
8632
9392
  * Change one mixer field of a track: the arrangement's setter with
8633
9393
  * `options` (an undo step; changes with one `gesture` id are one step). A
@@ -8644,8 +9404,8 @@ var DawEditorElement = class extends LitElement14 {
8644
9404
  * Change the given mixer fields of a track as ONE undo step (#843): all
8645
9405
  * of them carry one fresh gesture id. A field left out is not sent.
8646
9406
  */
8647
- _writeMixFields(trackId, mix) {
8648
- const options = { gesture: createMixerGesture2().id };
9407
+ _writeMixFields(trackId, mix, gesture = createMixerGesture2().id) {
9408
+ const options = { gesture };
8649
9409
  if (mix.volume !== void 0) this._writeMix(trackId, "volume", mix.volume, options);
8650
9410
  if (mix.pan !== void 0) this._writeMix(trackId, "pan", mix.pan, options);
8651
9411
  if (mix.muted !== void 0) this._writeMix(trackId, "muted", mix.muted, options);
@@ -8676,23 +9436,38 @@ var DawEditorElement = class extends LitElement14 {
8676
9436
  // --- Lifecycle ---
8677
9437
  connectedCallback() {
8678
9438
  super.connectedCallback();
8679
- window.addEventListener("keydown", this._onDragEscape, { capture: true });
8680
- this.addEventListener("daw-track-connected", this._onTrackConnected);
8681
- this.addEventListener("daw-track-update", this._onTrackUpdate);
8682
- this.addEventListener("daw-track-control", this._onTrackControl);
8683
- this.addEventListener("daw-track-remove", this._onTrackRemoveRequest);
8684
- this.addEventListener("daw-clip-connected", this._onClipConnected);
8685
- this.addEventListener("daw-clip-update", this._onClipUpdate);
9439
+ if (this._connection.signal.aborted) this._connection = new AbortController();
9440
+ this._follow(this._arrangement);
9441
+ this._refreshLinkStates();
9442
+ const { signal } = this._connection;
9443
+ window.addEventListener("keydown", this._onDragEscape, { capture: true, signal });
9444
+ this.addEventListener("daw-track-connected", this._onTrackConnected, {
9445
+ signal
9446
+ });
9447
+ this.addEventListener("daw-track-update", this._onTrackUpdate, { signal });
9448
+ this.addEventListener("daw-track-control", this._onTrackControl, { signal });
9449
+ this.addEventListener("daw-track-remove", this._onTrackRemoveRequest, {
9450
+ signal
9451
+ });
9452
+ this.addEventListener("daw-clip-connected", this._onClipConnected, {
9453
+ signal
9454
+ });
8686
9455
  this.addEventListener(
8687
9456
  "daw-annotation-track-connected",
8688
- this._onAnnotationTrackConnected
9457
+ this._onAnnotationTrackConnected,
9458
+ { signal }
8689
9459
  );
8690
- this.addEventListener("daw-annotation-select", this._onAnnotationSelect);
8691
- this.addEventListener("daw-track-reorder", this._onTrackReorder);
8692
- this.addEventListener("daw-track-reorder-grab", this._onTrackReorderGrab);
9460
+ this.addEventListener("daw-annotation-select", this._onAnnotationSelect, {
9461
+ signal
9462
+ });
9463
+ this.addEventListener("daw-track-reorder", this._onTrackReorder, { signal });
9464
+ this.addEventListener("daw-track-reorder-grab", this._onTrackReorderGrab, {
9465
+ signal
9466
+ });
8693
9467
  this._childObserver = new MutationObserver((mutations) => {
8694
9468
  const removedTracks = /* @__PURE__ */ new Map();
8695
9469
  const removedClips = /* @__PURE__ */ new Set();
9470
+ const clipsOfRemoved = /* @__PURE__ */ new Map();
8696
9471
  const addedTrackIds = /* @__PURE__ */ new Set();
8697
9472
  for (const mutation of mutations) {
8698
9473
  for (const node of mutation.addedNodes) {
@@ -8717,53 +9492,68 @@ var DawEditorElement = class extends LitElement14 {
8717
9492
  node.querySelectorAll?.("daw-clip").forEach((c) => {
8718
9493
  removedClips.add(c);
8719
9494
  });
9495
+ for (const t of node.tagName === "DAW-TRACK" ? [node] : [...node.querySelectorAll?.("daw-track") ?? []]) {
9496
+ clipsOfRemoved.set(t.trackId, [
9497
+ ...t.querySelectorAll("daw-clip")
9498
+ ]);
9499
+ }
8720
9500
  }
8721
9501
  }
8722
- let orderMayHaveChanged = addedTrackIds.size > 0;
9502
+ const movedTrackIds = /* @__PURE__ */ new Set();
8723
9503
  for (const [trackId] of removedTracks) {
8724
9504
  if (addedTrackIds.has(trackId)) {
8725
- orderMayHaveChanged = true;
9505
+ movedTrackIds.add(trackId);
8726
9506
  continue;
8727
9507
  }
8728
- this._onTrackRemoved(trackId);
9508
+ const children = (clipsOfRemoved.get(trackId) ?? []).filter((c) => !c.isConnected);
9509
+ this._inOneStep([this._historyOf(trackId)], () => {
9510
+ this._onTrackRemoved(trackId);
9511
+ for (const clip of children) {
9512
+ removedClips.delete(clip);
9513
+ this._onClipRemovedFromDom(clip);
9514
+ }
9515
+ });
8729
9516
  }
8730
9517
  for (const clip of removedClips) {
8731
- if (clip.isConnected) continue;
9518
+ if (clip.isConnected && this.contains(clip)) continue;
8732
9519
  this._onClipRemovedFromDom(clip);
8733
9520
  }
8734
- if (orderMayHaveChanged) this._syncEngineOrderToDom();
9521
+ if (movedTrackIds.size > 0) this._placeMovedTracks(movedTrackIds);
8735
9522
  });
8736
9523
  this._childObserver.observe(this, { childList: true, subtree: true });
8737
9524
  for (const [trackId, el] of [...this._trackElements]) {
8738
9525
  if (!this.contains(el)) this._onTrackRemoved(trackId);
8739
9526
  }
9527
+ const present = new Set(
9528
+ [...this.querySelectorAll("daw-clip")].map((c) => c.clipId)
9529
+ );
9530
+ for (const [trackId] of this._trackElements) {
9531
+ for (const clipId of this._extras.get(trackId)?.peaksSrc.keys() ?? []) {
9532
+ if (present.has(clipId)) continue;
9533
+ const holder = this._historyOf(trackId).getTracks().find((t) => t.clips.some((c) => c.id === clipId));
9534
+ if (holder) {
9535
+ this._removeClipFromTrack(holder.id, clipId);
9536
+ this._forgetClip(trackId, clipId);
9537
+ } else this._dropUnheldClip(trackId, clipId);
9538
+ }
9539
+ }
8740
9540
  if (this._externalAdapter && !this._engine) this._buildEngineReporting();
8741
9541
  }
8742
9542
  disconnectedCallback() {
8743
9543
  super.disconnectedCallback();
8744
- window.removeEventListener("keydown", this._onDragEscape, { capture: true });
9544
+ this._unfollow();
9545
+ this._unfollow = () => {
9546
+ };
9547
+ this._connection.abort(abortError("<daw-editor> was disconnected"));
8745
9548
  this._effectsManager?.disposeAll();
8746
9549
  this._effectsManager = null;
8747
- this.removeEventListener("daw-track-connected", this._onTrackConnected);
8748
- this.removeEventListener("daw-track-update", this._onTrackUpdate);
8749
- this.removeEventListener("daw-track-control", this._onTrackControl);
8750
- this.removeEventListener("daw-track-remove", this._onTrackRemoveRequest);
8751
- this.removeEventListener("daw-clip-connected", this._onClipConnected);
8752
- this.removeEventListener("daw-clip-update", this._onClipUpdate);
8753
- this.removeEventListener(
8754
- "daw-annotation-track-connected",
8755
- this._onAnnotationTrackConnected
8756
- );
8757
- this.removeEventListener("daw-annotation-select", this._onAnnotationSelect);
8758
- this.removeEventListener("daw-track-reorder", this._onTrackReorder);
8759
- this.removeEventListener("daw-track-reorder-grab", this._onTrackReorderGrab);
8760
9550
  this._cancelDrags(true);
8761
- for (const end of [...this._loadWaitEnds]) end();
8762
9551
  for (const trackId of this._entryQueue) {
8763
- if (this._trackElements.has(trackId) || !this._entryWaiters.has(trackId)) continue;
8764
- const nextTracks = new Map(this._tracks);
8765
- nextTracks.delete(trackId);
8766
- this._tracks = nextTracks;
9552
+ const pending = this._pending.get(trackId);
9553
+ if (!pending || "element" in pending || !this._entryWaiters.has(trackId)) continue;
9554
+ const nextPending = new Map(this._pending);
9555
+ nextPending.delete(trackId);
9556
+ this._pending = nextPending;
8767
9557
  this._entryQueue = this._entryQueue.filter((id) => id !== trackId);
8768
9558
  this._settleEntry(
8769
9559
  trackId,
@@ -8838,14 +9628,19 @@ var DawEditorElement = class extends LitElement14 {
8838
9628
  }
8839
9629
  }
8840
9630
  _onTrackRemoved(trackId) {
8841
- const existed = this._tracks.has(trackId);
9631
+ const existed = this._pending.has(trackId) || this._extras.has(trackId) || this._isEntered(trackId);
9632
+ const isPageTrack = this._trackElements.has(trackId);
9633
+ const history = this._historyOf(trackId, isPageTrack);
9634
+ const detached = this._extras.has(trackId) && !this._pending.has(trackId) && !history.getTracks().some((t) => t.id === trackId);
9635
+ const detachedClipIds = detached ? [...this._extras.get(trackId)?.peaksSrc.keys() ?? []] : [];
8842
9636
  this._rejectAwaitedClips(
8843
9637
  (_, awaitedTrackId) => awaitedTrackId === trackId,
8844
9638
  "the track of the clip was removed before the clip loaded"
8845
9639
  );
8846
9640
  this._entryQueue = this._entryQueue.filter((id) => id !== trackId);
8847
9641
  this._settleEntry(trackId, new Error('track "' + trackId + '" was removed before it entered'));
8848
- const arrangementTrack = this._arrangement.getTracks().find((t) => t.id === trackId);
9642
+ const holder = this._arrangementOf(trackId);
9643
+ const arrangementTrack = holder.getTracks().find((t) => t.id === trackId);
8849
9644
  const clipIds = arrangementTrack?.clips.map((c) => c.id) ?? [];
8850
9645
  this._announcer.forget(trackId, clipIds);
8851
9646
  if (clipIds.some((id) => this._previewPeaks.has(id))) {
@@ -8856,10 +9651,9 @@ var DawEditorElement = class extends LitElement14 {
8856
9651
  for (const id of clipIds) this._previewWaveforms.delete(id);
8857
9652
  this._trackElements.delete(trackId);
8858
9653
  this._effectsManager?.disposeTrackChain(trackId);
8859
- const removedTrack = this._engineTracks.get(trackId);
8860
- if (removedTrack) {
9654
+ if (arrangementTrack) {
8861
9655
  const nextPeaks = new Map(this._peaksData);
8862
- for (const clip of removedTrack.clips) {
9656
+ for (const clip of arrangementTrack.clips) {
8863
9657
  this._clipBuffers.delete(clip.id);
8864
9658
  this._clipOffsets.delete(clip.id);
8865
9659
  nextPeaks.delete(clip.id);
@@ -8867,17 +9661,24 @@ var DawEditorElement = class extends LitElement14 {
8867
9661
  }
8868
9662
  this._peaksData = nextPeaks;
8869
9663
  }
8870
- const nextTracks = new Map(this._tracks);
8871
- nextTracks.delete(trackId);
8872
- this._tracks = nextTracks;
8873
- const nextEngine = new Map(this._engineTracks);
8874
- nextEngine.delete(trackId);
8875
- this._engineTracks = nextEngine;
9664
+ const nextPending = new Map(this._pending);
9665
+ nextPending.delete(trackId);
9666
+ this._pending = nextPending;
9667
+ const nextExtras = new Map(this._extras);
9668
+ nextExtras.delete(trackId);
9669
+ this._extras = nextExtras;
9670
+ if (arrangementTrack) holder.removeTrack(trackId);
9671
+ else if (detached) {
9672
+ history.removeTrack(trackId, { undoable: false });
9673
+ for (const id of detachedClipIds) {
9674
+ this._purgeClipCaches(id);
9675
+ this._previewWaveforms.delete(id);
9676
+ }
9677
+ }
8876
9678
  this._recomputeDuration();
8877
- this._arrangement.removeTrack(trackId);
8878
9679
  this._recomputeZoomFloor();
8879
9680
  this._disposeSpectrogramControllerIfEmpty();
8880
- if (existed && nextEngine.size === 0) {
9681
+ if (existed && this._arrangement.getTracks().length === 0) {
8881
9682
  if (this._engine) {
8882
9683
  if (this._isPlaying) {
8883
9684
  this._withSeekSuppression(() => this._engine.stop());
@@ -8898,10 +9699,21 @@ var DawEditorElement = class extends LitElement14 {
8898
9699
  );
8899
9700
  }
8900
9701
  }
9702
+ /** The arrangement that holds a track: the one played, else the own one (a page track while handed in). */
9703
+ _arrangementOf(trackId) {
9704
+ const has = (a) => a.getTracks().some((t) => t.id === trackId);
9705
+ return has(this._arrangement) || !has(this._ownArrangement) ? this._arrangement : this._ownArrangement;
9706
+ }
9707
+ /** Rename a track in the arrangement (an undo step); the same name changes nothing. */
9708
+ _renameTrack(trackId, name) {
9709
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9710
+ if (!track || track.name === name) return;
9711
+ this._arrangement.updateTrack(trackId, (current) => ({ ...current, name }));
9712
+ }
8901
9713
  /** Drop the controller when no spectrogram tracks remain. */
8902
9714
  _disposeSpectrogramControllerIfEmpty() {
8903
9715
  if (!this._spectrogramController) return;
8904
- const stillNeeded = Array.from(this._tracks.values()).some(
9716
+ const stillNeeded = Array.from(this._extras.values()).some(
8905
9717
  (d) => d.renderMode === "spectrogram"
8906
9718
  );
8907
9719
  if (!stillNeeded) {
@@ -8910,96 +9722,92 @@ var DawEditorElement = class extends LitElement14 {
8910
9722
  this._lastSpectrogramViewport = null;
8911
9723
  }
8912
9724
  }
8913
- /** Reconcile `_tracks` descriptors with the engine's track list.
8914
- *
8915
- * ADD: engine.undo() restores removed tracks in ENGINE state only —
8916
- * without a synthesized descriptor the track plays and renders but shows
8917
- * "Untitled" controls and is missing from `editor.tracks`.
8918
- * PRUNE (the symmetric half): redo removes the track from engine state
8919
- * again — without pruning, the synthesized descriptor is a permanent
8920
- * ghost that even removeTrack() can't clean (no element, no engine
8921
- * entry). Never prunes tracks that are mid-load or element-backed —
8922
- * their descriptors legitimately precede their engine entries. */
8923
- _reconcileDescriptorsWithEngineTracks(tracks) {
8924
- const engineIds = new Set(tracks.map((t) => t.id));
8925
- let next = null;
8926
- for (const track of tracks) {
8927
- if (this._tracks.has(track.id)) continue;
8928
- next ?? (next = new Map(this._tracks));
8929
- next.set(track.id, {
8930
- name: track.name ?? "",
8931
- src: "",
8932
- kind: trackKind(track),
8933
- renderMode: trackDescriptorRenderMode(trackKind(track), "waveform"),
8934
- clips: []
8935
- });
9725
+ /**
9726
+ * A `<daw-clip>` now under `trackId` whose clip another track holds: the
9727
+ * clip moves to this track (one undo step) when both have entered the same
9728
+ * arrangement; a clip of the other kind stays with `daw-clip-error`.
9729
+ * Otherwise the old track lets it go and the element goes on as a new
9730
+ * arrival. Returns true when nothing more is to be done.
9731
+ */
9732
+ _rehomeClip(trackId, clipEl) {
9733
+ const clipId = clipEl.clipId;
9734
+ if (this._extras.get(trackId)?.peaksSrc.has(clipId)) return true;
9735
+ const arrangement = this._historyOf(trackId);
9736
+ if (arrangement.getTracks().some((t) => t.id === trackId && t.clips.some((c) => c.id === clipId))) {
9737
+ let peaksSrc2 = clipEl.peaksSrc || "";
9738
+ for (const [id, extras] of this._extras) {
9739
+ if (id === trackId || !extras.peaksSrc.has(clipId)) continue;
9740
+ peaksSrc2 = extras.peaksSrc.get(clipId) ?? peaksSrc2;
9741
+ this._forgetClip(id, clipId);
9742
+ }
9743
+ this._takeClip(trackId, clipId, peaksSrc2);
9744
+ return true;
8936
9745
  }
8937
- for (const trackId of this._tracks.keys()) {
8938
- if (engineIds.has(trackId) || this._entryQueue.includes(trackId) || this._trackElements.has(trackId)) {
8939
- continue;
9746
+ const fromTrackId = trackHoldingClip(arrangement, clipId, trackId);
9747
+ if (!fromTrackId) {
9748
+ for (const [id, extras] of this._extras) {
9749
+ if (id !== trackId && extras.peaksSrc.has(clipId)) this._forgetClip(id, clipId);
8940
9750
  }
8941
- next ?? (next = new Map(this._tracks));
8942
- next.delete(trackId);
9751
+ return false;
8943
9752
  }
8944
- for (const track of tracks) {
8945
- const desc = (next ?? this._tracks).get(track.id);
8946
- if (!desc || !desc.clips.some((c) => !isDomClip(c) && c.clipId !== void 0)) continue;
8947
- const reconciled = this._reconcileIdentifiedDropClips(desc.clips, track);
8948
- if (reconciled === desc.clips) continue;
8949
- next ?? (next = new Map(this._tracks));
8950
- next.set(track.id, { ...desc, clips: reconciled });
8951
- }
8952
- if (next) {
8953
- this._tracks = next;
8954
- }
8955
- }
8956
- /** Prune id-bearing drop descriptors the engine no longer has, and refresh
8957
- * the rest from their engine clip. Returns the SAME array when nothing
8958
- * changed, so an unchanged track never triggers a re-render. */
8959
- _reconcileIdentifiedDropClips(clips, track) {
8960
- const engineClips = new Map(track.clips.map((c) => [c.id, c]));
8961
- let changed = false;
8962
- const result = [];
8963
- for (const desc of clips) {
8964
- if (isDomClip(desc) || desc.clipId === void 0) {
8965
- result.push(desc);
8966
- continue;
8967
- }
8968
- const clip = engineClips.get(desc.clipId);
8969
- if (!clip) {
8970
- changed = true;
8971
- continue;
8972
- }
8973
- const sr = clip.sampleRate ?? this.effectiveSampleRate;
8974
- const start = clip.startSample / sr;
8975
- const duration = clip.durationSamples / sr;
8976
- const offset = clip.offsetSamples / sr;
8977
- const gain = clip.gain ?? desc.gain;
8978
- const name = clip.name ?? desc.name;
8979
- if (desc.start === start && desc.duration === duration && desc.offset === offset && desc.gain === gain && desc.name === name) {
8980
- result.push(desc);
8981
- continue;
8982
- }
8983
- changed = true;
8984
- result.push({ ...desc, start, duration, offset, gain, name });
9753
+ const entered = arrangement.getTracks().some((t) => t.id === trackId);
9754
+ if (!entered && this._pending.has(trackId)) return true;
9755
+ const toExtras = this._extras.get(trackId) ?? this._defaultExtras(trackId);
9756
+ if (!entered || !toExtras) {
9757
+ this._takeClip(trackId, clipId, this._takenPeaksSrc(clipId) ?? clipEl.peaksSrc ?? "");
9758
+ console.warn(
9759
+ '[dawcore] <daw-clip> cannot move into <daw-track> "' + (this._trackElements.get(trackId)?.name || "Untitled") + '": the track is not in the arrangement (an Undo took it out). Its clip stays in its track.'
9760
+ );
9761
+ this.dispatchEvent(
9762
+ new CustomEvent("daw-clip-error", {
9763
+ bubbles: true,
9764
+ composed: true,
9765
+ detail: {
9766
+ trackId,
9767
+ clipId,
9768
+ error: new Error('track "' + trackId + '" is not in the arrangement')
9769
+ }
9770
+ })
9771
+ );
9772
+ this._refreshLinkStates();
9773
+ return true;
9774
+ }
9775
+ const error = moveClipToTrack(arrangement, fromTrackId, trackId, clipId, toExtras.kind);
9776
+ if (error) {
9777
+ this._takeClip(trackId, clipId, this._extras.get(fromTrackId)?.peaksSrc.get(clipId) ?? "");
9778
+ console.warn(
9779
+ '[dawcore] <daw-clip> cannot move to track "' + (this._trackElements.get(trackId)?.name || "Untitled") + '" (' + String(error) + "): its clip stays in its track."
9780
+ );
9781
+ this.dispatchEvent(
9782
+ new CustomEvent("daw-clip-error", {
9783
+ bubbles: true,
9784
+ composed: true,
9785
+ detail: { trackId, clipId, error }
9786
+ })
9787
+ );
9788
+ return true;
9789
+ }
9790
+ const peaksSrc = this._takenPeaksSrc(clipId) ?? clipEl.peaksSrc ?? "";
9791
+ for (const [id, extras] of this._extras) {
9792
+ if (id !== trackId && extras.peaksSrc.has(clipId)) this._forgetClip(id, clipId);
8985
9793
  }
8986
- return changed ? result : clips;
9794
+ if (!this._extras.has(trackId)) this._extras = new Map(this._extras).set(trackId, toExtras);
9795
+ this._takeClip(trackId, clipId, peaksSrc);
9796
+ return true;
8987
9797
  }
8988
9798
  _onClipRemovedFromDom(clipEl) {
8989
9799
  const clipId = clipEl.clipId;
8990
- for (const t of this._arrangement.getTracks()) {
8991
- if (t.clips.some((c) => c.id === clipId)) {
8992
- this._removeClipFromTrack(t.id, clipId);
8993
- return;
9800
+ for (const arrangement of /* @__PURE__ */ new Set([this._arrangement, this._ownArrangement])) {
9801
+ for (const t of arrangement.getTracks()) {
9802
+ if (t.clips.some((c) => c.id === clipId)) {
9803
+ this._removeClipFromTrack(t.id, clipId);
9804
+ return;
9805
+ }
8994
9806
  }
8995
9807
  }
8996
- for (const [trackId, desc] of this._tracks) {
8997
- if (this._isEntered(trackId) || !desc.clips.some((c) => c.clipId === clipId)) continue;
8998
- this._tracks = new Map(this._tracks).set(trackId, {
8999
- ...desc,
9000
- clips: desc.clips.filter((c) => c.clipId !== clipId)
9001
- });
9002
- this._rejectAwaitedClips((id) => id === clipId, "the clip was removed before it loaded");
9808
+ for (const [trackId, extras] of this._extras) {
9809
+ if (!extras.peaksSrc.has(clipId)) continue;
9810
+ this._dropUnheldClip(trackId, clipId);
9003
9811
  return;
9004
9812
  }
9005
9813
  this._rejectAwaitedClips((id) => id === clipId, "the clip was removed before it loaded");
@@ -9016,12 +9824,15 @@ var DawEditorElement = class extends LitElement14 {
9016
9824
  * like any other; `daw-clip-ready` or `daw-clip-error` follows (#848).
9017
9825
  */
9018
9826
  _loadAndAppendClip(trackId, clipDesc) {
9019
- const trackDesc = this._tracks.get(trackId);
9020
- if (!trackDesc) return;
9827
+ const arrangement = this._arrangementOf(trackId);
9828
+ const track = arrangement.getTracks().find((t) => t.id === trackId);
9829
+ const extras = this._extras.get(trackId) ?? this._defaultExtras(trackId);
9830
+ if (!extras || !track) return;
9831
+ if (isDomClip(clipDesc)) this._takeClip(trackId, clipDesc.clipId, clipDesc.peaksSrc);
9021
9832
  const clipIsMidi = isMidiDescriptor(clipDesc);
9022
9833
  const kindError = clipKindError(
9023
- trackDesc.name,
9024
- trackDesc.kind,
9834
+ track.name ?? "",
9835
+ extras.kind,
9025
9836
  clipIsMidi,
9026
9837
  clipDesc.name || clipDesc.src || clipDesc.clipId
9027
9838
  );
@@ -9029,7 +9840,7 @@ var DawEditorElement = class extends LitElement14 {
9029
9840
  if (!clipIsMidi) this._announcer.expectClip(clipDesc.clipId);
9030
9841
  try {
9031
9842
  if (kindError) throw kindError;
9032
- this._arrangement.updateTrack(trackId, (current) => ({
9843
+ arrangement.updateTrack(trackId, (current) => ({
9033
9844
  ...current,
9034
9845
  clips: [...current.clips, clip]
9035
9846
  }));
@@ -9044,10 +9855,6 @@ var DawEditorElement = class extends LitElement14 {
9044
9855
  );
9045
9856
  return;
9046
9857
  }
9047
- this._tracks = new Map(this._tracks).set(trackId, {
9048
- ...trackDesc,
9049
- clips: [...trackDesc.clips, clipDesc]
9050
- });
9051
9858
  if (!clipIsMidi && clipDesc.peaksSrc) this._requestPreview(clipDesc.clipId, clipDesc.peaksSrc);
9052
9859
  }
9053
9860
  /**
@@ -9067,6 +9874,7 @@ var DawEditorElement = class extends LitElement14 {
9067
9874
  );
9068
9875
  return null;
9069
9876
  } catch (err) {
9877
+ if (isAbortError(err)) return null;
9070
9878
  console.warn(
9071
9879
  "[dawcore] Failed to load peaks from " + peaksSrc + ": " + String(err) + " \u2014 falling back to AudioBuffer generation"
9072
9880
  );
@@ -9095,20 +9903,24 @@ var DawEditorElement = class extends LitElement14 {
9095
9903
  }));
9096
9904
  }
9097
9905
  _applyClipUpdate(trackId, clipId, clipEl) {
9098
- const t = this._engineTracks.get(trackId);
9906
+ const t = this._arrangement.getTracks().find((track) => track.id === trackId);
9099
9907
  if (!t) {
9100
- console.warn('[dawcore] _applyClipUpdate: no engine track for id "' + trackId + '"');
9908
+ console.warn('[dawcore] _applyClipUpdate: no track for id "' + trackId + '"');
9101
9909
  return;
9102
9910
  }
9103
- const idx = t.clips.findIndex((c) => c.id === clipId);
9104
- if (idx === -1) {
9105
- const loading = this._arrangement.getTracks().find((track) => track.id === trackId)?.clips.some((c) => c.id === clipId);
9911
+ const loadedClip = this._loadedClip(trackId, clipId);
9912
+ if (!loadedClip) {
9913
+ const loading = t.clips.find((c) => c.id === clipId);
9914
+ if (loading && isLoadingClip5(loading)) {
9915
+ this._updateLoadingClip(trackId, loading, clipEl);
9916
+ return;
9917
+ }
9106
9918
  console.warn(
9107
- '[dawcore] _applyClipUpdate: clip "' + clipId + '" ' + (loading ? "is still loading; the change is dropped" : 'not found in track "' + trackId + '" (DOM/engine clip-id misalignment?)')
9919
+ '[dawcore] _applyClipUpdate: clip "' + clipId + '" not found in track "' + trackId + '" (DOM/engine clip-id misalignment?)'
9108
9920
  );
9109
9921
  return;
9110
9922
  }
9111
- const oldClip = t.clips[idx];
9923
+ const oldClip = loadedClip;
9112
9924
  const sr = oldClip.sampleRate ?? this.effectiveSampleRate;
9113
9925
  const isMidiNow = clipEl.midiNotes != null && !clipEl.src;
9114
9926
  const wasMidi = oldClip.midiNotes != null;
@@ -9125,6 +9937,9 @@ var DawEditorElement = class extends LitElement14 {
9125
9937
  return;
9126
9938
  }
9127
9939
  if (isMidiNow || wasMidi) {
9940
+ if (clipEl.midiNotes === oldClip.midiNotes && (clipEl.midiChannel ?? void 0) === oldClip.midiChannel && (clipEl.midiProgram ?? void 0) === oldClip.midiProgram && Math.round(clipEl.start * sr) === oldClip.startSample && Math.round(clipEl.offset * sr) === oldClip.offsetSamples && (clipEl.duration <= 0 || Math.round(clipEl.duration * sr) === oldClip.durationSamples) && clipEl.gain === (oldClip.gain ?? 1) && (clipEl.name || oldClip.name) === oldClip.name) {
9941
+ return;
9942
+ }
9128
9943
  const notes = validMidiNotes(clipEl.midiNotes ?? []);
9129
9944
  const noteSpanSeconds = notes.length ? notes.reduce((max, n) => Math.max(max, n.time + n.duration), 0) : 0;
9130
9945
  const sourceDurationSamples = Math.ceil(Math.max(noteSpanSeconds, clipEl.duration, 1) * sr);
@@ -9157,6 +9972,9 @@ var DawEditorElement = class extends LitElement14 {
9157
9972
  gain: clipEl.gain,
9158
9973
  name: clipEl.name || oldClip.name
9159
9974
  };
9975
+ if (newStartSample === oldClip.startSample && newDurationSamples === oldClip.durationSamples && newOffsetSamples === oldClip.offsetSamples && updatedClip.gain === (oldClip.gain ?? 1) && updatedClip.name === oldClip.name) {
9976
+ return;
9977
+ }
9160
9978
  const boundsChanged = oldClip.offsetSamples !== newOffsetSamples || oldClip.durationSamples !== newDurationSamples;
9161
9979
  if (boundsChanged) {
9162
9980
  this._clipOffsets.set(clipId, {
@@ -9170,9 +9988,55 @@ var DawEditorElement = class extends LitElement14 {
9170
9988
  }
9171
9989
  this._replaceClip(trackId, clipId, updatedClip);
9172
9990
  }
9991
+ /**
9992
+ * A change to a clip still loading (#848 P10): its times, gain and name in
9993
+ * seconds on the `LoadingClip`, one undo step; the audio loads into it.
9994
+ */
9995
+ _updateLoadingClip(trackId, clip, values) {
9996
+ const next = {
9997
+ ...clip,
9998
+ start: values.start,
9999
+ ...values.duration > 0 ? { duration: values.duration } : {},
10000
+ offset: values.offset,
10001
+ gain: values.gain,
10002
+ ...values.name ? { name: values.name } : {}
10003
+ };
10004
+ if ((next.start ?? 0) === (clip.start ?? 0) && next.duration === clip.duration && (next.offset ?? 0) === (clip.offset ?? 0) && (next.gain ?? 1) === (clip.gain ?? 1) && next.name === clip.name) {
10005
+ return;
10006
+ }
10007
+ this._arrangement.updateTrack(trackId, (current) => ({
10008
+ ...current,
10009
+ clips: current.clips.map((c) => c.id === clip.id ? next : c)
10010
+ }));
10011
+ }
9173
10012
  /** Remove a clip (loaded or still loading) from a track of the arrangement: an undo step. */
9174
- _removeClipFromTrack(trackId, clipId) {
9175
- const track = this._arrangement.getTracks().find((t) => t.id === trackId);
10013
+ /**
10014
+ * An aborted addClip (D3): its clip leaves for good, from the track it
10015
+ * entered or from what a waiting track will enter with.
10016
+ */
10017
+ _discardAddedClip(trackId, clipId) {
10018
+ const pending = this._pending.get(trackId);
10019
+ if (pending) {
10020
+ this._pending = new Map(this._pending).set(
10021
+ trackId,
10022
+ "element" in pending ? { ...pending, extraClips: pending.extraClips.filter((c) => c.clipId !== clipId) } : {
10023
+ ...pending,
10024
+ descriptor: {
10025
+ ...pending.descriptor,
10026
+ clips: pending.descriptor.clips.filter((c) => c.clipId !== clipId)
10027
+ }
10028
+ }
10029
+ );
10030
+ return;
10031
+ }
10032
+ const holder = this._arrangementOf(trackId).getTracks().find((t) => t.id === trackId);
10033
+ if (holder?.clips.some((c) => c.id === clipId)) {
10034
+ this._removeClipFromTrack(trackId, clipId, { undoable: false });
10035
+ }
10036
+ }
10037
+ _removeClipFromTrack(trackId, clipId, options = {}) {
10038
+ const arrangement = this._arrangementOf(trackId);
10039
+ const track = arrangement.getTracks().find((t) => t.id === trackId);
9176
10040
  if (!track) {
9177
10041
  console.warn('[dawcore] _removeClipFromTrack: no track for id "' + trackId + '"');
9178
10042
  return;
@@ -9190,20 +10054,43 @@ var DawEditorElement = class extends LitElement14 {
9190
10054
  nextPreview.delete(clipId);
9191
10055
  this._previewPeaks = nextPreview;
9192
10056
  }
9193
- const desc = this._tracks.get(trackId);
9194
- if (desc) {
9195
- this._tracks = new Map(this._tracks).set(trackId, {
9196
- ...desc,
9197
- clips: desc.clips.filter((c) => c.clipId !== clipId)
9198
- });
9199
- }
9200
- const wasLoading = track.clips.some((c) => c.id === clipId && isLoadingClip3(c));
9201
- this._arrangement.updateTrack(trackId, (current) => ({
9202
- ...current,
9203
- clips: current.clips.filter((c) => c.id !== clipId)
9204
- }));
10057
+ this._forgetClip(trackId, clipId);
10058
+ const wasLoading = track.clips.some((c) => c.id === clipId && isLoadingClip5(c));
10059
+ if (options.undoable === false) arrangement.removeClip(trackId, clipId, { undoable: false });
10060
+ else
10061
+ arrangement.updateTrack(trackId, (current) => ({
10062
+ ...current,
10063
+ clips: current.clips.filter((c) => c.id !== clipId)
10064
+ }));
9205
10065
  if (wasLoading) this._announcer.forgetClip(clipId);
9206
10066
  }
10067
+ /** Record that the editor took a clip of a track (with its `peaks-src`, '' when none). */
10068
+ _takeClip(trackId, clipId, peaksSrc) {
10069
+ const extras = this._extras.get(trackId);
10070
+ if (!extras || extras.peaksSrc.get(clipId) === peaksSrc) return;
10071
+ const next = new Map(extras.peaksSrc).set(clipId, peaksSrc);
10072
+ this._extras = new Map(this._extras).set(trackId, { ...extras, peaksSrc: next });
10073
+ }
10074
+ /**
10075
+ * A `<daw-clip>` the editor took is removed while the arrangement does not
10076
+ * hold its clip (its track or its own arrival undone, or refused): it is
10077
+ * gone for good, also from the undo and redo states, so no Redo brings it
10078
+ * back (maintainer's choice, #848).
10079
+ */
10080
+ _dropUnheldClip(trackId, clipId) {
10081
+ this._historyOf(trackId).removeClip(trackId, clipId, { undoable: false });
10082
+ this._purgeClipCaches(clipId);
10083
+ this._previewWaveforms.delete(clipId);
10084
+ this._forgetClip(trackId, clipId);
10085
+ }
10086
+ /** The editor no longer holds anything for a clip of a track. */
10087
+ _forgetClip(trackId, clipId) {
10088
+ const extras = this._extras.get(trackId);
10089
+ if (!extras?.peaksSrc.has(clipId)) return;
10090
+ const next = new Map(extras.peaksSrc);
10091
+ next.delete(clipId);
10092
+ this._extras = new Map(this._extras).set(trackId, { ...extras, peaksSrc: next });
10093
+ }
9207
10094
  _readTrackDescriptor(trackEl) {
9208
10095
  const clipEls = trackEl.querySelectorAll("daw-clip");
9209
10096
  const clips = [];
@@ -9279,12 +10166,9 @@ var DawEditorElement = class extends LitElement14 {
9279
10166
  _flushTrackEntries() {
9280
10167
  if (this._entryQueue.length === 0) return;
9281
10168
  if (!this._engine) return;
9282
- if (this._dragInProgress) {
9283
- this._flushAfterDrag();
9284
- return;
9285
- }
9286
- const queued = this._entryQueue;
9287
- this._entryQueue = [];
10169
+ const isPageTrack = (id) => this._trackElements.has(id);
10170
+ const queued = this._handedIn ? this._entryQueue.filter((id) => !isPageTrack(id)) : this._entryQueue;
10171
+ this._entryQueue = this._handedIn ? this._entryQueue.filter(isPageTrack) : [];
9288
10172
  const domOrder = [...this.querySelectorAll("daw-track")].map(
9289
10173
  (el) => el.trackId
9290
10174
  );
@@ -9293,12 +10177,8 @@ var DawEditorElement = class extends LitElement14 {
9293
10177
  return at === -1 ? domOrder.length : at;
9294
10178
  };
9295
10179
  const ordered = [...queued].sort((a, b) => position(a) - position(b));
9296
- const isPageTrack = (id) => {
9297
- const el = this._trackElements.get(id);
9298
- return el !== void 0 && !this._editorMadeTracks.has(el);
9299
- };
9300
10180
  const arrangement = this._arrangement;
9301
- const historyWasEmpty = !arrangement.canUndo && !arrangement.canRedo && !this._dragInProgress;
10181
+ const historyWasEmpty = !arrangement.canUndo && !arrangement.canRedo;
9302
10182
  let pageEntered = false;
9303
10183
  for (const id of ordered.filter(isPageTrack)) {
9304
10184
  if (this._enterTrack(id)) pageEntered = true;
@@ -9306,32 +10186,21 @@ var DawEditorElement = class extends LitElement14 {
9306
10186
  if (historyWasEmpty && pageEntered) arrangement.clearHistory();
9307
10187
  for (const id of ordered.filter((id2) => !isPageTrack(id2))) this._enterTrack(id);
9308
10188
  }
9309
- /** Flush the queue once the drag in progress has ended (its pointer or key is released). */
9310
- _flushAfterDrag() {
9311
- if (this._waitingForDragEnd) return;
9312
- this._waitingForDragEnd = true;
9313
- const events = ["pointerup", "pointercancel", "keyup"];
9314
- const retry = () => {
9315
- for (const type of events) window.removeEventListener(type, retry);
9316
- this._waitingForDragEnd = false;
9317
- setTimeout(() => this._flushTrackEntries(), 0);
9318
- };
9319
- for (const type of events) window.addEventListener(type, retry);
9320
- }
9321
10189
  /** Enter one registered track. False when it is gone, already in, or refused. */
9322
10190
  _enterTrack(trackId) {
9323
- const descriptor = this._tracks.get(trackId);
10191
+ const descriptor = this._pendingDescriptor(trackId);
9324
10192
  if (!descriptor || this._isEntered(trackId)) return false;
9325
10193
  const el = this._trackElements.get(trackId);
9326
10194
  const built = buildArrangementTrack(
9327
10195
  trackId,
9328
10196
  descriptor,
9329
- el ? mixOfElement(el) : DEFAULT_TRACK_MIX,
10197
+ this._mixOf(trackId),
9330
10198
  this.effectiveSampleRate
9331
10199
  );
9332
- if (built.descriptor !== descriptor) {
9333
- this._tracks = new Map(this._tracks).set(trackId, built.descriptor);
9334
- }
10200
+ const nextPending = new Map(this._pending);
10201
+ nextPending.delete(trackId);
10202
+ this._pending = nextPending;
10203
+ this._extras = new Map(this._extras).set(trackId, extrasOf(built.descriptor));
9335
10204
  for (const { clipId, error } of built.refused) {
9336
10205
  console.warn("[dawcore] " + error.message);
9337
10206
  this.dispatchEvent(
@@ -9347,14 +10216,45 @@ var DawEditorElement = class extends LitElement14 {
9347
10216
  trackId,
9348
10217
  this._arrangement.getTracks().map((t) => t.id)
9349
10218
  ) : void 0;
9350
- this._announcer.expect(trackId, built.refused.length);
9351
- for (const clip of built.track.clips) {
9352
- if (isLoadingClip3(clip)) this._announcer.expectClip(clip.id);
10219
+ const moved = this._takeOverMovedClips(trackId, built.track);
10220
+ const entering = moved.track;
10221
+ for (const { clipId, error } of moved.refused) {
10222
+ console.warn("[dawcore] " + error.message);
10223
+ this.dispatchEvent(
10224
+ new CustomEvent("daw-clip-error", {
10225
+ bubbles: true,
10226
+ composed: true,
10227
+ detail: { trackId, clipId, error }
10228
+ })
10229
+ );
10230
+ }
10231
+ this._announcer.expect(trackId, built.refused.length + moved.refused.length);
10232
+ for (const clip of entering.clips) {
10233
+ if (isLoadingClip5(clip)) this._announcer.expectClip(clip.id);
9353
10234
  }
9354
10235
  try {
9355
- this._arrangement.addTrack(built.track, index === void 0 ? void 0 : { index });
10236
+ if (moved.from.size === 0) {
10237
+ this._arrangement.addTrack(entering, index === void 0 ? void 0 : { index });
10238
+ } else {
10239
+ this._inOneStep([this._arrangement], () => {
10240
+ for (const [fromId, clipIds] of moved.from) {
10241
+ this._arrangement.updateTrack(fromId, (t) => ({
10242
+ ...t,
10243
+ clips: t.clips.filter((c) => !clipIds.has(c.id))
10244
+ }));
10245
+ for (const clipId of clipIds) this._forgetClip(fromId, clipId);
10246
+ }
10247
+ this._arrangement.addTrack(entering, index === void 0 ? void 0 : { index });
10248
+ });
10249
+ }
9356
10250
  } catch (err) {
9357
10251
  console.warn('[dawcore] Failed to add track "' + trackId + '": ' + String(err));
10252
+ if (!el) {
10253
+ const nextExtras = new Map(this._extras);
10254
+ nextExtras.delete(trackId);
10255
+ this._extras = nextExtras;
10256
+ }
10257
+ this._refreshLinkStates();
9358
10258
  this._settleEntry(trackId, err instanceof Error ? err : new Error(String(err)));
9359
10259
  this.dispatchEvent(
9360
10260
  new CustomEvent("daw-track-error", {
@@ -9365,8 +10265,9 @@ var DawEditorElement = class extends LitElement14 {
9365
10265
  );
9366
10266
  return false;
9367
10267
  }
9368
- this._settleEntry(trackId, null);
10268
+ this._settleEntry(trackId, ENTERED);
9369
10269
  for (const clipDesc of built.descriptor.clips) {
10270
+ if (clipDesc.clipId && moved.movedIds.has(clipDesc.clipId)) continue;
9370
10271
  if (clipDesc.peaksSrc && clipDesc.clipId && clipSourceOf(clipDesc)) {
9371
10272
  this._requestPreview(clipDesc.clipId, clipDesc.peaksSrc);
9372
10273
  }
@@ -9379,7 +10280,8 @@ var DawEditorElement = class extends LitElement14 {
9379
10280
  * `<daw-clip>` children keeps them. A track still queued reads the new
9380
10281
  * descriptor when it enters.
9381
10282
  */
9382
- _replaceShorthandClips(trackId, descriptor) {
10283
+ _replaceShorthandClips(trackId, trackEl) {
10284
+ const descriptor = this._readTrackDescriptor(trackEl);
9383
10285
  if (!this._isEntered(trackId) || descriptor.clips.some(isDomClip)) return;
9384
10286
  const built = buildArrangementTrack(
9385
10287
  trackId,
@@ -9387,7 +10289,13 @@ var DawEditorElement = class extends LitElement14 {
9387
10289
  DEFAULT_TRACK_MIX,
9388
10290
  this.effectiveSampleRate
9389
10291
  );
9390
- this._tracks = new Map(this._tracks).set(trackId, built.descriptor);
10292
+ const extras = this._extras.get(trackId);
10293
+ if (extras) {
10294
+ this._extras = new Map(this._extras).set(trackId, {
10295
+ ...extras,
10296
+ peaksSrc: extrasOf(built.descriptor).peaksSrc
10297
+ });
10298
+ }
9391
10299
  this._arrangement.updateTrack(trackId, (current) => ({ ...current, clips: built.track.clips }));
9392
10300
  }
9393
10301
  /** Run the load announcements over the arrangement's current state. */
@@ -9406,7 +10314,7 @@ var DawEditorElement = class extends LitElement14 {
9406
10314
  const waveformData = await this._resolvePeaks(peaksSrc);
9407
10315
  if (!waveformData) return;
9408
10316
  const clip = this._arrangement.getTracks().flatMap((t) => t.clips).find((c) => c.id === clipId);
9409
- if (!clip || !isLoadingClip3(clip)) return;
10317
+ if (!clip || !isLoadingClip5(clip)) return;
9410
10318
  const rate = waveformData.sample_rate;
9411
10319
  const offset = clip.offset ?? 0;
9412
10320
  const seconds = clip.duration ?? Math.max(0, waveformData.duration - offset);
@@ -9435,13 +10343,13 @@ var DawEditorElement = class extends LitElement14 {
9435
10343
  this._entryWaiters.set(trackId, { resolve, reject });
9436
10344
  });
9437
10345
  }
9438
- /** Settle the wait for a track's entry: entered (`null`), or refused or gone. */
9439
- _settleEntry(trackId, error) {
10346
+ /** Settle the wait for a track's entry: entered (`ENTERED`), or refused or gone (the reason).*/
10347
+ _settleEntry(trackId, outcome) {
9440
10348
  const waiter = this._entryWaiters.get(trackId);
9441
10349
  if (!waiter) return;
9442
10350
  this._entryWaiters.delete(trackId);
9443
- if (error) waiter.reject(error);
9444
- else waiter.resolve(trackId);
10351
+ if (outcome === ENTERED) waiter.resolve(trackId);
10352
+ else waiter.reject(outcome);
9445
10353
  }
9446
10354
  /**
9447
10355
  * A dropped file as a track with no element (a File cannot be an attribute):
@@ -9451,7 +10359,7 @@ var DawEditorElement = class extends LitElement14 {
9451
10359
  _addDroppedFile(file) {
9452
10360
  const trackId = crypto.randomUUID();
9453
10361
  const name = file.name.replace(/\.\w+$/, "");
9454
- this._tracks = new Map(this._tracks).set(trackId, {
10362
+ const descriptor = {
9455
10363
  name,
9456
10364
  src: "",
9457
10365
  kind: "audio",
@@ -9475,8 +10383,10 @@ var DawEditorElement = class extends LitElement14 {
9475
10383
  midiProgram: null
9476
10384
  }
9477
10385
  ]
9478
- });
10386
+ };
10387
+ this._pending = new Map(this._pending).set(trackId, { descriptor, mix: DEFAULT_TRACK_MIX });
9479
10388
  const entered = this._waitForEntry(trackId);
10389
+ this._endEntryOnSwap(trackId, entered);
9480
10390
  this._queueEntry(trackId);
9481
10391
  return entered;
9482
10392
  }
@@ -9484,12 +10394,29 @@ var DawEditorElement = class extends LitElement14 {
9484
10394
  * Take a track out for good: no undo step, and no undo or redo brings it
9485
10395
  * back (a dropped file that could not be loaded was never a declaration).
9486
10396
  */
9487
- _discardTrack(trackId) {
9488
- const track = this._arrangement.getTracks().find((t) => t.id === trackId);
10397
+ _discardTrack(trackId, from = this._arrangement) {
10398
+ if (from !== this._arrangement) {
10399
+ from.removeTrack(trackId, { undoable: false });
10400
+ if (this._extras.has(trackId)) {
10401
+ const nextExtras = new Map(this._extras);
10402
+ nextExtras.delete(trackId);
10403
+ this._extras = nextExtras;
10404
+ }
10405
+ return;
10406
+ }
10407
+ const track = from.getTracks().find((t) => t.id === trackId);
9489
10408
  this._announcer.forget(trackId, track?.clips.map((c) => c.id) ?? []);
9490
- this._arrangement.removeTrack(trackId, { undoable: false });
10409
+ from.removeTrack(trackId, { undoable: false });
9491
10410
  this._onTrackRemoved(trackId);
9492
10411
  }
10412
+ /** The signal of the arrangement played now: aborted when it is swapped out. */
10413
+ get _playSignal() {
10414
+ return this._playSignals.signalOf(this._arrangement);
10415
+ }
10416
+ /** @internal A caller's signal combined with the arrangement played now (loadMidi, D6). */
10417
+ _operationSignal(signal) {
10418
+ return signal ? AbortSignal.any([signal, this._playSignal]) : this._playSignal;
10419
+ }
9493
10420
  /**
9494
10421
  * Resolves once the track has loaded (`daw-track-ready`), or when the
9495
10422
  * editor is disconnected meanwhile (the track is kept and loads after a
@@ -9499,30 +10426,31 @@ var DawEditorElement = class extends LitElement14 {
9499
10426
  const state9 = this._announcer.stateOf(trackId);
9500
10427
  if (state9 === "ready") return Promise.resolve();
9501
10428
  if (state9 === "failed") return Promise.reject(this._announcer.errorOf(trackId));
10429
+ const ended = AbortSignal.any([this._playSignal, this._connection.signal]);
10430
+ if (ended.aborted) return Promise.resolve();
9502
10431
  return new Promise((resolve, reject) => {
9503
- const cleanup = () => {
9504
- this.removeEventListener("daw-track-ready", onReady);
9505
- this.removeEventListener("daw-track-error", onError);
9506
- this._loadWaitEnds.delete(end);
9507
- };
9508
- const onReady = (e) => {
9509
- if (e.detail.trackId !== trackId) return;
9510
- cleanup();
9511
- resolve();
9512
- };
9513
- const onError = (e) => {
9514
- const detail = e.detail;
9515
- if (detail.trackId !== trackId) return;
9516
- cleanup();
9517
- reject(detail.error instanceof Error ? detail.error : new Error(String(detail.error)));
9518
- };
9519
- const end = () => {
9520
- cleanup();
9521
- resolve();
9522
- };
9523
- this.addEventListener("daw-track-ready", onReady);
9524
- this.addEventListener("daw-track-error", onError);
9525
- this._loadWaitEnds.add(end);
10432
+ const done = new AbortController();
10433
+ const signal = AbortSignal.any([ended, done.signal]);
10434
+ this.addEventListener(
10435
+ "daw-track-ready",
10436
+ (e) => {
10437
+ if (e.detail.trackId !== trackId) return;
10438
+ done.abort();
10439
+ resolve();
10440
+ },
10441
+ { signal }
10442
+ );
10443
+ this.addEventListener(
10444
+ "daw-track-error",
10445
+ (e) => {
10446
+ const detail = e.detail;
10447
+ if (detail.trackId !== trackId) return;
10448
+ done.abort();
10449
+ reject(detail.error instanceof Error ? detail.error : new Error(String(detail.error)));
10450
+ },
10451
+ { signal }
10452
+ );
10453
+ ended.addEventListener("abort", () => resolve(), { signal: done.signal });
9526
10454
  });
9527
10455
  }
9528
10456
  /**
@@ -9538,14 +10466,14 @@ var DawEditorElement = class extends LitElement14 {
9538
10466
  }
9539
10467
  const sources = this._arrangement.sources.getSnapshot().sources;
9540
10468
  const failed = new Set(
9541
- track.clips.filter(isLoadingClip3).map((clip) => clip.src).filter((src) => sources.get(src)?.status === "failed")
10469
+ track.clips.filter(isLoadingClip5).map((clip) => clip.src).filter((src) => sources.get(src)?.status === "failed")
9542
10470
  );
9543
10471
  for (const src of failed) this._arrangement.retry(src);
9544
10472
  }
9545
10473
  _fetchPeaks(src) {
9546
10474
  const cached = this._peaksCache.get(src);
9547
10475
  if (cached) return cached;
9548
- const promise = loadWaveformDataFromUrl(src).catch((err) => {
10476
+ const promise = loadWaveformDataFromUrl(src, this._playSignal).catch((err) => {
9549
10477
  this._peaksCache.delete(src);
9550
10478
  throw err;
9551
10479
  });
@@ -9560,7 +10488,7 @@ var DawEditorElement = class extends LitElement14 {
9560
10488
  _recomputeDuration() {
9561
10489
  const sr = this.effectiveSampleRate;
9562
10490
  let maxSample = 0;
9563
- for (const track of this._engineTracks.values()) {
10491
+ for (const track of this._loadedTracks()) {
9564
10492
  for (const clip of track.clips) {
9565
10493
  const endSample = clip.startSample + clip.durationSamples;
9566
10494
  if (endSample > maxSample) maxSample = endSample;
@@ -9568,7 +10496,7 @@ var DawEditorElement = class extends LitElement14 {
9568
10496
  }
9569
10497
  for (const track of this._arrangement.getTracks()) {
9570
10498
  for (const clip of track.clips) {
9571
- if (!isLoadingClip3(clip)) continue;
10499
+ if (!isLoadingClip5(clip)) continue;
9572
10500
  const seconds = this._placeholderSeconds(clip);
9573
10501
  if (seconds === null) continue;
9574
10502
  maxSample = Math.max(maxSample, Math.round(((clip.start ?? 0) + seconds) * sr));
@@ -9607,6 +10535,16 @@ var DawEditorElement = class extends LitElement14 {
9607
10535
  this._buildEngine();
9608
10536
  } catch (err) {
9609
10537
  console.warn("[dawcore] Failed to build the engine: " + String(err));
10538
+ const error = err instanceof Error ? err : new Error(String(err));
10539
+ for (const trackId of [...this._entryQueue]) {
10540
+ const pending = this._pending.get(trackId);
10541
+ if (!pending || "element" in pending || !this._entryWaiters.has(trackId)) continue;
10542
+ const nextPending = new Map(this._pending);
10543
+ nextPending.delete(trackId);
10544
+ this._pending = nextPending;
10545
+ this._entryQueue = this._entryQueue.filter((id) => id !== trackId);
10546
+ this._settleEntry(trackId, error);
10547
+ }
9610
10548
  this.dispatchEvent(
9611
10549
  new CustomEvent("daw-error", {
9612
10550
  bubbles: true,
@@ -9648,8 +10586,11 @@ var DawEditorElement = class extends LitElement14 {
9648
10586
  });
9649
10587
  engine.on("stop", () => this._onEngineStop(engine));
9650
10588
  this._engine = engine;
10589
+ if (this._selectionStartTime !== 0 || this._selectionEndTime !== 0) {
10590
+ engine.setSelection(this._selectionStartTime, this._selectionEndTime);
10591
+ }
9651
10592
  this._onEngineState(engine.getState());
9652
- for (const track of this._engineTracks.values()) {
10593
+ for (const track of this._loadedTracks()) {
9653
10594
  for (const clip of track.clips) this._maybeRegisterSpectrogramClipAudio(track.id, clip);
9654
10595
  }
9655
10596
  this._flushTrackEntries();
@@ -9675,7 +10616,7 @@ var DawEditorElement = class extends LitElement14 {
9675
10616
  }
9676
10617
  }
9677
10618
  }
9678
- /** The engine's state changed: follow it (the one writer of `_engineTracks`). */
10619
+ /** The engine's state changed: draw it (the rows are read from the arrangement). */
9679
10620
  _onEngineState(engineState) {
9680
10621
  this._isPlaying = engineState.isPlaying;
9681
10622
  this._selectedTrackId = engineState.selectedTrackId;
@@ -9684,18 +10625,10 @@ var DawEditorElement = class extends LitElement14 {
9684
10625
  if (structuralChange || mixerChange) {
9685
10626
  this._lastTracksVersion = engineState.tracksVersion;
9686
10627
  this._lastMixerVersion = engineState.mixerVersion;
9687
- const nextTracks = /* @__PURE__ */ new Map();
9688
- for (const track of engineState.tracks) {
9689
- nextTracks.set(track.id, track);
9690
- }
9691
- this._engineTracks = nextTracks;
9692
- this._reconcileDescriptorsWithEngineTracks(engineState.tracks);
10628
+ this.requestUpdate();
9693
10629
  }
9694
10630
  if (structuralChange) {
9695
10631
  this._recomputeDuration();
9696
- if (!this._inOrderSync) {
9697
- this._syncDomToEngineOrder(engineState.tracks);
9698
- }
9699
10632
  this._effectsManager?.rewireTrackChains();
9700
10633
  const audioTracks = engineState.tracks.filter((t) => trackKind(t) !== "midi");
9701
10634
  this._adoptLoadedClips(audioTracks);
@@ -9721,17 +10654,18 @@ var DawEditorElement = class extends LitElement14 {
9721
10654
  this._engine = null;
9722
10655
  }
9723
10656
  }
9724
- async loadFiles(files) {
9725
- return loadFiles(this, files);
10657
+ async loadFiles(files, options = {}) {
10658
+ return loadFiles(this, files, options);
9726
10659
  }
9727
10660
  /**
9728
- * Imperatively load a `.mid` file (URL or File) and create N `<daw-track>`
9729
- * elements — one per note-bearing MIDI track. On any per-track failure,
9730
- * every `<daw-track>` appended during the call is removed (both successful
9731
- * and failed) so the editor returns to its pre-call state.
10661
+ * Imperatively load a `.mid` file (URL or File) and add N tracks (no
10662
+ * element, #848), one per note-bearing MIDI track. On any per-track
10663
+ * failure, every track the call added is removed with no undo step, so the
10664
+ * editor is as before the call.
9732
10665
  *
9733
- * `options.signal` is forwarded to `fetch()` only for URL sources; aborting
9734
- * after parsing does not cancel in-flight `addTrack` calls.
10666
+ * `options.signal` cancels the fetch, the parse and the tracks still
10667
+ * waiting to enter (combined with the arrangement played: a swap cancels
10668
+ * too); the call rejects with its `reason` and removes the tracks it added.
9735
10669
  *
9736
10670
  * Requires the optional `@dawcore/midi` peer dep — throws with an install
9737
10671
  * hint (and `console.warn`s the original error) when the dynamic import
@@ -9750,25 +10684,41 @@ var DawEditorElement = class extends LitElement14 {
9750
10684
  return this._ensureEngine();
9751
10685
  }
9752
10686
  /**
9753
- * Append a `<daw-track>` element built from `config` and resolve with its
9754
- * track id once the track has entered the arrangement (#848), before its
9755
- * audio has loaded. To follow loading, add the `daw-track-ready` /
9756
- * `daw-track-error` listener BEFORE calling: for a track with nothing to
9757
- * fetch, or whose audio is already loaded, it fires before this resolves.
9758
- * Without `editor.adapter` it waits for one. Rejects when the track is
9759
- * refused by the arrangement or removed before it enters.
10687
+ * Add a track built from `config` to the arrangement the editor plays when
10688
+ * it is called, and resolve with its id once it has entered (#848), before
10689
+ * its audio has loaded. A swap of `editor.arrangement` before it enters
10690
+ * rejects with an `AbortError` and the track enters nowhere; to add to
10691
+ * another arrangement, call that arrangement's own `addTrack`. No element is created: the track is drawn and listed like any
10692
+ * other, and `<daw-track>` children stay the page's declaration. To follow
10693
+ * loading, add the `daw-track-ready` / `daw-track-error` listener BEFORE
10694
+ * calling: for a track with nothing to fetch it fires before this
10695
+ * resolves. Without `editor.adapter` it waits for one. Rejects when the
10696
+ * arrangement refuses the track, when it is removed before it enters, or
10697
+ * when the engine cannot be built.
10698
+ *
10699
+ * `options.signal` (#848): aborting it before the track has entered takes
10700
+ * it out of the queue (it never enters) and rejects with its `reason`;
10701
+ * after that it changes nothing (the audio goes on loading). A signal
10702
+ * already aborted rejects at once and queues nothing.
9760
10703
  */
9761
- addTrack(config = {}) {
9762
- const trackEl = document.createElement("daw-track");
9763
- this._editorMadeTracks.add(trackEl);
9764
- if (config.name !== void 0) trackEl.setAttribute("name", config.name);
9765
- if (config.volume !== void 0) trackEl.volume = config.volume;
9766
- if (config.pan !== void 0) trackEl.pan = config.pan;
9767
- if (config.muted) trackEl.setAttribute("muted", "");
9768
- if (config.soloed) trackEl.setAttribute("soloed", "");
9769
- const kind = config.kind ?? (config.midi ? "midi" : void 0);
9770
- if (kind !== void 0) trackEl.setAttribute("kind", kind);
9771
- if (config.renderMode !== void 0) trackEl.setAttribute("render-mode", config.renderMode);
10704
+ addTrack(config = {}, options = {}) {
10705
+ const signal = options.signal;
10706
+ if (signal?.aborted) return Promise.reject(reasonOf(signal));
10707
+ const trackId = crypto.randomUUID();
10708
+ let kind = config.kind ?? (config.midi ? "midi" : "audio");
10709
+ if (kind !== "audio" && kind !== "midi") {
10710
+ console.warn(
10711
+ '[dawcore] addTrack: kind "' + String(kind) + `" is not a track kind ('audio' or 'midi'); using "audio"`
10712
+ );
10713
+ kind = "audio";
10714
+ }
10715
+ let renderMode = normalizeRenderMode(config.renderMode);
10716
+ if (renderMode === "both") {
10717
+ console.warn(
10718
+ `[dawcore] render-mode="both" is not yet supported; falling back to 'spectrogram'`
10719
+ );
10720
+ renderMode = "spectrogram";
10721
+ }
9772
10722
  const clipConfigs = [...config.clips ?? []];
9773
10723
  if (config.midi) {
9774
10724
  clipConfigs.push({
@@ -9777,115 +10727,194 @@ var DawEditorElement = class extends LitElement14 {
9777
10727
  midiProgram: config.midi.program
9778
10728
  });
9779
10729
  }
9780
- for (const clipConfig of clipConfigs) {
9781
- trackEl.appendChild(this._buildClipElement(clipConfig));
9782
- }
9783
- const entered = this._waitForEntry(trackEl.trackId);
9784
- this.appendChild(trackEl);
9785
- return entered;
10730
+ const descriptor = {
10731
+ name: config.name || "Untitled",
10732
+ src: "",
10733
+ kind,
10734
+ renderMode: trackDescriptorRenderMode(kind, renderMode),
10735
+ spectrogramConfig: config.spectrogramConfig ?? null,
10736
+ clips: clipConfigs.map((c) => clipDescriptorOf(c))
10737
+ };
10738
+ const mix = {
10739
+ volume: config.volume ?? DEFAULT_TRACK_MIX.volume,
10740
+ pan: config.pan ?? DEFAULT_TRACK_MIX.pan,
10741
+ muted: config.muted ?? false,
10742
+ soloed: config.soloed ?? false
10743
+ };
10744
+ this._pending = new Map(this._pending).set(trackId, { descriptor, mix });
10745
+ const entered = this._waitForEntry(trackId);
10746
+ this._endEntryOnSwap(trackId, entered);
10747
+ this._queueEntry(trackId);
10748
+ if (!signal) return entered;
10749
+ const settled = new AbortController();
10750
+ signal.addEventListener("abort", () => this._abortEntry(trackId, reasonOf(signal)), {
10751
+ signal: settled.signal
10752
+ });
10753
+ return entered.finally(() => settled.abort());
10754
+ }
10755
+ /**
10756
+ * A queued track goes into the arrangement played when it was queued: when
10757
+ * that one is swapped out first, the track leaves the queue and its wait
10758
+ * rejects with the swap's AbortError (addTrack, a dropped file).
10759
+ */
10760
+ _endEntryOnSwap(trackId, entered) {
10761
+ const settled = new AbortController();
10762
+ this._playSignal.addEventListener(
10763
+ "abort",
10764
+ (e) => this._abortEntry(trackId, reasonOf(e.target)),
10765
+ { signal: settled.signal }
10766
+ );
10767
+ void entered.then(
10768
+ () => settled.abort(),
10769
+ () => settled.abort()
10770
+ );
10771
+ }
10772
+ /** A track that has not entered leaves the queue and its wait rejects with `reason` (D4). */
10773
+ _abortEntry(trackId, reason) {
10774
+ if (!this._pending.has(trackId) || this._isEntered(trackId)) return;
10775
+ const nextPending = new Map(this._pending);
10776
+ nextPending.delete(trackId);
10777
+ this._pending = nextPending;
10778
+ this._settleEntry(trackId, reason);
10779
+ this.requestUpdate();
9786
10780
  }
9787
10781
  /**
9788
- * Remove a track by id. Equivalent to `trackElement.remove()` —
9789
- * the editor's MutationObserver handles engine and cache cleanup.
9790
- * No-op if no matching track exists.
10782
+ * Remove a track by id: its `<daw-track>` element is removed (the
10783
+ * MutationObserver does the rest), or, for a track with no element
10784
+ * (`addTrack`, a dropped file, an Undo), the track itself. One undo step.
10785
+ * Warns when no track has the id.
9791
10786
  */
9792
10787
  removeTrack(trackId) {
9793
10788
  const trackEl = this._trackElements.get(trackId);
9794
10789
  if (trackEl) {
9795
10790
  trackEl.remove();
9796
10791
  if (!this.isConnected) this._onTrackRemoved(trackId);
9797
- } else if (this._tracks.has(trackId) || this._isEntered(trackId)) {
10792
+ } else if (this._pending.has(trackId) || this._extras.has(trackId) || this._isEntered(trackId)) {
9798
10793
  this._onTrackRemoved(trackId);
9799
10794
  } else {
9800
10795
  console.warn('[dawcore] removeTrack: no track found for id "' + trackId + '"');
9801
10796
  }
9802
10797
  }
9803
10798
  /**
9804
- * Move a track to a new position in the vertical order (0-based index among
9805
- * `<daw-track>` elements). Element-backed tracks move their DOM element —
9806
- * the MutationObserver syncs the engine (single write path). Element-less
9807
- * tracks (undo-resurrected) reorder the engine directly.
10799
+ * Move a track to a 0-based position in the arrangement's order (every
10800
+ * track counts, those with no element too; `trackEl.index` and
10801
+ * `editor.tracks` give the positions). One undo step; no element moves.
9808
10802
  */
9809
10803
  reorderTrack(trackId, toIndex) {
9810
10804
  if (!Number.isFinite(toIndex)) {
9811
10805
  console.warn("[dawcore] reorderTrack: invalid toIndex " + String(toIndex));
9812
10806
  return;
9813
10807
  }
9814
- const el = this._trackElements.get(trackId);
9815
- if (el) {
9816
- const els = [...this.querySelectorAll("daw-track")];
9817
- const from = els.indexOf(el);
9818
- if (from === -1) return;
9819
- const clamped = Math.max(0, Math.min(toIndex, els.length - 1));
9820
- if (from === clamped) return;
9821
- const anchor = els[clamped];
9822
- if (clamped > from) anchor.after(el);
9823
- else anchor.before(el);
9824
- } else if (this._isEntered(trackId)) {
9825
- this._arrangement.reorderTrack(trackId, toIndex);
9826
- this.requestUpdate();
9827
- } else {
10808
+ if (!this._isEntered(trackId)) {
9828
10809
  console.warn('[dawcore] reorderTrack: no track found for id "' + trackId + '"');
10810
+ return;
9829
10811
  }
10812
+ const last = this._arrangement.getTracks().length - 1;
10813
+ this._arrangement.reorderTrack(trackId, Math.max(0, Math.min(Math.trunc(toIndex), last)));
9830
10814
  }
9831
10815
  /**
9832
- * Update reflected attributes on a track. The mixer fields go to their
9833
- * owner, the arrangement, as one undo step (#843; also while the track
9834
- * loads, #848). For DOM-element tracks the
9835
- * changes are also written to the `<daw-track>` element; for tracks
9836
- * without a DOM element (file drops) the descriptor is updated in place.
10816
+ * Change a track: the mix (one undo step, #843), the name (an undo step),
10817
+ * the render mode and spectrogram config (the editor's). The arrangement
10818
+ * is changed, never an element's attributes (#848): a `<daw-track>`'s
10819
+ * properties show the change. A track that has not entered yet gets it as
10820
+ * the value it enters with.
9837
10821
  */
9838
10822
  updateTrack(trackId, partial) {
10823
+ if (!this._isEntered(trackId)) {
10824
+ this._updatePendingTrack(trackId, partial);
10825
+ return;
10826
+ }
9839
10827
  const mix = {
9840
10828
  volume: partial.volume,
9841
10829
  pan: partial.pan,
9842
10830
  muted: partial.muted,
9843
10831
  soloed: partial.soloed
9844
10832
  };
9845
- const trackEl = this._trackElements.get(trackId);
9846
- if (trackEl) {
9847
- this._writeMixFields(trackId, mix);
9848
- if (partial.name !== void 0) trackEl.setAttribute("name", partial.name);
9849
- if (partial.volume !== void 0) trackEl.volume = partial.volume;
9850
- if (partial.pan !== void 0) trackEl.pan = partial.pan;
9851
- if (partial.muted !== void 0) {
9852
- if (partial.muted) trackEl.setAttribute("muted", "");
9853
- else trackEl.removeAttribute("muted");
9854
- }
9855
- if (partial.soloed !== void 0) {
9856
- if (partial.soloed) trackEl.setAttribute("soloed", "");
9857
- else trackEl.removeAttribute("soloed");
9858
- }
9859
- if (partial.renderMode !== void 0) trackEl.setAttribute("render-mode", partial.renderMode);
9860
- return;
9861
- }
9862
- const oldDesc = this._tracks.get(trackId);
9863
- if (!oldDesc) return;
9864
- let normalizedRenderMode = partial.renderMode === void 0 ? void 0 : normalizeRenderMode(partial.renderMode);
9865
- if (normalizedRenderMode === "both") {
10833
+ this._writeMixFields(trackId, mix);
10834
+ if (partial.name !== void 0) this._renameTrack(trackId, partial.name);
10835
+ const extras = this._extras.get(trackId) ?? this._defaultExtras(trackId);
10836
+ if (!extras) return;
10837
+ let renderMode = partial.renderMode === void 0 ? void 0 : normalizeRenderMode(partial.renderMode);
10838
+ if (renderMode === "both") {
9866
10839
  console.warn(
9867
10840
  `[dawcore] render-mode="both" is not yet supported; falling back to 'spectrogram'`
9868
10841
  );
9869
- normalizedRenderMode = "spectrogram";
10842
+ renderMode = "spectrogram";
9870
10843
  }
9871
- const newDesc = {
9872
- ...oldDesc,
9873
- ...partial.name !== void 0 && { name: partial.name },
9874
- ...normalizedRenderMode !== void 0 && {
9875
- renderMode: trackDescriptorRenderMode(oldDesc.kind, normalizedRenderMode)
10844
+ if (renderMode === void 0 && partial.spectrogramConfig === void 0) return;
10845
+ const next = {
10846
+ ...extras,
10847
+ ...renderMode !== void 0 && {
10848
+ renderMode: trackDescriptorRenderMode(extras.kind, renderMode)
10849
+ },
10850
+ ...partial.spectrogramConfig !== void 0 && {
10851
+ spectrogramConfig: partial.spectrogramConfig
9876
10852
  }
9877
10853
  };
9878
- this._tracks = new Map(this._tracks).set(trackId, newDesc);
9879
- this._writeMixFields(trackId, mix);
10854
+ this._extras = new Map(this._extras).set(trackId, next);
10855
+ if (next.spectrogramConfig !== extras.spectrogramConfig) {
10856
+ this._spectrogramController?.setTrackConfig(trackId, next.spectrogramConfig ?? null);
10857
+ }
10858
+ }
10859
+ /** `updateTrack` on a track waiting to enter: the values it will enter with. */
10860
+ _updatePendingTrack(trackId, partial) {
10861
+ const pending = this._pending.get(trackId);
10862
+ if (!pending) {
10863
+ console.warn('[dawcore] updateTrack: no track found for id "' + trackId + '"');
10864
+ return;
10865
+ }
10866
+ if ("element" in pending) {
10867
+ const el = pending.element;
10868
+ if (partial.name !== void 0) el.name = partial.name;
10869
+ if (partial.volume !== void 0) el.volume = partial.volume;
10870
+ if (partial.pan !== void 0) el.pan = partial.pan;
10871
+ if (partial.muted !== void 0) el.muted = partial.muted;
10872
+ if (partial.soloed !== void 0) el.soloed = partial.soloed;
10873
+ if (partial.renderMode !== void 0) el.renderMode = partial.renderMode;
10874
+ if (partial.spectrogramConfig !== void 0) el.spectrogramConfig = partial.spectrogramConfig;
10875
+ return;
10876
+ }
10877
+ const { descriptor, mix } = pending;
10878
+ this._pending = new Map(this._pending).set(trackId, {
10879
+ descriptor: {
10880
+ ...descriptor,
10881
+ ...partial.spectrogramConfig !== void 0 && {
10882
+ spectrogramConfig: partial.spectrogramConfig
10883
+ },
10884
+ ...partial.name !== void 0 && { name: partial.name },
10885
+ ...partial.renderMode !== void 0 && {
10886
+ renderMode: trackDescriptorRenderMode(
10887
+ descriptor.kind,
10888
+ normalizeRenderMode(partial.renderMode)
10889
+ )
10890
+ }
10891
+ },
10892
+ mix: {
10893
+ volume: partial.volume ?? mix.volume,
10894
+ pan: partial.pan ?? mix.pan,
10895
+ muted: partial.muted ?? mix.muted,
10896
+ soloed: partial.soloed ?? mix.soloed
10897
+ }
10898
+ });
9880
10899
  }
9881
10900
  /**
9882
- * Append a clip to an existing track. Builds a `<daw-clip>` from `config`
9883
- * and appends it to the track's DOM element; resolves with the new clip's
10901
+ * Add a clip to a track (with or without an element) and resolve with its
9884
10902
  * id once its audio has loaded (`daw-clip-ready`, before its peaks are
9885
- * drawn); rejects when it fails to load, is refused, or leaves the
9886
- * arrangement before it loads (a removal, an Undo).
10903
+ * drawn). The clip enters the arrangement as a loading clip, one undo
10904
+ * step; no `<daw-clip>` is created (#848). Rejects when it fails to load,
10905
+ * is refused (its kind), or leaves the arrangement before it loads (a
10906
+ * removal, an Undo). A clip added while the editor is detached loads once
10907
+ * a fresh adapter is set.
10908
+ *
10909
+ * `options.signal` (#848): aborting it before the clip has loaded rejects
10910
+ * with its `reason` and removes the clip for good (no undo step); after it
10911
+ * has loaded it changes nothing. A signal already aborted rejects at once
10912
+ * and adds nothing. A swap of `editor.arrangement` rejects the call with an
10913
+ * `AbortError`; its loading clip stays in the arrangement swapped out.
9887
10914
  */
9888
- addClip(trackId, config) {
10915
+ addClip(trackId, config, options = {}) {
10916
+ const callerSignal = options.signal;
10917
+ if (callerSignal?.aborted) return Promise.reject(reasonOf(callerSignal));
9889
10918
  if (!config.src) {
9890
10919
  return Promise.reject(
9891
10920
  new Error(
@@ -9893,38 +10922,45 @@ var DawEditorElement = class extends LitElement14 {
9893
10922
  )
9894
10923
  );
9895
10924
  }
9896
- const trackEl = this._trackElements.get(trackId);
9897
- if (!trackEl) {
9898
- return Promise.reject(
9899
- new Error(
9900
- 'addClip: no <daw-track> element for trackId "' + trackId + '" \u2014 addClip currently requires a DOM-backed track. Use editor.addTrack(config) first.'
9901
- )
9902
- );
9903
- }
9904
- if (!this._isEntered(trackId) && !this._entryQueue.includes(trackId)) {
10925
+ const pending = this._pending.get(trackId);
10926
+ if (!this._isEntered(trackId) && !pending) {
9905
10927
  return Promise.reject(
9906
10928
  new Error(
9907
- 'addClip: track "' + trackId + '" is not in the editor (an Undo took it out, or the arrangement refused it)'
10929
+ 'addClip: track "' + trackId + '" is not in the editor (an Undo took it out, the arrangement refused it, or no track has this id)'
9908
10930
  )
9909
10931
  );
9910
10932
  }
9911
- const clipEl = this._buildClipElement(config);
9912
- const clipId = clipEl.clipId;
10933
+ const clipDesc = clipDescriptorOf(config);
10934
+ const clipId = clipDesc.clipId;
9913
10935
  return new Promise((resolve, reject) => {
9914
10936
  let seen = false;
9915
- const onReady = (e) => {
9916
- if (e.detail.clipId !== clipId) return;
9917
- cleanup();
9918
- resolve(clipId);
9919
- };
9920
- const onError = (e) => {
9921
- const detail = e.detail;
9922
- if (detail.clipId !== clipId) return;
9923
- cleanup();
9924
- reject(detail.error instanceof Error ? detail.error : new Error(String(detail.error)));
10937
+ const call = new AbortController();
10938
+ const cleanup = () => {
10939
+ call.abort();
10940
+ this._awaitedClips.delete(clipId);
9925
10941
  };
9926
- const stopWatching = this._arrangement.subscribe(() => {
9927
- const present = this._arrangement.getTracks().some((t) => t.clips.some((c) => c.id === clipId));
10942
+ this.addEventListener(
10943
+ "daw-clip-ready",
10944
+ (e) => {
10945
+ if (e.detail.clipId !== clipId) return;
10946
+ cleanup();
10947
+ resolve(clipId);
10948
+ },
10949
+ { signal: call.signal }
10950
+ );
10951
+ this.addEventListener(
10952
+ "daw-clip-error",
10953
+ (e) => {
10954
+ const detail = e.detail;
10955
+ if (detail.clipId !== clipId) return;
10956
+ cleanup();
10957
+ reject(detail.error instanceof Error ? detail.error : new Error(String(detail.error)));
10958
+ },
10959
+ { signal: call.signal }
10960
+ );
10961
+ const watched = pending && "element" in pending && !this._isEntered(trackId) ? this._ownArrangement : this._arrangement;
10962
+ const stopWatching = watched.subscribe(() => {
10963
+ const present = watched.getTracks().some((t) => t.clips.some((c) => c.id === clipId));
9928
10964
  if (present) {
9929
10965
  seen = true;
9930
10966
  } else if (seen) {
@@ -9932,14 +10968,24 @@ var DawEditorElement = class extends LitElement14 {
9932
10968
  reject(new Error('clip "' + clipId + '" was removed before its audio loaded'));
9933
10969
  }
9934
10970
  });
9935
- const cleanup = () => {
9936
- this.removeEventListener("daw-clip-ready", onReady);
9937
- this.removeEventListener("daw-clip-error", onError);
9938
- stopWatching();
9939
- this._awaitedClips.delete(clipId);
9940
- };
9941
- this.addEventListener("daw-clip-ready", onReady);
9942
- this.addEventListener("daw-clip-error", onError);
10971
+ call.signal.addEventListener("abort", stopWatching);
10972
+ this._playSignals.signalOf(watched).addEventListener(
10973
+ "abort",
10974
+ (e) => {
10975
+ cleanup();
10976
+ reject(reasonOf(e.target));
10977
+ },
10978
+ { signal: call.signal }
10979
+ );
10980
+ callerSignal?.addEventListener(
10981
+ "abort",
10982
+ () => {
10983
+ cleanup();
10984
+ this._discardAddedClip(trackId, clipId);
10985
+ reject(reasonOf(callerSignal));
10986
+ },
10987
+ { signal: call.signal }
10988
+ );
9943
10989
  this._awaitedClips.set(clipId, {
9944
10990
  trackId,
9945
10991
  reject: (error) => {
@@ -9947,122 +10993,91 @@ var DawEditorElement = class extends LitElement14 {
9947
10993
  reject(error);
9948
10994
  }
9949
10995
  });
9950
- trackEl.appendChild(clipEl);
10996
+ if (this._isEntered(trackId)) {
10997
+ seen = true;
10998
+ this._loadAndAppendClip(trackId, clipDesc);
10999
+ } else if (pending) {
11000
+ this._pending = new Map(this._pending).set(
11001
+ trackId,
11002
+ "element" in pending ? { ...pending, extraClips: [...pending.extraClips, clipDesc] } : {
11003
+ ...pending,
11004
+ descriptor: {
11005
+ ...pending.descriptor,
11006
+ clips: [...pending.descriptor.clips, clipDesc]
11007
+ }
11008
+ }
11009
+ );
11010
+ }
9951
11011
  });
9952
11012
  }
9953
11013
  /**
9954
- * Remove a clip by id. Removes the matching `<daw-clip>` DOM element when
9955
- * present (MutationObserver handles cleanup); otherwise updates engine
9956
- * state directly. No-op if no matching clip exists.
11014
+ * Remove a clip by id: its `<daw-clip>` when there is one (the observer
11015
+ * removes the clip, as `select.remove(i)` removes an option), otherwise
11016
+ * the clip itself, one undo step. Undo brings the clip back with no
11017
+ * element. No-op with a warning when there is no such clip.
9957
11018
  */
9958
11019
  removeClip(trackId, clipId) {
9959
11020
  const trackEl = this._trackElements.get(trackId);
9960
- if (trackEl) {
9961
- const clipEl = [...trackEl.querySelectorAll("daw-clip")].find(
9962
- (c) => c.clipId === clipId
9963
- );
9964
- if (clipEl) {
9965
- clipEl.remove();
9966
- return;
9967
- }
11021
+ const clipEl = trackEl ? [...trackEl.querySelectorAll("daw-clip")].find(
11022
+ (c) => c.clipId === clipId
11023
+ ) : void 0;
11024
+ if (clipEl) {
11025
+ clipEl.remove();
11026
+ if (!this.isConnected && this._isEntered(trackId)) this._removeClipFromTrack(trackId, clipId);
11027
+ return;
9968
11028
  }
9969
11029
  if (this._isEntered(trackId)) {
9970
11030
  this._removeClipFromTrack(trackId, clipId);
9971
11031
  return;
9972
11032
  }
11033
+ const pending = this._pending.get(trackId);
11034
+ if (pending) {
11035
+ const without = (clips) => clips.filter((c) => c.clipId !== clipId);
11036
+ this._pending = new Map(this._pending).set(
11037
+ trackId,
11038
+ "element" in pending ? { ...pending, extraClips: without(pending.extraClips) } : {
11039
+ ...pending,
11040
+ descriptor: { ...pending.descriptor, clips: without(pending.descriptor.clips) }
11041
+ }
11042
+ );
11043
+ this._rejectAwaitedClips((id) => id === clipId, "the clip was removed before it loaded");
11044
+ return;
11045
+ }
9973
11046
  console.warn(
9974
11047
  '[dawcore] removeClip: no track found for id "' + trackId + '" (clipId "' + clipId + '")'
9975
11048
  );
9976
11049
  }
9977
11050
  /**
9978
- * Update a clip's position (start/duration/offset) or properties (gain/name).
9979
- * For DOM-element clips, writes properties on the `<daw-clip>` element which
9980
- * fires `daw-clip-update`; otherwise applies directly via `_applyClipUpdate`.
11051
+ * Change a clip's position (start/duration/offset), gain or name: one undo
11052
+ * step on the arrangement (#848; a clip still loading changes its loading
11053
+ * clip). A `<daw-clip>`'s properties show the change, its attributes do
11054
+ * not. Fades are a `<daw-clip>` declaration only (engine-side fades are
11055
+ * #489): `fadeIn` / `fadeOut` / `fadeType` here change nothing.
9981
11056
  *
9982
11057
  * Re-decoding (changing `src`) is not supported via this method — remove and
9983
11058
  * re-add the clip instead.
9984
- *
9985
- * Note: `fadeIn` / `fadeOut` / `fadeType` on the partial are written to the
9986
- * `<daw-clip>` element (so they round-trip in the descriptor), but engine-side
9987
- * fade application from `<daw-clip>` properties is not yet implemented — see
9988
- * the broader fade-engine integration tracked separately.
9989
11059
  */
9990
11060
  updateClip(trackId, clipId, partial) {
9991
- const trackEl = this._trackElements.get(trackId);
9992
- if (trackEl) {
9993
- const clipEl = [...trackEl.querySelectorAll("daw-clip")].find(
9994
- (c) => c.clipId === clipId
9995
- );
9996
- if (clipEl) {
9997
- if (partial.start !== void 0) clipEl.start = partial.start;
9998
- if (partial.duration !== void 0) clipEl.duration = partial.duration;
9999
- if (partial.offset !== void 0) clipEl.offset = partial.offset;
10000
- if (partial.gain !== void 0) clipEl.gain = partial.gain;
10001
- if (partial.name !== void 0) clipEl.setAttribute("name", partial.name);
10002
- if (partial.fadeIn !== void 0) clipEl.fadeIn = partial.fadeIn;
10003
- if (partial.fadeOut !== void 0) clipEl.fadeOut = partial.fadeOut;
10004
- if (partial.fadeType !== void 0) clipEl.setAttribute("fade-type", partial.fadeType);
10005
- return;
10006
- }
10007
- }
10008
- const t = this._engineTracks.get(trackId);
10009
- if (!t) {
11061
+ if (!this._isEntered(trackId)) {
10010
11062
  console.warn('[dawcore] updateClip: no track found for id "' + trackId + '"');
10011
11063
  return;
10012
11064
  }
10013
- const idx = t.clips.findIndex((c) => c.id === clipId);
10014
- if (idx === -1) {
11065
+ if (!this._clipValues(trackId, clipId)) {
10015
11066
  console.warn(
10016
11067
  '[dawcore] updateClip: clip "' + clipId + '" not found in track "' + trackId + '"'
10017
11068
  );
10018
11069
  return;
10019
11070
  }
10020
- const oldClip = t.clips[idx];
10021
- const sr = oldClip.sampleRate ?? this.effectiveSampleRate;
10022
- const updatedClip = {
10023
- ...oldClip,
10024
- ...partial.start !== void 0 && { startSample: Math.round(partial.start * sr) },
10025
- ...partial.duration !== void 0 && partial.duration > 0 && { durationSamples: Math.round(partial.duration * sr) },
10026
- ...partial.offset !== void 0 && { offsetSamples: Math.round(partial.offset * sr) },
10027
- ...partial.gain !== void 0 && { gain: partial.gain },
10028
- ...partial.name !== void 0 && { name: partial.name }
10029
- };
10030
- const desc = this._tracks.get(trackId);
10031
- if (desc?.clips.some((c) => c.clipId === clipId)) {
10032
- this._tracks = new Map(this._tracks).set(trackId, {
10033
- ...desc,
10034
- clips: desc.clips.map(
10035
- (c) => c.clipId === clipId ? {
10036
- ...c,
10037
- start: updatedClip.startSample / sr,
10038
- duration: updatedClip.durationSamples / sr,
10039
- offset: updatedClip.offsetSamples / sr,
10040
- ...partial.gain !== void 0 && { gain: partial.gain },
10041
- ...partial.name !== void 0 && { name: partial.name }
10042
- } : c
10043
- )
10044
- });
10045
- }
10046
- this._replaceClip(trackId, clipId, updatedClip);
10047
- }
10048
- _buildClipElement(config) {
10049
- const clipEl = document.createElement("daw-clip");
10050
- if (config.src !== void 0) clipEl.setAttribute("src", config.src);
10051
- if (config.peaksSrc !== void 0) clipEl.setAttribute("peaks-src", config.peaksSrc);
10052
- if (config.start !== void 0) clipEl.start = config.start;
10053
- if (config.duration !== void 0) clipEl.duration = config.duration;
10054
- if (config.offset !== void 0) clipEl.offset = config.offset;
10055
- if (config.gain !== void 0) clipEl.gain = config.gain;
10056
- if (config.name !== void 0) clipEl.setAttribute("name", config.name);
10057
- if (config.fadeIn !== void 0) clipEl.fadeIn = config.fadeIn;
10058
- if (config.fadeOut !== void 0) clipEl.fadeOut = config.fadeOut;
10059
- if (config.fadeType !== void 0) clipEl.setAttribute("fade-type", config.fadeType);
10060
- if (config.midiNotes !== void 0) clipEl.midiNotes = config.midiNotes;
10061
- if (config.midiChannel !== void 0)
10062
- clipEl.setAttribute("midi-channel", String(config.midiChannel));
10063
- if (config.midiProgram !== void 0)
10064
- clipEl.setAttribute("midi-program", String(config.midiProgram));
10065
- return clipEl;
11071
+ const request = {};
11072
+ if (partial.start !== void 0) request.start = partial.start;
11073
+ if (partial.duration !== void 0) request.duration = partial.duration;
11074
+ if (partial.offset !== void 0) request.offset = partial.offset;
11075
+ if (partial.gain !== void 0) request.gain = partial.gain;
11076
+ if (partial.name !== void 0) request.name = partial.name;
11077
+ if (partial.midiNotes !== void 0) request.midiNotes = partial.midiNotes;
11078
+ if (partial.midiChannel !== void 0) request.midiChannel = partial.midiChannel;
11079
+ if (partial.midiProgram !== void 0) request.midiProgram = partial.midiProgram;
11080
+ this._requestClipChange(trackId, clipId, request);
10066
11081
  }
10067
11082
  // --- Playback ---
10068
11083
  /**
@@ -10329,8 +11344,8 @@ var DawEditorElement = class extends LitElement14 {
10329
11344
  return;
10330
11345
  }
10331
11346
  const targetId = options?.trackId ?? this._selectedTrackId;
10332
- const target = targetId ? this._tracks.get(targetId) : void 0;
10333
- if (targetId && target?.kind === "midi") {
11347
+ const target = targetId ? this._arrangement.getTracks().find((t) => t.id === targetId) : void 0;
11348
+ if (targetId && target && trackKind(target) === "midi") {
10334
11349
  const error = new Error(
10335
11350
  'Cannot record onto MIDI track "' + target.name + '": a recording is audio. Select or create an audio track first.'
10336
11351
  );
@@ -10437,67 +11452,25 @@ var DawEditorElement = class extends LitElement14 {
10437
11452
  return (this._getOrderedTracks().length > 0 || this.scaleMode === "beats" || this.indefinitePlayback || this.fillViewport) && this.timescale;
10438
11453
  }
10439
11454
  /**
10440
- * DOM → engine: make the engine's track order match the light-DOM
10441
- * `<daw-track>` order. Single write path for reorders — editor-initiated
10442
- * (buttons/drag move the element) and consumer-initiated (insertBefore)
10443
- * mutations both land here via the MutationObserver. Element-less tracks
10444
- * (undo-resurrected) keep their engine positions (stable sort).
10445
- * Write-only-on-change: a no-op when orders already match, so the
10446
- * engine→DOM direction (statechange handler) converges in one pass.
11455
+ * `<daw-track>` elements the page moved (one MutationObserver batch): each
11456
+ * is placed after the arrangement track of the nearest `<daw-track>` before
11457
+ * it, in DOM order, as one undo step (#848 P13). Elements whose track is
11458
+ * not in the arrangement are left alone (a queued one enters at its DOM
11459
+ * position). The arrangement's own order changes (an Undo) move no element.
10447
11460
  */
10448
- _syncEngineOrderToDom() {
10449
- const engine = this._engine;
10450
- if (!engine) return;
10451
- const domOrder = [...this.querySelectorAll("daw-track")].map(
10452
- (el) => el.trackId
10453
- );
10454
- const engineIds = engine.getState().tracks.map((t) => t.id);
10455
- const inDom = new Set(domOrder);
10456
- const slots = engineIds.flatMap((id, i) => inDom.has(id) ? [i] : []);
10457
- const domSorted = domOrder.filter((id) => engineIds.includes(id));
10458
- const target = [...engineIds];
10459
- slots.forEach((slot, k) => {
10460
- target[slot] = domSorted[k];
10461
- });
10462
- if (target.every((id, i) => id === engineIds[i])) return;
10463
- this._inOrderSync = true;
11461
+ _placeMovedTracks(movedIds) {
11462
+ const els = [...this.querySelectorAll("daw-track")];
11463
+ const moved = els.filter((el) => movedIds.has(el.trackId) && this._isEntered(el.trackId));
11464
+ if (moved.length === 0) return;
11465
+ const arrangement = this._arrangement;
11466
+ arrangement.beginTransaction();
10464
11467
  try {
10465
- engine.beginTransaction();
10466
- const current = [...engineIds];
10467
- for (let i = 0; i < target.length; i++) {
10468
- if (current[i] === target[i]) continue;
10469
- engine.reorderTrack(target[i], i);
10470
- const from = current.indexOf(target[i]);
10471
- current.splice(from, 1);
10472
- current.splice(i, 0, target[i]);
10473
- }
10474
- engine.commitTransaction();
11468
+ for (const el of moved) {
11469
+ const others = arrangement.getTracks().map((t) => t.id).filter((id) => id !== el.trackId);
11470
+ arrangement.reorderTrack(el.trackId, entryIndex(els, el.trackId, others));
11471
+ }
10475
11472
  } finally {
10476
- this._inOrderSync = false;
10477
- }
10478
- this.requestUpdate();
10479
- }
10480
- /**
10481
- * Engine → DOM: after an engine-initiated order change (undo/redo), move
10482
- * `<daw-track>` elements to match engine order. The resulting mutations fire
10483
- * the observer's _syncEngineOrderToDom, which finds the orders equal and
10484
- * no-ops — converges in one pass (write-only-on-change).
10485
- */
10486
- _syncDomToEngineOrder(tracks) {
10487
- const els = [...this.querySelectorAll("daw-track")];
10488
- if (els.length < 2) return;
10489
- const byId = new Map(els.map((el) => [el.trackId, el]));
10490
- const desired = tracks.map((t) => byId.get(t.id)).filter((el) => el != null);
10491
- if (desired.length < 2) return;
10492
- const desiredSet = new Set(desired);
10493
- const slots = els.filter((el) => desiredSet.has(el));
10494
- if (desired.every((el, i) => el === slots[i])) return;
10495
- for (let i = 0; i < desired.length; i++) {
10496
- if (slots[i] === desired[i]) continue;
10497
- slots[i].before(desired[i]);
10498
- const from = slots.indexOf(desired[i]);
10499
- slots.splice(from, 1);
10500
- slots.splice(i, 0, desired[i]);
11473
+ arrangement.commitTransaction();
10501
11474
  }
10502
11475
  }
10503
11476
  /**
@@ -10507,9 +11480,12 @@ var DawEditorElement = class extends LitElement14 {
10507
11480
  _getOrderedTracks() {
10508
11481
  const rows = [];
10509
11482
  for (const track of this._arrangement.getTracks()) {
10510
- const loaded = this._engineTracks.get(track.id);
10511
- if (!loaded) continue;
10512
- rows.push([track.id, loaded, track.clips.filter(isLoadingClip3)]);
11483
+ const loaded = loadedTrack(
11484
+ track,
11485
+ this._mixOf(track.id),
11486
+ this._arrangement.recordingTrackIds.has(track.id)
11487
+ );
11488
+ rows.push([track.id, loaded, track.clips.filter(isLoadingClip5)]);
10513
11489
  }
10514
11490
  return rows;
10515
11491
  }
@@ -10578,7 +11554,11 @@ var DawEditorElement = class extends LitElement14 {
10578
11554
  selEndPx = this._selectionEndTime * sr / spp;
10579
11555
  }
10580
11556
  const orderedTracks = this._getOrderedTracks().map(([trackId, track, loading]) => {
10581
- const descriptor = this._tracks.get(trackId);
11557
+ const descriptor = {
11558
+ name: track.name ?? "",
11559
+ kind: trackKind(track),
11560
+ renderMode: this._renderModeOf(trackId)
11561
+ };
10582
11562
  const firstPeaks = [...track.clips, ...loading].map((c) => this._peaksData.get(c.id) ?? this._previewPeaks.get(c.id)).find((p) => p && p.data.length > 0);
10583
11563
  const recSession = this._recordingController.getSession(trackId);
10584
11564
  const numChannels = firstPeaks ? firstPeaks.data.length : recSession ? recSession.channelCount : 1;
@@ -10626,24 +11606,30 @@ var DawEditorElement = class extends LitElement14 {
10626
11606
  <span class="annotation-lane-name">${track.name}</span>
10627
11607
  </div>`
10628
11608
  )}
10629
- ${orderedTracks.map((t, i) => {
10630
- const mix = this._mixOf(t.trackId);
10631
- return html12`
10632
- <daw-track-controls
10633
- style="height: ${t.trackHeight}px;"
10634
- .trackId=${t.trackId}
10635
- .trackName=${t.descriptor?.name ?? "Untitled"}
10636
- .volume=${mix.volume}
10637
- .pan=${mix.pan}
10638
- .muted=${mix.muted}
10639
- .recording=${this._engine?.recordingTrackIds.has(t.trackId) ?? false}
10640
- .soloed=${mix.soloed}
10641
- .reorderable=${this.trackReordering}
10642
- .trackIndex=${i}
10643
- .trackCount=${orderedTracks.length}
10644
- ></daw-track-controls>
10645
- `;
10646
- })}
11609
+ ${repeat(
11610
+ orderedTracks,
11611
+ // Keyed by track: a swap or an outside reorder must not hand
11612
+ // a row (and a slider gesture held in it) to another track.
11613
+ (t) => t.trackId,
11614
+ (t, i) => {
11615
+ const mix = this._mixOf(t.trackId);
11616
+ return html12`
11617
+ <daw-track-controls
11618
+ style="height: ${t.trackHeight}px;"
11619
+ .trackId=${t.trackId}
11620
+ .trackName=${t.descriptor?.name ?? "Untitled"}
11621
+ .volume=${mix.volume}
11622
+ .pan=${mix.pan}
11623
+ .muted=${mix.muted}
11624
+ .recording=${this._engine?.recordingTrackIds.has(t.trackId) ?? false}
11625
+ .soloed=${mix.soloed}
11626
+ .reorderable=${this.trackReordering}
11627
+ .trackIndex=${i}
11628
+ .trackCount=${orderedTracks.length}
11629
+ ></daw-track-controls>
11630
+ `;
11631
+ }
11632
+ )}
10647
11633
  </div>
10648
11634
  </div>` : ""}
10649
11635
  <div class="scroll-area">
@@ -10674,149 +11660,158 @@ var DawEditorElement = class extends LitElement14 {
10674
11660
  ></daw-grid>` : ""}
10675
11661
  ${orderedTracks.length > 0 || this.scaleMode === "beats" || this.indefinitePlayback || this.fillViewport ? html12`<daw-selection .startPx=${selStartPx} .endPx=${selEndPx}></daw-selection>
10676
11662
  <daw-playhead></daw-playhead>` : ""}
10677
- ${orderedTracks.map((t) => {
10678
- const channelHeight = this.waveHeight;
10679
- return html12`
10680
- <div
10681
- class="track-row ${t.trackId === this._selectedTrackId ? "selected" : ""}"
10682
- style="height: ${t.trackHeight}px;"
10683
- data-track-id=${t.trackId}
10684
- >
10685
- ${t.track.clips.map((clip) => {
10686
- const peakData = this._peaksData.get(clip.id) ?? this._previewPeaks.get(clip.id);
10687
- let clipLeft;
10688
- let width;
10689
- if (this.scaleMode === "beats") {
10690
- const startTick = clip.startTick !== void 0 ? clip.startTick : this._secondsToTicks(clip.startSample / sr);
10691
- const durSec = clip.durationSamples / sr;
10692
- const startSec = clip.startTick !== void 0 ? this._ticksToSeconds(clip.startTick) : clip.startSample / sr;
10693
- const endTick = this._secondsToTicks(startSec + durSec);
10694
- clipLeft = Math.round(startTick / this.ticksPerPixel);
10695
- width = Math.round(endTick / this.ticksPerPixel) - clipLeft;
10696
- } else {
10697
- clipLeft = Math.floor(clip.startSample / spp);
10698
- width = clipPixelWidth(clip.startSample, clip.durationSamples, spp);
10699
- }
10700
- let clipSegments;
10701
- let segmentChannels;
10702
- if (this.scaleMode === "beats" && this.secondsToTicks) {
10703
- const audioBuffer = this._clipBuffers.get(clip.id);
10704
- const basePeaks = audioBuffer ? this._peakPipeline.getBaseScalePeaks(
10705
- audioBuffer,
10706
- this.mono,
10707
- clip.offsetSamples,
10708
- clip.durationSamples
10709
- ) : null;
10710
- if (basePeaks) {
10711
- const baseScale = basePeaks.scale;
10712
- segmentChannels = basePeaks.peaks.data;
10713
- const MIN_RENDER_STEP = 80;
10714
- const stepTicks = Math.max(MIN_RENDER_STEP, Math.ceil(this.ticksPerPixel));
11663
+ ${repeat(
11664
+ orderedTracks,
11665
+ (t) => t.trackId,
11666
+ (t) => {
11667
+ const channelHeight = this.waveHeight;
11668
+ return html12`
11669
+ <div
11670
+ class="track-row ${t.trackId === this._selectedTrackId ? "selected" : ""}"
11671
+ style="height: ${t.trackHeight}px;"
11672
+ data-track-id=${t.trackId}
11673
+ >
11674
+ ${t.track.clips.map((clip) => {
11675
+ const peakData = this._peaksData.get(clip.id) ?? this._previewPeaks.get(clip.id);
11676
+ let clipLeft;
11677
+ let width;
11678
+ if (this.scaleMode === "beats") {
11679
+ const startTick = clip.startTick !== void 0 ? clip.startTick : this._secondsToTicks(clip.startSample / sr);
11680
+ const durSec = clip.durationSamples / sr;
10715
11681
  const startSec = clip.startTick !== void 0 ? this._ticksToSeconds(clip.startTick) : clip.startSample / sr;
10716
- const clipOffsetSec = clip.offsetSamples / sr;
10717
- const segStartTick = clip.startTick !== void 0 ? clip.startTick : this._secondsToTicks(startSec);
10718
- const endTick = this._secondsToTicks(startSec + clip.durationSamples / sr);
10719
- clipSegments = [];
10720
- for (let tick = segStartTick; tick < endTick; tick += stepTicks) {
10721
- const segEndTick = Math.min(tick + stepTicks, endTick);
10722
- const segStartAudioSec = this._ticksToSeconds(tick) - startSec + clipOffsetSec;
10723
- const segEndAudioSec = this._ticksToSeconds(segEndTick) - startSec + clipOffsetSec;
10724
- const segStartSample = Math.round(segStartAudioSec * sr);
10725
- const segEndSample = Math.round(segEndAudioSec * sr);
10726
- const totalPeaks = clip.durationSamples / baseScale;
10727
- clipSegments.push({
10728
- peakStart: Math.max(
10729
- 0,
10730
- (segStartSample - clip.offsetSamples) / baseScale
10731
- ),
10732
- peakEnd: Math.min(
10733
- totalPeaks,
10734
- (segEndSample - clip.offsetSamples) / baseScale
10735
- ),
10736
- pixelStart: (tick - segStartTick) / this.ticksPerPixel,
10737
- pixelEnd: (segEndTick - segStartTick) / this.ticksPerPixel
10738
- });
11682
+ const endTick = this._secondsToTicks(startSec + durSec);
11683
+ clipLeft = Math.round(startTick / this.ticksPerPixel);
11684
+ width = Math.round(endTick / this.ticksPerPixel) - clipLeft;
11685
+ } else {
11686
+ clipLeft = Math.floor(clip.startSample / spp);
11687
+ width = clipPixelWidth(clip.startSample, clip.durationSamples, spp);
11688
+ }
11689
+ let clipSegments;
11690
+ let segmentChannels;
11691
+ if (this.scaleMode === "beats" && this.secondsToTicks) {
11692
+ const audioBuffer = this._clipBuffers.get(clip.id);
11693
+ const basePeaks = audioBuffer ? this._peakPipeline.getBaseScalePeaks(
11694
+ audioBuffer,
11695
+ this.mono,
11696
+ clip.offsetSamples,
11697
+ clip.durationSamples
11698
+ ) : null;
11699
+ if (basePeaks) {
11700
+ const baseScale = basePeaks.scale;
11701
+ segmentChannels = basePeaks.peaks.data;
11702
+ const MIN_RENDER_STEP = 80;
11703
+ const stepTicks = Math.max(
11704
+ MIN_RENDER_STEP,
11705
+ Math.ceil(this.ticksPerPixel)
11706
+ );
11707
+ const startSec = clip.startTick !== void 0 ? this._ticksToSeconds(clip.startTick) : clip.startSample / sr;
11708
+ const clipOffsetSec = clip.offsetSamples / sr;
11709
+ const segStartTick = clip.startTick !== void 0 ? clip.startTick : this._secondsToTicks(startSec);
11710
+ const endTick = this._secondsToTicks(
11711
+ startSec + clip.durationSamples / sr
11712
+ );
11713
+ clipSegments = [];
11714
+ for (let tick = segStartTick; tick < endTick; tick += stepTicks) {
11715
+ const segEndTick = Math.min(tick + stepTicks, endTick);
11716
+ const segStartAudioSec = this._ticksToSeconds(tick) - startSec + clipOffsetSec;
11717
+ const segEndAudioSec = this._ticksToSeconds(segEndTick) - startSec + clipOffsetSec;
11718
+ const segStartSample = Math.round(segStartAudioSec * sr);
11719
+ const segEndSample = Math.round(segEndAudioSec * sr);
11720
+ const totalPeaks = clip.durationSamples / baseScale;
11721
+ clipSegments.push({
11722
+ peakStart: Math.max(
11723
+ 0,
11724
+ (segStartSample - clip.offsetSamples) / baseScale
11725
+ ),
11726
+ peakEnd: Math.min(
11727
+ totalPeaks,
11728
+ (segEndSample - clip.offsetSamples) / baseScale
11729
+ ),
11730
+ pixelStart: (tick - segStartTick) / this.ticksPerPixel,
11731
+ pixelEnd: (segEndTick - segStartTick) / this.ticksPerPixel
11732
+ });
11733
+ }
10739
11734
  }
10740
11735
  }
10741
- }
10742
- const channels = segmentChannels ?? peakData?.data ?? [new Int16Array(0)];
10743
- const hdrH = this.clipHeaders ? this.clipHeaderHeight : 0;
10744
- const chH = this.waveHeight;
10745
- return html12` <div
10746
- class="clip-container"
10747
- style="left:${clipLeft}px;top:0;width:${width}px;height:${t.trackHeight}px;"
10748
- data-clip-id=${clip.id}
10749
- >
10750
- ${hdrH > 0 ? html12`<div
10751
- class="clip-header"
10752
- data-clip-id=${clip.id}
10753
- data-track-id=${t.trackId}
10754
- ?data-interactive=${this.interactiveClips}
10755
- >
10756
- <span>${clip.name || t.descriptor?.name || ""}</span>
10757
- </div>` : ""}
10758
- ${t.descriptor?.kind === "midi" ? html12`<daw-piano-roll
10759
- style="position:absolute;left:0;top:${hdrH}px;"
10760
- .midiNotes=${clip.midiNotes ?? []}
10761
- .length=${peakData?.length ?? width}
10762
- .waveHeight=${chH * channels.length}
10763
- .samplesPerPixel=${this._renderSpp}
10764
- .sampleRate=${this.effectiveSampleRate}
10765
- .clipOffsetSeconds=${(clip.offsetSamples ?? 0) / this.effectiveSampleRate}
10766
- .visibleStart=${this._viewport.visibleStart}
10767
- .visibleEnd=${this._viewport.visibleEnd}
10768
- .originX=${clipLeft}
10769
- ?selected=${t.trackId === this._selectedTrackId}
10770
- ></daw-piano-roll>` : t.descriptor?.renderMode === "spectrogram" ? channels.map(
10771
- (_chPeaks, chIdx) => html12`<daw-spectrogram
10772
- style="position:absolute;left:0;top:${hdrH + chIdx * chH}px;height:${chH}px;width:${peakData?.length ?? width}px;"
10773
- .clipId=${clip.id}
10774
- .trackId=${t.trackId}
10775
- .channelIndex=${chIdx}
10776
- .length=${peakData?.length ?? width}
10777
- .waveHeight=${chH}
10778
- .samplesPerPixel=${this._renderSpp}
10779
- .sampleRate=${this.effectiveSampleRate}
10780
- .clipOffsetSeconds=${(clip.offsetSamples ?? 0) / this.effectiveSampleRate}
10781
- .visibleStart=${this._viewport.visibleStart}
10782
- .visibleEnd=${this._viewport.visibleEnd}
10783
- .originX=${clipLeft}
10784
- ></daw-spectrogram>`
10785
- ) : channels.map(
10786
- (chPeaks, chIdx) => html12` <daw-waveform
10787
- style="position:absolute;left:0;top:${hdrH + chIdx * chH}px;"
10788
- .peaks=${chPeaks}
10789
- .length=${peakData?.length ?? width}
10790
- .waveHeight=${chH}
10791
- .barWidth=${this.barWidth}
10792
- .barGap=${this.barGap}
10793
- .roundedBars=${this.roundedBars}
10794
- .gain=${this.gainScaledWaveforms ? clip.gain ?? 1 : 1}
10795
- .visibleStart=${this._viewport.visibleStart}
10796
- .visibleEnd=${this._viewport.visibleEnd}
10797
- .originX=${clipLeft}
10798
- .segments=${clipSegments}
10799
- ></daw-waveform>`
10800
- )}
10801
- ${this.interactiveClips ? html12` <div
10802
- class="clip-boundary"
10803
- data-boundary-edge="left"
10804
- data-clip-id=${clip.id}
10805
- data-track-id=${t.trackId}
10806
- ></div>
10807
- <div
10808
- class="clip-boundary"
10809
- data-boundary-edge="right"
11736
+ const channels = segmentChannels ?? peakData?.data ?? [new Int16Array(0)];
11737
+ const hdrH = this.clipHeaders ? this.clipHeaderHeight : 0;
11738
+ const chH = this.waveHeight;
11739
+ return html12` <div
11740
+ class="clip-container"
11741
+ style="left:${clipLeft}px;top:0;width:${width}px;height:${t.trackHeight}px;"
11742
+ data-clip-id=${clip.id}
11743
+ >
11744
+ ${hdrH > 0 ? html12`<div
11745
+ class="clip-header"
10810
11746
  data-clip-id=${clip.id}
10811
11747
  data-track-id=${t.trackId}
10812
- ></div>` : ""}
10813
- </div>`;
10814
- })}
10815
- ${t.loading.map((clip) => this._renderPlaceholder(clip, t))}
10816
- ${this._renderRecordingPreview(t.trackId, channelHeight)}
10817
- </div>
10818
- `;
10819
- })}
11748
+ ?data-interactive=${this.interactiveClips}
11749
+ >
11750
+ <span>${clip.name || t.descriptor?.name || ""}</span>
11751
+ </div>` : ""}
11752
+ ${t.descriptor?.kind === "midi" ? html12`<daw-piano-roll
11753
+ style="position:absolute;left:0;top:${hdrH}px;"
11754
+ .midiNotes=${clip.midiNotes ?? []}
11755
+ .length=${peakData?.length ?? width}
11756
+ .waveHeight=${chH * channels.length}
11757
+ .samplesPerPixel=${this._renderSpp}
11758
+ .sampleRate=${this.effectiveSampleRate}
11759
+ .clipOffsetSeconds=${(clip.offsetSamples ?? 0) / this.effectiveSampleRate}
11760
+ .visibleStart=${this._viewport.visibleStart}
11761
+ .visibleEnd=${this._viewport.visibleEnd}
11762
+ .originX=${clipLeft}
11763
+ ?selected=${t.trackId === this._selectedTrackId}
11764
+ ></daw-piano-roll>` : t.descriptor?.renderMode === "spectrogram" ? channels.map(
11765
+ (_chPeaks, chIdx) => html12`<daw-spectrogram
11766
+ style="position:absolute;left:0;top:${hdrH + chIdx * chH}px;height:${chH}px;width:${peakData?.length ?? width}px;"
11767
+ .clipId=${clip.id}
11768
+ .trackId=${t.trackId}
11769
+ .channelIndex=${chIdx}
11770
+ .length=${peakData?.length ?? width}
11771
+ .waveHeight=${chH}
11772
+ .samplesPerPixel=${this._renderSpp}
11773
+ .sampleRate=${this.effectiveSampleRate}
11774
+ .clipOffsetSeconds=${(clip.offsetSamples ?? 0) / this.effectiveSampleRate}
11775
+ .visibleStart=${this._viewport.visibleStart}
11776
+ .visibleEnd=${this._viewport.visibleEnd}
11777
+ .originX=${clipLeft}
11778
+ ></daw-spectrogram>`
11779
+ ) : channels.map(
11780
+ (chPeaks, chIdx) => html12` <daw-waveform
11781
+ style="position:absolute;left:0;top:${hdrH + chIdx * chH}px;"
11782
+ .peaks=${chPeaks}
11783
+ .length=${peakData?.length ?? width}
11784
+ .waveHeight=${chH}
11785
+ .barWidth=${this.barWidth}
11786
+ .barGap=${this.barGap}
11787
+ .roundedBars=${this.roundedBars}
11788
+ .gain=${this.gainScaledWaveforms ? clip.gain ?? 1 : 1}
11789
+ .visibleStart=${this._viewport.visibleStart}
11790
+ .visibleEnd=${this._viewport.visibleEnd}
11791
+ .originX=${clipLeft}
11792
+ .segments=${clipSegments}
11793
+ ></daw-waveform>`
11794
+ )}
11795
+ ${this.interactiveClips ? html12` <div
11796
+ class="clip-boundary"
11797
+ data-boundary-edge="left"
11798
+ data-clip-id=${clip.id}
11799
+ data-track-id=${t.trackId}
11800
+ ></div>
11801
+ <div
11802
+ class="clip-boundary"
11803
+ data-boundary-edge="right"
11804
+ data-clip-id=${clip.id}
11805
+ data-track-id=${t.trackId}
11806
+ ></div>` : ""}
11807
+ </div>`;
11808
+ })}
11809
+ ${t.loading.map((clip) => this._renderPlaceholder(clip, t))}
11810
+ ${this._renderRecordingPreview(t.trackId, channelHeight)}
11811
+ </div>
11812
+ `;
11813
+ }
11814
+ )}
10820
11815
  </div>
10821
11816
  </div>
10822
11817
  </div>
@@ -10827,6 +11822,10 @@ var DawEditorElement = class extends LitElement14 {
10827
11822
  DawEditorElement.styles = [
10828
11823
  hostStyles,
10829
11824
  css11`
11825
+ /* The hidden attribute hides the element: :host sets display (modern-web-guidance custom-elements). */
11826
+ :host([hidden]) {
11827
+ display: none;
11828
+ }
10830
11829
  :host {
10831
11830
  display: flex;
10832
11831
  flex-direction: column;
@@ -11056,10 +12055,7 @@ __decorateClass([
11056
12055
  ], DawEditorElement.prototype, "_previewPeaks", 2);
11057
12056
  __decorateClass([
11058
12057
  state4()
11059
- ], DawEditorElement.prototype, "_tracks", 2);
11060
- __decorateClass([
11061
- state4()
11062
- ], DawEditorElement.prototype, "_engineTracks", 2);
12058
+ ], DawEditorElement.prototype, "_extras", 2);
11063
12059
  __decorateClass([
11064
12060
  state4()
11065
12061
  ], DawEditorElement.prototype, "_peaksData", 2);
@@ -11135,6 +12131,8 @@ var DawRecordButtonElement = class extends DawTransportButton {
11135
12131
  super(...arguments);
11136
12132
  this._isRecording = false;
11137
12133
  this._targetRef = null;
12134
+ /** The listeners on `_targetRef`, aborted when the target changes or the button disconnects. */
12135
+ this._targetListeners = null;
11138
12136
  this._onStart = () => {
11139
12137
  this._isRecording = true;
11140
12138
  };
@@ -11165,15 +12163,16 @@ var DawRecordButtonElement = class extends DawTransportButton {
11165
12163
  this._cleanupListeners();
11166
12164
  if (!target) return;
11167
12165
  this._targetRef = target;
11168
- target.addEventListener("daw-recording-start", this._onStart);
11169
- target.addEventListener("daw-recording-complete", this._onComplete);
11170
- target.addEventListener("daw-recording-error", this._onError);
12166
+ this._targetListeners = new AbortController();
12167
+ const { signal } = this._targetListeners;
12168
+ target.addEventListener("daw-recording-start", this._onStart, { signal });
12169
+ target.addEventListener("daw-recording-complete", this._onComplete, { signal });
12170
+ target.addEventListener("daw-recording-error", this._onError, { signal });
11171
12171
  }
11172
12172
  _cleanupListeners() {
11173
12173
  if (this._targetRef) {
11174
- this._targetRef.removeEventListener("daw-recording-start", this._onStart);
11175
- this._targetRef.removeEventListener("daw-recording-complete", this._onComplete);
11176
- this._targetRef.removeEventListener("daw-recording-error", this._onError);
12174
+ this._targetListeners?.abort();
12175
+ this._targetListeners = null;
11177
12176
  this._targetRef = null;
11178
12177
  }
11179
12178
  }
@@ -11244,6 +12243,9 @@ var DawKeyboardShortcutsElement = class extends LitElement16 {
11244
12243
  this._customShortcuts = [];
11245
12244
  this._editor = null;
11246
12245
  this._cachedShortcuts = null;
12246
+ // --- Lifecycle ---
12247
+ /** The listeners of this connection, aborted in disconnectedCallback. */
12248
+ this._listeners = null;
11247
12249
  // --- Event handler ---
11248
12250
  this._onKeyDown = (e) => {
11249
12251
  const shortcuts = this.shortcuts;
@@ -11302,7 +12304,6 @@ var DawKeyboardShortcutsElement = class extends LitElement16 {
11302
12304
  updated() {
11303
12305
  this._cachedShortcuts = null;
11304
12306
  }
11305
- // --- Lifecycle ---
11306
12307
  connectedCallback() {
11307
12308
  super.connectedCallback();
11308
12309
  for (const prop of [
@@ -11323,11 +12324,15 @@ var DawKeyboardShortcutsElement = class extends LitElement16 {
11323
12324
  "[dawcore] <daw-keyboard-shortcuts> must be placed inside a <daw-editor>. Preset shortcuts (playback, splitting, undo) will be inactive; only customShortcuts will fire."
11324
12325
  );
11325
12326
  }
11326
- document.addEventListener("keydown", this._onKeyDown);
12327
+ this._listeners?.abort();
12328
+ this._listeners = new AbortController();
12329
+ const { signal } = this._listeners;
12330
+ document.addEventListener("keydown", this._onKeyDown, { signal });
11327
12331
  }
11328
12332
  disconnectedCallback() {
11329
12333
  super.disconnectedCallback();
11330
- document.removeEventListener("keydown", this._onKeyDown);
12334
+ this._listeners?.abort();
12335
+ this._listeners = null;
11331
12336
  this._editor = null;
11332
12337
  }
11333
12338
  // No shadow DOM — render-less element
@@ -11653,20 +12658,25 @@ var DawTimeDisplayElement = class extends LitElement18 {
11653
12658
  this._format = detail.format;
11654
12659
  }
11655
12660
  };
12661
+ /** The listeners of this connection, aborted in disconnectedCallback. */
12662
+ this._listeners = null;
11656
12663
  }
11657
12664
  get target() {
11658
12665
  return resolveTransportTarget(this);
11659
12666
  }
11660
12667
  connectedCallback() {
11661
12668
  super.connectedCallback();
11662
- document.addEventListener("daw-timeupdate", this._onTimeUpdate);
11663
- document.addEventListener("daw-time-format-change", this._onFormatChange);
12669
+ this._listeners?.abort();
12670
+ this._listeners = new AbortController();
12671
+ const { signal } = this._listeners;
12672
+ document.addEventListener("daw-timeupdate", this._onTimeUpdate, { signal });
12673
+ document.addEventListener("daw-time-format-change", this._onFormatChange, { signal });
11664
12674
  requestAnimationFrame(() => this._syncFromTarget());
11665
12675
  }
11666
12676
  disconnectedCallback() {
11667
12677
  super.disconnectedCallback();
11668
- document.removeEventListener("daw-timeupdate", this._onTimeUpdate);
11669
- document.removeEventListener("daw-time-format-change", this._onFormatChange);
12678
+ this._listeners?.abort();
12679
+ this._listeners = null;
11670
12680
  }
11671
12681
  _syncFromTarget() {
11672
12682
  if (!this.isConnected) return;
@@ -11737,6 +12747,8 @@ var DawTimeFormatElement = class extends LitElement19 {
11737
12747
  warnUnsupportedOnce(this, ["setTimeFormat"]);
11738
12748
  }
11739
12749
  };
12750
+ /** The listeners of this connection, aborted in disconnectedCallback. */
12751
+ this._listeners = null;
11740
12752
  }
11741
12753
  get target() {
11742
12754
  return resolveTransportTarget(this);
@@ -11754,9 +12766,12 @@ var DawTimeFormatElement = class extends LitElement19 {
11754
12766
  }
11755
12767
  connectedCallback() {
11756
12768
  super.connectedCallback();
11757
- document.addEventListener("daw-time-format-change", this._onFormatChange);
11758
- this.addEventListener("pointerdown", this._onPointerDown);
11759
- this.addEventListener("pointerenter", this._onPointerEnter);
12769
+ this._listeners?.abort();
12770
+ this._listeners = new AbortController();
12771
+ const { signal } = this._listeners;
12772
+ document.addEventListener("daw-time-format-change", this._onFormatChange, { signal });
12773
+ this.addEventListener("pointerdown", this._onPointerDown, { signal });
12774
+ this.addEventListener("pointerenter", this._onPointerEnter, { signal });
11760
12775
  requestAnimationFrame(() => {
11761
12776
  if (!this.isConnected) return;
11762
12777
  const target = this.target;
@@ -11768,9 +12783,8 @@ var DawTimeFormatElement = class extends LitElement19 {
11768
12783
  }
11769
12784
  disconnectedCallback() {
11770
12785
  super.disconnectedCallback();
11771
- document.removeEventListener("daw-time-format-change", this._onFormatChange);
11772
- this.removeEventListener("pointerdown", this._onPointerDown);
11773
- this.removeEventListener("pointerenter", this._onPointerEnter);
12786
+ this._listeners?.abort();
12787
+ this._listeners = null;
11774
12788
  }
11775
12789
  updated() {
11776
12790
  const select = this.shadowRoot?.querySelector("select");
@@ -11825,7 +12839,7 @@ DawTimeFormatElement = __decorateClass([
11825
12839
  // src/elements/daw-player.ts
11826
12840
  import { LitElement as LitElement20, html as html18, css as css17 } from "lit";
11827
12841
  import { customElement as customElement23, property as property16, state as state8 } from "lit/decorators.js";
11828
- import { repeat } from "lit/directives/repeat.js";
12842
+ import { repeat as repeat2 } from "lit/directives/repeat.js";
11829
12843
  import { MediaElementPlayout } from "@waveform-playlist/media-element-playout";
11830
12844
  var MIN_RATE = 0.25;
11831
12845
  var MAX_RATE = 4;
@@ -11855,6 +12869,8 @@ var DawPlayerElement = class extends LitElement20 {
11855
12869
  this._channelPeaks = [];
11856
12870
  this._sampleRate = 48e3;
11857
12871
  this._resizeObserver = null;
12872
+ /** The peaks fetch in flight: a newer peaks-src or a disconnect aborts it (#848, D7). */
12873
+ this._peaksFetch = null;
11858
12874
  this._onPointerDown = (e) => {
11859
12875
  const area = e.currentTarget;
11860
12876
  const width = area.clientWidth;
@@ -11928,6 +12944,7 @@ var DawPlayerElement = class extends LitElement20 {
11928
12944
  const area = this.shadowRoot?.querySelector(".waveform-area");
11929
12945
  if (area) this._resizeObserver?.observe(area);
11930
12946
  });
12947
+ if (rebuilt && this.peaksSrc && !this._peaksSettled) void this._loadPeaks();
11931
12948
  if (rebuilt && this.src) {
11932
12949
  this._loadSource();
11933
12950
  this._playhead?.setPosition(0);
@@ -11949,7 +12966,7 @@ var DawPlayerElement = class extends LitElement20 {
11949
12966
  style="height:${this.waveHeight}px"
11950
12967
  @pointerdown=${this._onPointerDown}
11951
12968
  >
11952
- ${repeat(
12969
+ ${repeat2(
11953
12970
  this._channelPeaks,
11954
12971
  (_p, i) => i,
11955
12972
  (peaks) => html18`<daw-waveform
@@ -11972,6 +12989,8 @@ var DawPlayerElement = class extends LitElement20 {
11972
12989
  if (changed.has("mono")) this._renderWaveform();
11973
12990
  }
11974
12991
  async _loadPeaks() {
12992
+ this._peaksFetch?.abort();
12993
+ this._peaksFetch = null;
11975
12994
  this._waveformData = null;
11976
12995
  this._readyDispatched = false;
11977
12996
  this._peaksSettled = false;
@@ -11982,8 +13001,11 @@ var DawPlayerElement = class extends LitElement20 {
11982
13001
  return;
11983
13002
  }
11984
13003
  const requested = this.peaksSrc;
13004
+ const fetching = new AbortController();
13005
+ this._peaksFetch = fetching;
11985
13006
  try {
11986
- const wd = await loadWaveformDataFromUrl(requested);
13007
+ const wd = await loadWaveformDataFromUrl(requested, fetching.signal);
13008
+ if (this._peaksFetch === fetching) this._peaksFetch = null;
11987
13009
  if (this.peaksSrc !== requested) return;
11988
13010
  this._waveformData = wd;
11989
13011
  this._sampleRate = wd.sample_rate;
@@ -11991,6 +13013,7 @@ var DawPlayerElement = class extends LitElement20 {
11991
13013
  this._renderWaveform();
11992
13014
  this._maybeDispatchReady();
11993
13015
  } catch (err) {
13016
+ if (fetching.signal.aborted) return;
11994
13017
  if (this.peaksSrc !== requested) return;
11995
13018
  console.warn("[dawcore] <daw-player> failed to load peaks-src: " + String(err));
11996
13019
  this._peaksSettled = true;
@@ -12090,6 +13113,8 @@ var DawPlayerElement = class extends LitElement20 {
12090
13113
  this._engine.off("error", this._onError);
12091
13114
  this._engine.dispose();
12092
13115
  this._engineDisposed = true;
13116
+ this._peaksFetch?.abort();
13117
+ this._peaksFetch = null;
12093
13118
  }
12094
13119
  // --- Private event handlers (arrow fields for stable identity) ---
12095
13120
  _dispatch(name, detail) {
@@ -12116,6 +13141,10 @@ var DawPlayerElement = class extends LitElement20 {
12116
13141
  }
12117
13142
  };
12118
13143
  DawPlayerElement.styles = css17`
13144
+ /* The hidden attribute hides the element: :host sets display (modern-web-guidance custom-elements). */
13145
+ :host([hidden]) {
13146
+ display: none;
13147
+ }
12119
13148
  :host {
12120
13149
  display: block;
12121
13150
  position: relative;