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

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
 
@@ -2743,10 +2967,9 @@ function computeTemporalTicks(samplesPerPixel, sampleRate, duration, rulerHeight
2743
2967
  const { marker, bigStep, smallStep } = config;
2744
2968
  const canvasInfo = /* @__PURE__ */ new Map();
2745
2969
  const labels = [];
2746
- const pixPerSec = sampleRate / samplesPerPixel;
2747
2970
  for (let counter = 0; ; counter += smallStep) {
2748
- const pix = Math.floor(counter / 1e3 * pixPerSec);
2749
- if (pix >= widthX) break;
2971
+ const pix = Math.floor(counter * sampleRate / (1e3 * samplesPerPixel));
2972
+ if (!(pix < widthX)) break;
2750
2973
  if (counter % marker === 0) {
2751
2974
  canvasInfo.set(pix, rulerHeight);
2752
2975
  labels.push({ pix, text: formatTime(counter) });
@@ -2981,15 +3204,6 @@ function mixOfTrack(track) {
2981
3204
  function mixOfElement(el) {
2982
3205
  return { volume: el.volume, pan: el.pan, muted: el.muted, soloed: el.soloed };
2983
3206
  }
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
3207
  function clampNumber(value, min, max) {
2994
3208
  return Math.max(min, Math.min(max, Number(value)));
2995
3209
  }
@@ -3200,6 +3414,10 @@ var DawTrackControlsElement = class extends LitElement12 {
3200
3414
  }
3201
3415
  };
3202
3416
  DawTrackControlsElement.styles = css8`
3417
+ /* The hidden attribute hides the element: :host sets display (modern-web-guidance custom-elements). */
3418
+ :host([hidden]) {
3419
+ display: none;
3420
+ }
3203
3421
  :host {
3204
3422
  display: flex;
3205
3423
  flex-direction: column;
@@ -3661,6 +3879,8 @@ var ViewportController = class {
3661
3879
  this._scrollContainer = null;
3662
3880
  this._lastScrollLeft = 0;
3663
3881
  this._resizeObserver = null;
3882
+ /** The scroll listener on `_scrollContainer`, aborted when it is replaced or the host disconnects. */
3883
+ this._scrollListener = null;
3664
3884
  // Permissive defaults: render everything until scroll container is attached
3665
3885
  this.visibleStart = -Infinity;
3666
3886
  this.visibleEnd = Infinity;
@@ -3692,16 +3912,21 @@ var ViewportController = class {
3692
3912
  });
3693
3913
  }
3694
3914
  hostDisconnected() {
3695
- this._scrollContainer?.removeEventListener("scroll", this._onScroll);
3915
+ this._scrollListener?.abort();
3916
+ this._scrollListener = null;
3696
3917
  this._resizeObserver?.disconnect();
3697
3918
  this._resizeObserver = null;
3698
3919
  this._scrollContainer = null;
3699
3920
  }
3700
3921
  _attachScrollContainer(container) {
3701
- this._scrollContainer?.removeEventListener("scroll", this._onScroll);
3922
+ this._scrollListener?.abort();
3702
3923
  this._resizeObserver?.disconnect();
3703
3924
  this._scrollContainer = container;
3704
- container.addEventListener("scroll", this._onScroll, { passive: true });
3925
+ this._scrollListener = new AbortController();
3926
+ container.addEventListener("scroll", this._onScroll, {
3927
+ passive: true,
3928
+ signal: this._scrollListener.signal
3929
+ });
3705
3930
  this._update(container.scrollLeft, container.clientWidth);
3706
3931
  if (typeof ResizeObserver !== "undefined") {
3707
3932
  this._resizeObserver = new ResizeObserver(() => {
@@ -3728,9 +3953,11 @@ var ViewportController = class {
3728
3953
  var AudioResumeController = class {
3729
3954
  constructor(host) {
3730
3955
  this._target = null;
3956
+ /** The gesture listeners on `_target`: one controller per attach. */
3957
+ this._listeners = null;
3731
3958
  this._attached = false;
3732
3959
  this._generation = 0;
3733
- this._onGesture = (e) => {
3960
+ this._onGesture = () => {
3734
3961
  let ctx;
3735
3962
  try {
3736
3963
  ctx = this._host.audioContext;
@@ -3754,11 +3981,7 @@ var AudioResumeController = class {
3754
3981
  );
3755
3982
  });
3756
3983
  }
3757
- const otherType = e.type === "pointerdown" ? "keydown" : "pointerdown";
3758
- this._target?.removeEventListener(otherType, this._onGesture, {
3759
- capture: true
3760
- });
3761
- this._target = null;
3984
+ this._removeListeners();
3762
3985
  };
3763
3986
  this._host = host;
3764
3987
  host.addController(this);
@@ -3780,13 +4003,17 @@ var AudioResumeController = class {
3780
4003
  if (!resolvedTarget) return;
3781
4004
  this._target = resolvedTarget;
3782
4005
  this._attached = true;
4006
+ this._listeners = new AbortController();
4007
+ const { signal } = this._listeners;
3783
4008
  resolvedTarget.addEventListener("pointerdown", this._onGesture, {
3784
4009
  once: true,
3785
- capture: true
4010
+ capture: true,
4011
+ signal
3786
4012
  });
3787
4013
  resolvedTarget.addEventListener("keydown", this._onGesture, {
3788
4014
  once: true,
3789
- capture: true
4015
+ capture: true,
4016
+ signal
3790
4017
  });
3791
4018
  });
3792
4019
  }
@@ -3810,12 +4037,8 @@ var AudioResumeController = class {
3810
4037
  }
3811
4038
  _removeListeners() {
3812
4039
  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
- });
4040
+ this._listeners?.abort();
4041
+ this._listeners = null;
3819
4042
  this._target = null;
3820
4043
  }
3821
4044
  };
@@ -3839,6 +4062,8 @@ import {
3839
4062
  var RecordingController = class {
3840
4063
  constructor(host) {
3841
4064
  this._sessions = /* @__PURE__ */ new Map();
4065
+ /** Each session's mic-unplug listener, aborted when the session ends. */
4066
+ this._trackEndedListeners = /* @__PURE__ */ new WeakMap();
3842
4067
  /** Track IDs with a startRecording in flight (session not yet in _sessions).
3843
4068
  * The session is only set after several awaits — without this, two rapid
3844
4069
  * start calls both pass the _sessions guard and build two capture
@@ -3967,8 +4192,6 @@ var RecordingController = class {
3967
4192
  latencySamples,
3968
4193
  clipName: options.clipName,
3969
4194
  wasOverdub: options.overdub ?? false,
3970
- _onTrackEnded: onTrackEnded,
3971
- _audioTrack: audioTrack,
3972
4195
  stopAckResolve: null,
3973
4196
  stopPromise: null,
3974
4197
  stopping: false
@@ -3980,7 +4203,9 @@ var RecordingController = class {
3980
4203
  source.connect(workletNode);
3981
4204
  workletNode.port.postMessage({ command: "start", channelCount });
3982
4205
  if (audioTrack && onTrackEnded) {
3983
- audioTrack.addEventListener("ended", onTrackEnded);
4206
+ const listener = new AbortController();
4207
+ this._trackEndedListeners.set(session, listener);
4208
+ audioTrack.addEventListener("ended", onTrackEnded, { signal: listener.signal });
3984
4209
  }
3985
4210
  this._host._engine?.setTrackRecording(trackId, true);
3986
4211
  this._host.dispatchEvent(
@@ -4242,9 +4467,8 @@ var RecordingController = class {
4242
4467
  }
4243
4468
  }
4244
4469
  _removeTrackEndedListener(session) {
4245
- if (session._audioTrack && session._onTrackEnded) {
4246
- session._audioTrack.removeEventListener("ended", session._onTrackEnded);
4247
- }
4470
+ this._trackEndedListeners.get(session)?.abort();
4471
+ this._trackEndedListeners.delete(session);
4248
4472
  }
4249
4473
  _dispatchRecordingError(trackId, error) {
4250
4474
  this._host.dispatchEvent(
@@ -4316,6 +4540,8 @@ var AnnotationController = class {
4316
4540
  * Driven by daw-timeupdate, cleared on daw-stop, retained on pause.
4317
4541
  * Replaced immutably (a fresh Map) on every change. */
4318
4542
  this._playingIds = /* @__PURE__ */ new Map();
4543
+ /** The host listeners of this connection, aborted in hostDisconnected. */
4544
+ this._listeners = null;
4319
4545
  this._onDataChange = () => {
4320
4546
  this.deriveSecondsCaches();
4321
4547
  this._host.requestUpdate();
@@ -4367,11 +4593,14 @@ var AnnotationController = class {
4367
4593
  );
4368
4594
  }
4369
4595
  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);
4596
+ this._listeners?.abort();
4597
+ this._listeners = new AbortController();
4598
+ const { signal } = this._listeners;
4599
+ this._host.addEventListener("daw-annotation-update", this._onDataChange, { signal });
4600
+ this._host.addEventListener("daw-annotation-select", this._onDataChange, { signal });
4601
+ this._host.addEventListener("daw-annotation-connected", this._onDataChange, { signal });
4602
+ this._host.addEventListener("daw-timeupdate", this._onTimeUpdate, { signal });
4603
+ this._host.addEventListener("daw-stop", this._onStop, { signal });
4375
4604
  this._removalObserver = new MutationObserver((mutations) => {
4376
4605
  let changed = false;
4377
4606
  for (const m of mutations) {
@@ -4401,11 +4630,8 @@ var AnnotationController = class {
4401
4630
  this._removalObserver.observe(this._host, { childList: true, subtree: true });
4402
4631
  }
4403
4632
  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);
4633
+ this._listeners?.abort();
4634
+ this._listeners = null;
4409
4635
  this._removalObserver?.disconnect();
4410
4636
  this._removalObserver = null;
4411
4637
  this._tracks = [];
@@ -4635,6 +4861,8 @@ var PointerHandler = class {
4635
4861
  // still holds; zeroing only the host would desync the two).
4636
4862
  this._preDragSelectionStart = 0;
4637
4863
  this._preDragSelectionEnd = 0;
4864
+ /** The timeline's listeners of the seek / selection press in progress. */
4865
+ this._seekGesture = null;
4638
4866
  /** Cancels the armed clip drag; set while one is armed (#848). */
4639
4867
  this._cancelArmedClipDrag = null;
4640
4868
  this.onPointerDown = (e) => {
@@ -4651,11 +4879,10 @@ var PointerHandler = class {
4651
4879
  console.warn("[dawcore] setPointerCapture failed: " + String(err));
4652
4880
  }
4653
4881
  const onMove = (me) => clipHandler.onPointerMove(me);
4882
+ const gesture = new AbortController();
4654
4883
  const detach = (pointerId) => {
4655
4884
  this._cancelArmedClipDrag = null;
4656
- this._timeline?.removeEventListener("pointermove", onMove);
4657
- this._timeline?.removeEventListener("pointerup", onUp);
4658
- this._timeline?.removeEventListener("pointercancel", onCancel);
4885
+ gesture.abort();
4659
4886
  try {
4660
4887
  this._timeline?.releasePointerCapture(pointerId);
4661
4888
  } catch (err) {
@@ -4681,9 +4908,10 @@ var PointerHandler = class {
4681
4908
  );
4682
4909
  detach(downPointerId);
4683
4910
  };
4684
- this._timeline.addEventListener("pointermove", onMove);
4685
- this._timeline.addEventListener("pointerup", onUp);
4686
- this._timeline.addEventListener("pointercancel", onCancel);
4911
+ const { signal: signal2 } = gesture;
4912
+ this._timeline.addEventListener("pointermove", onMove, { signal: signal2 });
4913
+ this._timeline.addEventListener("pointerup", onUp, { signal: signal2 });
4914
+ this._timeline.addEventListener("pointercancel", onCancel, { signal: signal2 });
4687
4915
  }
4688
4916
  return;
4689
4917
  }
@@ -4706,9 +4934,12 @@ var PointerHandler = class {
4706
4934
  } catch (err) {
4707
4935
  console.warn("[dawcore] setPointerCapture failed: " + String(err));
4708
4936
  }
4709
- this._timeline.addEventListener("pointermove", this._onPointerMove);
4710
- this._timeline.addEventListener("pointerup", this._onPointerUp);
4711
- this._timeline.addEventListener("pointercancel", this._onPointerCancel);
4937
+ this._seekGesture?.abort();
4938
+ this._seekGesture = new AbortController();
4939
+ const { signal } = this._seekGesture;
4940
+ this._timeline.addEventListener("pointermove", this._onPointerMove, { signal });
4941
+ this._timeline.addEventListener("pointerup", this._onPointerUp, { signal });
4942
+ this._timeline.addEventListener("pointercancel", this._onPointerCancel, { signal });
4712
4943
  };
4713
4944
  this._onPointerMove = (e) => {
4714
4945
  if (!this._timeline) return;
@@ -4815,9 +5046,8 @@ var PointerHandler = class {
4815
5046
  "[dawcore] releasePointerCapture failed (may already be released): " + String(err)
4816
5047
  );
4817
5048
  }
4818
- this._timeline.removeEventListener("pointermove", this._onPointerMove);
4819
- this._timeline.removeEventListener("pointerup", this._onPointerUp);
4820
- this._timeline.removeEventListener("pointercancel", this._onPointerCancel);
5049
+ this._seekGesture?.abort();
5050
+ this._seekGesture = null;
4821
5051
  }
4822
5052
  _resetInteractionState() {
4823
5053
  this._isDragging = false;
@@ -4913,6 +5143,7 @@ var PointerHandler = class {
4913
5143
 
4914
5144
  // src/interactions/clip-pointer-handler.ts
4915
5145
  import { snapTickToGrid as snapTickToGrid2 } from "@waveform-playlist/core";
5146
+ import { constrainClipDrag } from "@waveform-playlist/engine";
4916
5147
  var ClipPointerHandler = class {
4917
5148
  constructor(host) {
4918
5149
  this._mode = null;
@@ -4929,6 +5160,10 @@ var ClipPointerHandler = class {
4929
5160
  this._originalOffsetSamples = 0;
4930
5161
  this._originalDurationSamples = 0;
4931
5162
  this._originalStartSample = 0;
5163
+ // Move: the dragged clip and the track's loaded clips, sorted, at drag start
5164
+ this._moveClip = null;
5165
+ this._moveSorted = [];
5166
+ this._committing = false;
4932
5167
  this._host = host;
4933
5168
  }
4934
5169
  /**
@@ -4953,6 +5188,18 @@ var ClipPointerHandler = class {
4953
5188
  }
4954
5189
  return Math.round(totalDeltaPx * h.renderSamplesPerPixel);
4955
5190
  }
5191
+ /** A sample delta from `anchorSample` in pixels: in tick space in beats mode,
5192
+ * so the drawn position does not drift from the sample round-trip. */
5193
+ _samplesToPx(anchorSample, deltaSamples) {
5194
+ const h = this._host;
5195
+ if (h.scaleMode === "beats") {
5196
+ const anchorSec = anchorSample / h.effectiveSampleRate;
5197
+ const anchorTick = h._secondsToTicks(anchorSec);
5198
+ const newTick = h._secondsToTicks(anchorSec + deltaSamples / h.effectiveSampleRate);
5199
+ return Math.round((newTick - anchorTick) / h.ticksPerPixel);
5200
+ }
5201
+ return Math.round(deltaSamples / h.renderSamplesPerPixel);
5202
+ }
4956
5203
  /** Returns true if a drag interaction is currently in progress. */
4957
5204
  get isActive() {
4958
5205
  return this._mode !== null;
@@ -4962,6 +5209,21 @@ var ClipPointerHandler = class {
4962
5209
  get isDragging() {
4963
5210
  return this._isDragging;
4964
5211
  }
5212
+ /**
5213
+ * The clip being dragged (past the threshold) with its bounds at the drag's
5214
+ * start, or null; null too while the release makes its one arrangement
5215
+ * call, so that call is not taken for an outside change (#848).
5216
+ */
5217
+ get draggedClip() {
5218
+ if (!this._isDragging || this._committing) return null;
5219
+ return {
5220
+ trackId: this._trackId,
5221
+ clipId: this._clipId,
5222
+ startSample: this._originalStartSample,
5223
+ durationSamples: this._originalDurationSamples,
5224
+ offsetSamples: this._originalOffsetSamples
5225
+ };
5226
+ }
4965
5227
  /**
4966
5228
  * Attempts to handle a pointerdown event on the given target element.
4967
5229
  * Returns true if the target is a recognized clip interaction element.
@@ -4999,11 +5261,10 @@ var ClipPointerHandler = class {
4999
5261
  }
5000
5262
  /**
5001
5263
  * 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.
5264
+ * clip's bounds now, not at the press, so a drag after an undo made during
5265
+ * the press starts from the clip as the undo left it (#848, review of
5266
+ * #915). Returns false when the clip is gone (the undo removed it): the
5267
+ * press is dropped.
5007
5268
  */
5008
5269
  _startDrag() {
5009
5270
  const engine = this._host.engine;
@@ -5015,13 +5276,17 @@ var ClipPointerHandler = class {
5015
5276
  this._originalStartSample = bounds.startSample;
5016
5277
  this._originalOffsetSamples = bounds.offsetSamples;
5017
5278
  this._originalDurationSamples = bounds.durationSamples;
5018
- engine.beginTransaction();
5279
+ if (this._mode === "move") {
5280
+ const track = engine.getState().tracks.find((t) => t.id === trackId);
5281
+ const clip = track?.clips.find((c) => c.id === clipId) ?? null;
5282
+ if (!track || !clip) return false;
5283
+ this._moveClip = clip;
5284
+ this._moveSorted = [...track.clips].sort((a, b) => a.startSample - b.startSample);
5285
+ }
5019
5286
  } else {
5020
- console.warn(
5021
- "[dawcore] drag start: engine unavailable, drag mutations will not be grouped for undo"
5022
- );
5287
+ console.warn("[dawcore] drag start: engine unavailable, the drag will not be applied");
5023
5288
  }
5024
- if (this._mode === "trim-left" || this._mode === "trim-right") {
5289
+ {
5025
5290
  const container = this._host.shadowRoot?.querySelector(
5026
5291
  `.clip-container[data-clip-id="${clipId}"]`
5027
5292
  );
@@ -5030,7 +5295,7 @@ var ClipPointerHandler = class {
5030
5295
  this._originalLeft = parseFloat(container.style.left) || 0;
5031
5296
  this._originalWidth = parseFloat(container.style.width) || 0;
5032
5297
  } else {
5033
- console.warn("[dawcore] clip container not found for trim visual feedback: " + clipId);
5298
+ console.warn("[dawcore] clip container not found for drag visual feedback: " + clipId);
5034
5299
  }
5035
5300
  }
5036
5301
  return true;
@@ -5054,10 +5319,13 @@ var ClipPointerHandler = class {
5054
5319
  if (!engine) return;
5055
5320
  if (this._mode === "move") {
5056
5321
  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;
5322
+ const clip = this._moveClip;
5323
+ const index = clip ? this._moveSorted.indexOf(clip) : -1;
5324
+ const delta = clip && index !== -1 ? constrainClipDrag(clip, totalSnappedDelta, this._moveSorted, index) : totalSnappedDelta;
5325
+ this._cumulativeDeltaSamples = delta;
5326
+ if (this._clipContainer) {
5327
+ const deltaPx = this._samplesToPx(this._originalStartSample, delta);
5328
+ this._clipContainer.style.left = this._originalLeft + deltaPx + "px";
5061
5329
  }
5062
5330
  } else {
5063
5331
  const boundary = this._mode === "trim-left" ? "left" : "right";
@@ -5069,17 +5337,7 @@ var ClipPointerHandler = class {
5069
5337
  boundary,
5070
5338
  rawDeltaSamples
5071
5339
  );
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
- }
5340
+ const deltaPx = this._samplesToPx(anchor, deltaSamples);
5083
5341
  this._cumulativeDeltaSamples = deltaSamples;
5084
5342
  if (this._clipContainer) {
5085
5343
  if (this._mode === "trim-left") {
@@ -5118,31 +5376,39 @@ var ClipPointerHandler = class {
5118
5376
  if (this._mode === null) return;
5119
5377
  try {
5120
5378
  if (!this._isDragging || this._cumulativeDeltaSamples === 0) {
5121
- this._restoreTrimVisual();
5379
+ this._restoreVisual();
5122
5380
  return;
5123
5381
  }
5124
5382
  const engine = this._host.engine;
5383
+ this._committing = true;
5125
5384
  if (this._mode === "move") {
5385
+ this._restoreVisual();
5126
5386
  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
- })
5387
+ const applied = engine.moveClip(
5388
+ this._trackId,
5389
+ this._clipId,
5390
+ this._cumulativeDeltaSamples
5138
5391
  );
5392
+ if (applied !== 0) {
5393
+ this._host.dispatchEvent(
5394
+ new CustomEvent("daw-clip-move", {
5395
+ bubbles: true,
5396
+ composed: true,
5397
+ detail: {
5398
+ trackId: this._trackId,
5399
+ clipId: this._clipId,
5400
+ deltaSamples: applied
5401
+ }
5402
+ })
5403
+ );
5404
+ }
5139
5405
  } else {
5140
5406
  console.warn(
5141
- "[dawcore] engine unavailable at move drop \u2014 audio may be out of sync for track " + this._trackId
5407
+ "[dawcore] engine unavailable at move drop \u2014 move not applied for clip " + this._clipId
5142
5408
  );
5143
5409
  }
5144
5410
  } else {
5145
- this._restoreTrimVisual();
5411
+ this._restoreVisual();
5146
5412
  const boundary = this._mode === "trim-left" ? "left" : "right";
5147
5413
  if (engine) {
5148
5414
  engine.trimClip(this._trackId, this._clipId, boundary, this._cumulativeDeltaSamples);
@@ -5165,13 +5431,7 @@ var ClipPointerHandler = class {
5165
5431
  }
5166
5432
  }
5167
5433
  } finally {
5168
- if (this._isDragging) {
5169
- if (this._cumulativeDeltaSamples !== 0) {
5170
- this._host.engine?.commitTransaction();
5171
- } else {
5172
- this._host.engine?.abortTransaction();
5173
- }
5174
- }
5434
+ this._committing = false;
5175
5435
  this._reset();
5176
5436
  }
5177
5437
  }
@@ -5179,16 +5439,13 @@ var ClipPointerHandler = class {
5179
5439
  *
5180
5440
  * pointercancel fires INSTEAD of pointerup on touch interruption, pen
5181
5441
  * 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). */
5442
+ * armed (hover keeps moving the clip). The drag wrote nothing to the
5443
+ * arrangement, so reverting is putting the view back. */
5186
5444
  onPointerCancel(_e) {
5187
5445
  if (this._mode === null) return;
5188
5446
  try {
5189
- this._restoreTrimVisual();
5447
+ this._restoreVisual();
5190
5448
  } finally {
5191
- if (this._isDragging) this._host.engine?.abortTransaction();
5192
5449
  this._reset();
5193
5450
  }
5194
5451
  }
@@ -5210,11 +5467,11 @@ var ClipPointerHandler = class {
5210
5467
  return true;
5211
5468
  }
5212
5469
  /** Restore clip container CSS AND waveform peaks to original values after
5213
- * a trim visual preview. Peaks matter: the drag wrote re-extracted peak
5470
+ * a drag's visual preview. Peaks matter: a trim wrote re-extracted peak
5214
5471
  * arrays imperatively onto the <daw-waveform> elements (bypassing Lit), and
5215
- * a cancelled/zero-delta trim makes no engine mutation — so no statechange
5472
+ * a cancelled/zero-delta drag makes no engine mutation — so no statechange
5216
5473
  * re-render will ever repair them. */
5217
- _restoreTrimVisual() {
5474
+ _restoreVisual() {
5218
5475
  if (this._clipContainer) {
5219
5476
  this._clipContainer.style.left = this._originalLeft + "px";
5220
5477
  this._clipContainer.style.width = this._originalWidth + "px";
@@ -5242,6 +5499,8 @@ var ClipPointerHandler = class {
5242
5499
  this._originalOffsetSamples = 0;
5243
5500
  this._originalDurationSamples = 0;
5244
5501
  this._originalStartSample = 0;
5502
+ this._moveClip = null;
5503
+ this._moveSorted = [];
5245
5504
  }
5246
5505
  };
5247
5506
 
@@ -5275,9 +5534,12 @@ var AnnotationDragHandler = class {
5275
5534
  if (index === -1) return;
5276
5535
  const edge = isBoundary ? boundary.getAttribute("data-edge") : null;
5277
5536
  const captureEl = isBoundary ? boundary : box;
5537
+ this._drag?.listeners.abort();
5538
+ const listeners = new AbortController();
5278
5539
  this._drag = {
5279
5540
  track,
5280
5541
  captureEl,
5542
+ listeners,
5281
5543
  pointerId: e.pointerId,
5282
5544
  startClientX: e.clientX,
5283
5545
  moved: false,
@@ -5292,9 +5554,10 @@ var AnnotationDragHandler = class {
5292
5554
  captureEl.setPointerCapture(e.pointerId);
5293
5555
  } catch {
5294
5556
  }
5295
- captureEl.addEventListener("pointermove", this._onPointerMove);
5296
- captureEl.addEventListener("pointerup", this._onPointerUp);
5297
- captureEl.addEventListener("pointercancel", this._onPointerCancel);
5557
+ const { signal } = listeners;
5558
+ captureEl.addEventListener("pointermove", this._onPointerMove, { signal });
5559
+ captureEl.addEventListener("pointerup", this._onPointerUp, { signal });
5560
+ captureEl.addEventListener("pointercancel", this._onPointerCancel, { signal });
5298
5561
  };
5299
5562
  /** Non-private (underscore convention) so tests can drive moves directly. */
5300
5563
  this._onPointerMove = (e) => {
@@ -5399,9 +5662,7 @@ var AnnotationDragHandler = class {
5399
5662
  drag.captureEl.releasePointerCapture(drag.pointerId);
5400
5663
  } catch {
5401
5664
  }
5402
- drag.captureEl.removeEventListener("pointermove", this._onPointerMove);
5403
- drag.captureEl.removeEventListener("pointerup", this._onPointerUp);
5404
- drag.captureEl.removeEventListener("pointercancel", this._onPointerCancel);
5665
+ drag.listeners.abort();
5405
5666
  this._drag = null;
5406
5667
  }
5407
5668
  };
@@ -5418,6 +5679,8 @@ var TrackReorderHandler = class _TrackReorderHandler {
5418
5679
  this._fromIndex = 0;
5419
5680
  this._targetIndex = 0;
5420
5681
  this._gripEl = null;
5682
+ /** The grip's listeners of the drag in progress: one controller per drag. */
5683
+ this._gesture = null;
5421
5684
  this.onGrab = (trackId, e, gripEl) => {
5422
5685
  if (this._trackId !== null) return;
5423
5686
  const column = this._host.shadowRoot?.querySelector(".controls-column");
@@ -5467,9 +5730,11 @@ var TrackReorderHandler = class _TrackReorderHandler {
5467
5730
  gripEl.setPointerCapture(e.pointerId);
5468
5731
  } catch {
5469
5732
  }
5470
- gripEl.addEventListener("pointermove", this._onPointerMove);
5471
- gripEl.addEventListener("pointerup", this._onPointerUp);
5472
- gripEl.addEventListener("pointercancel", this._onPointerCancel);
5733
+ this._gesture = new AbortController();
5734
+ const { signal } = this._gesture;
5735
+ gripEl.addEventListener("pointermove", this._onPointerMove, { signal });
5736
+ gripEl.addEventListener("pointerup", this._onPointerUp, { signal });
5737
+ gripEl.addEventListener("pointercancel", this._onPointerCancel, { signal });
5473
5738
  };
5474
5739
  this._onPointerMove = (e) => {
5475
5740
  if (e.pointerId !== this._pointerId || this._trackId === null) return;
@@ -5539,6 +5804,11 @@ var TrackReorderHandler = class _TrackReorderHandler {
5539
5804
  static _reducedMotion() {
5540
5805
  return typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
5541
5806
  }
5807
+ /** The dragged track and the order of the rows at the grab (#848), or null. */
5808
+ get draggedTrack() {
5809
+ if (this._trackId === null) return null;
5810
+ return { trackId: this._trackId, order: this._rows.map((r) => r.trackId) };
5811
+ }
5542
5812
  /** True from the grab until the drag ends or is cancelled. */
5543
5813
  get isActive() {
5544
5814
  return this._trackId !== null;
@@ -5568,9 +5838,8 @@ var TrackReorderHandler = class _TrackReorderHandler {
5568
5838
  this._lanes = [];
5569
5839
  const grip = this._gripEl;
5570
5840
  if (grip) {
5571
- grip.removeEventListener("pointermove", this._onPointerMove);
5572
- grip.removeEventListener("pointerup", this._onPointerUp);
5573
- grip.removeEventListener("pointercancel", this._onPointerCancel);
5841
+ this._gesture?.abort();
5842
+ this._gesture = null;
5574
5843
  try {
5575
5844
  grip.releasePointerCapture(this._pointerId);
5576
5845
  } catch {
@@ -5634,13 +5903,66 @@ function parseDisplayTime(value, format) {
5634
5903
  return Math.max(0, seconds);
5635
5904
  }
5636
5905
 
5906
+ // src/interactions/abort.ts
5907
+ function abortError(message) {
5908
+ return new DOMException(message, "AbortError");
5909
+ }
5910
+ function isAbortError(error) {
5911
+ return error?.name === "AbortError";
5912
+ }
5913
+ function reasonOf(signal) {
5914
+ return signal.reason;
5915
+ }
5916
+ var PlaySignals = class {
5917
+ constructor() {
5918
+ this._controllers = /* @__PURE__ */ new WeakMap();
5919
+ }
5920
+ /** The signal of an arrangement: aborted when it is next swapped out. */
5921
+ signalOf(arrangement) {
5922
+ let controller = this._controllers.get(arrangement);
5923
+ if (!controller) {
5924
+ controller = new AbortController();
5925
+ this._controllers.set(arrangement, controller);
5926
+ }
5927
+ return controller.signal;
5928
+ }
5929
+ /** The arrangement leaves play: its waits end with `reason`; a later play gets a new signal. */
5930
+ swappedOut(arrangement, reason) {
5931
+ const controller = this._controllers.get(arrangement);
5932
+ this._controllers.delete(arrangement);
5933
+ controller?.abort(reason);
5934
+ }
5935
+ };
5936
+ function untilAborted(promise, signal) {
5937
+ if (!signal) return promise;
5938
+ if (signal.aborted) return Promise.reject(reasonOf(signal));
5939
+ return new Promise((resolve, reject) => {
5940
+ const done = new AbortController();
5941
+ signal.addEventListener("abort", () => reject(reasonOf(signal)), { signal: done.signal });
5942
+ promise.then(
5943
+ (value) => {
5944
+ done.abort();
5945
+ resolve(value);
5946
+ },
5947
+ (error) => {
5948
+ done.abort();
5949
+ reject(error);
5950
+ }
5951
+ );
5952
+ });
5953
+ }
5954
+
5637
5955
  // src/interactions/file-loader.ts
5638
- async function loadFiles(host, files) {
5956
+ async function loadFiles(host, files, options = {}) {
5957
+ const signal = options.signal;
5958
+ if (signal?.aborted) throw reasonOf(signal);
5639
5959
  if (!files) {
5640
5960
  console.warn("[dawcore] loadFiles called with null/undefined");
5641
5961
  return { loaded: [], failed: [] };
5642
5962
  }
5643
5963
  const fileArray = Array.from(files);
5964
+ const target = host.arrangement;
5965
+ const played = host._operationSignal();
5644
5966
  const loaded = [];
5645
5967
  const failed = [];
5646
5968
  const dispatchLoadError = (file, error) => {
@@ -5660,6 +5982,10 @@ async function loadFiles(host, files) {
5660
5982
  dispatchLoadError(file, new Error("<daw-editor> was disconnected"));
5661
5983
  continue;
5662
5984
  }
5985
+ if (played.aborted) {
5986
+ dispatchLoadError(file, reasonOf(played));
5987
+ continue;
5988
+ }
5663
5989
  if (file.type && !file.type.startsWith("audio/")) {
5664
5990
  const error = new Error("Non-audio MIME type: " + file.type);
5665
5991
  console.warn("[dawcore] Skipping non-audio file: " + file.name + " (" + file.type + ")");
@@ -5668,12 +5994,26 @@ async function loadFiles(host, files) {
5668
5994
  }
5669
5995
  let trackId = null;
5670
5996
  try {
5671
- trackId = await host._addDroppedFile(file);
5672
- await host._whenTrackLoaded(trackId);
5997
+ const adding = host._addDroppedFile(file);
5998
+ trackId = await untilAborted(adding, signal).catch((err) => {
5999
+ if (signal?.aborted)
6000
+ void adding.then(
6001
+ (id) => host._discardTrack(id, target),
6002
+ () => {
6003
+ }
6004
+ );
6005
+ throw err;
6006
+ });
6007
+ await untilAborted(host._whenTrackLoaded(trackId), signal);
5673
6008
  loaded.push(trackId);
5674
6009
  } catch (err) {
6010
+ if (signal?.aborted) {
6011
+ for (const id of [...loaded, ...trackId !== null ? [trackId] : []])
6012
+ host._discardTrack(id, target);
6013
+ throw reasonOf(signal);
6014
+ }
5675
6015
  console.warn("[dawcore] Failed to load file: " + file.name + " \u2014 " + String(err));
5676
- if (trackId !== null) host._discardTrack(trackId);
6016
+ if (trackId !== null) host._discardTrack(trackId, target);
5677
6017
  dispatchLoadError(file, err);
5678
6018
  }
5679
6019
  }
@@ -5689,6 +6029,9 @@ async function loadMidiImpl(host, source, options = {}) {
5689
6029
  "loadMidi: startTime must be a non-negative finite number (got " + String(options.startTime) + ")"
5690
6030
  );
5691
6031
  }
6032
+ const signal = host._operationSignal(options.signal);
6033
+ const target = host.arrangement;
6034
+ if (signal.aborted) throw reasonOf(signal);
5692
6035
  let midiModule;
5693
6036
  try {
5694
6037
  midiModule = await import("@dawcore/midi");
@@ -5699,7 +6042,7 @@ async function loadMidiImpl(host, source, options = {}) {
5699
6042
  const { parseMidiUrl, parseMidiFile } = midiModule;
5700
6043
  let parsed;
5701
6044
  if (typeof source === "string") {
5702
- parsed = await parseMidiUrl(source, void 0, options.signal);
6045
+ parsed = await parseMidiUrl(source, void 0, signal);
5703
6046
  } else {
5704
6047
  let buffer;
5705
6048
  try {
@@ -5711,21 +6054,24 @@ async function loadMidiImpl(host, source, options = {}) {
5711
6054
  }
5712
6055
  parsed = parseMidiFile(buffer);
5713
6056
  }
5714
- const childrenBefore = new Set(host.querySelectorAll("daw-track"));
6057
+ if (signal.aborted) throw reasonOf(signal);
5715
6058
  const settlements = await Promise.allSettled(
5716
6059
  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
- })
6060
+ (t) => host.addTrack(
6061
+ {
6062
+ name: t.name,
6063
+ kind: "midi",
6064
+ clips: [
6065
+ {
6066
+ midiNotes: t.notes,
6067
+ midiChannel: t.channel,
6068
+ midiProgram: t.programNumber,
6069
+ start: startTime
6070
+ }
6071
+ ]
6072
+ },
6073
+ { signal }
6074
+ )
5729
6075
  )
5730
6076
  );
5731
6077
  const succeeded = [];
@@ -5738,17 +6084,14 @@ async function loadMidiImpl(host, source, options = {}) {
5738
6084
  }
5739
6085
  }
5740
6086
  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) {
6087
+ for (const trackId of succeeded) {
5745
6088
  try {
5746
- el.remove();
6089
+ host._discardTrack(trackId, target);
5747
6090
  } catch (cleanupErr) {
5748
6091
  console.warn("[dawcore] loadMidi cleanup failed for a track: " + String(cleanupErr));
5749
6092
  }
5750
6093
  }
5751
- await Promise.resolve();
6094
+ if (signal.aborted) throw reasonOf(signal);
5752
6095
  for (let i = 1; i < rejections.length; i++) {
5753
6096
  console.warn(
5754
6097
  "[dawcore] loadMidi: additional track failure (" + i + "): " + stringifyReason(rejections[i])
@@ -5828,33 +6171,6 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
5828
6171
  clip
5829
6172
  ]
5830
6173
  }));
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
6174
  if (host.isConnected) {
5859
6175
  host.dispatchEvent(
5860
6176
  new CustomEvent("daw-recording-clip-add", {
@@ -5937,18 +6253,18 @@ function performSplit(host, time) {
5937
6253
  );
5938
6254
  return false;
5939
6255
  }
6256
+ const leftClip = trackAfter.clips.find((c) => c.id === originalClipId);
5940
6257
  const newClips = trackAfter.clips.filter((c) => !clipIdsBefore.has(c.id));
5941
- if (newClips.length !== 2) {
6258
+ if (!leftClip || newClips.length !== 1) {
5942
6259
  if (newClips.length > 0) {
5943
6260
  console.warn(
5944
- "[dawcore] splitAtPlayhead: expected 2 new clips after split but got " + newClips.length
6261
+ "[dawcore] splitAtPlayhead: expected the original clip and 1 new clip after split but got " + newClips.length + " new"
5945
6262
  );
5946
6263
  }
5947
6264
  return false;
5948
6265
  }
5949
- const sorted = [...newClips].sort((a, b) => a.startSample - b.startSample);
5950
- const leftClipId = sorted[0].id;
5951
- const rightClipId = sorted[1].id;
6266
+ const leftClipId = leftClip.id;
6267
+ const rightClipId = newClips[0].id;
5952
6268
  host.dispatchEvent(
5953
6269
  new CustomEvent("daw-clip-split", {
5954
6270
  bubbles: true,
@@ -6248,6 +6564,113 @@ var LoadAnnouncer = class {
6248
6564
  }
6249
6565
  };
6250
6566
 
6567
+ // src/interactions/arrangement-view.ts
6568
+ import { isLoadingClip as isLoadingClip3 } from "@waveform-playlist/core";
6569
+ var views = /* @__PURE__ */ new WeakMap();
6570
+ function sameMix(a, b) {
6571
+ return a.volume === b.volume && a.pan === b.pan && a.muted === b.muted && a.soloed === b.soloed;
6572
+ }
6573
+ function loadedTrack(track, mix, recording) {
6574
+ const cached = views.get(track);
6575
+ if (cached && cached.recording === recording && sameMix(cached.mix, mix)) return cached.view;
6576
+ const view = {
6577
+ ...track,
6578
+ clips: track.clips.filter((c) => !isLoadingClip3(c)),
6579
+ volume: mix.volume,
6580
+ pan: mix.pan,
6581
+ muted: mix.muted || recording,
6582
+ soloed: mix.soloed
6583
+ };
6584
+ views.set(track, { mix: { ...mix }, recording, view });
6585
+ return view;
6586
+ }
6587
+ function mixOf(arrangement, trackId) {
6588
+ const mix = arrangement.getMixer().get(trackId);
6589
+ if (!mix) return null;
6590
+ return arrangement.recordingTrackIds.has(trackId) ? { ...mix, muted: true } : mix;
6591
+ }
6592
+ function clipSeconds(clip, fallbackSampleRate) {
6593
+ if (isLoadingClip3(clip)) {
6594
+ return { start: clip.start ?? 0, duration: clip.duration ?? 0, offset: clip.offset ?? 0 };
6595
+ }
6596
+ const sr = clip.sampleRate ?? fallbackSampleRate;
6597
+ return {
6598
+ start: clip.startSample / sr,
6599
+ duration: clip.durationSamples / sr,
6600
+ offset: clip.offsetSamples / sr
6601
+ };
6602
+ }
6603
+
6604
+ // src/interactions/arrangement-swap.ts
6605
+ import { isArrangement } from "@waveform-playlist/engine";
6606
+ function normalizeHandedIn(value, own) {
6607
+ if (value === null || value === void 0 || value === own) return null;
6608
+ if (!isArrangement(value)) {
6609
+ throw new TypeError(
6610
+ "[dawcore] editor.arrangement must be an arrangement made by createArrangement() (@waveform-playlist/engine), or null for the editor's own."
6611
+ );
6612
+ }
6613
+ return value;
6614
+ }
6615
+ function swapArrangement(host, next) {
6616
+ if (next === host._handedIn) return;
6617
+ if (host.isRecording) {
6618
+ console.warn(
6619
+ "[dawcore] editor.arrangement was not changed: a take is recording. Set it after stopRecording() resolves."
6620
+ );
6621
+ return;
6622
+ }
6623
+ host._cancelDrags();
6624
+ if (host.isPlaying) host.stop();
6625
+ const before = host._arrangement.getTracks().map((t) => t.id);
6626
+ host._releaseEngine();
6627
+ host._playArrangement(next);
6628
+ const kept = new Set(host._arrangement.getTracks().map((t) => t.id));
6629
+ for (const id of before) if (!kept.has(id)) host._disposeTrackChain(id);
6630
+ host._buildEngineIfReady();
6631
+ }
6632
+
6633
+ // src/interactions/drag-watch.ts
6634
+ import { isLoadingClip as isLoadingClip4 } from "@waveform-playlist/core";
6635
+ function clipDragChanged(arrangement, drag) {
6636
+ const clip = arrangement.getTracks().find((t) => t.id === drag.trackId)?.clips.find((c) => c.id === drag.clipId);
6637
+ if (!clip || isLoadingClip4(clip)) return true;
6638
+ return clip.startSample !== drag.startSample || clip.durationSamples !== drag.durationSamples || clip.offsetSamples !== drag.offsetSamples;
6639
+ }
6640
+ function trackDragChanged(arrangement, drag) {
6641
+ const ids = arrangement.getTracks().map((t) => t.id);
6642
+ if (!ids.includes(drag.trackId) || ids.length !== drag.order.length) return true;
6643
+ return ids.some((id, i) => id !== drag.order[i]);
6644
+ }
6645
+
6646
+ // src/interactions/clip-rehome.ts
6647
+ function trackHoldingClip(arrangement, clipId, exceptTrackId) {
6648
+ const track = arrangement.getTracks().find((t) => t.id !== exceptTrackId && t.clips.some((c) => c.id === clipId));
6649
+ return track?.id ?? null;
6650
+ }
6651
+ function moveClipToTrack(arrangement, fromTrackId, toTrackId, clipId, toKind) {
6652
+ const tracks = arrangement.getTracks();
6653
+ const clip = tracks.find((t) => t.id === fromTrackId)?.clips.find((c) => c.id === clipId);
6654
+ const to = tracks.find((t) => t.id === toTrackId);
6655
+ if (!clip || !to) return new Error('clip "' + clipId + '" or track "' + toTrackId + '" is gone');
6656
+ const isMidi = "midiNotes" in clip && clip.midiNotes != null;
6657
+ const kindError = clipKindError(to.name ?? "", toKind, isMidi, clip.name || clipId);
6658
+ if (kindError) return kindError;
6659
+ arrangement.beginTransaction();
6660
+ try {
6661
+ arrangement.updateTrack(fromTrackId, (t) => ({
6662
+ ...t,
6663
+ clips: t.clips.filter((c) => c.id !== clipId)
6664
+ }));
6665
+ arrangement.updateTrack(toTrackId, (t) => ({ ...t, clips: [...t.clips, clip] }));
6666
+ } catch (err) {
6667
+ arrangement.abortTransaction();
6668
+ return err instanceof Error ? err : new Error(String(err));
6669
+ }
6670
+ arrangement.commitTransaction();
6671
+ return null;
6672
+ }
6673
+
6251
6674
  // src/effects/effects-chain-controller.ts
6252
6675
  var idCounter = 0;
6253
6676
  var EffectsChainController = class {
@@ -7487,8 +7910,8 @@ async function buildOfflineChain(ctx, entries) {
7487
7910
 
7488
7911
  // src/interactions/peaks-loader.ts
7489
7912
  import WaveformData2 from "waveform-data";
7490
- async function loadWaveformDataFromUrl(src) {
7491
- const response = await fetch(src);
7913
+ async function loadWaveformDataFromUrl(src, signal) {
7914
+ const response = await fetch(src, signal ? { signal } : void 0);
7492
7915
  if (!response.ok) {
7493
7916
  throw new Error("[dawcore] Failed to fetch peaks data: " + response.statusText);
7494
7917
  }
@@ -7508,7 +7931,10 @@ var LINE_HEIGHT_PX = 16;
7508
7931
  var ScrollSyncController = class {
7509
7932
  constructor(host) {
7510
7933
  this._scrollContainer = null;
7511
- this._wheelTargets = /* @__PURE__ */ new Set();
7934
+ /** The scroll listener on `_scrollContainer`, aborted when it is replaced or detached. */
7935
+ this._scrollListener = null;
7936
+ /** Each wheel target and the controller of its listener. */
7937
+ this._wheelTargets = /* @__PURE__ */ new Map();
7512
7938
  this._warnedX = false;
7513
7939
  this._warnedY = false;
7514
7940
  /** Selector (in host shadow DOM) for the scroll container. */
@@ -7553,11 +7979,14 @@ var ScrollSyncController = class {
7553
7979
  });
7554
7980
  }
7555
7981
  hostDisconnected() {
7556
- this._scrollContainer?.removeEventListener("scroll", this._onScroll);
7982
+ this._detachAll();
7983
+ }
7984
+ /** Remove the scroll and every wheel listener. */
7985
+ _detachAll() {
7986
+ this._scrollListener?.abort();
7987
+ this._scrollListener = null;
7557
7988
  this._scrollContainer = null;
7558
- for (const target of this._wheelTargets) {
7559
- target.removeEventListener("wheel", this._onWheel);
7560
- }
7989
+ for (const listener of this._wheelTargets.values()) listener.abort();
7561
7990
  this._wheelTargets.clear();
7562
7991
  }
7563
7992
  /**
@@ -7583,29 +8012,31 @@ var ScrollSyncController = class {
7583
8012
  console.warn(
7584
8013
  '[dawcore] ScrollSyncController: scroll container "' + this.scrollSelector + '" was removed from the DOM \u2014 detaching listeners until it reappears.'
7585
8014
  );
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();
8015
+ this._detachAll();
7590
8016
  }
7591
8017
  return;
7592
8018
  }
7593
8019
  if (container !== this._scrollContainer) {
7594
- this._scrollContainer?.removeEventListener("scroll", this._onScroll);
8020
+ this._scrollListener?.abort();
7595
8021
  this._scrollContainer = container;
7596
- container.addEventListener("scroll", this._onScroll, { passive: true });
8022
+ this._scrollListener = new AbortController();
8023
+ container.addEventListener("scroll", this._onScroll, {
8024
+ passive: true,
8025
+ signal: this._scrollListener.signal
8026
+ });
7597
8027
  }
7598
8028
  const nextTargets = new Set(this._queryAll(this.wheelForwardSelector));
7599
- for (const old of this._wheelTargets) {
8029
+ for (const [old, listener] of [...this._wheelTargets]) {
7600
8030
  if (!nextTargets.has(old)) {
7601
- old.removeEventListener("wheel", this._onWheel);
8031
+ listener.abort();
7602
8032
  this._wheelTargets.delete(old);
7603
8033
  }
7604
8034
  }
7605
8035
  for (const next of nextTargets) {
7606
8036
  if (!this._wheelTargets.has(next)) {
7607
- next.addEventListener("wheel", this._onWheel, { passive: false });
7608
- this._wheelTargets.add(next);
8037
+ const listener = new AbortController();
8038
+ next.addEventListener("wheel", this._onWheel, { passive: false, signal: listener.signal });
8039
+ this._wheelTargets.set(next, listener);
7609
8040
  }
7610
8041
  }
7611
8042
  this._apply();
@@ -7710,7 +8141,38 @@ var PlaybackAnimationController = class {
7710
8141
 
7711
8142
  // src/elements/daw-editor.ts
7712
8143
  var RULER_HEIGHT = 30;
8144
+ function clipDescriptorOf(config) {
8145
+ return {
8146
+ kind: "drop",
8147
+ clipId: crypto.randomUUID(),
8148
+ src: config.src ?? "",
8149
+ peaksSrc: config.peaksSrc ?? "",
8150
+ start: config.start ?? 0,
8151
+ duration: config.duration ?? 0,
8152
+ offset: config.offset ?? 0,
8153
+ gain: config.gain ?? 1,
8154
+ name: config.name ?? "",
8155
+ fadeIn: config.fadeIn ?? 0,
8156
+ fadeOut: config.fadeOut ?? 0,
8157
+ fadeType: config.fadeType ?? "linear",
8158
+ midiNotes: config.midiNotes ?? null,
8159
+ midiChannel: config.midiChannel ?? null,
8160
+ midiProgram: config.midiProgram ?? null
8161
+ };
8162
+ }
8163
+ function extrasOf(descriptor) {
8164
+ return {
8165
+ kind: descriptor.kind,
8166
+ renderMode: descriptor.renderMode,
8167
+ spectrogramConfig: descriptor.spectrogramConfig,
8168
+ src: descriptor.src,
8169
+ peaksSrc: new Map(
8170
+ descriptor.clips.flatMap((c) => c.clipId ? [[c.clipId, c.peaksSrc]] : [])
8171
+ )
8172
+ };
8173
+ }
7713
8174
  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();";
8175
+ var ENTERED = /* @__PURE__ */ Symbol("entered");
7714
8176
  var DawEditorElement = class extends LitElement14 {
7715
8177
  constructor() {
7716
8178
  super();
@@ -7739,13 +8201,18 @@ var DawEditorElement = class extends LitElement14 {
7739
8201
  this._ppqn = 960;
7740
8202
  this.snapTo = "off";
7741
8203
  /**
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.
8204
+ * The editor's own arrangement (#848): the one owner of the tracks, the
8205
+ * clips, the mix, the undo history and loading of what the `<daw-track>`
8206
+ * children declare. Made with the editor, kept across a disconnect.
7745
8207
  */
7746
- this._arrangement = createArrangement();
7747
- /** Sends the load events, read from the arrangement (#848). */
8208
+ this._ownArrangement = createArrangement();
8209
+ /** An arrangement the app handed in (`editor.arrangement`), played alone; null: the own one. */
8210
+ this._handedIn = null;
8211
+ /** Sends the load events, read from the arrangement played (#848; a new one per swap). */
7748
8212
  this._announcer = new LoadAnnouncer((event) => this.dispatchEvent(event));
8213
+ /** Stops following the arrangement played (its sources and its tracks). */
8214
+ this._unfollow = () => {
8215
+ };
7749
8216
  /**
7750
8217
  * Ids of tracks registered (a `<daw-track>` connected, a file dropped) and
7751
8218
  * not yet in the arrangement: they enter at the next flush, once there is
@@ -7759,13 +8226,17 @@ var DawEditorElement = class extends LitElement14 {
7759
8226
  * loads settles it here, without a public event (#917).
7760
8227
  */
7761
8228
  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
8229
  this._previewPeaks = /* @__PURE__ */ new Map();
7765
8230
  /** The `.dat` data of those clips, handed to the peak pipeline when the audio arrives. */
7766
8231
  this._previewWaveforms = /* @__PURE__ */ new Map();
7767
- this._tracks = /* @__PURE__ */ new Map();
7768
- this._engineTracks = /* @__PURE__ */ new Map();
8232
+ /**
8233
+ * Tracks registered and not in the arrangement yet, with their declaration
8234
+ * (#848): a `<daw-track>` is read when it enters (its clips and attributes
8235
+ * as they are then); a dropped file carries its descriptor. The one place a
8236
+ * track's state lives until it enters.
8237
+ */
8238
+ this._pending = /* @__PURE__ */ new Map();
8239
+ this._extras = /* @__PURE__ */ new Map();
7769
8240
  this._peaksData = /* @__PURE__ */ new Map();
7770
8241
  this._isPlaying = false;
7771
8242
  this._duration = 0;
@@ -7839,6 +8310,8 @@ var DawEditorElement = class extends LitElement14 {
7839
8310
  s.scrollSelector = ".scroll-area";
7840
8311
  return s;
7841
8312
  })();
8313
+ /** One gesture id per track for the rest of this task: mix sets made together are one step (#843). */
8314
+ this._taskGestures = /* @__PURE__ */ new Map();
7842
8315
  /**
7843
8316
  * Cache of the last ViewportState forwarded to the spectrogram controller.
7844
8317
  * Lit's `updated()` fires on every reactive state change (`_isPlaying`,
@@ -7871,12 +8344,14 @@ var DawEditorElement = class extends LitElement14 {
7871
8344
  console.warn("[dawcore] Invalid daw-track-connected event detail: " + String(e.detail));
7872
8345
  return;
7873
8346
  }
7874
- if (this._tracks.has(trackId)) {
8347
+ if (this._pending.has(trackId) || this._extras.has(trackId) || this._isEntered(trackId)) {
7875
8348
  this._trackElements.set(trackId, trackEl);
7876
8349
  return;
7877
8350
  }
7878
- const descriptor = this._readTrackDescriptor(trackEl);
7879
- this._tracks = new Map(this._tracks).set(trackId, descriptor);
8351
+ this._pending = new Map(this._pending).set(trackId, {
8352
+ element: trackEl,
8353
+ extraClips: []
8354
+ });
7880
8355
  this._trackElements.set(trackId, trackEl);
7881
8356
  this._queueEntry(trackId);
7882
8357
  };
@@ -7885,50 +8360,33 @@ var DawEditorElement = class extends LitElement14 {
7885
8360
  if (!trackId) return;
7886
8361
  const trackEl = e.target.closest("daw-track");
7887
8362
  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);
8363
+ const old = this._extras.get(trackId);
8364
+ if (!old || !this._isEntered(trackId)) return;
7908
8365
  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
- }
8366
+ const next = {
8367
+ ...old,
8368
+ ...changed.includes("renderMode") && {
8369
+ renderMode: trackDescriptorRenderMode(old.kind, trackEl.renderMode)
8370
+ },
8371
+ ...changed.includes("spectrogramConfig") && {
8372
+ spectrogramConfig: trackEl.spectrogramConfig
8373
+ },
8374
+ ...changed.includes("src") && { src: trackEl.src }
8375
+ };
8376
+ this._extras = new Map(this._extras).set(trackId, next);
8377
+ if (old.src !== next.src) this._replaceShorthandClips(trackId, trackEl);
8378
+ const loaded = this._loadedTracks().find((t) => t.id === trackId)?.clips ?? [];
8379
+ if (next.renderMode === "spectrogram" && old.renderMode !== "spectrogram") {
8380
+ for (const clip of loaded) this._maybeRegisterSpectrogramClipAudio(trackId, clip);
8381
+ }
8382
+ if (next.renderMode !== "spectrogram" && old.renderMode === "spectrogram") {
8383
+ if (this._spectrogramController) {
8384
+ for (const clip of loaded) this._spectrogramController.unregisterClipAudio(clip.id);
7927
8385
  }
7928
8386
  this._disposeSpectrogramControllerIfEmpty();
7929
8387
  }
7930
- if (descriptor.spectrogramConfig !== oldDescriptor?.spectrogramConfig) {
7931
- this._spectrogramController?.setTrackConfig(trackId, descriptor.spectrogramConfig ?? null);
8388
+ if (next.spectrogramConfig !== old.spectrogramConfig) {
8389
+ this._spectrogramController?.setTrackConfig(trackId, next.spectrogramConfig ?? null);
7932
8390
  }
7933
8391
  };
7934
8392
  this._onTrackControl = (e) => {
@@ -7947,7 +8405,7 @@ var DawEditorElement = class extends LitElement14 {
7947
8405
  })
7948
8406
  );
7949
8407
  }
7950
- if (this._tracks.has(trackId)) {
8408
+ if (this._isEntered(trackId)) {
7951
8409
  const options = typeof gesture === "string" ? { gesture } : void 0;
7952
8410
  if (prop === "volume") this._writeMix(trackId, "volume", clampNumber(value, 0, 1), options);
7953
8411
  if (prop === "pan") this._writeMix(trackId, "pan", clampNumber(value, -1, 1), options);
@@ -7973,56 +8431,42 @@ var DawEditorElement = class extends LitElement14 {
7973
8431
  const trackEl = clipEl.closest("daw-track");
7974
8432
  if (!trackEl) return;
7975
8433
  const trackId = trackEl.trackId;
7976
- if (!this._isEntered(trackId)) {
8434
+ if (this._rehomeClip(trackId, clipEl)) return;
8435
+ const entered = this._arrangementOf(trackId).getTracks().some((t) => t.id === trackId);
8436
+ if (!entered && !this._pending.has(trackId) && this._trackLinkState(trackId) === "detached") {
8437
+ this._takeClip(trackId, clipEl.clipId, clipEl.peaksSrc || "");
8438
+ console.warn(
8439
+ detachedWarning(
8440
+ '<daw-track> "' + (trackEl.name || "Untitled") + '"',
8441
+ "a <daw-clip> added to it",
8442
+ this._detachedReason()
8443
+ )
8444
+ );
8445
+ this._rejectAwaitedClips(
8446
+ (id) => id === clipEl.clipId,
8447
+ 'addClip: track "' + trackId + '" is detached'
8448
+ );
8449
+ this._refreshLinkStates();
8450
+ return;
8451
+ }
8452
+ if (!entered) {
7977
8453
  if (!this._entryQueue.includes(trackId)) {
7978
8454
  this._rejectAwaitedClips(
7979
8455
  (id) => id === clipEl.clipId,
7980
8456
  'addClip: track "' + trackId + '" is not in the editor (an Undo took it out)'
7981
8457
  );
7982
- return;
7983
8458
  }
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
8459
  return;
7996
8460
  }
8461
+ if (this._extras.get(trackId)?.peaksSrc.has(clipEl.clipId)) return;
7997
8462
  this._loadAndAppendClip(trackId, this._readClipDescriptor(clipEl));
7998
8463
  };
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
8464
  /** Who waits for a track to enter (addTrack, a dropped file). */
8023
8465
  this._entryWaiters = /* @__PURE__ */ new Map();
8024
- /** Ends the waits of `_whenTrackLoaded` (as loaded) when the editor is disconnected. */
8025
- this._loadWaitEnds = /* @__PURE__ */ new Set();
8466
+ /** One AbortController per arrangement while it is played (D2, interactions/abort.ts). */
8467
+ this._playSignals = new PlaySignals();
8468
+ /** One AbortController per connection: aborted in disconnectedCallback (D8). */
8469
+ this._connection = new AbortController();
8026
8470
  /** Last versions the statechange handler worked from; reset for each engine. */
8027
8471
  this._lastTracksVersion = -1;
8028
8472
  this._lastMixerVersion = -1;
@@ -8089,15 +8533,7 @@ var DawEditorElement = class extends LitElement14 {
8089
8533
  }
8090
8534
  return time * this.effectiveSampleRate / this.samplesPerPixel;
8091
8535
  };
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
- });
8536
+ this._follow(this._ownArrangement);
8101
8537
  }
8102
8538
  get samplesPerPixel() {
8103
8539
  return this._samplesPerPixel;
@@ -8219,8 +8655,7 @@ var DawEditorElement = class extends LitElement14 {
8219
8655
  * render — even if no canvases have been registered yet.
8220
8656
  */
8221
8657
  _maybeRegisterSpectrogramClipAudio(trackId, clip) {
8222
- const descriptor = this._tracks.get(trackId);
8223
- if (descriptor?.renderMode !== "spectrogram") return;
8658
+ if (this._renderModeOf(trackId) !== "spectrogram") return;
8224
8659
  const buffer = clip.audioBuffer ?? this._clipBuffers.get(clip.id);
8225
8660
  if (!buffer) return;
8226
8661
  const channelData = [];
@@ -8292,9 +8727,100 @@ var DawEditorElement = class extends LitElement14 {
8292
8727
  }
8293
8728
  return null;
8294
8729
  }
8295
- /** Reject the `addClip()` calls waiting for clips that match `which`. */
8296
- _rejectAwaitedClips(which, message) {
8297
- for (const [clipId, awaited] of [...this._awaitedClips]) {
8730
+ /** The arrangement played now: a handed-in one, else the editor's own. */
8731
+ get _arrangement() {
8732
+ return this._handedIn ?? this._ownArrangement;
8733
+ }
8734
+ /**
8735
+ * The arrangement the editor plays (#848 PR 3): one handed in by the app,
8736
+ * or else the editor's own, whose content the `<daw-track>` children
8737
+ * declare. Setting one plays it alone, like `video.srcObject`: the
8738
+ * children are not added to it and show `:state(detached)` while it is
8739
+ * set; `null` (or the editor's own) goes back to the own arrangement with
8740
+ * what it held. A swap keeps the adapter: playback stops, a new engine is
8741
+ * built on the new arrangement. Refused (with a warning) during a take.
8742
+ * The editor never disposes or clears an arrangement it was handed.
8743
+ * Throws a `TypeError` for a value that is not an arrangement.
8744
+ */
8745
+ get arrangement() {
8746
+ return this._arrangement;
8747
+ }
8748
+ set arrangement(value) {
8749
+ swapArrangement(this, normalizeHandedIn(value, this._ownArrangement));
8750
+ }
8751
+ /**
8752
+ * Follow the arrangement played: a source that fails changes no track,
8753
+ * only `sources` tells of it (the events, the failed look); the elements'
8754
+ * link states follow its tracks (a structural change only, not every
8755
+ * mixer frame).
8756
+ */
8757
+ _follow(arrangement) {
8758
+ this._unfollow();
8759
+ const stopSources = arrangement.sources.subscribe(() => {
8760
+ this._announceLoading();
8761
+ this.requestUpdate();
8762
+ });
8763
+ let tracksVersion = arrangement.tracksVersion;
8764
+ const stopTracks = arrangement.subscribe(() => {
8765
+ this._watchDrags();
8766
+ if (arrangement.tracksVersion === tracksVersion) return;
8767
+ tracksVersion = arrangement.tracksVersion;
8768
+ this._refreshLinkStates();
8769
+ });
8770
+ this._unfollow = () => {
8771
+ stopSources();
8772
+ stopTracks();
8773
+ };
8774
+ }
8775
+ /**
8776
+ * A change to the arrangement while a drag is in progress came from
8777
+ * elsewhere (a drag writes nothing until its release): cancel the drag
8778
+ * when it changed what is dragged (#848 P2, interactions/drag-watch.ts).
8779
+ */
8780
+ _watchDrags() {
8781
+ const clip = this._clipPointer.draggedClip;
8782
+ if (clip && clipDragChanged(this._arrangement, clip)) this._pointer.cancelClipDrag();
8783
+ const track = this._trackReorderDrag.draggedTrack;
8784
+ if (track && trackDragChanged(this._arrangement, track)) this._trackReorderDrag.cancel();
8785
+ }
8786
+ // --- The swap (interactions/arrangement-swap.ts) ---
8787
+ /** @internal */
8788
+ _releaseEngine() {
8789
+ if (!this._engine) return;
8790
+ try {
8791
+ this._engine.dispose({ keepAdapter: true });
8792
+ } catch (err) {
8793
+ console.warn("[dawcore] Error releasing the engine: " + String(err));
8794
+ }
8795
+ this._engine = null;
8796
+ }
8797
+ /** @internal */
8798
+ _disposeTrackChain(trackId) {
8799
+ this._effectsManager?.disposeTrackChain(trackId);
8800
+ }
8801
+ /** @internal */
8802
+ _playArrangement(next) {
8803
+ this._playSignals.swappedOut(
8804
+ this._arrangement,
8805
+ abortError("the arrangement was swapped out (editor.arrangement) before it finished")
8806
+ );
8807
+ this._handedIn = next;
8808
+ this._announcer = new LoadAnnouncer((event) => this.dispatchEvent(event));
8809
+ this._follow(this._arrangement);
8810
+ this._currentTime = 0;
8811
+ this._stopPlayhead();
8812
+ this._recomputeDuration();
8813
+ this._refreshLinkStates();
8814
+ this._announceLoading();
8815
+ this.requestUpdate();
8816
+ }
8817
+ /** @internal */
8818
+ _buildEngineIfReady() {
8819
+ if (this._externalAdapter && this.isConnected && !this._engine) this._buildEngineReporting();
8820
+ }
8821
+ /** Reject the `addClip()` calls waiting for clips that match `which`. */
8822
+ _rejectAwaitedClips(which, message) {
8823
+ for (const [clipId, awaited] of [...this._awaitedClips]) {
8298
8824
  if (which(clipId, awaited.trackId)) awaited.reject(new Error(message));
8299
8825
  }
8300
8826
  }
@@ -8400,7 +8926,7 @@ var DawEditorElement = class extends LitElement14 {
8400
8926
  {
8401
8927
  effectiveSampleRate: this.effectiveSampleRate,
8402
8928
  duration: this._duration,
8403
- tracks: [...this._engineTracks.values()],
8929
+ tracks: this._loadedTracks(),
8404
8930
  masterVolume: this._engine?.getState().masterVolume ?? 1,
8405
8931
  getMasterEffectsState: () => this.getEffectsState(),
8406
8932
  getTrackEffectsState: (trackId) => this.getTrackEffectsState(trackId)
@@ -8525,11 +9051,26 @@ var DawEditorElement = class extends LitElement14 {
8525
9051
  * Returns false for unknown track/clip IDs (defensive).
8526
9052
  */
8527
9053
  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);
9054
+ const clip = this._loadedClip(trackId, clipId);
8531
9055
  return clip?.midiNotes != null;
8532
9056
  }
9057
+ /** The arrangement's tracks as they are played: loaded clips, the current mix (#848). */
9058
+ _loadedTracks() {
9059
+ const arrangement = this._arrangement;
9060
+ return arrangement.getTracks().map(
9061
+ (t) => loadedTrack(
9062
+ t,
9063
+ arrangement.getMixer().get(t.id) ?? mixOfTrack(t),
9064
+ arrangement.recordingTrackIds.has(t.id)
9065
+ )
9066
+ );
9067
+ }
9068
+ /** A loaded clip of a track of the arrangement, or undefined. */
9069
+ _loadedClip(trackId, clipId) {
9070
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9071
+ const clip = track?.clips.find((c) => c.id === clipId);
9072
+ return clip && !isLoadingClip5(clip) ? clip : void 0;
9073
+ }
8533
9074
  get effectiveSampleRate() {
8534
9075
  return this.sampleRate;
8535
9076
  }
@@ -8608,11 +9149,80 @@ var DawEditorElement = class extends LitElement14 {
8608
9149
  * the arrangement is not listed (its descriptor stays for a Redo).
8609
9150
  */
8610
9151
  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);
9152
+ const listed = this._arrangement.getTracks().map((track) => this._listTrack(track));
9153
+ const queue = this._handedIn ? this._entryQueue.filter((id) => !this._trackElements.has(id)) : this._entryQueue;
9154
+ const waiting = queue.flatMap((trackId) => {
9155
+ const descriptor = this._pendingDescriptor(trackId);
8614
9156
  return descriptor ? [{ trackId, ...descriptor, ...this._mixOf(trackId) }] : [];
8615
9157
  });
9158
+ return [...listed, ...waiting];
9159
+ }
9160
+ /** A track of the arrangement as `editor.tracks` lists it: everything read from the arrangement. */
9161
+ _listTrack(track) {
9162
+ const extras = this._extras.get(track.id);
9163
+ const clipEls = new Map(
9164
+ [...this.querySelectorAll("daw-clip")].map((el) => [
9165
+ el.clipId,
9166
+ el
9167
+ ])
9168
+ );
9169
+ const sr = this.effectiveSampleRate;
9170
+ const clips = track.clips.map((clip) => {
9171
+ const el = clipEls.get(clip.id);
9172
+ const times = clipSeconds(clip, sr);
9173
+ const midi = isLoadingClip5(clip) ? null : clip;
9174
+ const base = {
9175
+ src: typeof clip.src === "string" ? clip.src : "",
9176
+ peaksSrc: extras?.peaksSrc.get(clip.id) ?? this._takenPeaksSrc(clip.id) ?? "",
9177
+ ...times,
9178
+ gain: clip.gain ?? 1,
9179
+ name: clip.name ?? "",
9180
+ fadeIn: el?.fadeIn ?? 0,
9181
+ fadeOut: el?.fadeOut ?? 0,
9182
+ fadeType: el?.fadeType ?? "linear",
9183
+ midiNotes: midi?.midiNotes ?? null,
9184
+ midiChannel: midi?.midiChannel ?? null,
9185
+ midiProgram: midi?.midiProgram ?? null
9186
+ };
9187
+ return el ? { kind: "dom", clipId: clip.id, ...base } : { kind: "drop", clipId: clip.id, ...base };
9188
+ });
9189
+ return {
9190
+ trackId: track.id,
9191
+ name: track.name ?? "",
9192
+ src: extras?.src ?? "",
9193
+ kind: trackKind(track),
9194
+ renderMode: this._renderModeOf(track.id),
9195
+ spectrogramConfig: extras?.spectrogramConfig ?? null,
9196
+ clips,
9197
+ ...this._mixOf(track.id)
9198
+ };
9199
+ }
9200
+ /** A pending track's declaration: its element's attributes and clips now, or its descriptor. */
9201
+ _pendingDescriptor(trackId) {
9202
+ const pending = this._pending.get(trackId);
9203
+ if (!pending) return null;
9204
+ if (!("element" in pending)) return pending.descriptor;
9205
+ const read = this._readTrackDescriptor(pending.element);
9206
+ return pending.extraClips.length > 0 ? { ...read, clips: [...read.clips, ...pending.extraClips] } : read;
9207
+ }
9208
+ /** The extras a track of the arrangement takes when the editor has none for it. */
9209
+ _defaultExtras(trackId) {
9210
+ const track = this._arrangementOf(trackId).getTracks().find((t) => t.id === trackId);
9211
+ if (!track) return null;
9212
+ const kind = trackKind(track);
9213
+ return {
9214
+ kind,
9215
+ renderMode: trackDescriptorRenderMode(kind, "waveform"),
9216
+ src: "",
9217
+ peaksSrc: /* @__PURE__ */ new Map()
9218
+ };
9219
+ }
9220
+ /** How a track is drawn: its extras, else from its kind (an undo-restored track has none). */
9221
+ _renderModeOf(trackId) {
9222
+ const extras = this._extras.get(trackId);
9223
+ if (extras) return extras.renderMode;
9224
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9225
+ return trackDescriptorRenderMode(track ? trackKind(track) : "audio", "waveform");
8616
9226
  }
8617
9227
  /**
8618
9228
  * A track's mix, from its one owner, the arrangement (#843), as the engine
@@ -8621,13 +9231,162 @@ var DawEditorElement = class extends LitElement14 {
8621
9231
  * waiting to enter shows what its element declares.
8622
9232
  */
8623
9233
  _mixOf(trackId) {
8624
- const played = this._engineTracks.get(trackId);
8625
- if (played) return mixOfTrack(played);
8626
- const mix = this._arrangement.getMixer().get(trackId);
9234
+ const mix = mixOf(this._arrangement, trackId);
8627
9235
  if (mix) return mix;
9236
+ const pending = this._pending.get(trackId);
9237
+ if (pending && "mix" in pending) return pending.mix;
8628
9238
  const el = this._trackElements.get(trackId);
8629
9239
  return el ? mixOfElement(el) : DEFAULT_TRACK_MIX;
8630
9240
  }
9241
+ // --- Element links (#848, interactions/element-links.ts) ---
9242
+ /** @internal */
9243
+ _trackLinkState(trackId) {
9244
+ if (this._handedIn && this._trackElements.has(trackId)) return "detached";
9245
+ if (this._isEntered(trackId)) return "live";
9246
+ return this._extras.has(trackId) && !this._pending.has(trackId) ? "detached" : "pending";
9247
+ }
9248
+ /** @internal */
9249
+ _clipLinkState(trackId, clipId) {
9250
+ const track = this._trackLinkState(trackId);
9251
+ if (track !== "live") return track;
9252
+ const held = this._arrangement.getTracks().some((t) => t.clips.some((c) => c.id === clipId));
9253
+ if (held) return "live";
9254
+ return this._extras.get(trackId)?.peaksSrc.has(clipId) ? "detached" : "pending";
9255
+ }
9256
+ /** @internal The stored mix (not a take's mute) and the name. */
9257
+ _trackValues(trackId) {
9258
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9259
+ const mix = this._arrangement.getMixer().get(trackId);
9260
+ if (!track || !mix) return null;
9261
+ return { ...mix, name: track.name ?? "" };
9262
+ }
9263
+ /** @internal */
9264
+ _clipValues(trackId, clipId) {
9265
+ const clip = this._arrangement.getTracks().find((t) => t.id === this._clipHolderId(trackId, clipId))?.clips.find((c) => c.id === clipId);
9266
+ if (!clip) return null;
9267
+ const midi = isLoadingClip5(clip) ? null : clip;
9268
+ return {
9269
+ ...clipSeconds(clip, this.effectiveSampleRate),
9270
+ gain: clip.gain ?? 1,
9271
+ name: clip.name ?? "",
9272
+ midiNotes: midi?.midiNotes ?? null,
9273
+ midiChannel: midi?.midiChannel ?? null,
9274
+ midiProgram: midi?.midiProgram ?? null
9275
+ };
9276
+ }
9277
+ /** @internal A property or attribute set on a live `<daw-track>`: one undo step per field kind. */
9278
+ _requestTrackChange(trackId, partial) {
9279
+ const { name, ...mix } = partial;
9280
+ if (Object.keys(mix).length > 0) this._writeMixFields(trackId, mix, this._taskGesture(trackId));
9281
+ if (name !== void 0) this._renameTrack(trackId, name || "Untitled");
9282
+ }
9283
+ _taskGesture(trackId) {
9284
+ let id = this._taskGestures.get(trackId);
9285
+ if (!id) {
9286
+ id = createMixerGesture2().id;
9287
+ this._taskGestures.set(trackId, id);
9288
+ if (this._taskGestures.size === 1) queueMicrotask(() => this._taskGestures.clear());
9289
+ }
9290
+ return id;
9291
+ }
9292
+ /** @internal A property or attribute set on a live `<daw-clip>`: one undo step. */
9293
+ _requestClipChange(trackId, clipId, partial) {
9294
+ const current = this._clipValues(trackId, clipId);
9295
+ if (!current) return;
9296
+ const holderId = this._clipHolderId(trackId, clipId);
9297
+ const clip = this._arrangement.getTracks().find((t) => t.id === holderId)?.clips.find((c) => c.id === clipId);
9298
+ const src = clip && typeof clip.src === "string" ? clip.src : "";
9299
+ this._applyClipUpdate(holderId, clipId, { ...current, ...partial, src });
9300
+ }
9301
+ /**
9302
+ * The clips of an entering track that another track of the arrangement
9303
+ * holds (the page moved their `<daw-clip>` here while the track waited):
9304
+ * the track takes the held clip as it is, and `from` names what leaves
9305
+ * where. A held clip of the other kind is refused and stays.
9306
+ */
9307
+ _takeOverMovedClips(trackId, track) {
9308
+ const from = /* @__PURE__ */ new Map();
9309
+ const movedIds = /* @__PURE__ */ new Set();
9310
+ const refused = [];
9311
+ const others = this._arrangement.getTracks().filter((t) => t.id !== trackId);
9312
+ const kind = trackKind(track);
9313
+ const clips = [];
9314
+ for (const clip of track.clips) {
9315
+ const holder = others.find((t) => t.clips.some((c) => c.id === clip.id));
9316
+ const held = holder?.clips.find((c) => c.id === clip.id);
9317
+ if (!holder || !held) {
9318
+ clips.push(clip);
9319
+ continue;
9320
+ }
9321
+ const isMidi = "midiNotes" in held && held.midiNotes != null;
9322
+ const error = clipKindError(track.name ?? "", kind, isMidi, held.name || held.id);
9323
+ if (error) {
9324
+ refused.push({ clipId: clip.id, error });
9325
+ continue;
9326
+ }
9327
+ clips.push(held);
9328
+ movedIds.add(clip.id);
9329
+ const ids = from.get(holder.id) ?? /* @__PURE__ */ new Set();
9330
+ from.set(holder.id, ids.add(clip.id));
9331
+ }
9332
+ return {
9333
+ track: movedIds.size || refused.length ? { ...track, clips } : track,
9334
+ from,
9335
+ movedIds,
9336
+ refused
9337
+ };
9338
+ }
9339
+ /** Run `fn` as one undo step of each arrangement it changes. */
9340
+ _inOneStep(arrangements, fn) {
9341
+ for (const a of arrangements) a.beginTransaction();
9342
+ try {
9343
+ fn();
9344
+ } finally {
9345
+ for (const a of arrangements) a.commitTransaction();
9346
+ }
9347
+ }
9348
+ /** The `peaks-src` some track took for a clip element, if any. */
9349
+ _takenPeaksSrc(clipId) {
9350
+ for (const extras of this._extras.values()) {
9351
+ const peaksSrc = extras.peaksSrc.get(clipId);
9352
+ if (peaksSrc !== void 0) return peaksSrc;
9353
+ }
9354
+ return void 0;
9355
+ }
9356
+ /**
9357
+ * The arrangement whose history holds a track: the one that holds it now,
9358
+ * or else, for a page track, the own one (an Undo took it out there; a
9359
+ * handed-in arrangement may be played meanwhile), or else the one played.
9360
+ */
9361
+ _historyOf(trackId, isPageTrack = this._trackElements.has(trackId)) {
9362
+ const holder = this._arrangementOf(trackId);
9363
+ if (holder.getTracks().some((t) => t.id === trackId)) return holder;
9364
+ return isPageTrack ? this._ownArrangement : holder;
9365
+ }
9366
+ /** The track of the arrangement played that holds a clip: `trackId` when it does, or else the one that does. */
9367
+ _clipHolderId(trackId, clipId) {
9368
+ const tracks = this._arrangement.getTracks();
9369
+ if (tracks.some((t) => t.id === trackId && t.clips.some((c) => c.id === clipId)))
9370
+ return trackId;
9371
+ return tracks.find((t) => t.clips.some((c) => c.id === clipId))?.id ?? trackId;
9372
+ }
9373
+ /** @internal */
9374
+ _trackKind(trackId) {
9375
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9376
+ return track ? trackKind(track) : null;
9377
+ }
9378
+ /** @internal */
9379
+ _trackIndex(trackId) {
9380
+ return this._arrangement.getTracks().findIndex((t) => t.id === trackId);
9381
+ }
9382
+ /** @internal */
9383
+ _detachedReason() {
9384
+ return this._handedIn ? "a handed-in arrangement is set (editor.arrangement)" : "its track or clip is not in the arrangement the editor plays";
9385
+ }
9386
+ /** Set or clear `:state(detached)` on every registered element (#848). */
9387
+ _refreshLinkStates() {
9388
+ refreshLinkStates(this, this._trackElements);
9389
+ }
8631
9390
  /**
8632
9391
  * Change one mixer field of a track: the arrangement's setter with
8633
9392
  * `options` (an undo step; changes with one `gesture` id are one step). A
@@ -8644,8 +9403,8 @@ var DawEditorElement = class extends LitElement14 {
8644
9403
  * Change the given mixer fields of a track as ONE undo step (#843): all
8645
9404
  * of them carry one fresh gesture id. A field left out is not sent.
8646
9405
  */
8647
- _writeMixFields(trackId, mix) {
8648
- const options = { gesture: createMixerGesture2().id };
9406
+ _writeMixFields(trackId, mix, gesture = createMixerGesture2().id) {
9407
+ const options = { gesture };
8649
9408
  if (mix.volume !== void 0) this._writeMix(trackId, "volume", mix.volume, options);
8650
9409
  if (mix.pan !== void 0) this._writeMix(trackId, "pan", mix.pan, options);
8651
9410
  if (mix.muted !== void 0) this._writeMix(trackId, "muted", mix.muted, options);
@@ -8676,23 +9435,38 @@ var DawEditorElement = class extends LitElement14 {
8676
9435
  // --- Lifecycle ---
8677
9436
  connectedCallback() {
8678
9437
  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);
9438
+ if (this._connection.signal.aborted) this._connection = new AbortController();
9439
+ this._follow(this._arrangement);
9440
+ this._refreshLinkStates();
9441
+ const { signal } = this._connection;
9442
+ window.addEventListener("keydown", this._onDragEscape, { capture: true, signal });
9443
+ this.addEventListener("daw-track-connected", this._onTrackConnected, {
9444
+ signal
9445
+ });
9446
+ this.addEventListener("daw-track-update", this._onTrackUpdate, { signal });
9447
+ this.addEventListener("daw-track-control", this._onTrackControl, { signal });
9448
+ this.addEventListener("daw-track-remove", this._onTrackRemoveRequest, {
9449
+ signal
9450
+ });
9451
+ this.addEventListener("daw-clip-connected", this._onClipConnected, {
9452
+ signal
9453
+ });
8686
9454
  this.addEventListener(
8687
9455
  "daw-annotation-track-connected",
8688
- this._onAnnotationTrackConnected
9456
+ this._onAnnotationTrackConnected,
9457
+ { signal }
8689
9458
  );
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);
9459
+ this.addEventListener("daw-annotation-select", this._onAnnotationSelect, {
9460
+ signal
9461
+ });
9462
+ this.addEventListener("daw-track-reorder", this._onTrackReorder, { signal });
9463
+ this.addEventListener("daw-track-reorder-grab", this._onTrackReorderGrab, {
9464
+ signal
9465
+ });
8693
9466
  this._childObserver = new MutationObserver((mutations) => {
8694
9467
  const removedTracks = /* @__PURE__ */ new Map();
8695
9468
  const removedClips = /* @__PURE__ */ new Set();
9469
+ const clipsOfRemoved = /* @__PURE__ */ new Map();
8696
9470
  const addedTrackIds = /* @__PURE__ */ new Set();
8697
9471
  for (const mutation of mutations) {
8698
9472
  for (const node of mutation.addedNodes) {
@@ -8717,53 +9491,68 @@ var DawEditorElement = class extends LitElement14 {
8717
9491
  node.querySelectorAll?.("daw-clip").forEach((c) => {
8718
9492
  removedClips.add(c);
8719
9493
  });
9494
+ for (const t of node.tagName === "DAW-TRACK" ? [node] : [...node.querySelectorAll?.("daw-track") ?? []]) {
9495
+ clipsOfRemoved.set(t.trackId, [
9496
+ ...t.querySelectorAll("daw-clip")
9497
+ ]);
9498
+ }
8720
9499
  }
8721
9500
  }
8722
- let orderMayHaveChanged = addedTrackIds.size > 0;
9501
+ const movedTrackIds = /* @__PURE__ */ new Set();
8723
9502
  for (const [trackId] of removedTracks) {
8724
9503
  if (addedTrackIds.has(trackId)) {
8725
- orderMayHaveChanged = true;
9504
+ movedTrackIds.add(trackId);
8726
9505
  continue;
8727
9506
  }
8728
- this._onTrackRemoved(trackId);
9507
+ const children = (clipsOfRemoved.get(trackId) ?? []).filter((c) => !c.isConnected);
9508
+ this._inOneStep([this._historyOf(trackId)], () => {
9509
+ this._onTrackRemoved(trackId);
9510
+ for (const clip of children) {
9511
+ removedClips.delete(clip);
9512
+ this._onClipRemovedFromDom(clip);
9513
+ }
9514
+ });
8729
9515
  }
8730
9516
  for (const clip of removedClips) {
8731
- if (clip.isConnected) continue;
9517
+ if (clip.isConnected && this.contains(clip)) continue;
8732
9518
  this._onClipRemovedFromDom(clip);
8733
9519
  }
8734
- if (orderMayHaveChanged) this._syncEngineOrderToDom();
9520
+ if (movedTrackIds.size > 0) this._placeMovedTracks(movedTrackIds);
8735
9521
  });
8736
9522
  this._childObserver.observe(this, { childList: true, subtree: true });
8737
9523
  for (const [trackId, el] of [...this._trackElements]) {
8738
9524
  if (!this.contains(el)) this._onTrackRemoved(trackId);
8739
9525
  }
9526
+ const present = new Set(
9527
+ [...this.querySelectorAll("daw-clip")].map((c) => c.clipId)
9528
+ );
9529
+ for (const [trackId] of this._trackElements) {
9530
+ for (const clipId of this._extras.get(trackId)?.peaksSrc.keys() ?? []) {
9531
+ if (present.has(clipId)) continue;
9532
+ const holder = this._historyOf(trackId).getTracks().find((t) => t.clips.some((c) => c.id === clipId));
9533
+ if (holder) {
9534
+ this._removeClipFromTrack(holder.id, clipId);
9535
+ this._forgetClip(trackId, clipId);
9536
+ } else this._dropUnheldClip(trackId, clipId);
9537
+ }
9538
+ }
8740
9539
  if (this._externalAdapter && !this._engine) this._buildEngineReporting();
8741
9540
  }
8742
9541
  disconnectedCallback() {
8743
9542
  super.disconnectedCallback();
8744
- window.removeEventListener("keydown", this._onDragEscape, { capture: true });
9543
+ this._unfollow();
9544
+ this._unfollow = () => {
9545
+ };
9546
+ this._connection.abort(abortError("<daw-editor> was disconnected"));
8745
9547
  this._effectsManager?.disposeAll();
8746
9548
  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
9549
  this._cancelDrags(true);
8761
- for (const end of [...this._loadWaitEnds]) end();
8762
9550
  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;
9551
+ const pending = this._pending.get(trackId);
9552
+ if (!pending || "element" in pending || !this._entryWaiters.has(trackId)) continue;
9553
+ const nextPending = new Map(this._pending);
9554
+ nextPending.delete(trackId);
9555
+ this._pending = nextPending;
8767
9556
  this._entryQueue = this._entryQueue.filter((id) => id !== trackId);
8768
9557
  this._settleEntry(
8769
9558
  trackId,
@@ -8838,14 +9627,19 @@ var DawEditorElement = class extends LitElement14 {
8838
9627
  }
8839
9628
  }
8840
9629
  _onTrackRemoved(trackId) {
8841
- const existed = this._tracks.has(trackId);
9630
+ const existed = this._pending.has(trackId) || this._extras.has(trackId) || this._isEntered(trackId);
9631
+ const isPageTrack = this._trackElements.has(trackId);
9632
+ const history = this._historyOf(trackId, isPageTrack);
9633
+ const detached = this._extras.has(trackId) && !this._pending.has(trackId) && !history.getTracks().some((t) => t.id === trackId);
9634
+ const detachedClipIds = detached ? [...this._extras.get(trackId)?.peaksSrc.keys() ?? []] : [];
8842
9635
  this._rejectAwaitedClips(
8843
9636
  (_, awaitedTrackId) => awaitedTrackId === trackId,
8844
9637
  "the track of the clip was removed before the clip loaded"
8845
9638
  );
8846
9639
  this._entryQueue = this._entryQueue.filter((id) => id !== trackId);
8847
9640
  this._settleEntry(trackId, new Error('track "' + trackId + '" was removed before it entered'));
8848
- const arrangementTrack = this._arrangement.getTracks().find((t) => t.id === trackId);
9641
+ const holder = this._arrangementOf(trackId);
9642
+ const arrangementTrack = holder.getTracks().find((t) => t.id === trackId);
8849
9643
  const clipIds = arrangementTrack?.clips.map((c) => c.id) ?? [];
8850
9644
  this._announcer.forget(trackId, clipIds);
8851
9645
  if (clipIds.some((id) => this._previewPeaks.has(id))) {
@@ -8856,10 +9650,9 @@ var DawEditorElement = class extends LitElement14 {
8856
9650
  for (const id of clipIds) this._previewWaveforms.delete(id);
8857
9651
  this._trackElements.delete(trackId);
8858
9652
  this._effectsManager?.disposeTrackChain(trackId);
8859
- const removedTrack = this._engineTracks.get(trackId);
8860
- if (removedTrack) {
9653
+ if (arrangementTrack) {
8861
9654
  const nextPeaks = new Map(this._peaksData);
8862
- for (const clip of removedTrack.clips) {
9655
+ for (const clip of arrangementTrack.clips) {
8863
9656
  this._clipBuffers.delete(clip.id);
8864
9657
  this._clipOffsets.delete(clip.id);
8865
9658
  nextPeaks.delete(clip.id);
@@ -8867,17 +9660,24 @@ var DawEditorElement = class extends LitElement14 {
8867
9660
  }
8868
9661
  this._peaksData = nextPeaks;
8869
9662
  }
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;
9663
+ const nextPending = new Map(this._pending);
9664
+ nextPending.delete(trackId);
9665
+ this._pending = nextPending;
9666
+ const nextExtras = new Map(this._extras);
9667
+ nextExtras.delete(trackId);
9668
+ this._extras = nextExtras;
9669
+ if (arrangementTrack) holder.removeTrack(trackId);
9670
+ else if (detached) {
9671
+ history.removeTrack(trackId, { undoable: false });
9672
+ for (const id of detachedClipIds) {
9673
+ this._purgeClipCaches(id);
9674
+ this._previewWaveforms.delete(id);
9675
+ }
9676
+ }
8876
9677
  this._recomputeDuration();
8877
- this._arrangement.removeTrack(trackId);
8878
9678
  this._recomputeZoomFloor();
8879
9679
  this._disposeSpectrogramControllerIfEmpty();
8880
- if (existed && nextEngine.size === 0) {
9680
+ if (existed && this._arrangement.getTracks().length === 0) {
8881
9681
  if (this._engine) {
8882
9682
  if (this._isPlaying) {
8883
9683
  this._withSeekSuppression(() => this._engine.stop());
@@ -8898,10 +9698,21 @@ var DawEditorElement = class extends LitElement14 {
8898
9698
  );
8899
9699
  }
8900
9700
  }
9701
+ /** The arrangement that holds a track: the one played, else the own one (a page track while handed in). */
9702
+ _arrangementOf(trackId) {
9703
+ const has = (a) => a.getTracks().some((t) => t.id === trackId);
9704
+ return has(this._arrangement) || !has(this._ownArrangement) ? this._arrangement : this._ownArrangement;
9705
+ }
9706
+ /** Rename a track in the arrangement (an undo step); the same name changes nothing. */
9707
+ _renameTrack(trackId, name) {
9708
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9709
+ if (!track || track.name === name) return;
9710
+ this._arrangement.updateTrack(trackId, (current) => ({ ...current, name }));
9711
+ }
8901
9712
  /** Drop the controller when no spectrogram tracks remain. */
8902
9713
  _disposeSpectrogramControllerIfEmpty() {
8903
9714
  if (!this._spectrogramController) return;
8904
- const stillNeeded = Array.from(this._tracks.values()).some(
9715
+ const stillNeeded = Array.from(this._extras.values()).some(
8905
9716
  (d) => d.renderMode === "spectrogram"
8906
9717
  );
8907
9718
  if (!stillNeeded) {
@@ -8910,96 +9721,92 @@ var DawEditorElement = class extends LitElement14 {
8910
9721
  this._lastSpectrogramViewport = null;
8911
9722
  }
8912
9723
  }
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
- });
9724
+ /**
9725
+ * A `<daw-clip>` now under `trackId` whose clip another track holds: the
9726
+ * clip moves to this track (one undo step) when both have entered the same
9727
+ * arrangement; a clip of the other kind stays with `daw-clip-error`.
9728
+ * Otherwise the old track lets it go and the element goes on as a new
9729
+ * arrival. Returns true when nothing more is to be done.
9730
+ */
9731
+ _rehomeClip(trackId, clipEl) {
9732
+ const clipId = clipEl.clipId;
9733
+ if (this._extras.get(trackId)?.peaksSrc.has(clipId)) return true;
9734
+ const arrangement = this._historyOf(trackId);
9735
+ if (arrangement.getTracks().some((t) => t.id === trackId && t.clips.some((c) => c.id === clipId))) {
9736
+ let peaksSrc2 = clipEl.peaksSrc || "";
9737
+ for (const [id, extras] of this._extras) {
9738
+ if (id === trackId || !extras.peaksSrc.has(clipId)) continue;
9739
+ peaksSrc2 = extras.peaksSrc.get(clipId) ?? peaksSrc2;
9740
+ this._forgetClip(id, clipId);
9741
+ }
9742
+ this._takeClip(trackId, clipId, peaksSrc2);
9743
+ return true;
8936
9744
  }
8937
- for (const trackId of this._tracks.keys()) {
8938
- if (engineIds.has(trackId) || this._entryQueue.includes(trackId) || this._trackElements.has(trackId)) {
8939
- continue;
9745
+ const fromTrackId = trackHoldingClip(arrangement, clipId, trackId);
9746
+ if (!fromTrackId) {
9747
+ for (const [id, extras] of this._extras) {
9748
+ if (id !== trackId && extras.peaksSrc.has(clipId)) this._forgetClip(id, clipId);
8940
9749
  }
8941
- next ?? (next = new Map(this._tracks));
8942
- next.delete(trackId);
9750
+ return false;
8943
9751
  }
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 });
9752
+ const entered = arrangement.getTracks().some((t) => t.id === trackId);
9753
+ if (!entered && this._pending.has(trackId)) return true;
9754
+ const toExtras = this._extras.get(trackId) ?? this._defaultExtras(trackId);
9755
+ if (!entered || !toExtras) {
9756
+ this._takeClip(trackId, clipId, this._takenPeaksSrc(clipId) ?? clipEl.peaksSrc ?? "");
9757
+ console.warn(
9758
+ '[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.'
9759
+ );
9760
+ this.dispatchEvent(
9761
+ new CustomEvent("daw-clip-error", {
9762
+ bubbles: true,
9763
+ composed: true,
9764
+ detail: {
9765
+ trackId,
9766
+ clipId,
9767
+ error: new Error('track "' + trackId + '" is not in the arrangement')
9768
+ }
9769
+ })
9770
+ );
9771
+ this._refreshLinkStates();
9772
+ return true;
9773
+ }
9774
+ const error = moveClipToTrack(arrangement, fromTrackId, trackId, clipId, toExtras.kind);
9775
+ if (error) {
9776
+ this._takeClip(trackId, clipId, this._extras.get(fromTrackId)?.peaksSrc.get(clipId) ?? "");
9777
+ console.warn(
9778
+ '[dawcore] <daw-clip> cannot move to track "' + (this._trackElements.get(trackId)?.name || "Untitled") + '" (' + String(error) + "): its clip stays in its track."
9779
+ );
9780
+ this.dispatchEvent(
9781
+ new CustomEvent("daw-clip-error", {
9782
+ bubbles: true,
9783
+ composed: true,
9784
+ detail: { trackId, clipId, error }
9785
+ })
9786
+ );
9787
+ return true;
9788
+ }
9789
+ const peaksSrc = this._takenPeaksSrc(clipId) ?? clipEl.peaksSrc ?? "";
9790
+ for (const [id, extras] of this._extras) {
9791
+ if (id !== trackId && extras.peaksSrc.has(clipId)) this._forgetClip(id, clipId);
8985
9792
  }
8986
- return changed ? result : clips;
9793
+ if (!this._extras.has(trackId)) this._extras = new Map(this._extras).set(trackId, toExtras);
9794
+ this._takeClip(trackId, clipId, peaksSrc);
9795
+ return true;
8987
9796
  }
8988
9797
  _onClipRemovedFromDom(clipEl) {
8989
9798
  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;
9799
+ for (const arrangement of /* @__PURE__ */ new Set([this._arrangement, this._ownArrangement])) {
9800
+ for (const t of arrangement.getTracks()) {
9801
+ if (t.clips.some((c) => c.id === clipId)) {
9802
+ this._removeClipFromTrack(t.id, clipId);
9803
+ return;
9804
+ }
8994
9805
  }
8995
9806
  }
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");
9807
+ for (const [trackId, extras] of this._extras) {
9808
+ if (!extras.peaksSrc.has(clipId)) continue;
9809
+ this._dropUnheldClip(trackId, clipId);
9003
9810
  return;
9004
9811
  }
9005
9812
  this._rejectAwaitedClips((id) => id === clipId, "the clip was removed before it loaded");
@@ -9016,12 +9823,15 @@ var DawEditorElement = class extends LitElement14 {
9016
9823
  * like any other; `daw-clip-ready` or `daw-clip-error` follows (#848).
9017
9824
  */
9018
9825
  _loadAndAppendClip(trackId, clipDesc) {
9019
- const trackDesc = this._tracks.get(trackId);
9020
- if (!trackDesc) return;
9826
+ const arrangement = this._arrangementOf(trackId);
9827
+ const track = arrangement.getTracks().find((t) => t.id === trackId);
9828
+ const extras = this._extras.get(trackId) ?? this._defaultExtras(trackId);
9829
+ if (!extras || !track) return;
9830
+ if (isDomClip(clipDesc)) this._takeClip(trackId, clipDesc.clipId, clipDesc.peaksSrc);
9021
9831
  const clipIsMidi = isMidiDescriptor(clipDesc);
9022
9832
  const kindError = clipKindError(
9023
- trackDesc.name,
9024
- trackDesc.kind,
9833
+ track.name ?? "",
9834
+ extras.kind,
9025
9835
  clipIsMidi,
9026
9836
  clipDesc.name || clipDesc.src || clipDesc.clipId
9027
9837
  );
@@ -9029,7 +9839,7 @@ var DawEditorElement = class extends LitElement14 {
9029
9839
  if (!clipIsMidi) this._announcer.expectClip(clipDesc.clipId);
9030
9840
  try {
9031
9841
  if (kindError) throw kindError;
9032
- this._arrangement.updateTrack(trackId, (current) => ({
9842
+ arrangement.updateTrack(trackId, (current) => ({
9033
9843
  ...current,
9034
9844
  clips: [...current.clips, clip]
9035
9845
  }));
@@ -9044,10 +9854,6 @@ var DawEditorElement = class extends LitElement14 {
9044
9854
  );
9045
9855
  return;
9046
9856
  }
9047
- this._tracks = new Map(this._tracks).set(trackId, {
9048
- ...trackDesc,
9049
- clips: [...trackDesc.clips, clipDesc]
9050
- });
9051
9857
  if (!clipIsMidi && clipDesc.peaksSrc) this._requestPreview(clipDesc.clipId, clipDesc.peaksSrc);
9052
9858
  }
9053
9859
  /**
@@ -9067,6 +9873,7 @@ var DawEditorElement = class extends LitElement14 {
9067
9873
  );
9068
9874
  return null;
9069
9875
  } catch (err) {
9876
+ if (isAbortError(err)) return null;
9070
9877
  console.warn(
9071
9878
  "[dawcore] Failed to load peaks from " + peaksSrc + ": " + String(err) + " \u2014 falling back to AudioBuffer generation"
9072
9879
  );
@@ -9095,20 +9902,24 @@ var DawEditorElement = class extends LitElement14 {
9095
9902
  }));
9096
9903
  }
9097
9904
  _applyClipUpdate(trackId, clipId, clipEl) {
9098
- const t = this._engineTracks.get(trackId);
9905
+ const t = this._arrangement.getTracks().find((track) => track.id === trackId);
9099
9906
  if (!t) {
9100
- console.warn('[dawcore] _applyClipUpdate: no engine track for id "' + trackId + '"');
9907
+ console.warn('[dawcore] _applyClipUpdate: no track for id "' + trackId + '"');
9101
9908
  return;
9102
9909
  }
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);
9910
+ const loadedClip = this._loadedClip(trackId, clipId);
9911
+ if (!loadedClip) {
9912
+ const loading = t.clips.find((c) => c.id === clipId);
9913
+ if (loading && isLoadingClip5(loading)) {
9914
+ this._updateLoadingClip(trackId, loading, clipEl);
9915
+ return;
9916
+ }
9106
9917
  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?)')
9918
+ '[dawcore] _applyClipUpdate: clip "' + clipId + '" not found in track "' + trackId + '" (DOM/engine clip-id misalignment?)'
9108
9919
  );
9109
9920
  return;
9110
9921
  }
9111
- const oldClip = t.clips[idx];
9922
+ const oldClip = loadedClip;
9112
9923
  const sr = oldClip.sampleRate ?? this.effectiveSampleRate;
9113
9924
  const isMidiNow = clipEl.midiNotes != null && !clipEl.src;
9114
9925
  const wasMidi = oldClip.midiNotes != null;
@@ -9125,6 +9936,9 @@ var DawEditorElement = class extends LitElement14 {
9125
9936
  return;
9126
9937
  }
9127
9938
  if (isMidiNow || wasMidi) {
9939
+ 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) {
9940
+ return;
9941
+ }
9128
9942
  const notes = validMidiNotes(clipEl.midiNotes ?? []);
9129
9943
  const noteSpanSeconds = notes.length ? notes.reduce((max, n) => Math.max(max, n.time + n.duration), 0) : 0;
9130
9944
  const sourceDurationSamples = Math.ceil(Math.max(noteSpanSeconds, clipEl.duration, 1) * sr);
@@ -9157,6 +9971,9 @@ var DawEditorElement = class extends LitElement14 {
9157
9971
  gain: clipEl.gain,
9158
9972
  name: clipEl.name || oldClip.name
9159
9973
  };
9974
+ if (newStartSample === oldClip.startSample && newDurationSamples === oldClip.durationSamples && newOffsetSamples === oldClip.offsetSamples && updatedClip.gain === (oldClip.gain ?? 1) && updatedClip.name === oldClip.name) {
9975
+ return;
9976
+ }
9160
9977
  const boundsChanged = oldClip.offsetSamples !== newOffsetSamples || oldClip.durationSamples !== newDurationSamples;
9161
9978
  if (boundsChanged) {
9162
9979
  this._clipOffsets.set(clipId, {
@@ -9170,9 +9987,55 @@ var DawEditorElement = class extends LitElement14 {
9170
9987
  }
9171
9988
  this._replaceClip(trackId, clipId, updatedClip);
9172
9989
  }
9990
+ /**
9991
+ * A change to a clip still loading (#848 P10): its times, gain and name in
9992
+ * seconds on the `LoadingClip`, one undo step; the audio loads into it.
9993
+ */
9994
+ _updateLoadingClip(trackId, clip, values) {
9995
+ const next = {
9996
+ ...clip,
9997
+ start: values.start,
9998
+ ...values.duration > 0 ? { duration: values.duration } : {},
9999
+ offset: values.offset,
10000
+ gain: values.gain,
10001
+ ...values.name ? { name: values.name } : {}
10002
+ };
10003
+ 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) {
10004
+ return;
10005
+ }
10006
+ this._arrangement.updateTrack(trackId, (current) => ({
10007
+ ...current,
10008
+ clips: current.clips.map((c) => c.id === clip.id ? next : c)
10009
+ }));
10010
+ }
9173
10011
  /** 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);
10012
+ /**
10013
+ * An aborted addClip (D3): its clip leaves for good, from the track it
10014
+ * entered or from what a waiting track will enter with.
10015
+ */
10016
+ _discardAddedClip(trackId, clipId) {
10017
+ const pending = this._pending.get(trackId);
10018
+ if (pending) {
10019
+ this._pending = new Map(this._pending).set(
10020
+ trackId,
10021
+ "element" in pending ? { ...pending, extraClips: pending.extraClips.filter((c) => c.clipId !== clipId) } : {
10022
+ ...pending,
10023
+ descriptor: {
10024
+ ...pending.descriptor,
10025
+ clips: pending.descriptor.clips.filter((c) => c.clipId !== clipId)
10026
+ }
10027
+ }
10028
+ );
10029
+ return;
10030
+ }
10031
+ const holder = this._arrangementOf(trackId).getTracks().find((t) => t.id === trackId);
10032
+ if (holder?.clips.some((c) => c.id === clipId)) {
10033
+ this._removeClipFromTrack(trackId, clipId, { undoable: false });
10034
+ }
10035
+ }
10036
+ _removeClipFromTrack(trackId, clipId, options = {}) {
10037
+ const arrangement = this._arrangementOf(trackId);
10038
+ const track = arrangement.getTracks().find((t) => t.id === trackId);
9176
10039
  if (!track) {
9177
10040
  console.warn('[dawcore] _removeClipFromTrack: no track for id "' + trackId + '"');
9178
10041
  return;
@@ -9190,20 +10053,43 @@ var DawEditorElement = class extends LitElement14 {
9190
10053
  nextPreview.delete(clipId);
9191
10054
  this._previewPeaks = nextPreview;
9192
10055
  }
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
- }));
10056
+ this._forgetClip(trackId, clipId);
10057
+ const wasLoading = track.clips.some((c) => c.id === clipId && isLoadingClip5(c));
10058
+ if (options.undoable === false) arrangement.removeClip(trackId, clipId, { undoable: false });
10059
+ else
10060
+ arrangement.updateTrack(trackId, (current) => ({
10061
+ ...current,
10062
+ clips: current.clips.filter((c) => c.id !== clipId)
10063
+ }));
9205
10064
  if (wasLoading) this._announcer.forgetClip(clipId);
9206
10065
  }
10066
+ /** Record that the editor took a clip of a track (with its `peaks-src`, '' when none). */
10067
+ _takeClip(trackId, clipId, peaksSrc) {
10068
+ const extras = this._extras.get(trackId);
10069
+ if (!extras || extras.peaksSrc.get(clipId) === peaksSrc) return;
10070
+ const next = new Map(extras.peaksSrc).set(clipId, peaksSrc);
10071
+ this._extras = new Map(this._extras).set(trackId, { ...extras, peaksSrc: next });
10072
+ }
10073
+ /**
10074
+ * A `<daw-clip>` the editor took is removed while the arrangement does not
10075
+ * hold its clip (its track or its own arrival undone, or refused): it is
10076
+ * gone for good, also from the undo and redo states, so no Redo brings it
10077
+ * back (maintainer's choice, #848).
10078
+ */
10079
+ _dropUnheldClip(trackId, clipId) {
10080
+ this._historyOf(trackId).removeClip(trackId, clipId, { undoable: false });
10081
+ this._purgeClipCaches(clipId);
10082
+ this._previewWaveforms.delete(clipId);
10083
+ this._forgetClip(trackId, clipId);
10084
+ }
10085
+ /** The editor no longer holds anything for a clip of a track. */
10086
+ _forgetClip(trackId, clipId) {
10087
+ const extras = this._extras.get(trackId);
10088
+ if (!extras?.peaksSrc.has(clipId)) return;
10089
+ const next = new Map(extras.peaksSrc);
10090
+ next.delete(clipId);
10091
+ this._extras = new Map(this._extras).set(trackId, { ...extras, peaksSrc: next });
10092
+ }
9207
10093
  _readTrackDescriptor(trackEl) {
9208
10094
  const clipEls = trackEl.querySelectorAll("daw-clip");
9209
10095
  const clips = [];
@@ -9279,12 +10165,9 @@ var DawEditorElement = class extends LitElement14 {
9279
10165
  _flushTrackEntries() {
9280
10166
  if (this._entryQueue.length === 0) return;
9281
10167
  if (!this._engine) return;
9282
- if (this._dragInProgress) {
9283
- this._flushAfterDrag();
9284
- return;
9285
- }
9286
- const queued = this._entryQueue;
9287
- this._entryQueue = [];
10168
+ const isPageTrack = (id) => this._trackElements.has(id);
10169
+ const queued = this._handedIn ? this._entryQueue.filter((id) => !isPageTrack(id)) : this._entryQueue;
10170
+ this._entryQueue = this._handedIn ? this._entryQueue.filter(isPageTrack) : [];
9288
10171
  const domOrder = [...this.querySelectorAll("daw-track")].map(
9289
10172
  (el) => el.trackId
9290
10173
  );
@@ -9293,12 +10176,8 @@ var DawEditorElement = class extends LitElement14 {
9293
10176
  return at === -1 ? domOrder.length : at;
9294
10177
  };
9295
10178
  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
10179
  const arrangement = this._arrangement;
9301
- const historyWasEmpty = !arrangement.canUndo && !arrangement.canRedo && !this._dragInProgress;
10180
+ const historyWasEmpty = !arrangement.canUndo && !arrangement.canRedo;
9302
10181
  let pageEntered = false;
9303
10182
  for (const id of ordered.filter(isPageTrack)) {
9304
10183
  if (this._enterTrack(id)) pageEntered = true;
@@ -9306,32 +10185,21 @@ var DawEditorElement = class extends LitElement14 {
9306
10185
  if (historyWasEmpty && pageEntered) arrangement.clearHistory();
9307
10186
  for (const id of ordered.filter((id2) => !isPageTrack(id2))) this._enterTrack(id);
9308
10187
  }
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
10188
  /** Enter one registered track. False when it is gone, already in, or refused. */
9322
10189
  _enterTrack(trackId) {
9323
- const descriptor = this._tracks.get(trackId);
10190
+ const descriptor = this._pendingDescriptor(trackId);
9324
10191
  if (!descriptor || this._isEntered(trackId)) return false;
9325
10192
  const el = this._trackElements.get(trackId);
9326
10193
  const built = buildArrangementTrack(
9327
10194
  trackId,
9328
10195
  descriptor,
9329
- el ? mixOfElement(el) : DEFAULT_TRACK_MIX,
10196
+ this._mixOf(trackId),
9330
10197
  this.effectiveSampleRate
9331
10198
  );
9332
- if (built.descriptor !== descriptor) {
9333
- this._tracks = new Map(this._tracks).set(trackId, built.descriptor);
9334
- }
10199
+ const nextPending = new Map(this._pending);
10200
+ nextPending.delete(trackId);
10201
+ this._pending = nextPending;
10202
+ this._extras = new Map(this._extras).set(trackId, extrasOf(built.descriptor));
9335
10203
  for (const { clipId, error } of built.refused) {
9336
10204
  console.warn("[dawcore] " + error.message);
9337
10205
  this.dispatchEvent(
@@ -9347,14 +10215,45 @@ var DawEditorElement = class extends LitElement14 {
9347
10215
  trackId,
9348
10216
  this._arrangement.getTracks().map((t) => t.id)
9349
10217
  ) : 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);
10218
+ const moved = this._takeOverMovedClips(trackId, built.track);
10219
+ const entering = moved.track;
10220
+ for (const { clipId, error } of moved.refused) {
10221
+ console.warn("[dawcore] " + error.message);
10222
+ this.dispatchEvent(
10223
+ new CustomEvent("daw-clip-error", {
10224
+ bubbles: true,
10225
+ composed: true,
10226
+ detail: { trackId, clipId, error }
10227
+ })
10228
+ );
10229
+ }
10230
+ this._announcer.expect(trackId, built.refused.length + moved.refused.length);
10231
+ for (const clip of entering.clips) {
10232
+ if (isLoadingClip5(clip)) this._announcer.expectClip(clip.id);
9353
10233
  }
9354
10234
  try {
9355
- this._arrangement.addTrack(built.track, index === void 0 ? void 0 : { index });
10235
+ if (moved.from.size === 0) {
10236
+ this._arrangement.addTrack(entering, index === void 0 ? void 0 : { index });
10237
+ } else {
10238
+ this._inOneStep([this._arrangement], () => {
10239
+ for (const [fromId, clipIds] of moved.from) {
10240
+ this._arrangement.updateTrack(fromId, (t) => ({
10241
+ ...t,
10242
+ clips: t.clips.filter((c) => !clipIds.has(c.id))
10243
+ }));
10244
+ for (const clipId of clipIds) this._forgetClip(fromId, clipId);
10245
+ }
10246
+ this._arrangement.addTrack(entering, index === void 0 ? void 0 : { index });
10247
+ });
10248
+ }
9356
10249
  } catch (err) {
9357
10250
  console.warn('[dawcore] Failed to add track "' + trackId + '": ' + String(err));
10251
+ if (!el) {
10252
+ const nextExtras = new Map(this._extras);
10253
+ nextExtras.delete(trackId);
10254
+ this._extras = nextExtras;
10255
+ }
10256
+ this._refreshLinkStates();
9358
10257
  this._settleEntry(trackId, err instanceof Error ? err : new Error(String(err)));
9359
10258
  this.dispatchEvent(
9360
10259
  new CustomEvent("daw-track-error", {
@@ -9365,8 +10264,9 @@ var DawEditorElement = class extends LitElement14 {
9365
10264
  );
9366
10265
  return false;
9367
10266
  }
9368
- this._settleEntry(trackId, null);
10267
+ this._settleEntry(trackId, ENTERED);
9369
10268
  for (const clipDesc of built.descriptor.clips) {
10269
+ if (clipDesc.clipId && moved.movedIds.has(clipDesc.clipId)) continue;
9370
10270
  if (clipDesc.peaksSrc && clipDesc.clipId && clipSourceOf(clipDesc)) {
9371
10271
  this._requestPreview(clipDesc.clipId, clipDesc.peaksSrc);
9372
10272
  }
@@ -9379,7 +10279,8 @@ var DawEditorElement = class extends LitElement14 {
9379
10279
  * `<daw-clip>` children keeps them. A track still queued reads the new
9380
10280
  * descriptor when it enters.
9381
10281
  */
9382
- _replaceShorthandClips(trackId, descriptor) {
10282
+ _replaceShorthandClips(trackId, trackEl) {
10283
+ const descriptor = this._readTrackDescriptor(trackEl);
9383
10284
  if (!this._isEntered(trackId) || descriptor.clips.some(isDomClip)) return;
9384
10285
  const built = buildArrangementTrack(
9385
10286
  trackId,
@@ -9387,7 +10288,13 @@ var DawEditorElement = class extends LitElement14 {
9387
10288
  DEFAULT_TRACK_MIX,
9388
10289
  this.effectiveSampleRate
9389
10290
  );
9390
- this._tracks = new Map(this._tracks).set(trackId, built.descriptor);
10291
+ const extras = this._extras.get(trackId);
10292
+ if (extras) {
10293
+ this._extras = new Map(this._extras).set(trackId, {
10294
+ ...extras,
10295
+ peaksSrc: extrasOf(built.descriptor).peaksSrc
10296
+ });
10297
+ }
9391
10298
  this._arrangement.updateTrack(trackId, (current) => ({ ...current, clips: built.track.clips }));
9392
10299
  }
9393
10300
  /** Run the load announcements over the arrangement's current state. */
@@ -9406,7 +10313,7 @@ var DawEditorElement = class extends LitElement14 {
9406
10313
  const waveformData = await this._resolvePeaks(peaksSrc);
9407
10314
  if (!waveformData) return;
9408
10315
  const clip = this._arrangement.getTracks().flatMap((t) => t.clips).find((c) => c.id === clipId);
9409
- if (!clip || !isLoadingClip3(clip)) return;
10316
+ if (!clip || !isLoadingClip5(clip)) return;
9410
10317
  const rate = waveformData.sample_rate;
9411
10318
  const offset = clip.offset ?? 0;
9412
10319
  const seconds = clip.duration ?? Math.max(0, waveformData.duration - offset);
@@ -9435,13 +10342,13 @@ var DawEditorElement = class extends LitElement14 {
9435
10342
  this._entryWaiters.set(trackId, { resolve, reject });
9436
10343
  });
9437
10344
  }
9438
- /** Settle the wait for a track's entry: entered (`null`), or refused or gone. */
9439
- _settleEntry(trackId, error) {
10345
+ /** Settle the wait for a track's entry: entered (`ENTERED`), or refused or gone (the reason).*/
10346
+ _settleEntry(trackId, outcome) {
9440
10347
  const waiter = this._entryWaiters.get(trackId);
9441
10348
  if (!waiter) return;
9442
10349
  this._entryWaiters.delete(trackId);
9443
- if (error) waiter.reject(error);
9444
- else waiter.resolve(trackId);
10350
+ if (outcome === ENTERED) waiter.resolve(trackId);
10351
+ else waiter.reject(outcome);
9445
10352
  }
9446
10353
  /**
9447
10354
  * A dropped file as a track with no element (a File cannot be an attribute):
@@ -9451,7 +10358,7 @@ var DawEditorElement = class extends LitElement14 {
9451
10358
  _addDroppedFile(file) {
9452
10359
  const trackId = crypto.randomUUID();
9453
10360
  const name = file.name.replace(/\.\w+$/, "");
9454
- this._tracks = new Map(this._tracks).set(trackId, {
10361
+ const descriptor = {
9455
10362
  name,
9456
10363
  src: "",
9457
10364
  kind: "audio",
@@ -9475,8 +10382,10 @@ var DawEditorElement = class extends LitElement14 {
9475
10382
  midiProgram: null
9476
10383
  }
9477
10384
  ]
9478
- });
10385
+ };
10386
+ this._pending = new Map(this._pending).set(trackId, { descriptor, mix: DEFAULT_TRACK_MIX });
9479
10387
  const entered = this._waitForEntry(trackId);
10388
+ this._endEntryOnSwap(trackId, entered);
9480
10389
  this._queueEntry(trackId);
9481
10390
  return entered;
9482
10391
  }
@@ -9484,12 +10393,29 @@ var DawEditorElement = class extends LitElement14 {
9484
10393
  * Take a track out for good: no undo step, and no undo or redo brings it
9485
10394
  * back (a dropped file that could not be loaded was never a declaration).
9486
10395
  */
9487
- _discardTrack(trackId) {
9488
- const track = this._arrangement.getTracks().find((t) => t.id === trackId);
10396
+ _discardTrack(trackId, from = this._arrangement) {
10397
+ if (from !== this._arrangement) {
10398
+ from.removeTrack(trackId, { undoable: false });
10399
+ if (this._extras.has(trackId)) {
10400
+ const nextExtras = new Map(this._extras);
10401
+ nextExtras.delete(trackId);
10402
+ this._extras = nextExtras;
10403
+ }
10404
+ return;
10405
+ }
10406
+ const track = from.getTracks().find((t) => t.id === trackId);
9489
10407
  this._announcer.forget(trackId, track?.clips.map((c) => c.id) ?? []);
9490
- this._arrangement.removeTrack(trackId, { undoable: false });
10408
+ from.removeTrack(trackId, { undoable: false });
9491
10409
  this._onTrackRemoved(trackId);
9492
10410
  }
10411
+ /** The signal of the arrangement played now: aborted when it is swapped out. */
10412
+ get _playSignal() {
10413
+ return this._playSignals.signalOf(this._arrangement);
10414
+ }
10415
+ /** @internal A caller's signal combined with the arrangement played now (loadMidi, D6). */
10416
+ _operationSignal(signal) {
10417
+ return signal ? AbortSignal.any([signal, this._playSignal]) : this._playSignal;
10418
+ }
9493
10419
  /**
9494
10420
  * Resolves once the track has loaded (`daw-track-ready`), or when the
9495
10421
  * editor is disconnected meanwhile (the track is kept and loads after a
@@ -9499,30 +10425,31 @@ var DawEditorElement = class extends LitElement14 {
9499
10425
  const state9 = this._announcer.stateOf(trackId);
9500
10426
  if (state9 === "ready") return Promise.resolve();
9501
10427
  if (state9 === "failed") return Promise.reject(this._announcer.errorOf(trackId));
10428
+ const ended = AbortSignal.any([this._playSignal, this._connection.signal]);
10429
+ if (ended.aborted) return Promise.resolve();
9502
10430
  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);
10431
+ const done = new AbortController();
10432
+ const signal = AbortSignal.any([ended, done.signal]);
10433
+ this.addEventListener(
10434
+ "daw-track-ready",
10435
+ (e) => {
10436
+ if (e.detail.trackId !== trackId) return;
10437
+ done.abort();
10438
+ resolve();
10439
+ },
10440
+ { signal }
10441
+ );
10442
+ this.addEventListener(
10443
+ "daw-track-error",
10444
+ (e) => {
10445
+ const detail = e.detail;
10446
+ if (detail.trackId !== trackId) return;
10447
+ done.abort();
10448
+ reject(detail.error instanceof Error ? detail.error : new Error(String(detail.error)));
10449
+ },
10450
+ { signal }
10451
+ );
10452
+ ended.addEventListener("abort", () => resolve(), { signal: done.signal });
9526
10453
  });
9527
10454
  }
9528
10455
  /**
@@ -9538,14 +10465,14 @@ var DawEditorElement = class extends LitElement14 {
9538
10465
  }
9539
10466
  const sources = this._arrangement.sources.getSnapshot().sources;
9540
10467
  const failed = new Set(
9541
- track.clips.filter(isLoadingClip3).map((clip) => clip.src).filter((src) => sources.get(src)?.status === "failed")
10468
+ track.clips.filter(isLoadingClip5).map((clip) => clip.src).filter((src) => sources.get(src)?.status === "failed")
9542
10469
  );
9543
10470
  for (const src of failed) this._arrangement.retry(src);
9544
10471
  }
9545
10472
  _fetchPeaks(src) {
9546
10473
  const cached = this._peaksCache.get(src);
9547
10474
  if (cached) return cached;
9548
- const promise = loadWaveformDataFromUrl(src).catch((err) => {
10475
+ const promise = loadWaveformDataFromUrl(src, this._playSignal).catch((err) => {
9549
10476
  this._peaksCache.delete(src);
9550
10477
  throw err;
9551
10478
  });
@@ -9560,7 +10487,7 @@ var DawEditorElement = class extends LitElement14 {
9560
10487
  _recomputeDuration() {
9561
10488
  const sr = this.effectiveSampleRate;
9562
10489
  let maxSample = 0;
9563
- for (const track of this._engineTracks.values()) {
10490
+ for (const track of this._loadedTracks()) {
9564
10491
  for (const clip of track.clips) {
9565
10492
  const endSample = clip.startSample + clip.durationSamples;
9566
10493
  if (endSample > maxSample) maxSample = endSample;
@@ -9568,7 +10495,7 @@ var DawEditorElement = class extends LitElement14 {
9568
10495
  }
9569
10496
  for (const track of this._arrangement.getTracks()) {
9570
10497
  for (const clip of track.clips) {
9571
- if (!isLoadingClip3(clip)) continue;
10498
+ if (!isLoadingClip5(clip)) continue;
9572
10499
  const seconds = this._placeholderSeconds(clip);
9573
10500
  if (seconds === null) continue;
9574
10501
  maxSample = Math.max(maxSample, Math.round(((clip.start ?? 0) + seconds) * sr));
@@ -9607,6 +10534,16 @@ var DawEditorElement = class extends LitElement14 {
9607
10534
  this._buildEngine();
9608
10535
  } catch (err) {
9609
10536
  console.warn("[dawcore] Failed to build the engine: " + String(err));
10537
+ const error = err instanceof Error ? err : new Error(String(err));
10538
+ for (const trackId of [...this._entryQueue]) {
10539
+ const pending = this._pending.get(trackId);
10540
+ if (!pending || "element" in pending || !this._entryWaiters.has(trackId)) continue;
10541
+ const nextPending = new Map(this._pending);
10542
+ nextPending.delete(trackId);
10543
+ this._pending = nextPending;
10544
+ this._entryQueue = this._entryQueue.filter((id) => id !== trackId);
10545
+ this._settleEntry(trackId, error);
10546
+ }
9610
10547
  this.dispatchEvent(
9611
10548
  new CustomEvent("daw-error", {
9612
10549
  bubbles: true,
@@ -9648,8 +10585,11 @@ var DawEditorElement = class extends LitElement14 {
9648
10585
  });
9649
10586
  engine.on("stop", () => this._onEngineStop(engine));
9650
10587
  this._engine = engine;
10588
+ if (this._selectionStartTime !== 0 || this._selectionEndTime !== 0) {
10589
+ engine.setSelection(this._selectionStartTime, this._selectionEndTime);
10590
+ }
9651
10591
  this._onEngineState(engine.getState());
9652
- for (const track of this._engineTracks.values()) {
10592
+ for (const track of this._loadedTracks()) {
9653
10593
  for (const clip of track.clips) this._maybeRegisterSpectrogramClipAudio(track.id, clip);
9654
10594
  }
9655
10595
  this._flushTrackEntries();
@@ -9675,7 +10615,7 @@ var DawEditorElement = class extends LitElement14 {
9675
10615
  }
9676
10616
  }
9677
10617
  }
9678
- /** The engine's state changed: follow it (the one writer of `_engineTracks`). */
10618
+ /** The engine's state changed: draw it (the rows are read from the arrangement). */
9679
10619
  _onEngineState(engineState) {
9680
10620
  this._isPlaying = engineState.isPlaying;
9681
10621
  this._selectedTrackId = engineState.selectedTrackId;
@@ -9684,18 +10624,10 @@ var DawEditorElement = class extends LitElement14 {
9684
10624
  if (structuralChange || mixerChange) {
9685
10625
  this._lastTracksVersion = engineState.tracksVersion;
9686
10626
  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);
10627
+ this.requestUpdate();
9693
10628
  }
9694
10629
  if (structuralChange) {
9695
10630
  this._recomputeDuration();
9696
- if (!this._inOrderSync) {
9697
- this._syncDomToEngineOrder(engineState.tracks);
9698
- }
9699
10631
  this._effectsManager?.rewireTrackChains();
9700
10632
  const audioTracks = engineState.tracks.filter((t) => trackKind(t) !== "midi");
9701
10633
  this._adoptLoadedClips(audioTracks);
@@ -9721,17 +10653,18 @@ var DawEditorElement = class extends LitElement14 {
9721
10653
  this._engine = null;
9722
10654
  }
9723
10655
  }
9724
- async loadFiles(files) {
9725
- return loadFiles(this, files);
10656
+ async loadFiles(files, options = {}) {
10657
+ return loadFiles(this, files, options);
9726
10658
  }
9727
10659
  /**
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.
10660
+ * Imperatively load a `.mid` file (URL or File) and add N tracks (no
10661
+ * element, #848), one per note-bearing MIDI track. On any per-track
10662
+ * failure, every track the call added is removed with no undo step, so the
10663
+ * editor is as before the call.
9732
10664
  *
9733
- * `options.signal` is forwarded to `fetch()` only for URL sources; aborting
9734
- * after parsing does not cancel in-flight `addTrack` calls.
10665
+ * `options.signal` cancels the fetch, the parse and the tracks still
10666
+ * waiting to enter (combined with the arrangement played: a swap cancels
10667
+ * too); the call rejects with its `reason` and removes the tracks it added.
9735
10668
  *
9736
10669
  * Requires the optional `@dawcore/midi` peer dep — throws with an install
9737
10670
  * hint (and `console.warn`s the original error) when the dynamic import
@@ -9750,25 +10683,41 @@ var DawEditorElement = class extends LitElement14 {
9750
10683
  return this._ensureEngine();
9751
10684
  }
9752
10685
  /**
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.
10686
+ * Add a track built from `config` to the arrangement the editor plays when
10687
+ * it is called, and resolve with its id once it has entered (#848), before
10688
+ * its audio has loaded. A swap of `editor.arrangement` before it enters
10689
+ * rejects with an `AbortError` and the track enters nowhere; to add to
10690
+ * another arrangement, call that arrangement's own `addTrack`. No element is created: the track is drawn and listed like any
10691
+ * other, and `<daw-track>` children stay the page's declaration. To follow
10692
+ * loading, add the `daw-track-ready` / `daw-track-error` listener BEFORE
10693
+ * calling: for a track with nothing to fetch it fires before this
10694
+ * resolves. Without `editor.adapter` it waits for one. Rejects when the
10695
+ * arrangement refuses the track, when it is removed before it enters, or
10696
+ * when the engine cannot be built.
10697
+ *
10698
+ * `options.signal` (#848): aborting it before the track has entered takes
10699
+ * it out of the queue (it never enters) and rejects with its `reason`;
10700
+ * after that it changes nothing (the audio goes on loading). A signal
10701
+ * already aborted rejects at once and queues nothing.
9760
10702
  */
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);
10703
+ addTrack(config = {}, options = {}) {
10704
+ const signal = options.signal;
10705
+ if (signal?.aborted) return Promise.reject(reasonOf(signal));
10706
+ const trackId = crypto.randomUUID();
10707
+ let kind = config.kind ?? (config.midi ? "midi" : "audio");
10708
+ if (kind !== "audio" && kind !== "midi") {
10709
+ console.warn(
10710
+ '[dawcore] addTrack: kind "' + String(kind) + `" is not a track kind ('audio' or 'midi'); using "audio"`
10711
+ );
10712
+ kind = "audio";
10713
+ }
10714
+ let renderMode = normalizeRenderMode(config.renderMode);
10715
+ if (renderMode === "both") {
10716
+ console.warn(
10717
+ `[dawcore] render-mode="both" is not yet supported; falling back to 'spectrogram'`
10718
+ );
10719
+ renderMode = "spectrogram";
10720
+ }
9772
10721
  const clipConfigs = [...config.clips ?? []];
9773
10722
  if (config.midi) {
9774
10723
  clipConfigs.push({
@@ -9777,115 +10726,194 @@ var DawEditorElement = class extends LitElement14 {
9777
10726
  midiProgram: config.midi.program
9778
10727
  });
9779
10728
  }
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;
10729
+ const descriptor = {
10730
+ name: config.name || "Untitled",
10731
+ src: "",
10732
+ kind,
10733
+ renderMode: trackDescriptorRenderMode(kind, renderMode),
10734
+ spectrogramConfig: config.spectrogramConfig ?? null,
10735
+ clips: clipConfigs.map((c) => clipDescriptorOf(c))
10736
+ };
10737
+ const mix = {
10738
+ volume: config.volume ?? DEFAULT_TRACK_MIX.volume,
10739
+ pan: config.pan ?? DEFAULT_TRACK_MIX.pan,
10740
+ muted: config.muted ?? false,
10741
+ soloed: config.soloed ?? false
10742
+ };
10743
+ this._pending = new Map(this._pending).set(trackId, { descriptor, mix });
10744
+ const entered = this._waitForEntry(trackId);
10745
+ this._endEntryOnSwap(trackId, entered);
10746
+ this._queueEntry(trackId);
10747
+ if (!signal) return entered;
10748
+ const settled = new AbortController();
10749
+ signal.addEventListener("abort", () => this._abortEntry(trackId, reasonOf(signal)), {
10750
+ signal: settled.signal
10751
+ });
10752
+ return entered.finally(() => settled.abort());
10753
+ }
10754
+ /**
10755
+ * A queued track goes into the arrangement played when it was queued: when
10756
+ * that one is swapped out first, the track leaves the queue and its wait
10757
+ * rejects with the swap's AbortError (addTrack, a dropped file).
10758
+ */
10759
+ _endEntryOnSwap(trackId, entered) {
10760
+ const settled = new AbortController();
10761
+ this._playSignal.addEventListener(
10762
+ "abort",
10763
+ (e) => this._abortEntry(trackId, reasonOf(e.target)),
10764
+ { signal: settled.signal }
10765
+ );
10766
+ void entered.then(
10767
+ () => settled.abort(),
10768
+ () => settled.abort()
10769
+ );
10770
+ }
10771
+ /** A track that has not entered leaves the queue and its wait rejects with `reason` (D4). */
10772
+ _abortEntry(trackId, reason) {
10773
+ if (!this._pending.has(trackId) || this._isEntered(trackId)) return;
10774
+ const nextPending = new Map(this._pending);
10775
+ nextPending.delete(trackId);
10776
+ this._pending = nextPending;
10777
+ this._settleEntry(trackId, reason);
10778
+ this.requestUpdate();
9786
10779
  }
9787
10780
  /**
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.
10781
+ * Remove a track by id: its `<daw-track>` element is removed (the
10782
+ * MutationObserver does the rest), or, for a track with no element
10783
+ * (`addTrack`, a dropped file, an Undo), the track itself. One undo step.
10784
+ * Warns when no track has the id.
9791
10785
  */
9792
10786
  removeTrack(trackId) {
9793
10787
  const trackEl = this._trackElements.get(trackId);
9794
10788
  if (trackEl) {
9795
10789
  trackEl.remove();
9796
10790
  if (!this.isConnected) this._onTrackRemoved(trackId);
9797
- } else if (this._tracks.has(trackId) || this._isEntered(trackId)) {
10791
+ } else if (this._pending.has(trackId) || this._extras.has(trackId) || this._isEntered(trackId)) {
9798
10792
  this._onTrackRemoved(trackId);
9799
10793
  } else {
9800
10794
  console.warn('[dawcore] removeTrack: no track found for id "' + trackId + '"');
9801
10795
  }
9802
10796
  }
9803
10797
  /**
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.
10798
+ * Move a track to a 0-based position in the arrangement's order (every
10799
+ * track counts, those with no element too; `trackEl.index` and
10800
+ * `editor.tracks` give the positions). One undo step; no element moves.
9808
10801
  */
9809
10802
  reorderTrack(trackId, toIndex) {
9810
10803
  if (!Number.isFinite(toIndex)) {
9811
10804
  console.warn("[dawcore] reorderTrack: invalid toIndex " + String(toIndex));
9812
10805
  return;
9813
10806
  }
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 {
10807
+ if (!this._isEntered(trackId)) {
9828
10808
  console.warn('[dawcore] reorderTrack: no track found for id "' + trackId + '"');
10809
+ return;
9829
10810
  }
10811
+ const last = this._arrangement.getTracks().length - 1;
10812
+ this._arrangement.reorderTrack(trackId, Math.max(0, Math.min(Math.trunc(toIndex), last)));
9830
10813
  }
9831
10814
  /**
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.
10815
+ * Change a track: the mix (one undo step, #843), the name (an undo step),
10816
+ * the render mode and spectrogram config (the editor's). The arrangement
10817
+ * is changed, never an element's attributes (#848): a `<daw-track>`'s
10818
+ * properties show the change. A track that has not entered yet gets it as
10819
+ * the value it enters with.
9837
10820
  */
9838
10821
  updateTrack(trackId, partial) {
10822
+ if (!this._isEntered(trackId)) {
10823
+ this._updatePendingTrack(trackId, partial);
10824
+ return;
10825
+ }
9839
10826
  const mix = {
9840
10827
  volume: partial.volume,
9841
10828
  pan: partial.pan,
9842
10829
  muted: partial.muted,
9843
10830
  soloed: partial.soloed
9844
10831
  };
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") {
10832
+ this._writeMixFields(trackId, mix);
10833
+ if (partial.name !== void 0) this._renameTrack(trackId, partial.name);
10834
+ const extras = this._extras.get(trackId) ?? this._defaultExtras(trackId);
10835
+ if (!extras) return;
10836
+ let renderMode = partial.renderMode === void 0 ? void 0 : normalizeRenderMode(partial.renderMode);
10837
+ if (renderMode === "both") {
9866
10838
  console.warn(
9867
10839
  `[dawcore] render-mode="both" is not yet supported; falling back to 'spectrogram'`
9868
10840
  );
9869
- normalizedRenderMode = "spectrogram";
10841
+ renderMode = "spectrogram";
9870
10842
  }
9871
- const newDesc = {
9872
- ...oldDesc,
9873
- ...partial.name !== void 0 && { name: partial.name },
9874
- ...normalizedRenderMode !== void 0 && {
9875
- renderMode: trackDescriptorRenderMode(oldDesc.kind, normalizedRenderMode)
10843
+ if (renderMode === void 0 && partial.spectrogramConfig === void 0) return;
10844
+ const next = {
10845
+ ...extras,
10846
+ ...renderMode !== void 0 && {
10847
+ renderMode: trackDescriptorRenderMode(extras.kind, renderMode)
10848
+ },
10849
+ ...partial.spectrogramConfig !== void 0 && {
10850
+ spectrogramConfig: partial.spectrogramConfig
9876
10851
  }
9877
10852
  };
9878
- this._tracks = new Map(this._tracks).set(trackId, newDesc);
9879
- this._writeMixFields(trackId, mix);
10853
+ this._extras = new Map(this._extras).set(trackId, next);
10854
+ if (next.spectrogramConfig !== extras.spectrogramConfig) {
10855
+ this._spectrogramController?.setTrackConfig(trackId, next.spectrogramConfig ?? null);
10856
+ }
10857
+ }
10858
+ /** `updateTrack` on a track waiting to enter: the values it will enter with. */
10859
+ _updatePendingTrack(trackId, partial) {
10860
+ const pending = this._pending.get(trackId);
10861
+ if (!pending) {
10862
+ console.warn('[dawcore] updateTrack: no track found for id "' + trackId + '"');
10863
+ return;
10864
+ }
10865
+ if ("element" in pending) {
10866
+ const el = pending.element;
10867
+ if (partial.name !== void 0) el.name = partial.name;
10868
+ if (partial.volume !== void 0) el.volume = partial.volume;
10869
+ if (partial.pan !== void 0) el.pan = partial.pan;
10870
+ if (partial.muted !== void 0) el.muted = partial.muted;
10871
+ if (partial.soloed !== void 0) el.soloed = partial.soloed;
10872
+ if (partial.renderMode !== void 0) el.renderMode = partial.renderMode;
10873
+ if (partial.spectrogramConfig !== void 0) el.spectrogramConfig = partial.spectrogramConfig;
10874
+ return;
10875
+ }
10876
+ const { descriptor, mix } = pending;
10877
+ this._pending = new Map(this._pending).set(trackId, {
10878
+ descriptor: {
10879
+ ...descriptor,
10880
+ ...partial.spectrogramConfig !== void 0 && {
10881
+ spectrogramConfig: partial.spectrogramConfig
10882
+ },
10883
+ ...partial.name !== void 0 && { name: partial.name },
10884
+ ...partial.renderMode !== void 0 && {
10885
+ renderMode: trackDescriptorRenderMode(
10886
+ descriptor.kind,
10887
+ normalizeRenderMode(partial.renderMode)
10888
+ )
10889
+ }
10890
+ },
10891
+ mix: {
10892
+ volume: partial.volume ?? mix.volume,
10893
+ pan: partial.pan ?? mix.pan,
10894
+ muted: partial.muted ?? mix.muted,
10895
+ soloed: partial.soloed ?? mix.soloed
10896
+ }
10897
+ });
9880
10898
  }
9881
10899
  /**
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
10900
+ * Add a clip to a track (with or without an element) and resolve with its
9884
10901
  * 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).
10902
+ * drawn). The clip enters the arrangement as a loading clip, one undo
10903
+ * step; no `<daw-clip>` is created (#848). Rejects when it fails to load,
10904
+ * is refused (its kind), or leaves the arrangement before it loads (a
10905
+ * removal, an Undo). A clip added while the editor is detached loads once
10906
+ * a fresh adapter is set.
10907
+ *
10908
+ * `options.signal` (#848): aborting it before the clip has loaded rejects
10909
+ * with its `reason` and removes the clip for good (no undo step); after it
10910
+ * has loaded it changes nothing. A signal already aborted rejects at once
10911
+ * and adds nothing. A swap of `editor.arrangement` rejects the call with an
10912
+ * `AbortError`; its loading clip stays in the arrangement swapped out.
9887
10913
  */
9888
- addClip(trackId, config) {
10914
+ addClip(trackId, config, options = {}) {
10915
+ const callerSignal = options.signal;
10916
+ if (callerSignal?.aborted) return Promise.reject(reasonOf(callerSignal));
9889
10917
  if (!config.src) {
9890
10918
  return Promise.reject(
9891
10919
  new Error(
@@ -9893,38 +10921,45 @@ var DawEditorElement = class extends LitElement14 {
9893
10921
  )
9894
10922
  );
9895
10923
  }
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)) {
10924
+ const pending = this._pending.get(trackId);
10925
+ if (!this._isEntered(trackId) && !pending) {
9905
10926
  return Promise.reject(
9906
10927
  new Error(
9907
- 'addClip: track "' + trackId + '" is not in the editor (an Undo took it out, or the arrangement refused it)'
10928
+ 'addClip: track "' + trackId + '" is not in the editor (an Undo took it out, the arrangement refused it, or no track has this id)'
9908
10929
  )
9909
10930
  );
9910
10931
  }
9911
- const clipEl = this._buildClipElement(config);
9912
- const clipId = clipEl.clipId;
10932
+ const clipDesc = clipDescriptorOf(config);
10933
+ const clipId = clipDesc.clipId;
9913
10934
  return new Promise((resolve, reject) => {
9914
10935
  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)));
10936
+ const call = new AbortController();
10937
+ const cleanup = () => {
10938
+ call.abort();
10939
+ this._awaitedClips.delete(clipId);
9925
10940
  };
9926
- const stopWatching = this._arrangement.subscribe(() => {
9927
- const present = this._arrangement.getTracks().some((t) => t.clips.some((c) => c.id === clipId));
10941
+ this.addEventListener(
10942
+ "daw-clip-ready",
10943
+ (e) => {
10944
+ if (e.detail.clipId !== clipId) return;
10945
+ cleanup();
10946
+ resolve(clipId);
10947
+ },
10948
+ { signal: call.signal }
10949
+ );
10950
+ this.addEventListener(
10951
+ "daw-clip-error",
10952
+ (e) => {
10953
+ const detail = e.detail;
10954
+ if (detail.clipId !== clipId) return;
10955
+ cleanup();
10956
+ reject(detail.error instanceof Error ? detail.error : new Error(String(detail.error)));
10957
+ },
10958
+ { signal: call.signal }
10959
+ );
10960
+ const watched = pending && "element" in pending && !this._isEntered(trackId) ? this._ownArrangement : this._arrangement;
10961
+ const stopWatching = watched.subscribe(() => {
10962
+ const present = watched.getTracks().some((t) => t.clips.some((c) => c.id === clipId));
9928
10963
  if (present) {
9929
10964
  seen = true;
9930
10965
  } else if (seen) {
@@ -9932,14 +10967,24 @@ var DawEditorElement = class extends LitElement14 {
9932
10967
  reject(new Error('clip "' + clipId + '" was removed before its audio loaded'));
9933
10968
  }
9934
10969
  });
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);
10970
+ call.signal.addEventListener("abort", stopWatching);
10971
+ this._playSignals.signalOf(watched).addEventListener(
10972
+ "abort",
10973
+ (e) => {
10974
+ cleanup();
10975
+ reject(reasonOf(e.target));
10976
+ },
10977
+ { signal: call.signal }
10978
+ );
10979
+ callerSignal?.addEventListener(
10980
+ "abort",
10981
+ () => {
10982
+ cleanup();
10983
+ this._discardAddedClip(trackId, clipId);
10984
+ reject(reasonOf(callerSignal));
10985
+ },
10986
+ { signal: call.signal }
10987
+ );
9943
10988
  this._awaitedClips.set(clipId, {
9944
10989
  trackId,
9945
10990
  reject: (error) => {
@@ -9947,122 +10992,91 @@ var DawEditorElement = class extends LitElement14 {
9947
10992
  reject(error);
9948
10993
  }
9949
10994
  });
9950
- trackEl.appendChild(clipEl);
10995
+ if (this._isEntered(trackId)) {
10996
+ seen = true;
10997
+ this._loadAndAppendClip(trackId, clipDesc);
10998
+ } else if (pending) {
10999
+ this._pending = new Map(this._pending).set(
11000
+ trackId,
11001
+ "element" in pending ? { ...pending, extraClips: [...pending.extraClips, clipDesc] } : {
11002
+ ...pending,
11003
+ descriptor: {
11004
+ ...pending.descriptor,
11005
+ clips: [...pending.descriptor.clips, clipDesc]
11006
+ }
11007
+ }
11008
+ );
11009
+ }
9951
11010
  });
9952
11011
  }
9953
11012
  /**
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.
11013
+ * Remove a clip by id: its `<daw-clip>` when there is one (the observer
11014
+ * removes the clip, as `select.remove(i)` removes an option), otherwise
11015
+ * the clip itself, one undo step. Undo brings the clip back with no
11016
+ * element. No-op with a warning when there is no such clip.
9957
11017
  */
9958
11018
  removeClip(trackId, clipId) {
9959
11019
  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
- }
11020
+ const clipEl = trackEl ? [...trackEl.querySelectorAll("daw-clip")].find(
11021
+ (c) => c.clipId === clipId
11022
+ ) : void 0;
11023
+ if (clipEl) {
11024
+ clipEl.remove();
11025
+ if (!this.isConnected && this._isEntered(trackId)) this._removeClipFromTrack(trackId, clipId);
11026
+ return;
9968
11027
  }
9969
11028
  if (this._isEntered(trackId)) {
9970
11029
  this._removeClipFromTrack(trackId, clipId);
9971
11030
  return;
9972
11031
  }
11032
+ const pending = this._pending.get(trackId);
11033
+ if (pending) {
11034
+ const without = (clips) => clips.filter((c) => c.clipId !== clipId);
11035
+ this._pending = new Map(this._pending).set(
11036
+ trackId,
11037
+ "element" in pending ? { ...pending, extraClips: without(pending.extraClips) } : {
11038
+ ...pending,
11039
+ descriptor: { ...pending.descriptor, clips: without(pending.descriptor.clips) }
11040
+ }
11041
+ );
11042
+ this._rejectAwaitedClips((id) => id === clipId, "the clip was removed before it loaded");
11043
+ return;
11044
+ }
9973
11045
  console.warn(
9974
11046
  '[dawcore] removeClip: no track found for id "' + trackId + '" (clipId "' + clipId + '")'
9975
11047
  );
9976
11048
  }
9977
11049
  /**
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`.
11050
+ * Change a clip's position (start/duration/offset), gain or name: one undo
11051
+ * step on the arrangement (#848; a clip still loading changes its loading
11052
+ * clip). A `<daw-clip>`'s properties show the change, its attributes do
11053
+ * not. Fades are a `<daw-clip>` declaration only (engine-side fades are
11054
+ * #489): `fadeIn` / `fadeOut` / `fadeType` here change nothing.
9981
11055
  *
9982
11056
  * Re-decoding (changing `src`) is not supported via this method — remove and
9983
11057
  * 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
11058
  */
9990
11059
  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) {
11060
+ if (!this._isEntered(trackId)) {
10010
11061
  console.warn('[dawcore] updateClip: no track found for id "' + trackId + '"');
10011
11062
  return;
10012
11063
  }
10013
- const idx = t.clips.findIndex((c) => c.id === clipId);
10014
- if (idx === -1) {
11064
+ if (!this._clipValues(trackId, clipId)) {
10015
11065
  console.warn(
10016
11066
  '[dawcore] updateClip: clip "' + clipId + '" not found in track "' + trackId + '"'
10017
11067
  );
10018
11068
  return;
10019
11069
  }
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;
11070
+ const request = {};
11071
+ if (partial.start !== void 0) request.start = partial.start;
11072
+ if (partial.duration !== void 0) request.duration = partial.duration;
11073
+ if (partial.offset !== void 0) request.offset = partial.offset;
11074
+ if (partial.gain !== void 0) request.gain = partial.gain;
11075
+ if (partial.name !== void 0) request.name = partial.name;
11076
+ if (partial.midiNotes !== void 0) request.midiNotes = partial.midiNotes;
11077
+ if (partial.midiChannel !== void 0) request.midiChannel = partial.midiChannel;
11078
+ if (partial.midiProgram !== void 0) request.midiProgram = partial.midiProgram;
11079
+ this._requestClipChange(trackId, clipId, request);
10066
11080
  }
10067
11081
  // --- Playback ---
10068
11082
  /**
@@ -10329,8 +11343,8 @@ var DawEditorElement = class extends LitElement14 {
10329
11343
  return;
10330
11344
  }
10331
11345
  const targetId = options?.trackId ?? this._selectedTrackId;
10332
- const target = targetId ? this._tracks.get(targetId) : void 0;
10333
- if (targetId && target?.kind === "midi") {
11346
+ const target = targetId ? this._arrangement.getTracks().find((t) => t.id === targetId) : void 0;
11347
+ if (targetId && target && trackKind(target) === "midi") {
10334
11348
  const error = new Error(
10335
11349
  'Cannot record onto MIDI track "' + target.name + '": a recording is audio. Select or create an audio track first.'
10336
11350
  );
@@ -10437,67 +11451,25 @@ var DawEditorElement = class extends LitElement14 {
10437
11451
  return (this._getOrderedTracks().length > 0 || this.scaleMode === "beats" || this.indefinitePlayback || this.fillViewport) && this.timescale;
10438
11452
  }
10439
11453
  /**
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.
11454
+ * `<daw-track>` elements the page moved (one MutationObserver batch): each
11455
+ * is placed after the arrangement track of the nearest `<daw-track>` before
11456
+ * it, in DOM order, as one undo step (#848 P13). Elements whose track is
11457
+ * not in the arrangement are left alone (a queued one enters at its DOM
11458
+ * position). The arrangement's own order changes (an Undo) move no element.
10447
11459
  */
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;
11460
+ _placeMovedTracks(movedIds) {
11461
+ const els = [...this.querySelectorAll("daw-track")];
11462
+ const moved = els.filter((el) => movedIds.has(el.trackId) && this._isEntered(el.trackId));
11463
+ if (moved.length === 0) return;
11464
+ const arrangement = this._arrangement;
11465
+ arrangement.beginTransaction();
10464
11466
  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();
11467
+ for (const el of moved) {
11468
+ const others = arrangement.getTracks().map((t) => t.id).filter((id) => id !== el.trackId);
11469
+ arrangement.reorderTrack(el.trackId, entryIndex(els, el.trackId, others));
11470
+ }
10475
11471
  } 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]);
11472
+ arrangement.commitTransaction();
10501
11473
  }
10502
11474
  }
10503
11475
  /**
@@ -10507,9 +11479,12 @@ var DawEditorElement = class extends LitElement14 {
10507
11479
  _getOrderedTracks() {
10508
11480
  const rows = [];
10509
11481
  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)]);
11482
+ const loaded = loadedTrack(
11483
+ track,
11484
+ this._mixOf(track.id),
11485
+ this._arrangement.recordingTrackIds.has(track.id)
11486
+ );
11487
+ rows.push([track.id, loaded, track.clips.filter(isLoadingClip5)]);
10513
11488
  }
10514
11489
  return rows;
10515
11490
  }
@@ -10578,7 +11553,11 @@ var DawEditorElement = class extends LitElement14 {
10578
11553
  selEndPx = this._selectionEndTime * sr / spp;
10579
11554
  }
10580
11555
  const orderedTracks = this._getOrderedTracks().map(([trackId, track, loading]) => {
10581
- const descriptor = this._tracks.get(trackId);
11556
+ const descriptor = {
11557
+ name: track.name ?? "",
11558
+ kind: trackKind(track),
11559
+ renderMode: this._renderModeOf(trackId)
11560
+ };
10582
11561
  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
11562
  const recSession = this._recordingController.getSession(trackId);
10584
11563
  const numChannels = firstPeaks ? firstPeaks.data.length : recSession ? recSession.channelCount : 1;
@@ -10626,24 +11605,30 @@ var DawEditorElement = class extends LitElement14 {
10626
11605
  <span class="annotation-lane-name">${track.name}</span>
10627
11606
  </div>`
10628
11607
  )}
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
- })}
11608
+ ${repeat(
11609
+ orderedTracks,
11610
+ // Keyed by track: a swap or an outside reorder must not hand
11611
+ // a row (and a slider gesture held in it) to another track.
11612
+ (t) => t.trackId,
11613
+ (t, i) => {
11614
+ const mix = this._mixOf(t.trackId);
11615
+ return html12`
11616
+ <daw-track-controls
11617
+ style="height: ${t.trackHeight}px;"
11618
+ .trackId=${t.trackId}
11619
+ .trackName=${t.descriptor?.name ?? "Untitled"}
11620
+ .volume=${mix.volume}
11621
+ .pan=${mix.pan}
11622
+ .muted=${mix.muted}
11623
+ .recording=${this._engine?.recordingTrackIds.has(t.trackId) ?? false}
11624
+ .soloed=${mix.soloed}
11625
+ .reorderable=${this.trackReordering}
11626
+ .trackIndex=${i}
11627
+ .trackCount=${orderedTracks.length}
11628
+ ></daw-track-controls>
11629
+ `;
11630
+ }
11631
+ )}
10647
11632
  </div>
10648
11633
  </div>` : ""}
10649
11634
  <div class="scroll-area">
@@ -10674,149 +11659,158 @@ var DawEditorElement = class extends LitElement14 {
10674
11659
  ></daw-grid>` : ""}
10675
11660
  ${orderedTracks.length > 0 || this.scaleMode === "beats" || this.indefinitePlayback || this.fillViewport ? html12`<daw-selection .startPx=${selStartPx} .endPx=${selEndPx}></daw-selection>
10676
11661
  <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));
11662
+ ${repeat(
11663
+ orderedTracks,
11664
+ (t) => t.trackId,
11665
+ (t) => {
11666
+ const channelHeight = this.waveHeight;
11667
+ return html12`
11668
+ <div
11669
+ class="track-row ${t.trackId === this._selectedTrackId ? "selected" : ""}"
11670
+ style="height: ${t.trackHeight}px;"
11671
+ data-track-id=${t.trackId}
11672
+ >
11673
+ ${t.track.clips.map((clip) => {
11674
+ const peakData = this._peaksData.get(clip.id) ?? this._previewPeaks.get(clip.id);
11675
+ let clipLeft;
11676
+ let width;
11677
+ if (this.scaleMode === "beats") {
11678
+ const startTick = clip.startTick !== void 0 ? clip.startTick : this._secondsToTicks(clip.startSample / sr);
11679
+ const durSec = clip.durationSamples / sr;
10715
11680
  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
- });
11681
+ const endTick = this._secondsToTicks(startSec + durSec);
11682
+ clipLeft = Math.round(startTick / this.ticksPerPixel);
11683
+ width = Math.round(endTick / this.ticksPerPixel) - clipLeft;
11684
+ } else {
11685
+ clipLeft = Math.floor(clip.startSample / spp);
11686
+ width = clipPixelWidth(clip.startSample, clip.durationSamples, spp);
11687
+ }
11688
+ let clipSegments;
11689
+ let segmentChannels;
11690
+ if (this.scaleMode === "beats" && this.secondsToTicks) {
11691
+ const audioBuffer = this._clipBuffers.get(clip.id);
11692
+ const basePeaks = audioBuffer ? this._peakPipeline.getBaseScalePeaks(
11693
+ audioBuffer,
11694
+ this.mono,
11695
+ clip.offsetSamples,
11696
+ clip.durationSamples
11697
+ ) : null;
11698
+ if (basePeaks) {
11699
+ const baseScale = basePeaks.scale;
11700
+ segmentChannels = basePeaks.peaks.data;
11701
+ const MIN_RENDER_STEP = 80;
11702
+ const stepTicks = Math.max(
11703
+ MIN_RENDER_STEP,
11704
+ Math.ceil(this.ticksPerPixel)
11705
+ );
11706
+ const startSec = clip.startTick !== void 0 ? this._ticksToSeconds(clip.startTick) : clip.startSample / sr;
11707
+ const clipOffsetSec = clip.offsetSamples / sr;
11708
+ const segStartTick = clip.startTick !== void 0 ? clip.startTick : this._secondsToTicks(startSec);
11709
+ const endTick = this._secondsToTicks(
11710
+ startSec + clip.durationSamples / sr
11711
+ );
11712
+ clipSegments = [];
11713
+ for (let tick = segStartTick; tick < endTick; tick += stepTicks) {
11714
+ const segEndTick = Math.min(tick + stepTicks, endTick);
11715
+ const segStartAudioSec = this._ticksToSeconds(tick) - startSec + clipOffsetSec;
11716
+ const segEndAudioSec = this._ticksToSeconds(segEndTick) - startSec + clipOffsetSec;
11717
+ const segStartSample = Math.round(segStartAudioSec * sr);
11718
+ const segEndSample = Math.round(segEndAudioSec * sr);
11719
+ const totalPeaks = clip.durationSamples / baseScale;
11720
+ clipSegments.push({
11721
+ peakStart: Math.max(
11722
+ 0,
11723
+ (segStartSample - clip.offsetSamples) / baseScale
11724
+ ),
11725
+ peakEnd: Math.min(
11726
+ totalPeaks,
11727
+ (segEndSample - clip.offsetSamples) / baseScale
11728
+ ),
11729
+ pixelStart: (tick - segStartTick) / this.ticksPerPixel,
11730
+ pixelEnd: (segEndTick - segStartTick) / this.ticksPerPixel
11731
+ });
11732
+ }
10739
11733
  }
10740
11734
  }
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"
11735
+ const channels = segmentChannels ?? peakData?.data ?? [new Int16Array(0)];
11736
+ const hdrH = this.clipHeaders ? this.clipHeaderHeight : 0;
11737
+ const chH = this.waveHeight;
11738
+ return html12` <div
11739
+ class="clip-container"
11740
+ style="left:${clipLeft}px;top:0;width:${width}px;height:${t.trackHeight}px;"
11741
+ data-clip-id=${clip.id}
11742
+ >
11743
+ ${hdrH > 0 ? html12`<div
11744
+ class="clip-header"
10810
11745
  data-clip-id=${clip.id}
10811
11746
  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
- })}
11747
+ ?data-interactive=${this.interactiveClips}
11748
+ >
11749
+ <span>${clip.name || t.descriptor?.name || ""}</span>
11750
+ </div>` : ""}
11751
+ ${t.descriptor?.kind === "midi" ? html12`<daw-piano-roll
11752
+ style="position:absolute;left:0;top:${hdrH}px;"
11753
+ .midiNotes=${clip.midiNotes ?? []}
11754
+ .length=${peakData?.length ?? width}
11755
+ .waveHeight=${chH * channels.length}
11756
+ .samplesPerPixel=${this._renderSpp}
11757
+ .sampleRate=${this.effectiveSampleRate}
11758
+ .clipOffsetSeconds=${(clip.offsetSamples ?? 0) / this.effectiveSampleRate}
11759
+ .visibleStart=${this._viewport.visibleStart}
11760
+ .visibleEnd=${this._viewport.visibleEnd}
11761
+ .originX=${clipLeft}
11762
+ ?selected=${t.trackId === this._selectedTrackId}
11763
+ ></daw-piano-roll>` : t.descriptor?.renderMode === "spectrogram" ? channels.map(
11764
+ (_chPeaks, chIdx) => html12`<daw-spectrogram
11765
+ style="position:absolute;left:0;top:${hdrH + chIdx * chH}px;height:${chH}px;width:${peakData?.length ?? width}px;"
11766
+ .clipId=${clip.id}
11767
+ .trackId=${t.trackId}
11768
+ .channelIndex=${chIdx}
11769
+ .length=${peakData?.length ?? width}
11770
+ .waveHeight=${chH}
11771
+ .samplesPerPixel=${this._renderSpp}
11772
+ .sampleRate=${this.effectiveSampleRate}
11773
+ .clipOffsetSeconds=${(clip.offsetSamples ?? 0) / this.effectiveSampleRate}
11774
+ .visibleStart=${this._viewport.visibleStart}
11775
+ .visibleEnd=${this._viewport.visibleEnd}
11776
+ .originX=${clipLeft}
11777
+ ></daw-spectrogram>`
11778
+ ) : channels.map(
11779
+ (chPeaks, chIdx) => html12` <daw-waveform
11780
+ style="position:absolute;left:0;top:${hdrH + chIdx * chH}px;"
11781
+ .peaks=${chPeaks}
11782
+ .length=${peakData?.length ?? width}
11783
+ .waveHeight=${chH}
11784
+ .barWidth=${this.barWidth}
11785
+ .barGap=${this.barGap}
11786
+ .roundedBars=${this.roundedBars}
11787
+ .gain=${this.gainScaledWaveforms ? clip.gain ?? 1 : 1}
11788
+ .visibleStart=${this._viewport.visibleStart}
11789
+ .visibleEnd=${this._viewport.visibleEnd}
11790
+ .originX=${clipLeft}
11791
+ .segments=${clipSegments}
11792
+ ></daw-waveform>`
11793
+ )}
11794
+ ${this.interactiveClips ? html12` <div
11795
+ class="clip-boundary"
11796
+ data-boundary-edge="left"
11797
+ data-clip-id=${clip.id}
11798
+ data-track-id=${t.trackId}
11799
+ ></div>
11800
+ <div
11801
+ class="clip-boundary"
11802
+ data-boundary-edge="right"
11803
+ data-clip-id=${clip.id}
11804
+ data-track-id=${t.trackId}
11805
+ ></div>` : ""}
11806
+ </div>`;
11807
+ })}
11808
+ ${t.loading.map((clip) => this._renderPlaceholder(clip, t))}
11809
+ ${this._renderRecordingPreview(t.trackId, channelHeight)}
11810
+ </div>
11811
+ `;
11812
+ }
11813
+ )}
10820
11814
  </div>
10821
11815
  </div>
10822
11816
  </div>
@@ -10827,6 +11821,10 @@ var DawEditorElement = class extends LitElement14 {
10827
11821
  DawEditorElement.styles = [
10828
11822
  hostStyles,
10829
11823
  css11`
11824
+ /* The hidden attribute hides the element: :host sets display (modern-web-guidance custom-elements). */
11825
+ :host([hidden]) {
11826
+ display: none;
11827
+ }
10830
11828
  :host {
10831
11829
  display: flex;
10832
11830
  flex-direction: column;
@@ -11056,10 +12054,7 @@ __decorateClass([
11056
12054
  ], DawEditorElement.prototype, "_previewPeaks", 2);
11057
12055
  __decorateClass([
11058
12056
  state4()
11059
- ], DawEditorElement.prototype, "_tracks", 2);
11060
- __decorateClass([
11061
- state4()
11062
- ], DawEditorElement.prototype, "_engineTracks", 2);
12057
+ ], DawEditorElement.prototype, "_extras", 2);
11063
12058
  __decorateClass([
11064
12059
  state4()
11065
12060
  ], DawEditorElement.prototype, "_peaksData", 2);
@@ -11135,6 +12130,8 @@ var DawRecordButtonElement = class extends DawTransportButton {
11135
12130
  super(...arguments);
11136
12131
  this._isRecording = false;
11137
12132
  this._targetRef = null;
12133
+ /** The listeners on `_targetRef`, aborted when the target changes or the button disconnects. */
12134
+ this._targetListeners = null;
11138
12135
  this._onStart = () => {
11139
12136
  this._isRecording = true;
11140
12137
  };
@@ -11165,15 +12162,16 @@ var DawRecordButtonElement = class extends DawTransportButton {
11165
12162
  this._cleanupListeners();
11166
12163
  if (!target) return;
11167
12164
  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);
12165
+ this._targetListeners = new AbortController();
12166
+ const { signal } = this._targetListeners;
12167
+ target.addEventListener("daw-recording-start", this._onStart, { signal });
12168
+ target.addEventListener("daw-recording-complete", this._onComplete, { signal });
12169
+ target.addEventListener("daw-recording-error", this._onError, { signal });
11171
12170
  }
11172
12171
  _cleanupListeners() {
11173
12172
  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);
12173
+ this._targetListeners?.abort();
12174
+ this._targetListeners = null;
11177
12175
  this._targetRef = null;
11178
12176
  }
11179
12177
  }
@@ -11244,6 +12242,9 @@ var DawKeyboardShortcutsElement = class extends LitElement16 {
11244
12242
  this._customShortcuts = [];
11245
12243
  this._editor = null;
11246
12244
  this._cachedShortcuts = null;
12245
+ // --- Lifecycle ---
12246
+ /** The listeners of this connection, aborted in disconnectedCallback. */
12247
+ this._listeners = null;
11247
12248
  // --- Event handler ---
11248
12249
  this._onKeyDown = (e) => {
11249
12250
  const shortcuts = this.shortcuts;
@@ -11302,7 +12303,6 @@ var DawKeyboardShortcutsElement = class extends LitElement16 {
11302
12303
  updated() {
11303
12304
  this._cachedShortcuts = null;
11304
12305
  }
11305
- // --- Lifecycle ---
11306
12306
  connectedCallback() {
11307
12307
  super.connectedCallback();
11308
12308
  for (const prop of [
@@ -11323,11 +12323,15 @@ var DawKeyboardShortcutsElement = class extends LitElement16 {
11323
12323
  "[dawcore] <daw-keyboard-shortcuts> must be placed inside a <daw-editor>. Preset shortcuts (playback, splitting, undo) will be inactive; only customShortcuts will fire."
11324
12324
  );
11325
12325
  }
11326
- document.addEventListener("keydown", this._onKeyDown);
12326
+ this._listeners?.abort();
12327
+ this._listeners = new AbortController();
12328
+ const { signal } = this._listeners;
12329
+ document.addEventListener("keydown", this._onKeyDown, { signal });
11327
12330
  }
11328
12331
  disconnectedCallback() {
11329
12332
  super.disconnectedCallback();
11330
- document.removeEventListener("keydown", this._onKeyDown);
12333
+ this._listeners?.abort();
12334
+ this._listeners = null;
11331
12335
  this._editor = null;
11332
12336
  }
11333
12337
  // No shadow DOM — render-less element
@@ -11653,20 +12657,25 @@ var DawTimeDisplayElement = class extends LitElement18 {
11653
12657
  this._format = detail.format;
11654
12658
  }
11655
12659
  };
12660
+ /** The listeners of this connection, aborted in disconnectedCallback. */
12661
+ this._listeners = null;
11656
12662
  }
11657
12663
  get target() {
11658
12664
  return resolveTransportTarget(this);
11659
12665
  }
11660
12666
  connectedCallback() {
11661
12667
  super.connectedCallback();
11662
- document.addEventListener("daw-timeupdate", this._onTimeUpdate);
11663
- document.addEventListener("daw-time-format-change", this._onFormatChange);
12668
+ this._listeners?.abort();
12669
+ this._listeners = new AbortController();
12670
+ const { signal } = this._listeners;
12671
+ document.addEventListener("daw-timeupdate", this._onTimeUpdate, { signal });
12672
+ document.addEventListener("daw-time-format-change", this._onFormatChange, { signal });
11664
12673
  requestAnimationFrame(() => this._syncFromTarget());
11665
12674
  }
11666
12675
  disconnectedCallback() {
11667
12676
  super.disconnectedCallback();
11668
- document.removeEventListener("daw-timeupdate", this._onTimeUpdate);
11669
- document.removeEventListener("daw-time-format-change", this._onFormatChange);
12677
+ this._listeners?.abort();
12678
+ this._listeners = null;
11670
12679
  }
11671
12680
  _syncFromTarget() {
11672
12681
  if (!this.isConnected) return;
@@ -11737,6 +12746,8 @@ var DawTimeFormatElement = class extends LitElement19 {
11737
12746
  warnUnsupportedOnce(this, ["setTimeFormat"]);
11738
12747
  }
11739
12748
  };
12749
+ /** The listeners of this connection, aborted in disconnectedCallback. */
12750
+ this._listeners = null;
11740
12751
  }
11741
12752
  get target() {
11742
12753
  return resolveTransportTarget(this);
@@ -11754,9 +12765,12 @@ var DawTimeFormatElement = class extends LitElement19 {
11754
12765
  }
11755
12766
  connectedCallback() {
11756
12767
  super.connectedCallback();
11757
- document.addEventListener("daw-time-format-change", this._onFormatChange);
11758
- this.addEventListener("pointerdown", this._onPointerDown);
11759
- this.addEventListener("pointerenter", this._onPointerEnter);
12768
+ this._listeners?.abort();
12769
+ this._listeners = new AbortController();
12770
+ const { signal } = this._listeners;
12771
+ document.addEventListener("daw-time-format-change", this._onFormatChange, { signal });
12772
+ this.addEventListener("pointerdown", this._onPointerDown, { signal });
12773
+ this.addEventListener("pointerenter", this._onPointerEnter, { signal });
11760
12774
  requestAnimationFrame(() => {
11761
12775
  if (!this.isConnected) return;
11762
12776
  const target = this.target;
@@ -11768,9 +12782,8 @@ var DawTimeFormatElement = class extends LitElement19 {
11768
12782
  }
11769
12783
  disconnectedCallback() {
11770
12784
  super.disconnectedCallback();
11771
- document.removeEventListener("daw-time-format-change", this._onFormatChange);
11772
- this.removeEventListener("pointerdown", this._onPointerDown);
11773
- this.removeEventListener("pointerenter", this._onPointerEnter);
12785
+ this._listeners?.abort();
12786
+ this._listeners = null;
11774
12787
  }
11775
12788
  updated() {
11776
12789
  const select = this.shadowRoot?.querySelector("select");
@@ -11825,7 +12838,7 @@ DawTimeFormatElement = __decorateClass([
11825
12838
  // src/elements/daw-player.ts
11826
12839
  import { LitElement as LitElement20, html as html18, css as css17 } from "lit";
11827
12840
  import { customElement as customElement23, property as property16, state as state8 } from "lit/decorators.js";
11828
- import { repeat } from "lit/directives/repeat.js";
12841
+ import { repeat as repeat2 } from "lit/directives/repeat.js";
11829
12842
  import { MediaElementPlayout } from "@waveform-playlist/media-element-playout";
11830
12843
  var MIN_RATE = 0.25;
11831
12844
  var MAX_RATE = 4;
@@ -11855,6 +12868,8 @@ var DawPlayerElement = class extends LitElement20 {
11855
12868
  this._channelPeaks = [];
11856
12869
  this._sampleRate = 48e3;
11857
12870
  this._resizeObserver = null;
12871
+ /** The peaks fetch in flight: a newer peaks-src or a disconnect aborts it (#848, D7). */
12872
+ this._peaksFetch = null;
11858
12873
  this._onPointerDown = (e) => {
11859
12874
  const area = e.currentTarget;
11860
12875
  const width = area.clientWidth;
@@ -11928,6 +12943,7 @@ var DawPlayerElement = class extends LitElement20 {
11928
12943
  const area = this.shadowRoot?.querySelector(".waveform-area");
11929
12944
  if (area) this._resizeObserver?.observe(area);
11930
12945
  });
12946
+ if (rebuilt && this.peaksSrc && !this._peaksSettled) void this._loadPeaks();
11931
12947
  if (rebuilt && this.src) {
11932
12948
  this._loadSource();
11933
12949
  this._playhead?.setPosition(0);
@@ -11949,7 +12965,7 @@ var DawPlayerElement = class extends LitElement20 {
11949
12965
  style="height:${this.waveHeight}px"
11950
12966
  @pointerdown=${this._onPointerDown}
11951
12967
  >
11952
- ${repeat(
12968
+ ${repeat2(
11953
12969
  this._channelPeaks,
11954
12970
  (_p, i) => i,
11955
12971
  (peaks) => html18`<daw-waveform
@@ -11972,6 +12988,8 @@ var DawPlayerElement = class extends LitElement20 {
11972
12988
  if (changed.has("mono")) this._renderWaveform();
11973
12989
  }
11974
12990
  async _loadPeaks() {
12991
+ this._peaksFetch?.abort();
12992
+ this._peaksFetch = null;
11975
12993
  this._waveformData = null;
11976
12994
  this._readyDispatched = false;
11977
12995
  this._peaksSettled = false;
@@ -11982,8 +13000,11 @@ var DawPlayerElement = class extends LitElement20 {
11982
13000
  return;
11983
13001
  }
11984
13002
  const requested = this.peaksSrc;
13003
+ const fetching = new AbortController();
13004
+ this._peaksFetch = fetching;
11985
13005
  try {
11986
- const wd = await loadWaveformDataFromUrl(requested);
13006
+ const wd = await loadWaveformDataFromUrl(requested, fetching.signal);
13007
+ if (this._peaksFetch === fetching) this._peaksFetch = null;
11987
13008
  if (this.peaksSrc !== requested) return;
11988
13009
  this._waveformData = wd;
11989
13010
  this._sampleRate = wd.sample_rate;
@@ -11991,6 +13012,7 @@ var DawPlayerElement = class extends LitElement20 {
11991
13012
  this._renderWaveform();
11992
13013
  this._maybeDispatchReady();
11993
13014
  } catch (err) {
13015
+ if (fetching.signal.aborted) return;
11994
13016
  if (this.peaksSrc !== requested) return;
11995
13017
  console.warn("[dawcore] <daw-player> failed to load peaks-src: " + String(err));
11996
13018
  this._peaksSettled = true;
@@ -12090,6 +13112,8 @@ var DawPlayerElement = class extends LitElement20 {
12090
13112
  this._engine.off("error", this._onError);
12091
13113
  this._engine.dispose();
12092
13114
  this._engineDisposed = true;
13115
+ this._peaksFetch?.abort();
13116
+ this._peaksFetch = null;
12093
13117
  }
12094
13118
  // --- Private event handlers (arrow fields for stable identity) ---
12095
13119
  _dispatch(name, detail) {
@@ -12116,6 +13140,10 @@ var DawPlayerElement = class extends LitElement20 {
12116
13140
  }
12117
13141
  };
12118
13142
  DawPlayerElement.styles = css17`
13143
+ /* The hidden attribute hides the element: :host sets display (modern-web-guidance custom-elements). */
13144
+ :host([hidden]) {
13145
+ display: none;
13146
+ }
12119
13147
  :host {
12120
13148
  display: block;
12121
13149
  position: relative;