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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -82,7 +82,7 @@ __export(index_exports, {
82
82
  module.exports = __toCommonJS(index_exports);
83
83
 
84
84
  // <define:__INSTALL_SPECS__>
85
- 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" };
85
+ 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" };
86
86
 
87
87
  // src/elements/daw-annotation.ts
88
88
  var import_lit = require("lit");
@@ -333,6 +333,8 @@ var DawAnnotationTrackElement = class extends import_lit2.LitElement {
333
333
  };
334
334
  // --- Lifecycle ---
335
335
  this._childObserver = null;
336
+ /** The listeners of this connection, aborted in disconnectedCallback. */
337
+ this._listeners = null;
336
338
  }
337
339
  get activeAnnotationId() {
338
340
  return this._activeAnnotationId;
@@ -533,7 +535,13 @@ var DawAnnotationTrackElement = class extends import_lit2.LitElement {
533
535
  delete this["annotationShortcuts"];
534
536
  this.annotationShortcuts = value;
535
537
  }
536
- document.addEventListener("keydown", this._onKeyDownCapture, true);
538
+ this._listeners?.abort();
539
+ this._listeners = new AbortController();
540
+ document.addEventListener("keydown", this._onKeyDownCapture, {
541
+ capture: true,
542
+ // capture phase
543
+ signal: this._listeners.signal
544
+ });
537
545
  setTimeout(() => {
538
546
  this.dispatchEvent(
539
547
  new CustomEvent("daw-annotation-track-connected", {
@@ -552,7 +560,8 @@ var DawAnnotationTrackElement = class extends import_lit2.LitElement {
552
560
  }
553
561
  disconnectedCallback() {
554
562
  super.disconnectedCallback();
555
- document.removeEventListener("keydown", this._onKeyDownCapture, true);
563
+ this._listeners?.abort();
564
+ this._listeners = null;
556
565
  this._childObserver?.disconnect();
557
566
  this._childObserver = null;
558
567
  }
@@ -626,6 +635,8 @@ var DawAnnotationListElement = class extends import_lit3.LitElement {
626
635
  * blur event doesn't re-enter `_commitEdit` (cancel already restores the
627
636
  * text and clears `_editingId` itself). */
628
637
  this._cancelling = false;
638
+ /** The listeners of this connection, aborted in disconnectedCallback. */
639
+ this._listeners = null;
629
640
  this._onSelect = (e) => {
630
641
  if (e.target !== this.track) return;
631
642
  this._activeId = e.detail.annotation?.id ?? null;
@@ -683,15 +694,17 @@ var DawAnnotationListElement = class extends import_lit3.LitElement {
683
694
  }
684
695
  connectedCallback() {
685
696
  super.connectedCallback();
686
- document.addEventListener("daw-annotation-select", this._onSelect);
687
- document.addEventListener("daw-timeupdate", this._onTimeUpdate);
688
- document.addEventListener("daw-stop", this._onStop);
697
+ this._listeners?.abort();
698
+ this._listeners = new AbortController();
699
+ const { signal } = this._listeners;
700
+ document.addEventListener("daw-annotation-select", this._onSelect, { signal });
701
+ document.addEventListener("daw-timeupdate", this._onTimeUpdate, { signal });
702
+ document.addEventListener("daw-stop", this._onStop, { signal });
689
703
  }
690
704
  disconnectedCallback() {
691
705
  super.disconnectedCallback();
692
- document.removeEventListener("daw-annotation-select", this._onSelect);
693
- document.removeEventListener("daw-timeupdate", this._onTimeUpdate);
694
- document.removeEventListener("daw-stop", this._onStop);
706
+ this._listeners?.abort();
707
+ this._listeners = null;
695
708
  this._observer?.disconnect();
696
709
  this._observer = null;
697
710
  this._observedTrack = null;
@@ -833,6 +846,10 @@ var DawAnnotationListElement = class extends import_lit3.LitElement {
833
846
  }
834
847
  };
835
848
  DawAnnotationListElement.styles = import_lit3.css`
849
+ /* The hidden attribute hides the element: :host sets display (modern-web-guidance custom-elements). */
850
+ :host([hidden]) {
851
+ display: none;
852
+ }
836
853
  :host {
837
854
  display: block;
838
855
  max-height: var(--daw-annotation-list-max-height, 240px);
@@ -892,68 +909,174 @@ DawAnnotationListElement = __decorateClass([
892
909
  // src/elements/daw-clip.ts
893
910
  var import_lit4 = require("lit");
894
911
  var import_decorators4 = require("lit/decorators.js");
912
+
913
+ // src/interactions/element-links.ts
914
+ function linkHostOf(el) {
915
+ const editor = el.closest("daw-editor");
916
+ return editor && typeof editor._trackLinkState === "function" ? editor : null;
917
+ }
918
+ function refreshLinkStates(host, trackEls) {
919
+ for (const [trackId, trackEl] of trackEls) {
920
+ trackEl._setDetached(host._trackLinkState(trackId) === "detached");
921
+ for (const clipEl of trackEl.querySelectorAll("daw-clip")) {
922
+ const clip = clipEl;
923
+ clip._setDetached(host._clipLinkState(trackId, clip.clipId) === "detached");
924
+ }
925
+ }
926
+ }
927
+ function detachedWarning(element, change, reason) {
928
+ return "[dawcore] " + element + " is detached (" + reason + "): " + change + " changes nothing. Remove the element and insert it again to declare a new one.";
929
+ }
930
+ function setCustomState(internals, name, on) {
931
+ const states = internals?.states;
932
+ if (!states) return;
933
+ if (on) states.add(name);
934
+ else states.delete(name);
935
+ }
936
+
937
+ // src/elements/daw-clip.ts
895
938
  var DawClipElement = class extends import_lit4.LitElement {
896
939
  constructor() {
897
940
  super(...arguments);
898
941
  this.src = "";
899
942
  this.peaksSrc = "";
900
- this.start = 0;
901
- this.duration = 0;
902
- this.offset = 0;
903
- this.gain = 1;
904
- this.name = "";
905
943
  this.color = "";
906
944
  this.fadeIn = 0;
907
945
  this.fadeOut = 0;
908
946
  this.fadeType = "linear";
909
- this.midiNotes = null;
910
- this._midiChannel = null;
911
- this._midiProgram = null;
947
+ /** What the page declared: the attributes, and a property set before the clip entered. */
948
+ this._declared = {
949
+ start: 0,
950
+ duration: 0,
951
+ offset: 0,
952
+ gain: 1,
953
+ name: "",
954
+ midiNotes: null,
955
+ midiChannel: null,
956
+ midiProgram: null
957
+ };
958
+ this._fromAttribute = false;
959
+ this._internals = this.attachInternals?.() ?? null;
912
960
  this.clipId = crypto.randomUUID();
913
961
  // Removal is detected by the editor's MutationObserver — detached elements
914
962
  // cannot bubble events to ancestors.
915
963
  this._hasRendered = false;
916
964
  }
965
+ get start() {
966
+ return this._linked("start");
967
+ }
968
+ set start(value) {
969
+ this._request("start", value);
970
+ }
971
+ get duration() {
972
+ return this._linked("duration");
973
+ }
974
+ set duration(value) {
975
+ this._request("duration", value);
976
+ }
977
+ get offset() {
978
+ return this._linked("offset");
979
+ }
980
+ set offset(value) {
981
+ this._request("offset", value);
982
+ }
983
+ get gain() {
984
+ return this._linked("gain");
985
+ }
986
+ set gain(value) {
987
+ this._request("gain", value);
988
+ }
989
+ get name() {
990
+ return this._linked("name");
991
+ }
992
+ set name(value) {
993
+ this._request("name", value ?? "");
994
+ }
995
+ get midiNotes() {
996
+ return this._linked("midiNotes");
997
+ }
998
+ set midiNotes(value) {
999
+ this._request("midiNotes", value ?? null);
1000
+ }
917
1001
  get midiChannel() {
918
- return this._midiChannel;
1002
+ return this._linked("midiChannel");
919
1003
  }
920
1004
  set midiChannel(value) {
921
- const old = this._midiChannel;
922
- if (value === null) {
923
- this._midiChannel = null;
924
- this.requestUpdate("midiChannel", old);
925
- return;
926
- }
927
- if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0 || value > 15) {
1005
+ if (value !== null && (!Number.isFinite(value) || !Number.isInteger(value) || value < 0 || value > 15)) {
928
1006
  console.warn("[dawcore] daw-clip midi-channel " + value + " is out of range 0-15 \u2014 ignored");
929
1007
  return;
930
1008
  }
931
- this._midiChannel = value;
932
- this.requestUpdate("midiChannel", old);
1009
+ this._request("midiChannel", value);
933
1010
  }
934
1011
  get midiProgram() {
935
- return this._midiProgram;
1012
+ return this._linked("midiProgram");
936
1013
  }
937
1014
  set midiProgram(value) {
938
- const old = this._midiProgram;
939
- if (value === null) {
940
- this._midiProgram = null;
941
- this.requestUpdate("midiProgram", old);
942
- return;
943
- }
944
- if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0 || value > 127) {
1015
+ if (value !== null && (!Number.isFinite(value) || !Number.isInteger(value) || value < 0 || value > 127)) {
945
1016
  console.warn("[dawcore] daw-clip midi-program " + value + " is out of range 0-127 \u2014 ignored");
946
1017
  return;
947
1018
  }
948
- this._midiProgram = value;
949
- this.requestUpdate("midiProgram", old);
1019
+ this._request("midiProgram", value);
1020
+ }
1021
+ attributeChangedCallback(name, old, value) {
1022
+ this._fromAttribute = true;
1023
+ try {
1024
+ super.attributeChangedCallback(name, old, value);
1025
+ } finally {
1026
+ this._fromAttribute = false;
1027
+ }
1028
+ }
1029
+ get _trackId() {
1030
+ return this.closest("daw-track")?.trackId ?? "";
1031
+ }
1032
+ _linked(key) {
1033
+ const host = linkHostOf(this);
1034
+ const trackId = this._trackId;
1035
+ const live = host && trackId && host._clipLinkState(trackId, this.clipId) === "live" ? host._clipValues(trackId, this.clipId) : null;
1036
+ return live ? live[key] : this._declared[key];
1037
+ }
1038
+ _request(key, value) {
1039
+ const old = this._linked(key);
1040
+ const host = linkHostOf(this);
1041
+ const trackId = this._trackId;
1042
+ const state9 = host && trackId ? host._clipLinkState(trackId, this.clipId) : "pending";
1043
+ if (this._fromAttribute || state9 === "pending") {
1044
+ this._declared = { ...this._declared, [key]: value };
1045
+ }
1046
+ if (state9 === "live") {
1047
+ host._requestClipChange(trackId, this.clipId, { [key]: value });
1048
+ } else if (state9 === "detached") {
1049
+ const label = '<daw-clip> of track "' + trackId + '"';
1050
+ console.warn(detachedWarning(label, key + " = " + String(value), host._detachedReason()));
1051
+ }
1052
+ this.requestUpdate(key, old);
1053
+ }
1054
+ /** @internal Shown as `:state(detached)` (#848). */
1055
+ _setDetached(detached) {
1056
+ setCustomState(this._internals, "detached", detached);
950
1057
  }
951
1058
  // Light DOM — no visual rendering, just a data container
952
1059
  createRenderRoot() {
953
1060
  return this;
954
1061
  }
1062
+ /**
1063
+ * A move with `Node.moveBefore()` (#848; modern-web-guidance
1064
+ * `custom-elements`): the browser calls this instead of
1065
+ * `disconnectedCallback` → `connectedCallback`, so the element stays
1066
+ * connected, and Lit's disconnect and connect do not run. It announces
1067
+ * itself again, as a connect does, so the editor sees its new place: a
1068
+ * clip in another track, a track back in an editor (#848; a real-Chromium
1069
+ * check found both missed with an empty hook).
1070
+ */
1071
+ connectedMoveCallback() {
1072
+ this._announceConnected();
1073
+ }
955
1074
  connectedCallback() {
956
1075
  super.connectedCallback();
1076
+ this._announceConnected();
1077
+ }
1078
+ /** Tell the editor this element is here (a connect or a moveBefore() move). */
1079
+ _announceConnected() {
957
1080
  setTimeout(() => {
958
1081
  this.dispatchEvent(
959
1082
  new CustomEvent("daw-clip-connected", {
@@ -1003,20 +1126,20 @@ __decorateClass([
1003
1126
  (0, import_decorators4.property)({ attribute: "peaks-src" })
1004
1127
  ], DawClipElement.prototype, "peaksSrc", 2);
1005
1128
  __decorateClass([
1006
- (0, import_decorators4.property)({ type: Number })
1007
- ], DawClipElement.prototype, "start", 2);
1129
+ (0, import_decorators4.property)({ type: Number, noAccessor: true })
1130
+ ], DawClipElement.prototype, "start", 1);
1008
1131
  __decorateClass([
1009
- (0, import_decorators4.property)({ type: Number })
1010
- ], DawClipElement.prototype, "duration", 2);
1132
+ (0, import_decorators4.property)({ type: Number, noAccessor: true })
1133
+ ], DawClipElement.prototype, "duration", 1);
1011
1134
  __decorateClass([
1012
- (0, import_decorators4.property)({ type: Number })
1013
- ], DawClipElement.prototype, "offset", 2);
1135
+ (0, import_decorators4.property)({ type: Number, noAccessor: true })
1136
+ ], DawClipElement.prototype, "offset", 1);
1014
1137
  __decorateClass([
1015
- (0, import_decorators4.property)({ type: Number })
1016
- ], DawClipElement.prototype, "gain", 2);
1138
+ (0, import_decorators4.property)({ type: Number, noAccessor: true })
1139
+ ], DawClipElement.prototype, "gain", 1);
1017
1140
  __decorateClass([
1018
- (0, import_decorators4.property)()
1019
- ], DawClipElement.prototype, "name", 2);
1141
+ (0, import_decorators4.property)({ noAccessor: true })
1142
+ ], DawClipElement.prototype, "name", 1);
1020
1143
  __decorateClass([
1021
1144
  (0, import_decorators4.property)()
1022
1145
  ], DawClipElement.prototype, "color", 2);
@@ -1030,8 +1153,8 @@ __decorateClass([
1030
1153
  (0, import_decorators4.property)({ attribute: "fade-type" })
1031
1154
  ], DawClipElement.prototype, "fadeType", 2);
1032
1155
  __decorateClass([
1033
- (0, import_decorators4.property)({ attribute: false })
1034
- ], DawClipElement.prototype, "midiNotes", 2);
1156
+ (0, import_decorators4.property)({ attribute: false, noAccessor: true })
1157
+ ], DawClipElement.prototype, "midiNotes", 1);
1035
1158
  __decorateClass([
1036
1159
  (0, import_decorators4.property)({ type: Number, attribute: "midi-channel", noAccessor: true })
1037
1160
  ], DawClipElement.prototype, "midiChannel", 1);
@@ -1078,11 +1201,10 @@ var DawTrackElement = class extends import_lit5.LitElement {
1078
1201
  constructor() {
1079
1202
  super(...arguments);
1080
1203
  this.src = "";
1081
- this.name = "";
1082
- this.volume = 1;
1083
- this.pan = 0;
1084
- this.muted = false;
1085
- this.soloed = false;
1204
+ /** What the page declared: the attributes, and a property set before the track entered. */
1205
+ this._declared = { name: "", volume: 1, pan: 0, muted: false, soloed: false };
1206
+ this._fromAttribute = false;
1207
+ this._internals = this.attachInternals?.() ?? null;
1086
1208
  this._kind = "audio";
1087
1209
  this._renderMode = "waveform";
1088
1210
  this.spectrogramConfig = null;
@@ -1092,10 +1214,86 @@ var DawTrackElement = class extends import_lit5.LitElement {
1092
1214
  // cannot bubble events to ancestors).
1093
1215
  this._hasRendered = false;
1094
1216
  }
1217
+ get name() {
1218
+ return this._linked("name");
1219
+ }
1220
+ set name(value) {
1221
+ this._request("name", value ?? "");
1222
+ }
1223
+ get volume() {
1224
+ return this._linked("volume");
1225
+ }
1226
+ set volume(value) {
1227
+ this._request("volume", value);
1228
+ }
1229
+ get pan() {
1230
+ return this._linked("pan");
1231
+ }
1232
+ set pan(value) {
1233
+ this._request("pan", value);
1234
+ }
1235
+ get muted() {
1236
+ return this._linked("muted");
1237
+ }
1238
+ set muted(value) {
1239
+ this._request("muted", Boolean(value));
1240
+ }
1241
+ get soloed() {
1242
+ return this._linked("soloed");
1243
+ }
1244
+ set soloed(value) {
1245
+ this._request("soloed", Boolean(value));
1246
+ }
1247
+ /** The track's position in the arrangement the editor plays; -1 when it is not there. */
1248
+ get index() {
1249
+ return linkHostOf(this)?._trackIndex(this.trackId) ?? -1;
1250
+ }
1251
+ attributeChangedCallback(name, old, value) {
1252
+ this._fromAttribute = true;
1253
+ try {
1254
+ super.attributeChangedCallback(name, old, value);
1255
+ } finally {
1256
+ this._fromAttribute = false;
1257
+ }
1258
+ }
1259
+ _linked(key) {
1260
+ const host = linkHostOf(this);
1261
+ const live = host?._trackLinkState(this.trackId) === "live" ? host._trackValues(this.trackId) : null;
1262
+ return live ? live[key] : this._declared[key];
1263
+ }
1264
+ _request(key, value) {
1265
+ const old = this._linked(key);
1266
+ const host = linkHostOf(this);
1267
+ const state9 = host?._trackLinkState(this.trackId) ?? "pending";
1268
+ if (this._fromAttribute || state9 === "pending") {
1269
+ this._declared = { ...this._declared, [key]: value };
1270
+ }
1271
+ if (state9 === "live") {
1272
+ host._requestTrackChange(this.trackId, { [key]: value });
1273
+ } else if (state9 === "detached") {
1274
+ const label = '<daw-track name="' + this._declared.name + '">';
1275
+ console.warn(detachedWarning(label, key + " = " + String(value), host._detachedReason()));
1276
+ }
1277
+ this.requestUpdate(key, old);
1278
+ }
1279
+ /** @internal Shown as `:state(detached)` (#848). */
1280
+ _setDetached(detached) {
1281
+ setCustomState(this._internals, "detached", detached);
1282
+ }
1095
1283
  get kind() {
1096
- return this._kind;
1284
+ const host = linkHostOf(this);
1285
+ const live = host?._trackLinkState(this.trackId) === "live" ? host._trackKind(this.trackId) : null;
1286
+ return live ?? this._kind;
1097
1287
  }
1098
1288
  set kind(value) {
1289
+ const host = linkHostOf(this);
1290
+ const live = host?._trackLinkState(this.trackId) === "live" ? host._trackKind(this.trackId) : null;
1291
+ if (live && value !== live) {
1292
+ console.warn(
1293
+ '[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.'
1294
+ );
1295
+ if (!this._fromAttribute) return;
1296
+ }
1099
1297
  if (value !== "audio" && value !== "midi") {
1100
1298
  console.warn(
1101
1299
  '[dawcore] <daw-track kind="' + String(value) + `"> is not a track kind ('audio' or 'midi'); keeping "` + this._kind + '"'
@@ -1187,8 +1385,24 @@ var DawTrackElement = class extends import_lit5.LitElement {
1187
1385
  }
1188
1386
  return editor;
1189
1387
  }
1388
+ /**
1389
+ * A move with `Node.moveBefore()` (#848; modern-web-guidance
1390
+ * `custom-elements`): the browser calls this instead of
1391
+ * `disconnectedCallback` → `connectedCallback`, so the element stays
1392
+ * connected, and Lit's disconnect and connect do not run. It announces
1393
+ * itself again, as a connect does, so the editor sees its new place: a
1394
+ * clip in another track, a track back in an editor (#848; a real-Chromium
1395
+ * check found both missed with an empty hook).
1396
+ */
1397
+ connectedMoveCallback() {
1398
+ this._announceConnected();
1399
+ }
1190
1400
  connectedCallback() {
1191
1401
  super.connectedCallback();
1402
+ this._announceConnected();
1403
+ }
1404
+ /** Tell the editor this element is here (a connect or a moveBefore() move). */
1405
+ _announceConnected() {
1192
1406
  setTimeout(() => {
1193
1407
  this.dispatchEvent(
1194
1408
  new CustomEvent("daw-track-connected", {
@@ -1221,20 +1435,20 @@ __decorateClass([
1221
1435
  (0, import_decorators5.property)()
1222
1436
  ], DawTrackElement.prototype, "src", 2);
1223
1437
  __decorateClass([
1224
- (0, import_decorators5.property)()
1225
- ], DawTrackElement.prototype, "name", 2);
1438
+ (0, import_decorators5.property)({ noAccessor: true })
1439
+ ], DawTrackElement.prototype, "name", 1);
1226
1440
  __decorateClass([
1227
- (0, import_decorators5.property)({ type: Number })
1228
- ], DawTrackElement.prototype, "volume", 2);
1441
+ (0, import_decorators5.property)({ type: Number, noAccessor: true })
1442
+ ], DawTrackElement.prototype, "volume", 1);
1229
1443
  __decorateClass([
1230
- (0, import_decorators5.property)({ type: Number })
1231
- ], DawTrackElement.prototype, "pan", 2);
1444
+ (0, import_decorators5.property)({ type: Number, noAccessor: true })
1445
+ ], DawTrackElement.prototype, "pan", 1);
1232
1446
  __decorateClass([
1233
- (0, import_decorators5.property)({ type: Boolean })
1234
- ], DawTrackElement.prototype, "muted", 2);
1447
+ (0, import_decorators5.property)({ type: Boolean, noAccessor: true })
1448
+ ], DawTrackElement.prototype, "muted", 1);
1235
1449
  __decorateClass([
1236
- (0, import_decorators5.property)({ type: Boolean })
1237
- ], DawTrackElement.prototype, "soloed", 2);
1450
+ (0, import_decorators5.property)({ type: Boolean, noAccessor: true })
1451
+ ], DawTrackElement.prototype, "soloed", 1);
1238
1452
  __decorateClass([
1239
1453
  (0, import_decorators5.property)({ reflect: true, noAccessor: true })
1240
1454
  ], DawTrackElement.prototype, "kind", 1);
@@ -1988,6 +2202,8 @@ function warnUnsupportedOnce(element, methods) {
1988
2202
  var DawTransportButton = class extends import_lit10.LitElement {
1989
2203
  constructor() {
1990
2204
  super(...arguments);
2205
+ /** The host's capability listeners, one controller per connection. */
2206
+ this._capabilityListeners = null;
1991
2207
  this._onCapabilityPointerEnter = () => {
1992
2208
  this.requestUpdate();
1993
2209
  };
@@ -2025,8 +2241,11 @@ var DawTransportButton = class extends import_lit10.LitElement {
2025
2241
  }
2026
2242
  connectedCallback() {
2027
2243
  super.connectedCallback();
2028
- this.addEventListener("pointerdown", this._onCapabilityPointerDown);
2029
- this.addEventListener("pointerenter", this._onCapabilityPointerEnter);
2244
+ this._capabilityListeners?.abort();
2245
+ this._capabilityListeners = new AbortController();
2246
+ const { signal } = this._capabilityListeners;
2247
+ this.addEventListener("pointerdown", this._onCapabilityPointerDown, { signal });
2248
+ this.addEventListener("pointerenter", this._onCapabilityPointerEnter, { signal });
2030
2249
  requestAnimationFrame(() => {
2031
2250
  if (!this.isConnected) return;
2032
2251
  this.requestUpdate();
@@ -2034,8 +2253,8 @@ var DawTransportButton = class extends import_lit10.LitElement {
2034
2253
  }
2035
2254
  disconnectedCallback() {
2036
2255
  super.disconnectedCallback();
2037
- this.removeEventListener("pointerdown", this._onCapabilityPointerDown);
2038
- this.removeEventListener("pointerenter", this._onCapabilityPointerEnter);
2256
+ this._capabilityListeners?.abort();
2257
+ this._capabilityListeners = null;
2039
2258
  }
2040
2259
  };
2041
2260
  /** Methods the transport target must implement for this control to be
@@ -2065,6 +2284,8 @@ var DawPlayButtonElement = class extends DawTransportButton {
2065
2284
  super(...arguments);
2066
2285
  this._isRecording = false;
2067
2286
  this._targetRef = null;
2287
+ /** The listeners on `_targetRef`, aborted when the target changes or the button disconnects. */
2288
+ this._targetListeners = null;
2068
2289
  this._onRecStart = () => {
2069
2290
  this._isRecording = true;
2070
2291
  };
@@ -2095,15 +2316,16 @@ var DawPlayButtonElement = class extends DawTransportButton {
2095
2316
  this._cleanupListeners();
2096
2317
  if (!target) return;
2097
2318
  this._targetRef = target;
2098
- target.addEventListener("daw-recording-start", this._onRecStart);
2099
- target.addEventListener("daw-recording-complete", this._onRecEnd);
2100
- target.addEventListener("daw-recording-error", this._onRecEnd);
2319
+ this._targetListeners = new AbortController();
2320
+ const { signal } = this._targetListeners;
2321
+ target.addEventListener("daw-recording-start", this._onRecStart, { signal });
2322
+ target.addEventListener("daw-recording-complete", this._onRecEnd, { signal });
2323
+ target.addEventListener("daw-recording-error", this._onRecEnd, { signal });
2101
2324
  }
2102
2325
  _cleanupListeners() {
2103
2326
  if (this._targetRef) {
2104
- this._targetRef.removeEventListener("daw-recording-start", this._onRecStart);
2105
- this._targetRef.removeEventListener("daw-recording-complete", this._onRecEnd);
2106
- this._targetRef.removeEventListener("daw-recording-error", this._onRecEnd);
2327
+ this._targetListeners?.abort();
2328
+ this._targetListeners = null;
2107
2329
  this._targetRef = null;
2108
2330
  }
2109
2331
  }
@@ -2141,6 +2363,8 @@ var DawPauseButtonElement = class extends DawTransportButton {
2141
2363
  this._isPaused = false;
2142
2364
  this._isRecording = false;
2143
2365
  this._targetRef = null;
2366
+ /** The listeners on `_targetRef`, aborted when the target changes or the button disconnects. */
2367
+ this._targetListeners = null;
2144
2368
  this._onRecStart = () => {
2145
2369
  this._isRecording = true;
2146
2370
  };
@@ -2179,19 +2403,18 @@ var DawPauseButtonElement = class extends DawTransportButton {
2179
2403
  this._cleanupListeners();
2180
2404
  if (!target) return;
2181
2405
  this._targetRef = target;
2182
- target.addEventListener("daw-recording-start", this._onRecStart);
2183
- target.addEventListener("daw-recording-complete", this._onRecEnd);
2184
- target.addEventListener("daw-recording-error", this._onRecEnd);
2185
- target.addEventListener("daw-recording-pause", this._onRecPause);
2186
- target.addEventListener("daw-recording-resume", this._onRecResume);
2406
+ this._targetListeners = new AbortController();
2407
+ const { signal } = this._targetListeners;
2408
+ target.addEventListener("daw-recording-start", this._onRecStart, { signal });
2409
+ target.addEventListener("daw-recording-complete", this._onRecEnd, { signal });
2410
+ target.addEventListener("daw-recording-error", this._onRecEnd, { signal });
2411
+ target.addEventListener("daw-recording-pause", this._onRecPause, { signal });
2412
+ target.addEventListener("daw-recording-resume", this._onRecResume, { signal });
2187
2413
  }
2188
2414
  _cleanupListeners() {
2189
2415
  if (this._targetRef) {
2190
- this._targetRef.removeEventListener("daw-recording-start", this._onRecStart);
2191
- this._targetRef.removeEventListener("daw-recording-complete", this._onRecEnd);
2192
- this._targetRef.removeEventListener("daw-recording-error", this._onRecEnd);
2193
- this._targetRef.removeEventListener("daw-recording-pause", this._onRecPause);
2194
- this._targetRef.removeEventListener("daw-recording-resume", this._onRecResume);
2416
+ this._targetListeners?.abort();
2417
+ this._targetListeners = null;
2195
2418
  this._targetRef = null;
2196
2419
  }
2197
2420
  }
@@ -2281,7 +2504,8 @@ DawStopButtonElement = __decorateClass([
2281
2504
  // src/elements/daw-editor.ts
2282
2505
  var import_lit19 = require("lit");
2283
2506
  var import_decorators16 = require("lit/decorators.js");
2284
- var import_core19 = require("@waveform-playlist/core");
2507
+ var import_repeat = require("lit/directives/repeat.js");
2508
+ var import_core21 = require("@waveform-playlist/core");
2285
2509
 
2286
2510
  // src/workers/peaksWorker.ts
2287
2511
  var import_waveform_data = __toESM(require("waveform-data"));
@@ -3026,7 +3250,7 @@ DawRulerElement = __decorateClass([
3026
3250
  ], DawRulerElement);
3027
3251
 
3028
3252
  // src/elements/daw-editor.ts
3029
- var import_engine = require("@waveform-playlist/engine");
3253
+ var import_engine3 = require("@waveform-playlist/engine");
3030
3254
 
3031
3255
  // src/utils/track-mix.ts
3032
3256
  var DEFAULT_TRACK_MIX = Object.freeze({
@@ -3041,15 +3265,6 @@ function mixOfTrack(track) {
3041
3265
  function mixOfElement(el) {
3042
3266
  return { volume: el.volume, pan: el.pan, muted: el.muted, soloed: el.soloed };
3043
3267
  }
3044
- function pickMix(mix, names) {
3045
- const named = new Set(names);
3046
- return {
3047
- ...named.has("volume") && { volume: mix.volume },
3048
- ...named.has("pan") && { pan: mix.pan },
3049
- ...named.has("muted") && { muted: mix.muted },
3050
- ...named.has("soloed") && { soloed: mix.soloed }
3051
- };
3052
- }
3053
3268
  function clampNumber(value, min, max) {
3054
3269
  return Math.max(min, Math.min(max, Number(value)));
3055
3270
  }
@@ -3260,6 +3475,10 @@ var DawTrackControlsElement = class extends import_lit15.LitElement {
3260
3475
  }
3261
3476
  };
3262
3477
  DawTrackControlsElement.styles = import_lit15.css`
3478
+ /* The hidden attribute hides the element: :host sets display (modern-web-guidance custom-elements). */
3479
+ :host([hidden]) {
3480
+ display: none;
3481
+ }
3263
3482
  :host {
3264
3483
  display: flex;
3265
3484
  flex-direction: column;
@@ -3721,6 +3940,8 @@ var ViewportController = class {
3721
3940
  this._scrollContainer = null;
3722
3941
  this._lastScrollLeft = 0;
3723
3942
  this._resizeObserver = null;
3943
+ /** The scroll listener on `_scrollContainer`, aborted when it is replaced or the host disconnects. */
3944
+ this._scrollListener = null;
3724
3945
  // Permissive defaults: render everything until scroll container is attached
3725
3946
  this.visibleStart = -Infinity;
3726
3947
  this.visibleEnd = Infinity;
@@ -3752,16 +3973,21 @@ var ViewportController = class {
3752
3973
  });
3753
3974
  }
3754
3975
  hostDisconnected() {
3755
- this._scrollContainer?.removeEventListener("scroll", this._onScroll);
3976
+ this._scrollListener?.abort();
3977
+ this._scrollListener = null;
3756
3978
  this._resizeObserver?.disconnect();
3757
3979
  this._resizeObserver = null;
3758
3980
  this._scrollContainer = null;
3759
3981
  }
3760
3982
  _attachScrollContainer(container) {
3761
- this._scrollContainer?.removeEventListener("scroll", this._onScroll);
3983
+ this._scrollListener?.abort();
3762
3984
  this._resizeObserver?.disconnect();
3763
3985
  this._scrollContainer = container;
3764
- container.addEventListener("scroll", this._onScroll, { passive: true });
3986
+ this._scrollListener = new AbortController();
3987
+ container.addEventListener("scroll", this._onScroll, {
3988
+ passive: true,
3989
+ signal: this._scrollListener.signal
3990
+ });
3765
3991
  this._update(container.scrollLeft, container.clientWidth);
3766
3992
  if (typeof ResizeObserver !== "undefined") {
3767
3993
  this._resizeObserver = new ResizeObserver(() => {
@@ -3788,9 +4014,11 @@ var ViewportController = class {
3788
4014
  var AudioResumeController = class {
3789
4015
  constructor(host) {
3790
4016
  this._target = null;
4017
+ /** The gesture listeners on `_target`: one controller per attach. */
4018
+ this._listeners = null;
3791
4019
  this._attached = false;
3792
4020
  this._generation = 0;
3793
- this._onGesture = (e) => {
4021
+ this._onGesture = () => {
3794
4022
  let ctx;
3795
4023
  try {
3796
4024
  ctx = this._host.audioContext;
@@ -3814,11 +4042,7 @@ var AudioResumeController = class {
3814
4042
  );
3815
4043
  });
3816
4044
  }
3817
- const otherType = e.type === "pointerdown" ? "keydown" : "pointerdown";
3818
- this._target?.removeEventListener(otherType, this._onGesture, {
3819
- capture: true
3820
- });
3821
- this._target = null;
4045
+ this._removeListeners();
3822
4046
  };
3823
4047
  this._host = host;
3824
4048
  host.addController(this);
@@ -3840,13 +4064,17 @@ var AudioResumeController = class {
3840
4064
  if (!resolvedTarget) return;
3841
4065
  this._target = resolvedTarget;
3842
4066
  this._attached = true;
4067
+ this._listeners = new AbortController();
4068
+ const { signal } = this._listeners;
3843
4069
  resolvedTarget.addEventListener("pointerdown", this._onGesture, {
3844
4070
  once: true,
3845
- capture: true
4071
+ capture: true,
4072
+ signal
3846
4073
  });
3847
4074
  resolvedTarget.addEventListener("keydown", this._onGesture, {
3848
4075
  once: true,
3849
- capture: true
4076
+ capture: true,
4077
+ signal
3850
4078
  });
3851
4079
  });
3852
4080
  }
@@ -3870,12 +4098,8 @@ var AudioResumeController = class {
3870
4098
  }
3871
4099
  _removeListeners() {
3872
4100
  if (!this._target) return;
3873
- this._target.removeEventListener("pointerdown", this._onGesture, {
3874
- capture: true
3875
- });
3876
- this._target.removeEventListener("keydown", this._onGesture, {
3877
- capture: true
3878
- });
4101
+ this._listeners?.abort();
4102
+ this._listeners = null;
3879
4103
  this._target = null;
3880
4104
  }
3881
4105
  };
@@ -3894,6 +4118,8 @@ var import_core6 = require("@waveform-playlist/core");
3894
4118
  var RecordingController = class {
3895
4119
  constructor(host) {
3896
4120
  this._sessions = /* @__PURE__ */ new Map();
4121
+ /** Each session's mic-unplug listener, aborted when the session ends. */
4122
+ this._trackEndedListeners = /* @__PURE__ */ new WeakMap();
3897
4123
  /** Track IDs with a startRecording in flight (session not yet in _sessions).
3898
4124
  * The session is only set after several awaits — without this, two rapid
3899
4125
  * start calls both pass the _sessions guard and build two capture
@@ -4022,8 +4248,6 @@ var RecordingController = class {
4022
4248
  latencySamples,
4023
4249
  clipName: options.clipName,
4024
4250
  wasOverdub: options.overdub ?? false,
4025
- _onTrackEnded: onTrackEnded,
4026
- _audioTrack: audioTrack,
4027
4251
  stopAckResolve: null,
4028
4252
  stopPromise: null,
4029
4253
  stopping: false
@@ -4035,7 +4259,9 @@ var RecordingController = class {
4035
4259
  source.connect(workletNode);
4036
4260
  workletNode.port.postMessage({ command: "start", channelCount });
4037
4261
  if (audioTrack && onTrackEnded) {
4038
- audioTrack.addEventListener("ended", onTrackEnded);
4262
+ const listener = new AbortController();
4263
+ this._trackEndedListeners.set(session, listener);
4264
+ audioTrack.addEventListener("ended", onTrackEnded, { signal: listener.signal });
4039
4265
  }
4040
4266
  this._host._engine?.setTrackRecording(trackId, true);
4041
4267
  this._host.dispatchEvent(
@@ -4297,9 +4523,8 @@ var RecordingController = class {
4297
4523
  }
4298
4524
  }
4299
4525
  _removeTrackEndedListener(session) {
4300
- if (session._audioTrack && session._onTrackEnded) {
4301
- session._audioTrack.removeEventListener("ended", session._onTrackEnded);
4302
- }
4526
+ this._trackEndedListeners.get(session)?.abort();
4527
+ this._trackEndedListeners.delete(session);
4303
4528
  }
4304
4529
  _dispatchRecordingError(trackId, error) {
4305
4530
  this._host.dispatchEvent(
@@ -4371,6 +4596,8 @@ var AnnotationController = class {
4371
4596
  * Driven by daw-timeupdate, cleared on daw-stop, retained on pause.
4372
4597
  * Replaced immutably (a fresh Map) on every change. */
4373
4598
  this._playingIds = /* @__PURE__ */ new Map();
4599
+ /** The host listeners of this connection, aborted in hostDisconnected. */
4600
+ this._listeners = null;
4374
4601
  this._onDataChange = () => {
4375
4602
  this.deriveSecondsCaches();
4376
4603
  this._host.requestUpdate();
@@ -4422,11 +4649,14 @@ var AnnotationController = class {
4422
4649
  );
4423
4650
  }
4424
4651
  hostConnected() {
4425
- this._host.addEventListener("daw-annotation-update", this._onDataChange);
4426
- this._host.addEventListener("daw-annotation-select", this._onDataChange);
4427
- this._host.addEventListener("daw-annotation-connected", this._onDataChange);
4428
- this._host.addEventListener("daw-timeupdate", this._onTimeUpdate);
4429
- this._host.addEventListener("daw-stop", this._onStop);
4652
+ this._listeners?.abort();
4653
+ this._listeners = new AbortController();
4654
+ const { signal } = this._listeners;
4655
+ this._host.addEventListener("daw-annotation-update", this._onDataChange, { signal });
4656
+ this._host.addEventListener("daw-annotation-select", this._onDataChange, { signal });
4657
+ this._host.addEventListener("daw-annotation-connected", this._onDataChange, { signal });
4658
+ this._host.addEventListener("daw-timeupdate", this._onTimeUpdate, { signal });
4659
+ this._host.addEventListener("daw-stop", this._onStop, { signal });
4430
4660
  this._removalObserver = new MutationObserver((mutations) => {
4431
4661
  let changed = false;
4432
4662
  for (const m of mutations) {
@@ -4456,11 +4686,8 @@ var AnnotationController = class {
4456
4686
  this._removalObserver.observe(this._host, { childList: true, subtree: true });
4457
4687
  }
4458
4688
  hostDisconnected() {
4459
- this._host.removeEventListener("daw-annotation-update", this._onDataChange);
4460
- this._host.removeEventListener("daw-annotation-select", this._onDataChange);
4461
- this._host.removeEventListener("daw-annotation-connected", this._onDataChange);
4462
- this._host.removeEventListener("daw-timeupdate", this._onTimeUpdate);
4463
- this._host.removeEventListener("daw-stop", this._onStop);
4689
+ this._listeners?.abort();
4690
+ this._listeners = null;
4464
4691
  this._removalObserver?.disconnect();
4465
4692
  this._removalObserver = null;
4466
4693
  this._tracks = [];
@@ -4685,6 +4912,8 @@ var PointerHandler = class {
4685
4912
  // still holds; zeroing only the host would desync the two).
4686
4913
  this._preDragSelectionStart = 0;
4687
4914
  this._preDragSelectionEnd = 0;
4915
+ /** The timeline's listeners of the seek / selection press in progress. */
4916
+ this._seekGesture = null;
4688
4917
  /** Cancels the armed clip drag; set while one is armed (#848). */
4689
4918
  this._cancelArmedClipDrag = null;
4690
4919
  this.onPointerDown = (e) => {
@@ -4701,11 +4930,10 @@ var PointerHandler = class {
4701
4930
  console.warn("[dawcore] setPointerCapture failed: " + String(err));
4702
4931
  }
4703
4932
  const onMove = (me) => clipHandler.onPointerMove(me);
4933
+ const gesture = new AbortController();
4704
4934
  const detach = (pointerId) => {
4705
4935
  this._cancelArmedClipDrag = null;
4706
- this._timeline?.removeEventListener("pointermove", onMove);
4707
- this._timeline?.removeEventListener("pointerup", onUp);
4708
- this._timeline?.removeEventListener("pointercancel", onCancel);
4936
+ gesture.abort();
4709
4937
  try {
4710
4938
  this._timeline?.releasePointerCapture(pointerId);
4711
4939
  } catch (err) {
@@ -4731,9 +4959,10 @@ var PointerHandler = class {
4731
4959
  );
4732
4960
  detach(downPointerId);
4733
4961
  };
4734
- this._timeline.addEventListener("pointermove", onMove);
4735
- this._timeline.addEventListener("pointerup", onUp);
4736
- this._timeline.addEventListener("pointercancel", onCancel);
4962
+ const { signal: signal2 } = gesture;
4963
+ this._timeline.addEventListener("pointermove", onMove, { signal: signal2 });
4964
+ this._timeline.addEventListener("pointerup", onUp, { signal: signal2 });
4965
+ this._timeline.addEventListener("pointercancel", onCancel, { signal: signal2 });
4737
4966
  }
4738
4967
  return;
4739
4968
  }
@@ -4756,9 +4985,12 @@ var PointerHandler = class {
4756
4985
  } catch (err) {
4757
4986
  console.warn("[dawcore] setPointerCapture failed: " + String(err));
4758
4987
  }
4759
- this._timeline.addEventListener("pointermove", this._onPointerMove);
4760
- this._timeline.addEventListener("pointerup", this._onPointerUp);
4761
- this._timeline.addEventListener("pointercancel", this._onPointerCancel);
4988
+ this._seekGesture?.abort();
4989
+ this._seekGesture = new AbortController();
4990
+ const { signal } = this._seekGesture;
4991
+ this._timeline.addEventListener("pointermove", this._onPointerMove, { signal });
4992
+ this._timeline.addEventListener("pointerup", this._onPointerUp, { signal });
4993
+ this._timeline.addEventListener("pointercancel", this._onPointerCancel, { signal });
4762
4994
  };
4763
4995
  this._onPointerMove = (e) => {
4764
4996
  if (!this._timeline) return;
@@ -4865,9 +5097,8 @@ var PointerHandler = class {
4865
5097
  "[dawcore] releasePointerCapture failed (may already be released): " + String(err)
4866
5098
  );
4867
5099
  }
4868
- this._timeline.removeEventListener("pointermove", this._onPointerMove);
4869
- this._timeline.removeEventListener("pointerup", this._onPointerUp);
4870
- this._timeline.removeEventListener("pointercancel", this._onPointerCancel);
5100
+ this._seekGesture?.abort();
5101
+ this._seekGesture = null;
4871
5102
  }
4872
5103
  _resetInteractionState() {
4873
5104
  this._isDragging = false;
@@ -4963,6 +5194,7 @@ var PointerHandler = class {
4963
5194
 
4964
5195
  // src/interactions/clip-pointer-handler.ts
4965
5196
  var import_core9 = require("@waveform-playlist/core");
5197
+ var import_engine = require("@waveform-playlist/engine");
4966
5198
  var ClipPointerHandler = class {
4967
5199
  constructor(host) {
4968
5200
  this._mode = null;
@@ -4979,6 +5211,10 @@ var ClipPointerHandler = class {
4979
5211
  this._originalOffsetSamples = 0;
4980
5212
  this._originalDurationSamples = 0;
4981
5213
  this._originalStartSample = 0;
5214
+ // Move: the dragged clip and the track's loaded clips, sorted, at drag start
5215
+ this._moveClip = null;
5216
+ this._moveSorted = [];
5217
+ this._committing = false;
4982
5218
  this._host = host;
4983
5219
  }
4984
5220
  /**
@@ -5003,6 +5239,18 @@ var ClipPointerHandler = class {
5003
5239
  }
5004
5240
  return Math.round(totalDeltaPx * h.renderSamplesPerPixel);
5005
5241
  }
5242
+ /** A sample delta from `anchorSample` in pixels: in tick space in beats mode,
5243
+ * so the drawn position does not drift from the sample round-trip. */
5244
+ _samplesToPx(anchorSample, deltaSamples) {
5245
+ const h = this._host;
5246
+ if (h.scaleMode === "beats") {
5247
+ const anchorSec = anchorSample / h.effectiveSampleRate;
5248
+ const anchorTick = h._secondsToTicks(anchorSec);
5249
+ const newTick = h._secondsToTicks(anchorSec + deltaSamples / h.effectiveSampleRate);
5250
+ return Math.round((newTick - anchorTick) / h.ticksPerPixel);
5251
+ }
5252
+ return Math.round(deltaSamples / h.renderSamplesPerPixel);
5253
+ }
5006
5254
  /** Returns true if a drag interaction is currently in progress. */
5007
5255
  get isActive() {
5008
5256
  return this._mode !== null;
@@ -5012,6 +5260,21 @@ var ClipPointerHandler = class {
5012
5260
  get isDragging() {
5013
5261
  return this._isDragging;
5014
5262
  }
5263
+ /**
5264
+ * The clip being dragged (past the threshold) with its bounds at the drag's
5265
+ * start, or null; null too while the release makes its one arrangement
5266
+ * call, so that call is not taken for an outside change (#848).
5267
+ */
5268
+ get draggedClip() {
5269
+ if (!this._isDragging || this._committing) return null;
5270
+ return {
5271
+ trackId: this._trackId,
5272
+ clipId: this._clipId,
5273
+ startSample: this._originalStartSample,
5274
+ durationSamples: this._originalDurationSamples,
5275
+ offsetSamples: this._originalOffsetSamples
5276
+ };
5277
+ }
5015
5278
  /**
5016
5279
  * Attempts to handle a pointerdown event on the given target element.
5017
5280
  * Returns true if the target is a recognized clip interaction element.
@@ -5049,11 +5312,10 @@ var ClipPointerHandler = class {
5049
5312
  }
5050
5313
  /**
5051
5314
  * The press has become a drag (the pointer passed the threshold): take the
5052
- * clip's bounds and open the transaction now, not at the press. An undo
5053
- * made during the press (it is not a drag, so undo works) then has no
5054
- * transaction to abort, and the drag that follows starts from the clip as
5055
- * the undo left it, one undo step (#848, review of #915). Returns false
5056
- * when the clip is gone (the undo removed it): the press is dropped.
5315
+ * clip's bounds now, not at the press, so a drag after an undo made during
5316
+ * the press starts from the clip as the undo left it (#848, review of
5317
+ * #915). Returns false when the clip is gone (the undo removed it): the
5318
+ * press is dropped.
5057
5319
  */
5058
5320
  _startDrag() {
5059
5321
  const engine = this._host.engine;
@@ -5065,13 +5327,17 @@ var ClipPointerHandler = class {
5065
5327
  this._originalStartSample = bounds.startSample;
5066
5328
  this._originalOffsetSamples = bounds.offsetSamples;
5067
5329
  this._originalDurationSamples = bounds.durationSamples;
5068
- engine.beginTransaction();
5330
+ if (this._mode === "move") {
5331
+ const track = engine.getState().tracks.find((t) => t.id === trackId);
5332
+ const clip = track?.clips.find((c) => c.id === clipId) ?? null;
5333
+ if (!track || !clip) return false;
5334
+ this._moveClip = clip;
5335
+ this._moveSorted = [...track.clips].sort((a, b) => a.startSample - b.startSample);
5336
+ }
5069
5337
  } else {
5070
- console.warn(
5071
- "[dawcore] drag start: engine unavailable, drag mutations will not be grouped for undo"
5072
- );
5338
+ console.warn("[dawcore] drag start: engine unavailable, the drag will not be applied");
5073
5339
  }
5074
- if (this._mode === "trim-left" || this._mode === "trim-right") {
5340
+ {
5075
5341
  const container = this._host.shadowRoot?.querySelector(
5076
5342
  `.clip-container[data-clip-id="${clipId}"]`
5077
5343
  );
@@ -5080,7 +5346,7 @@ var ClipPointerHandler = class {
5080
5346
  this._originalLeft = parseFloat(container.style.left) || 0;
5081
5347
  this._originalWidth = parseFloat(container.style.width) || 0;
5082
5348
  } else {
5083
- console.warn("[dawcore] clip container not found for trim visual feedback: " + clipId);
5349
+ console.warn("[dawcore] clip container not found for drag visual feedback: " + clipId);
5084
5350
  }
5085
5351
  }
5086
5352
  return true;
@@ -5104,10 +5370,13 @@ var ClipPointerHandler = class {
5104
5370
  if (!engine) return;
5105
5371
  if (this._mode === "move") {
5106
5372
  const totalSnappedDelta = this._snapDeltaToSamples(totalDeltaPx, this._originalStartSample);
5107
- const incrementalDeltaSamples = totalSnappedDelta - this._cumulativeDeltaSamples;
5108
- if (incrementalDeltaSamples !== 0) {
5109
- const applied = engine.moveClip(this._trackId, this._clipId, incrementalDeltaSamples, true);
5110
- this._cumulativeDeltaSamples += applied;
5373
+ const clip = this._moveClip;
5374
+ const index = clip ? this._moveSorted.indexOf(clip) : -1;
5375
+ const delta = clip && index !== -1 ? (0, import_engine.constrainClipDrag)(clip, totalSnappedDelta, this._moveSorted, index) : totalSnappedDelta;
5376
+ this._cumulativeDeltaSamples = delta;
5377
+ if (this._clipContainer) {
5378
+ const deltaPx = this._samplesToPx(this._originalStartSample, delta);
5379
+ this._clipContainer.style.left = this._originalLeft + deltaPx + "px";
5111
5380
  }
5112
5381
  } else {
5113
5382
  const boundary = this._mode === "trim-left" ? "left" : "right";
@@ -5119,17 +5388,7 @@ var ClipPointerHandler = class {
5119
5388
  boundary,
5120
5389
  rawDeltaSamples
5121
5390
  );
5122
- let deltaPx;
5123
- if (this._host.scaleMode === "beats") {
5124
- const h = this._host;
5125
- const anchorSec = anchor / h.effectiveSampleRate;
5126
- const anchorTick = h._secondsToTicks(anchorSec);
5127
- const newSec = anchorSec + deltaSamples / h.effectiveSampleRate;
5128
- const newTick = h._secondsToTicks(newSec);
5129
- deltaPx = Math.round((newTick - anchorTick) / h.ticksPerPixel);
5130
- } else {
5131
- deltaPx = Math.round(deltaSamples / this._host.renderSamplesPerPixel);
5132
- }
5391
+ const deltaPx = this._samplesToPx(anchor, deltaSamples);
5133
5392
  this._cumulativeDeltaSamples = deltaSamples;
5134
5393
  if (this._clipContainer) {
5135
5394
  if (this._mode === "trim-left") {
@@ -5168,31 +5427,39 @@ var ClipPointerHandler = class {
5168
5427
  if (this._mode === null) return;
5169
5428
  try {
5170
5429
  if (!this._isDragging || this._cumulativeDeltaSamples === 0) {
5171
- this._restoreTrimVisual();
5430
+ this._restoreVisual();
5172
5431
  return;
5173
5432
  }
5174
5433
  const engine = this._host.engine;
5434
+ this._committing = true;
5175
5435
  if (this._mode === "move") {
5436
+ this._restoreVisual();
5176
5437
  if (engine) {
5177
- engine.updateTrack(this._trackId);
5178
- this._host.dispatchEvent(
5179
- new CustomEvent("daw-clip-move", {
5180
- bubbles: true,
5181
- composed: true,
5182
- detail: {
5183
- trackId: this._trackId,
5184
- clipId: this._clipId,
5185
- deltaSamples: this._cumulativeDeltaSamples
5186
- }
5187
- })
5438
+ const applied = engine.moveClip(
5439
+ this._trackId,
5440
+ this._clipId,
5441
+ this._cumulativeDeltaSamples
5188
5442
  );
5443
+ if (applied !== 0) {
5444
+ this._host.dispatchEvent(
5445
+ new CustomEvent("daw-clip-move", {
5446
+ bubbles: true,
5447
+ composed: true,
5448
+ detail: {
5449
+ trackId: this._trackId,
5450
+ clipId: this._clipId,
5451
+ deltaSamples: applied
5452
+ }
5453
+ })
5454
+ );
5455
+ }
5189
5456
  } else {
5190
5457
  console.warn(
5191
- "[dawcore] engine unavailable at move drop \u2014 audio may be out of sync for track " + this._trackId
5458
+ "[dawcore] engine unavailable at move drop \u2014 move not applied for clip " + this._clipId
5192
5459
  );
5193
5460
  }
5194
5461
  } else {
5195
- this._restoreTrimVisual();
5462
+ this._restoreVisual();
5196
5463
  const boundary = this._mode === "trim-left" ? "left" : "right";
5197
5464
  if (engine) {
5198
5465
  engine.trimClip(this._trackId, this._clipId, boundary, this._cumulativeDeltaSamples);
@@ -5215,13 +5482,7 @@ var ClipPointerHandler = class {
5215
5482
  }
5216
5483
  }
5217
5484
  } finally {
5218
- if (this._isDragging) {
5219
- if (this._cumulativeDeltaSamples !== 0) {
5220
- this._host.engine?.commitTransaction();
5221
- } else {
5222
- this._host.engine?.abortTransaction();
5223
- }
5224
- }
5485
+ this._committing = false;
5225
5486
  this._reset();
5226
5487
  }
5227
5488
  }
@@ -5229,16 +5490,13 @@ var ClipPointerHandler = class {
5229
5490
  *
5230
5491
  * pointercancel fires INSTEAD of pointerup on touch interruption, pen
5231
5492
  * leaving hover range, or OS gestures. Without this handler the drag stays
5232
- * armed (hover keeps moving the clip), the engine transaction stays open
5233
- * (every later edit becomes un-undoable until some drag commits), and the
5234
- * per-frame skipAdapter moveClip mutations are never synced or rolled back
5235
- * (waveform and audio permanently disagree). */
5493
+ * armed (hover keeps moving the clip). The drag wrote nothing to the
5494
+ * arrangement, so reverting is putting the view back. */
5236
5495
  onPointerCancel(_e) {
5237
5496
  if (this._mode === null) return;
5238
5497
  try {
5239
- this._restoreTrimVisual();
5498
+ this._restoreVisual();
5240
5499
  } finally {
5241
- if (this._isDragging) this._host.engine?.abortTransaction();
5242
5500
  this._reset();
5243
5501
  }
5244
5502
  }
@@ -5260,11 +5518,11 @@ var ClipPointerHandler = class {
5260
5518
  return true;
5261
5519
  }
5262
5520
  /** Restore clip container CSS AND waveform peaks to original values after
5263
- * a trim visual preview. Peaks matter: the drag wrote re-extracted peak
5521
+ * a drag's visual preview. Peaks matter: a trim wrote re-extracted peak
5264
5522
  * arrays imperatively onto the <daw-waveform> elements (bypassing Lit), and
5265
- * a cancelled/zero-delta trim makes no engine mutation — so no statechange
5523
+ * a cancelled/zero-delta drag makes no engine mutation — so no statechange
5266
5524
  * re-render will ever repair them. */
5267
- _restoreTrimVisual() {
5525
+ _restoreVisual() {
5268
5526
  if (this._clipContainer) {
5269
5527
  this._clipContainer.style.left = this._originalLeft + "px";
5270
5528
  this._clipContainer.style.width = this._originalWidth + "px";
@@ -5292,6 +5550,8 @@ var ClipPointerHandler = class {
5292
5550
  this._originalOffsetSamples = 0;
5293
5551
  this._originalDurationSamples = 0;
5294
5552
  this._originalStartSample = 0;
5553
+ this._moveClip = null;
5554
+ this._moveSorted = [];
5295
5555
  }
5296
5556
  };
5297
5557
 
@@ -5322,9 +5582,12 @@ var AnnotationDragHandler = class {
5322
5582
  if (index === -1) return;
5323
5583
  const edge = isBoundary ? boundary.getAttribute("data-edge") : null;
5324
5584
  const captureEl = isBoundary ? boundary : box;
5585
+ this._drag?.listeners.abort();
5586
+ const listeners = new AbortController();
5325
5587
  this._drag = {
5326
5588
  track,
5327
5589
  captureEl,
5590
+ listeners,
5328
5591
  pointerId: e.pointerId,
5329
5592
  startClientX: e.clientX,
5330
5593
  moved: false,
@@ -5339,9 +5602,10 @@ var AnnotationDragHandler = class {
5339
5602
  captureEl.setPointerCapture(e.pointerId);
5340
5603
  } catch {
5341
5604
  }
5342
- captureEl.addEventListener("pointermove", this._onPointerMove);
5343
- captureEl.addEventListener("pointerup", this._onPointerUp);
5344
- captureEl.addEventListener("pointercancel", this._onPointerCancel);
5605
+ const { signal } = listeners;
5606
+ captureEl.addEventListener("pointermove", this._onPointerMove, { signal });
5607
+ captureEl.addEventListener("pointerup", this._onPointerUp, { signal });
5608
+ captureEl.addEventListener("pointercancel", this._onPointerCancel, { signal });
5345
5609
  };
5346
5610
  /** Non-private (underscore convention) so tests can drive moves directly. */
5347
5611
  this._onPointerMove = (e) => {
@@ -5446,9 +5710,7 @@ var AnnotationDragHandler = class {
5446
5710
  drag.captureEl.releasePointerCapture(drag.pointerId);
5447
5711
  } catch {
5448
5712
  }
5449
- drag.captureEl.removeEventListener("pointermove", this._onPointerMove);
5450
- drag.captureEl.removeEventListener("pointerup", this._onPointerUp);
5451
- drag.captureEl.removeEventListener("pointercancel", this._onPointerCancel);
5713
+ drag.listeners.abort();
5452
5714
  this._drag = null;
5453
5715
  }
5454
5716
  };
@@ -5465,6 +5727,8 @@ var TrackReorderHandler = class _TrackReorderHandler {
5465
5727
  this._fromIndex = 0;
5466
5728
  this._targetIndex = 0;
5467
5729
  this._gripEl = null;
5730
+ /** The grip's listeners of the drag in progress: one controller per drag. */
5731
+ this._gesture = null;
5468
5732
  this.onGrab = (trackId, e, gripEl) => {
5469
5733
  if (this._trackId !== null) return;
5470
5734
  const column = this._host.shadowRoot?.querySelector(".controls-column");
@@ -5514,9 +5778,11 @@ var TrackReorderHandler = class _TrackReorderHandler {
5514
5778
  gripEl.setPointerCapture(e.pointerId);
5515
5779
  } catch {
5516
5780
  }
5517
- gripEl.addEventListener("pointermove", this._onPointerMove);
5518
- gripEl.addEventListener("pointerup", this._onPointerUp);
5519
- gripEl.addEventListener("pointercancel", this._onPointerCancel);
5781
+ this._gesture = new AbortController();
5782
+ const { signal } = this._gesture;
5783
+ gripEl.addEventListener("pointermove", this._onPointerMove, { signal });
5784
+ gripEl.addEventListener("pointerup", this._onPointerUp, { signal });
5785
+ gripEl.addEventListener("pointercancel", this._onPointerCancel, { signal });
5520
5786
  };
5521
5787
  this._onPointerMove = (e) => {
5522
5788
  if (e.pointerId !== this._pointerId || this._trackId === null) return;
@@ -5586,6 +5852,11 @@ var TrackReorderHandler = class _TrackReorderHandler {
5586
5852
  static _reducedMotion() {
5587
5853
  return typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
5588
5854
  }
5855
+ /** The dragged track and the order of the rows at the grab (#848), or null. */
5856
+ get draggedTrack() {
5857
+ if (this._trackId === null) return null;
5858
+ return { trackId: this._trackId, order: this._rows.map((r) => r.trackId) };
5859
+ }
5589
5860
  /** True from the grab until the drag ends or is cancelled. */
5590
5861
  get isActive() {
5591
5862
  return this._trackId !== null;
@@ -5615,9 +5886,8 @@ var TrackReorderHandler = class _TrackReorderHandler {
5615
5886
  this._lanes = [];
5616
5887
  const grip = this._gripEl;
5617
5888
  if (grip) {
5618
- grip.removeEventListener("pointermove", this._onPointerMove);
5619
- grip.removeEventListener("pointerup", this._onPointerUp);
5620
- grip.removeEventListener("pointercancel", this._onPointerCancel);
5889
+ this._gesture?.abort();
5890
+ this._gesture = null;
5621
5891
  try {
5622
5892
  grip.releasePointerCapture(this._pointerId);
5623
5893
  } catch {
@@ -5681,13 +5951,66 @@ function parseDisplayTime(value, format) {
5681
5951
  return Math.max(0, seconds);
5682
5952
  }
5683
5953
 
5954
+ // src/interactions/abort.ts
5955
+ function abortError(message) {
5956
+ return new DOMException(message, "AbortError");
5957
+ }
5958
+ function isAbortError(error) {
5959
+ return error?.name === "AbortError";
5960
+ }
5961
+ function reasonOf(signal) {
5962
+ return signal.reason;
5963
+ }
5964
+ var PlaySignals = class {
5965
+ constructor() {
5966
+ this._controllers = /* @__PURE__ */ new WeakMap();
5967
+ }
5968
+ /** The signal of an arrangement: aborted when it is next swapped out. */
5969
+ signalOf(arrangement) {
5970
+ let controller = this._controllers.get(arrangement);
5971
+ if (!controller) {
5972
+ controller = new AbortController();
5973
+ this._controllers.set(arrangement, controller);
5974
+ }
5975
+ return controller.signal;
5976
+ }
5977
+ /** The arrangement leaves play: its waits end with `reason`; a later play gets a new signal. */
5978
+ swappedOut(arrangement, reason) {
5979
+ const controller = this._controllers.get(arrangement);
5980
+ this._controllers.delete(arrangement);
5981
+ controller?.abort(reason);
5982
+ }
5983
+ };
5984
+ function untilAborted(promise, signal) {
5985
+ if (!signal) return promise;
5986
+ if (signal.aborted) return Promise.reject(reasonOf(signal));
5987
+ return new Promise((resolve, reject) => {
5988
+ const done = new AbortController();
5989
+ signal.addEventListener("abort", () => reject(reasonOf(signal)), { signal: done.signal });
5990
+ promise.then(
5991
+ (value) => {
5992
+ done.abort();
5993
+ resolve(value);
5994
+ },
5995
+ (error) => {
5996
+ done.abort();
5997
+ reject(error);
5998
+ }
5999
+ );
6000
+ });
6001
+ }
6002
+
5684
6003
  // src/interactions/file-loader.ts
5685
- async function loadFiles(host, files) {
6004
+ async function loadFiles(host, files, options = {}) {
6005
+ const signal = options.signal;
6006
+ if (signal?.aborted) throw reasonOf(signal);
5686
6007
  if (!files) {
5687
6008
  console.warn("[dawcore] loadFiles called with null/undefined");
5688
6009
  return { loaded: [], failed: [] };
5689
6010
  }
5690
6011
  const fileArray = Array.from(files);
6012
+ const target = host.arrangement;
6013
+ const played = host._operationSignal();
5691
6014
  const loaded = [];
5692
6015
  const failed = [];
5693
6016
  const dispatchLoadError = (file, error) => {
@@ -5707,6 +6030,10 @@ async function loadFiles(host, files) {
5707
6030
  dispatchLoadError(file, new Error("<daw-editor> was disconnected"));
5708
6031
  continue;
5709
6032
  }
6033
+ if (played.aborted) {
6034
+ dispatchLoadError(file, reasonOf(played));
6035
+ continue;
6036
+ }
5710
6037
  if (file.type && !file.type.startsWith("audio/")) {
5711
6038
  const error = new Error("Non-audio MIME type: " + file.type);
5712
6039
  console.warn("[dawcore] Skipping non-audio file: " + file.name + " (" + file.type + ")");
@@ -5715,12 +6042,26 @@ async function loadFiles(host, files) {
5715
6042
  }
5716
6043
  let trackId = null;
5717
6044
  try {
5718
- trackId = await host._addDroppedFile(file);
5719
- await host._whenTrackLoaded(trackId);
6045
+ const adding = host._addDroppedFile(file);
6046
+ trackId = await untilAborted(adding, signal).catch((err) => {
6047
+ if (signal?.aborted)
6048
+ void adding.then(
6049
+ (id) => host._discardTrack(id, target),
6050
+ () => {
6051
+ }
6052
+ );
6053
+ throw err;
6054
+ });
6055
+ await untilAborted(host._whenTrackLoaded(trackId), signal);
5720
6056
  loaded.push(trackId);
5721
6057
  } catch (err) {
6058
+ if (signal?.aborted) {
6059
+ for (const id of [...loaded, ...trackId !== null ? [trackId] : []])
6060
+ host._discardTrack(id, target);
6061
+ throw reasonOf(signal);
6062
+ }
5722
6063
  console.warn("[dawcore] Failed to load file: " + file.name + " \u2014 " + String(err));
5723
- if (trackId !== null) host._discardTrack(trackId);
6064
+ if (trackId !== null) host._discardTrack(trackId, target);
5724
6065
  dispatchLoadError(file, err);
5725
6066
  }
5726
6067
  }
@@ -5736,6 +6077,9 @@ async function loadMidiImpl(host, source, options = {}) {
5736
6077
  "loadMidi: startTime must be a non-negative finite number (got " + String(options.startTime) + ")"
5737
6078
  );
5738
6079
  }
6080
+ const signal = host._operationSignal(options.signal);
6081
+ const target = host.arrangement;
6082
+ if (signal.aborted) throw reasonOf(signal);
5739
6083
  let midiModule;
5740
6084
  try {
5741
6085
  midiModule = await import("@dawcore/midi");
@@ -5746,7 +6090,7 @@ async function loadMidiImpl(host, source, options = {}) {
5746
6090
  const { parseMidiUrl, parseMidiFile } = midiModule;
5747
6091
  let parsed;
5748
6092
  if (typeof source === "string") {
5749
- parsed = await parseMidiUrl(source, void 0, options.signal);
6093
+ parsed = await parseMidiUrl(source, void 0, signal);
5750
6094
  } else {
5751
6095
  let buffer;
5752
6096
  try {
@@ -5758,21 +6102,24 @@ async function loadMidiImpl(host, source, options = {}) {
5758
6102
  }
5759
6103
  parsed = parseMidiFile(buffer);
5760
6104
  }
5761
- const childrenBefore = new Set(host.querySelectorAll("daw-track"));
6105
+ if (signal.aborted) throw reasonOf(signal);
5762
6106
  const settlements = await Promise.allSettled(
5763
6107
  parsed.tracks.map(
5764
- (t) => host.addTrack({
5765
- name: t.name,
5766
- kind: "midi",
5767
- clips: [
5768
- {
5769
- midiNotes: t.notes,
5770
- midiChannel: t.channel,
5771
- midiProgram: t.programNumber,
5772
- start: startTime
5773
- }
5774
- ]
5775
- })
6108
+ (t) => host.addTrack(
6109
+ {
6110
+ name: t.name,
6111
+ kind: "midi",
6112
+ clips: [
6113
+ {
6114
+ midiNotes: t.notes,
6115
+ midiChannel: t.channel,
6116
+ midiProgram: t.programNumber,
6117
+ start: startTime
6118
+ }
6119
+ ]
6120
+ },
6121
+ { signal }
6122
+ )
5776
6123
  )
5777
6124
  );
5778
6125
  const succeeded = [];
@@ -5785,17 +6132,14 @@ async function loadMidiImpl(host, source, options = {}) {
5785
6132
  }
5786
6133
  }
5787
6134
  if (rejections.length > 0) {
5788
- const appendedTracks = Array.from(host.querySelectorAll("daw-track")).filter(
5789
- (el) => !childrenBefore.has(el)
5790
- );
5791
- for (const el of appendedTracks) {
6135
+ for (const trackId of succeeded) {
5792
6136
  try {
5793
- el.remove();
6137
+ host._discardTrack(trackId, target);
5794
6138
  } catch (cleanupErr) {
5795
6139
  console.warn("[dawcore] loadMidi cleanup failed for a track: " + String(cleanupErr));
5796
6140
  }
5797
6141
  }
5798
- await Promise.resolve();
6142
+ if (signal.aborted) throw reasonOf(signal);
5799
6143
  for (let i = 1; i < rejections.length; i++) {
5800
6144
  console.warn(
5801
6145
  "[dawcore] loadMidi: additional track failure (" + i + "): " + stringifyReason(rejections[i])
@@ -5875,33 +6219,6 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
5875
6219
  clip
5876
6220
  ]
5877
6221
  }));
5878
- const desc = host._tracks.get(trackId);
5879
- if (desc) {
5880
- const sr = host.effectiveSampleRate;
5881
- const clipDesc = {
5882
- kind: "drop",
5883
- // The take has no <daw-clip> element — the engine id is the only
5884
- // handle updateClip()/removeClip() can address it by (#659).
5885
- clipId: clip.id,
5886
- src: "",
5887
- peaksSrc: "",
5888
- start: startSample / sr,
5889
- duration: durSamples / sr,
5890
- offset: 0,
5891
- gain: 1,
5892
- name: clipName ?? "Recording",
5893
- fadeIn: 0,
5894
- fadeOut: 0,
5895
- fadeType: "linear",
5896
- midiNotes: null,
5897
- midiChannel: null,
5898
- midiProgram: null
5899
- };
5900
- host._tracks = new Map(host._tracks).set(trackId, {
5901
- ...desc,
5902
- clips: [...desc.clips, clipDesc]
5903
- });
5904
- }
5905
6222
  if (host.isConnected) {
5906
6223
  host.dispatchEvent(
5907
6224
  new CustomEvent("daw-recording-clip-add", {
@@ -5984,18 +6301,18 @@ function performSplit(host, time) {
5984
6301
  );
5985
6302
  return false;
5986
6303
  }
6304
+ const leftClip = trackAfter.clips.find((c) => c.id === originalClipId);
5987
6305
  const newClips = trackAfter.clips.filter((c) => !clipIdsBefore.has(c.id));
5988
- if (newClips.length !== 2) {
6306
+ if (!leftClip || newClips.length !== 1) {
5989
6307
  if (newClips.length > 0) {
5990
6308
  console.warn(
5991
- "[dawcore] splitAtPlayhead: expected 2 new clips after split but got " + newClips.length
6309
+ "[dawcore] splitAtPlayhead: expected the original clip and 1 new clip after split but got " + newClips.length + " new"
5992
6310
  );
5993
6311
  }
5994
6312
  return false;
5995
6313
  }
5996
- const sorted = [...newClips].sort((a, b) => a.startSample - b.startSample);
5997
- const leftClipId = sorted[0].id;
5998
- const rightClipId = sorted[1].id;
6314
+ const leftClipId = leftClip.id;
6315
+ const rightClipId = newClips[0].id;
5999
6316
  host.dispatchEvent(
6000
6317
  new CustomEvent("daw-clip-split", {
6001
6318
  bubbles: true,
@@ -6295,6 +6612,113 @@ var LoadAnnouncer = class {
6295
6612
  }
6296
6613
  };
6297
6614
 
6615
+ // src/interactions/arrangement-view.ts
6616
+ var import_core15 = require("@waveform-playlist/core");
6617
+ var views = /* @__PURE__ */ new WeakMap();
6618
+ function sameMix(a, b) {
6619
+ return a.volume === b.volume && a.pan === b.pan && a.muted === b.muted && a.soloed === b.soloed;
6620
+ }
6621
+ function loadedTrack(track, mix, recording) {
6622
+ const cached = views.get(track);
6623
+ if (cached && cached.recording === recording && sameMix(cached.mix, mix)) return cached.view;
6624
+ const view = {
6625
+ ...track,
6626
+ clips: track.clips.filter((c) => !(0, import_core15.isLoadingClip)(c)),
6627
+ volume: mix.volume,
6628
+ pan: mix.pan,
6629
+ muted: mix.muted || recording,
6630
+ soloed: mix.soloed
6631
+ };
6632
+ views.set(track, { mix: { ...mix }, recording, view });
6633
+ return view;
6634
+ }
6635
+ function mixOf(arrangement, trackId) {
6636
+ const mix = arrangement.getMixer().get(trackId);
6637
+ if (!mix) return null;
6638
+ return arrangement.recordingTrackIds.has(trackId) ? { ...mix, muted: true } : mix;
6639
+ }
6640
+ function clipSeconds(clip, fallbackSampleRate) {
6641
+ if ((0, import_core15.isLoadingClip)(clip)) {
6642
+ return { start: clip.start ?? 0, duration: clip.duration ?? 0, offset: clip.offset ?? 0 };
6643
+ }
6644
+ const sr = clip.sampleRate ?? fallbackSampleRate;
6645
+ return {
6646
+ start: clip.startSample / sr,
6647
+ duration: clip.durationSamples / sr,
6648
+ offset: clip.offsetSamples / sr
6649
+ };
6650
+ }
6651
+
6652
+ // src/interactions/arrangement-swap.ts
6653
+ var import_engine2 = require("@waveform-playlist/engine");
6654
+ function normalizeHandedIn(value, own) {
6655
+ if (value === null || value === void 0 || value === own) return null;
6656
+ if (!(0, import_engine2.isArrangement)(value)) {
6657
+ throw new TypeError(
6658
+ "[dawcore] editor.arrangement must be an arrangement made by createArrangement() (@waveform-playlist/engine), or null for the editor's own."
6659
+ );
6660
+ }
6661
+ return value;
6662
+ }
6663
+ function swapArrangement(host, next) {
6664
+ if (next === host._handedIn) return;
6665
+ if (host.isRecording) {
6666
+ console.warn(
6667
+ "[dawcore] editor.arrangement was not changed: a take is recording. Set it after stopRecording() resolves."
6668
+ );
6669
+ return;
6670
+ }
6671
+ host._cancelDrags();
6672
+ if (host.isPlaying) host.stop();
6673
+ const before = host._arrangement.getTracks().map((t) => t.id);
6674
+ host._releaseEngine();
6675
+ host._playArrangement(next);
6676
+ const kept = new Set(host._arrangement.getTracks().map((t) => t.id));
6677
+ for (const id of before) if (!kept.has(id)) host._disposeTrackChain(id);
6678
+ host._buildEngineIfReady();
6679
+ }
6680
+
6681
+ // src/interactions/drag-watch.ts
6682
+ var import_core16 = require("@waveform-playlist/core");
6683
+ function clipDragChanged(arrangement, drag) {
6684
+ const clip = arrangement.getTracks().find((t) => t.id === drag.trackId)?.clips.find((c) => c.id === drag.clipId);
6685
+ if (!clip || (0, import_core16.isLoadingClip)(clip)) return true;
6686
+ return clip.startSample !== drag.startSample || clip.durationSamples !== drag.durationSamples || clip.offsetSamples !== drag.offsetSamples;
6687
+ }
6688
+ function trackDragChanged(arrangement, drag) {
6689
+ const ids = arrangement.getTracks().map((t) => t.id);
6690
+ if (!ids.includes(drag.trackId) || ids.length !== drag.order.length) return true;
6691
+ return ids.some((id, i) => id !== drag.order[i]);
6692
+ }
6693
+
6694
+ // src/interactions/clip-rehome.ts
6695
+ function trackHoldingClip(arrangement, clipId, exceptTrackId) {
6696
+ const track = arrangement.getTracks().find((t) => t.id !== exceptTrackId && t.clips.some((c) => c.id === clipId));
6697
+ return track?.id ?? null;
6698
+ }
6699
+ function moveClipToTrack(arrangement, fromTrackId, toTrackId, clipId, toKind) {
6700
+ const tracks = arrangement.getTracks();
6701
+ const clip = tracks.find((t) => t.id === fromTrackId)?.clips.find((c) => c.id === clipId);
6702
+ const to = tracks.find((t) => t.id === toTrackId);
6703
+ if (!clip || !to) return new Error('clip "' + clipId + '" or track "' + toTrackId + '" is gone');
6704
+ const isMidi = "midiNotes" in clip && clip.midiNotes != null;
6705
+ const kindError = clipKindError(to.name ?? "", toKind, isMidi, clip.name || clipId);
6706
+ if (kindError) return kindError;
6707
+ arrangement.beginTransaction();
6708
+ try {
6709
+ arrangement.updateTrack(fromTrackId, (t) => ({
6710
+ ...t,
6711
+ clips: t.clips.filter((c) => c.id !== clipId)
6712
+ }));
6713
+ arrangement.updateTrack(toTrackId, (t) => ({ ...t, clips: [...t.clips, clip] }));
6714
+ } catch (err) {
6715
+ arrangement.abortTransaction();
6716
+ return err instanceof Error ? err : new Error(String(err));
6717
+ }
6718
+ arrangement.commitTransaction();
6719
+ return null;
6720
+ }
6721
+
6298
6722
  // src/effects/effects-chain-controller.ts
6299
6723
  var idCounter = 0;
6300
6724
  var EffectsChainController = class {
@@ -6508,10 +6932,10 @@ function loadFaustModule(feature) {
6508
6932
  }
6509
6933
 
6510
6934
  // src/effects/effects-manager.ts
6511
- var import_core16 = require("@waveform-playlist/core");
6935
+ var import_core18 = require("@waveform-playlist/core");
6512
6936
 
6513
6937
  // src/effects/effect-registry.ts
6514
- var import_core15 = require("@waveform-playlist/core");
6938
+ var import_core17 = require("@waveform-playlist/core");
6515
6939
  var MAX_DELAY_SECONDS = 10;
6516
6940
  function singleNode(node, applyParams) {
6517
6941
  return { input: node, output: node, applyParams };
@@ -6587,8 +7011,8 @@ function biquadDefinition(spec) {
6587
7011
  };
6588
7012
  }
6589
7013
  function registerBuiltIn(type, definition) {
6590
- if (!(0, import_core15.getEffectDefinitions)().has(type)) {
6591
- (0, import_core15.registerEffect)(type, { ...definition, builtIn: true });
7014
+ if (!(0, import_core17.getEffectDefinitions)().has(type)) {
7015
+ (0, import_core17.registerEffect)(type, { ...definition, builtIn: true });
6592
7016
  }
6593
7017
  }
6594
7018
  function registerBuiltIns() {
@@ -6743,7 +7167,7 @@ var EffectsManager = class {
6743
7167
  /** Run a registered effect's async `prepare` hook on the adapter's
6744
7168
  * context, so the synchronous addEffect() can create it. */
6745
7169
  async prepareEffect(type) {
6746
- await (0, import_core16.prepareEffect)(type, this._requireWiring().audioContext);
7170
+ await (0, import_core18.prepareEffect)(type, this._requireWiring().audioContext);
6747
7171
  }
6748
7172
  // --- Track chains ---
6749
7173
  addTrackEffect(trackId, target, type, params) {
@@ -6948,7 +7372,7 @@ var EffectsManager = class {
6948
7372
  this._runOp(chain, target, "setParams", effectId, { [paramId]: value });
6949
7373
  };
6950
7374
  if (entry.kind === "native") {
6951
- const definition = (0, import_core16.getEffectDefinitions)().get(entry.type);
7375
+ const definition = (0, import_core18.getEffectDefinitions)().get(entry.type);
6952
7376
  if (!definition) {
6953
7377
  throw new Error(
6954
7378
  PREFIX2 + 'openEffectGui: no registry definition for effect type "' + entry.type + '"'
@@ -7007,7 +7431,7 @@ var EffectsManager = class {
7007
7431
  }
7008
7432
  _addToChain(chain, target, type, params) {
7009
7433
  const audioContext = this._requireWiring().audioContext;
7010
- const created = (0, import_core16.createEffectInstance)(type, audioContext, params);
7434
+ const created = (0, import_core18.createEffectInstance)(type, audioContext, params);
7011
7435
  const effectId = chain.add({
7012
7436
  kind: "native",
7013
7437
  type,
@@ -7179,8 +7603,8 @@ var EffectsManager = class {
7179
7603
  if (entry.kind === "native") {
7180
7604
  try {
7181
7605
  const liveContext = this._requireWiring().audioContext;
7182
- if ((0, import_core16.needsPrepare)(entry.type, liveContext)) {
7183
- await (0, import_core16.ensureEffectPrepared)(entry.type, liveContext);
7606
+ if ((0, import_core18.needsPrepare)(entry.type, liveContext)) {
7607
+ await (0, import_core18.ensureEffectPrepared)(entry.type, liveContext);
7184
7608
  if (superseded() || chain.disposed) return;
7185
7609
  }
7186
7610
  const id = this._addToChain(chain, target, entry.type, entry.params);
@@ -7355,8 +7779,8 @@ function toWamParameterMap(params) {
7355
7779
  }
7356
7780
 
7357
7781
  // src/interactions/export-audio.ts
7358
- var import_core17 = require("@waveform-playlist/core");
7359
- var import_core18 = require("@waveform-playlist/core");
7782
+ var import_core19 = require("@waveform-playlist/core");
7783
+ var import_core20 = require("@waveform-playlist/core");
7360
7784
  var PREFIX3 = "[waveform-playlist] ";
7361
7785
  async function exportAudioImpl(host, options = {}) {
7362
7786
  const sampleRate = options.sampleRate ?? host.effectiveSampleRate;
@@ -7391,7 +7815,7 @@ async function exportAudioImpl(host, options = {}) {
7391
7815
  cleanups.push(chain.dispose);
7392
7816
  const volume = ctx.createGain();
7393
7817
  volume.gain.value = track.volume;
7394
- const panStage = (0, import_core17.createPanStage)(ctx, track.pan, (0, import_core17.trackChannelCount)(track));
7818
+ const panStage = (0, import_core19.createPanStage)(ctx, track.pan, (0, import_core19.trackChannelCount)(track));
7395
7819
  cleanups.push(panStage.dispose);
7396
7820
  chain.output.connect(volume);
7397
7821
  volume.connect(panStage.input);
@@ -7473,12 +7897,12 @@ async function buildOfflineChain(ctx, entries) {
7473
7897
  continue;
7474
7898
  }
7475
7899
  if (entry.kind === "native") {
7476
- const definition = (0, import_core18.getEffectDefinitions)().get(entry.type);
7900
+ const definition = (0, import_core20.getEffectDefinitions)().get(entry.type);
7477
7901
  if (entry.bypassed && definition && !definition.wetParam) {
7478
7902
  continue;
7479
7903
  }
7480
- await (0, import_core18.ensureEffectPrepared)(entry.type, ctx);
7481
- const created = (0, import_core18.createEffectInstance)(entry.type, ctx, entry.params);
7904
+ await (0, import_core20.ensureEffectPrepared)(entry.type, ctx);
7905
+ const created = (0, import_core20.createEffectInstance)(entry.type, ctx, entry.params);
7482
7906
  if (entry.bypassed && created.wetParam) {
7483
7907
  created.instance.applyParams({ [created.wetParam]: 0 });
7484
7908
  }
@@ -7520,8 +7944,8 @@ async function buildOfflineChain(ctx, entries) {
7520
7944
 
7521
7945
  // src/interactions/peaks-loader.ts
7522
7946
  var import_waveform_data2 = __toESM(require("waveform-data"));
7523
- async function loadWaveformDataFromUrl(src) {
7524
- const response = await fetch(src);
7947
+ async function loadWaveformDataFromUrl(src, signal) {
7948
+ const response = await fetch(src, signal ? { signal } : void 0);
7525
7949
  if (!response.ok) {
7526
7950
  throw new Error("[dawcore] Failed to fetch peaks data: " + response.statusText);
7527
7951
  }
@@ -7541,7 +7965,10 @@ var LINE_HEIGHT_PX = 16;
7541
7965
  var ScrollSyncController = class {
7542
7966
  constructor(host) {
7543
7967
  this._scrollContainer = null;
7544
- this._wheelTargets = /* @__PURE__ */ new Set();
7968
+ /** The scroll listener on `_scrollContainer`, aborted when it is replaced or detached. */
7969
+ this._scrollListener = null;
7970
+ /** Each wheel target and the controller of its listener. */
7971
+ this._wheelTargets = /* @__PURE__ */ new Map();
7545
7972
  this._warnedX = false;
7546
7973
  this._warnedY = false;
7547
7974
  /** Selector (in host shadow DOM) for the scroll container. */
@@ -7586,11 +8013,14 @@ var ScrollSyncController = class {
7586
8013
  });
7587
8014
  }
7588
8015
  hostDisconnected() {
7589
- this._scrollContainer?.removeEventListener("scroll", this._onScroll);
8016
+ this._detachAll();
8017
+ }
8018
+ /** Remove the scroll and every wheel listener. */
8019
+ _detachAll() {
8020
+ this._scrollListener?.abort();
8021
+ this._scrollListener = null;
7590
8022
  this._scrollContainer = null;
7591
- for (const target of this._wheelTargets) {
7592
- target.removeEventListener("wheel", this._onWheel);
7593
- }
8023
+ for (const listener of this._wheelTargets.values()) listener.abort();
7594
8024
  this._wheelTargets.clear();
7595
8025
  }
7596
8026
  /**
@@ -7616,29 +8046,31 @@ var ScrollSyncController = class {
7616
8046
  console.warn(
7617
8047
  '[dawcore] ScrollSyncController: scroll container "' + this.scrollSelector + '" was removed from the DOM \u2014 detaching listeners until it reappears.'
7618
8048
  );
7619
- this._scrollContainer.removeEventListener("scroll", this._onScroll);
7620
- this._scrollContainer = null;
7621
- for (const t of this._wheelTargets) t.removeEventListener("wheel", this._onWheel);
7622
- this._wheelTargets.clear();
8049
+ this._detachAll();
7623
8050
  }
7624
8051
  return;
7625
8052
  }
7626
8053
  if (container !== this._scrollContainer) {
7627
- this._scrollContainer?.removeEventListener("scroll", this._onScroll);
8054
+ this._scrollListener?.abort();
7628
8055
  this._scrollContainer = container;
7629
- container.addEventListener("scroll", this._onScroll, { passive: true });
8056
+ this._scrollListener = new AbortController();
8057
+ container.addEventListener("scroll", this._onScroll, {
8058
+ passive: true,
8059
+ signal: this._scrollListener.signal
8060
+ });
7630
8061
  }
7631
8062
  const nextTargets = new Set(this._queryAll(this.wheelForwardSelector));
7632
- for (const old of this._wheelTargets) {
8063
+ for (const [old, listener] of [...this._wheelTargets]) {
7633
8064
  if (!nextTargets.has(old)) {
7634
- old.removeEventListener("wheel", this._onWheel);
8065
+ listener.abort();
7635
8066
  this._wheelTargets.delete(old);
7636
8067
  }
7637
8068
  }
7638
8069
  for (const next of nextTargets) {
7639
8070
  if (!this._wheelTargets.has(next)) {
7640
- next.addEventListener("wheel", this._onWheel, { passive: false });
7641
- this._wheelTargets.add(next);
8071
+ const listener = new AbortController();
8072
+ next.addEventListener("wheel", this._onWheel, { passive: false, signal: listener.signal });
8073
+ this._wheelTargets.set(next, listener);
7642
8074
  }
7643
8075
  }
7644
8076
  this._apply();
@@ -7744,7 +8176,38 @@ var PlaybackAnimationController = class {
7744
8176
  // src/elements/daw-editor.ts
7745
8177
  var import_meta = {};
7746
8178
  var RULER_HEIGHT = 30;
8179
+ function clipDescriptorOf(config) {
8180
+ return {
8181
+ kind: "drop",
8182
+ clipId: crypto.randomUUID(),
8183
+ src: config.src ?? "",
8184
+ peaksSrc: config.peaksSrc ?? "",
8185
+ start: config.start ?? 0,
8186
+ duration: config.duration ?? 0,
8187
+ offset: config.offset ?? 0,
8188
+ gain: config.gain ?? 1,
8189
+ name: config.name ?? "",
8190
+ fadeIn: config.fadeIn ?? 0,
8191
+ fadeOut: config.fadeOut ?? 0,
8192
+ fadeType: config.fadeType ?? "linear",
8193
+ midiNotes: config.midiNotes ?? null,
8194
+ midiChannel: config.midiChannel ?? null,
8195
+ midiProgram: config.midiProgram ?? null
8196
+ };
8197
+ }
8198
+ function extrasOf(descriptor) {
8199
+ return {
8200
+ kind: descriptor.kind,
8201
+ renderMode: descriptor.renderMode,
8202
+ spectrogramConfig: descriptor.spectrogramConfig,
8203
+ src: descriptor.src,
8204
+ peaksSrc: new Map(
8205
+ descriptor.clips.flatMap((c) => c.clipId ? [[c.clipId, c.peaksSrc]] : [])
8206
+ )
8207
+ };
8208
+ }
7747
8209
  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();";
8210
+ var ENTERED = /* @__PURE__ */ Symbol("entered");
7748
8211
  var DawEditorElement = class extends import_lit19.LitElement {
7749
8212
  constructor() {
7750
8213
  super();
@@ -7773,13 +8236,18 @@ var DawEditorElement = class extends import_lit19.LitElement {
7773
8236
  this._ppqn = 960;
7774
8237
  this.snapTo = "off";
7775
8238
  /**
7776
- * The one owner of the tracks, the clips, the mix, the undo history and
7777
- * loading (#848). Made with the editor, kept across a disconnect; the
7778
- * engine plays it once there is an adapter.
8239
+ * The editor's own arrangement (#848): the one owner of the tracks, the
8240
+ * clips, the mix, the undo history and loading of what the `<daw-track>`
8241
+ * children declare. Made with the editor, kept across a disconnect.
7779
8242
  */
7780
- this._arrangement = (0, import_engine.createArrangement)();
7781
- /** Sends the load events, read from the arrangement (#848). */
8243
+ this._ownArrangement = (0, import_engine3.createArrangement)();
8244
+ /** An arrangement the app handed in (`editor.arrangement`), played alone; null: the own one. */
8245
+ this._handedIn = null;
8246
+ /** Sends the load events, read from the arrangement played (#848; a new one per swap). */
7782
8247
  this._announcer = new LoadAnnouncer((event) => this.dispatchEvent(event));
8248
+ /** Stops following the arrangement played (its sources and its tracks). */
8249
+ this._unfollow = () => {
8250
+ };
7783
8251
  /**
7784
8252
  * Ids of tracks registered (a `<daw-track>` connected, a file dropped) and
7785
8253
  * not yet in the arrangement: they enter at the next flush, once there is
@@ -7793,13 +8261,17 @@ var DawEditorElement = class extends import_lit19.LitElement {
7793
8261
  * loads settles it here, without a public event (#917).
7794
8262
  */
7795
8263
  this._awaitedClips = /* @__PURE__ */ new Map();
7796
- /** `<daw-track>` elements `addTrack()` made: every other one is the page's (the history rule). */
7797
- this._editorMadeTracks = /* @__PURE__ */ new WeakSet();
7798
8264
  this._previewPeaks = /* @__PURE__ */ new Map();
7799
8265
  /** The `.dat` data of those clips, handed to the peak pipeline when the audio arrives. */
7800
8266
  this._previewWaveforms = /* @__PURE__ */ new Map();
7801
- this._tracks = /* @__PURE__ */ new Map();
7802
- this._engineTracks = /* @__PURE__ */ new Map();
8267
+ /**
8268
+ * Tracks registered and not in the arrangement yet, with their declaration
8269
+ * (#848): a `<daw-track>` is read when it enters (its clips and attributes
8270
+ * as they are then); a dropped file carries its descriptor. The one place a
8271
+ * track's state lives until it enters.
8272
+ */
8273
+ this._pending = /* @__PURE__ */ new Map();
8274
+ this._extras = /* @__PURE__ */ new Map();
7803
8275
  this._peaksData = /* @__PURE__ */ new Map();
7804
8276
  this._isPlaying = false;
7805
8277
  this._duration = 0;
@@ -7873,6 +8345,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
7873
8345
  s.scrollSelector = ".scroll-area";
7874
8346
  return s;
7875
8347
  })();
8348
+ /** One gesture id per track for the rest of this task: mix sets made together are one step (#843). */
8349
+ this._taskGestures = /* @__PURE__ */ new Map();
7876
8350
  /**
7877
8351
  * Cache of the last ViewportState forwarded to the spectrogram controller.
7878
8352
  * Lit's `updated()` fires on every reactive state change (`_isPlaying`,
@@ -7905,12 +8379,14 @@ var DawEditorElement = class extends import_lit19.LitElement {
7905
8379
  console.warn("[dawcore] Invalid daw-track-connected event detail: " + String(e.detail));
7906
8380
  return;
7907
8381
  }
7908
- if (this._tracks.has(trackId)) {
8382
+ if (this._pending.has(trackId) || this._extras.has(trackId) || this._isEntered(trackId)) {
7909
8383
  this._trackElements.set(trackId, trackEl);
7910
8384
  return;
7911
8385
  }
7912
- const descriptor = this._readTrackDescriptor(trackEl);
7913
- this._tracks = new Map(this._tracks).set(trackId, descriptor);
8386
+ this._pending = new Map(this._pending).set(trackId, {
8387
+ element: trackEl,
8388
+ extraClips: []
8389
+ });
7914
8390
  this._trackElements.set(trackId, trackEl);
7915
8391
  this._queueEntry(trackId);
7916
8392
  };
@@ -7919,50 +8395,33 @@ var DawEditorElement = class extends import_lit19.LitElement {
7919
8395
  if (!trackId) return;
7920
8396
  const trackEl = e.target.closest("daw-track");
7921
8397
  if (!trackEl) return;
7922
- const oldDescriptor = this._tracks.get(trackId);
7923
- let descriptor = this._readTrackDescriptor(trackEl);
7924
- if (oldDescriptor && oldDescriptor.kind !== descriptor.kind) {
7925
- console.warn(
7926
- '[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.'
7927
- );
7928
- descriptor = {
7929
- ...descriptor,
7930
- kind: oldDescriptor.kind,
7931
- renderMode: trackDescriptorRenderMode(oldDescriptor.kind, trackEl.renderMode)
7932
- };
7933
- const keptKind = oldDescriptor.kind;
7934
- queueMicrotask(() => {
7935
- trackEl.kind = keptKind;
7936
- });
7937
- }
7938
- if (oldDescriptor && oldDescriptor.src === descriptor.src && !descriptor.clips.some(isDomClip) && !oldDescriptor.clips.some(isDomClip)) {
7939
- descriptor = { ...descriptor, clips: oldDescriptor.clips };
7940
- }
7941
- this._tracks = new Map(this._tracks).set(trackId, descriptor);
8398
+ const old = this._extras.get(trackId);
8399
+ if (!old || !this._isEntered(trackId)) return;
7942
8400
  const changed = Array.isArray(e.detail.changed) ? e.detail.changed : [];
7943
- this._writeMixFields(trackId, pickMix(mixOfElement(trackEl), changed));
7944
- if (oldDescriptor && oldDescriptor.src !== descriptor.src) {
7945
- this._replaceShorthandClips(trackId, descriptor);
7946
- }
7947
- if (descriptor.renderMode === "spectrogram" && oldDescriptor?.renderMode !== "spectrogram") {
7948
- const engineTrack = this._engineTracks.get(trackId);
7949
- if (engineTrack) {
7950
- for (const clip of engineTrack.clips) {
7951
- this._maybeRegisterSpectrogramClipAudio(trackId, clip);
7952
- }
7953
- }
7954
- }
7955
- if (descriptor.renderMode !== "spectrogram" && oldDescriptor?.renderMode === "spectrogram") {
7956
- const engineTrack = this._engineTracks.get(trackId);
7957
- if (engineTrack && this._spectrogramController) {
7958
- for (const clip of engineTrack.clips) {
7959
- this._spectrogramController.unregisterClipAudio(clip.id);
7960
- }
8401
+ const next = {
8402
+ ...old,
8403
+ ...changed.includes("renderMode") && {
8404
+ renderMode: trackDescriptorRenderMode(old.kind, trackEl.renderMode)
8405
+ },
8406
+ ...changed.includes("spectrogramConfig") && {
8407
+ spectrogramConfig: trackEl.spectrogramConfig
8408
+ },
8409
+ ...changed.includes("src") && { src: trackEl.src }
8410
+ };
8411
+ this._extras = new Map(this._extras).set(trackId, next);
8412
+ if (old.src !== next.src) this._replaceShorthandClips(trackId, trackEl);
8413
+ const loaded = this._loadedTracks().find((t) => t.id === trackId)?.clips ?? [];
8414
+ if (next.renderMode === "spectrogram" && old.renderMode !== "spectrogram") {
8415
+ for (const clip of loaded) this._maybeRegisterSpectrogramClipAudio(trackId, clip);
8416
+ }
8417
+ if (next.renderMode !== "spectrogram" && old.renderMode === "spectrogram") {
8418
+ if (this._spectrogramController) {
8419
+ for (const clip of loaded) this._spectrogramController.unregisterClipAudio(clip.id);
7961
8420
  }
7962
8421
  this._disposeSpectrogramControllerIfEmpty();
7963
8422
  }
7964
- if (descriptor.spectrogramConfig !== oldDescriptor?.spectrogramConfig) {
7965
- this._spectrogramController?.setTrackConfig(trackId, descriptor.spectrogramConfig ?? null);
8423
+ if (next.spectrogramConfig !== old.spectrogramConfig) {
8424
+ this._spectrogramController?.setTrackConfig(trackId, next.spectrogramConfig ?? null);
7966
8425
  }
7967
8426
  };
7968
8427
  this._onTrackControl = (e) => {
@@ -7981,7 +8440,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
7981
8440
  })
7982
8441
  );
7983
8442
  }
7984
- if (this._tracks.has(trackId)) {
8443
+ if (this._isEntered(trackId)) {
7985
8444
  const options = typeof gesture === "string" ? { gesture } : void 0;
7986
8445
  if (prop === "volume") this._writeMix(trackId, "volume", clampNumber(value, 0, 1), options);
7987
8446
  if (prop === "pan") this._writeMix(trackId, "pan", clampNumber(value, -1, 1), options);
@@ -8007,56 +8466,42 @@ var DawEditorElement = class extends import_lit19.LitElement {
8007
8466
  const trackEl = clipEl.closest("daw-track");
8008
8467
  if (!trackEl) return;
8009
8468
  const trackId = trackEl.trackId;
8010
- if (!this._isEntered(trackId)) {
8469
+ if (this._rehomeClip(trackId, clipEl)) return;
8470
+ const entered = this._arrangementOf(trackId).getTracks().some((t) => t.id === trackId);
8471
+ if (!entered && !this._pending.has(trackId) && this._trackLinkState(trackId) === "detached") {
8472
+ this._takeClip(trackId, clipEl.clipId, clipEl.peaksSrc || "");
8473
+ console.warn(
8474
+ detachedWarning(
8475
+ '<daw-track> "' + (trackEl.name || "Untitled") + '"',
8476
+ "a <daw-clip> added to it",
8477
+ this._detachedReason()
8478
+ )
8479
+ );
8480
+ this._rejectAwaitedClips(
8481
+ (id) => id === clipEl.clipId,
8482
+ 'addClip: track "' + trackId + '" is detached'
8483
+ );
8484
+ this._refreshLinkStates();
8485
+ return;
8486
+ }
8487
+ if (!entered) {
8011
8488
  if (!this._entryQueue.includes(trackId)) {
8012
8489
  this._rejectAwaitedClips(
8013
8490
  (id) => id === clipEl.clipId,
8014
8491
  'addClip: track "' + trackId + '" is not in the editor (an Undo took it out)'
8015
8492
  );
8016
- return;
8017
- }
8018
- const desc = this._tracks.get(trackId);
8019
- if (desc && !desc.clips.some((c) => isDomClip(c) && c.clipId === clipEl.clipId)) {
8020
- this._tracks = new Map(this._tracks).set(trackId, {
8021
- ...desc,
8022
- clips: [...desc.clips, this._readClipDescriptor(clipEl)]
8023
- });
8024
8493
  }
8025
8494
  return;
8026
8495
  }
8027
- const loadedDesc = this._tracks.get(trackId);
8028
- if (loadedDesc && loadedDesc.clips.some((c) => isDomClip(c) && c.clipId === clipEl.clipId)) {
8029
- return;
8030
- }
8496
+ if (this._extras.get(trackId)?.peaksSrc.has(clipEl.clipId)) return;
8031
8497
  this._loadAndAppendClip(trackId, this._readClipDescriptor(clipEl));
8032
8498
  };
8033
- this._onClipUpdate = (e) => {
8034
- const clipEl = e.target;
8035
- if (!(clipEl instanceof HTMLElement) || clipEl.tagName !== "DAW-CLIP") return;
8036
- const detail = e.detail;
8037
- if (!detail.trackId) {
8038
- console.warn(
8039
- "[dawcore] daw-clip-update fired from a <daw-clip> not nested in a <daw-track> \u2014 ignored"
8040
- );
8041
- return;
8042
- }
8043
- const desc = this._tracks.get(detail.trackId);
8044
- if (desc && !this._isEntered(detail.trackId)) {
8045
- this._tracks = new Map(this._tracks).set(detail.trackId, {
8046
- ...desc,
8047
- clips: desc.clips.map(
8048
- (c) => isDomClip(c) && c.clipId === clipEl.clipId ? this._readClipDescriptor(clipEl) : c
8049
- )
8050
- });
8051
- return;
8052
- }
8053
- this._applyClipUpdate(detail.trackId, detail.clipId, clipEl);
8054
- };
8055
- this._waitingForDragEnd = false;
8056
8499
  /** Who waits for a track to enter (addTrack, a dropped file). */
8057
8500
  this._entryWaiters = /* @__PURE__ */ new Map();
8058
- /** Ends the waits of `_whenTrackLoaded` (as loaded) when the editor is disconnected. */
8059
- this._loadWaitEnds = /* @__PURE__ */ new Set();
8501
+ /** One AbortController per arrangement while it is played (D2, interactions/abort.ts). */
8502
+ this._playSignals = new PlaySignals();
8503
+ /** One AbortController per connection: aborted in disconnectedCallback (D8). */
8504
+ this._connection = new AbortController();
8060
8505
  /** Last versions the statechange handler worked from; reset for each engine. */
8061
8506
  this._lastTracksVersion = -1;
8062
8507
  this._lastMixerVersion = -1;
@@ -8123,15 +8568,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
8123
8568
  }
8124
8569
  return time * this.effectiveSampleRate / this.samplesPerPixel;
8125
8570
  };
8126
- /** Guards the statechange handler's engine→DOM sync (Task: reorder #612)
8127
- * while the observer is pushing DOM order INTO the engine — the intermediate
8128
- * statechange emissions during the transaction would otherwise bounce
8129
- * half-applied orders back into the DOM. */
8130
- this._inOrderSync = false;
8131
- this._arrangement.sources.subscribe(() => {
8132
- this._announceLoading();
8133
- this.requestUpdate();
8134
- });
8571
+ this._follow(this._ownArrangement);
8135
8572
  }
8136
8573
  get samplesPerPixel() {
8137
8574
  return this._samplesPerPixel;
@@ -8253,8 +8690,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
8253
8690
  * render — even if no canvases have been registered yet.
8254
8691
  */
8255
8692
  _maybeRegisterSpectrogramClipAudio(trackId, clip) {
8256
- const descriptor = this._tracks.get(trackId);
8257
- if (descriptor?.renderMode !== "spectrogram") return;
8693
+ if (this._renderModeOf(trackId) !== "spectrogram") return;
8258
8694
  const buffer = clip.audioBuffer ?? this._clipBuffers.get(clip.id);
8259
8695
  if (!buffer) return;
8260
8696
  const channelData = [];
@@ -8326,6 +8762,97 @@ var DawEditorElement = class extends import_lit19.LitElement {
8326
8762
  }
8327
8763
  return null;
8328
8764
  }
8765
+ /** The arrangement played now: a handed-in one, else the editor's own. */
8766
+ get _arrangement() {
8767
+ return this._handedIn ?? this._ownArrangement;
8768
+ }
8769
+ /**
8770
+ * The arrangement the editor plays (#848 PR 3): one handed in by the app,
8771
+ * or else the editor's own, whose content the `<daw-track>` children
8772
+ * declare. Setting one plays it alone, like `video.srcObject`: the
8773
+ * children are not added to it and show `:state(detached)` while it is
8774
+ * set; `null` (or the editor's own) goes back to the own arrangement with
8775
+ * what it held. A swap keeps the adapter: playback stops, a new engine is
8776
+ * built on the new arrangement. Refused (with a warning) during a take.
8777
+ * The editor never disposes or clears an arrangement it was handed.
8778
+ * Throws a `TypeError` for a value that is not an arrangement.
8779
+ */
8780
+ get arrangement() {
8781
+ return this._arrangement;
8782
+ }
8783
+ set arrangement(value) {
8784
+ swapArrangement(this, normalizeHandedIn(value, this._ownArrangement));
8785
+ }
8786
+ /**
8787
+ * Follow the arrangement played: a source that fails changes no track,
8788
+ * only `sources` tells of it (the events, the failed look); the elements'
8789
+ * link states follow its tracks (a structural change only, not every
8790
+ * mixer frame).
8791
+ */
8792
+ _follow(arrangement) {
8793
+ this._unfollow();
8794
+ const stopSources = arrangement.sources.subscribe(() => {
8795
+ this._announceLoading();
8796
+ this.requestUpdate();
8797
+ });
8798
+ let tracksVersion = arrangement.tracksVersion;
8799
+ const stopTracks = arrangement.subscribe(() => {
8800
+ this._watchDrags();
8801
+ if (arrangement.tracksVersion === tracksVersion) return;
8802
+ tracksVersion = arrangement.tracksVersion;
8803
+ this._refreshLinkStates();
8804
+ });
8805
+ this._unfollow = () => {
8806
+ stopSources();
8807
+ stopTracks();
8808
+ };
8809
+ }
8810
+ /**
8811
+ * A change to the arrangement while a drag is in progress came from
8812
+ * elsewhere (a drag writes nothing until its release): cancel the drag
8813
+ * when it changed what is dragged (#848 P2, interactions/drag-watch.ts).
8814
+ */
8815
+ _watchDrags() {
8816
+ const clip = this._clipPointer.draggedClip;
8817
+ if (clip && clipDragChanged(this._arrangement, clip)) this._pointer.cancelClipDrag();
8818
+ const track = this._trackReorderDrag.draggedTrack;
8819
+ if (track && trackDragChanged(this._arrangement, track)) this._trackReorderDrag.cancel();
8820
+ }
8821
+ // --- The swap (interactions/arrangement-swap.ts) ---
8822
+ /** @internal */
8823
+ _releaseEngine() {
8824
+ if (!this._engine) return;
8825
+ try {
8826
+ this._engine.dispose({ keepAdapter: true });
8827
+ } catch (err) {
8828
+ console.warn("[dawcore] Error releasing the engine: " + String(err));
8829
+ }
8830
+ this._engine = null;
8831
+ }
8832
+ /** @internal */
8833
+ _disposeTrackChain(trackId) {
8834
+ this._effectsManager?.disposeTrackChain(trackId);
8835
+ }
8836
+ /** @internal */
8837
+ _playArrangement(next) {
8838
+ this._playSignals.swappedOut(
8839
+ this._arrangement,
8840
+ abortError("the arrangement was swapped out (editor.arrangement) before it finished")
8841
+ );
8842
+ this._handedIn = next;
8843
+ this._announcer = new LoadAnnouncer((event) => this.dispatchEvent(event));
8844
+ this._follow(this._arrangement);
8845
+ this._currentTime = 0;
8846
+ this._stopPlayhead();
8847
+ this._recomputeDuration();
8848
+ this._refreshLinkStates();
8849
+ this._announceLoading();
8850
+ this.requestUpdate();
8851
+ }
8852
+ /** @internal */
8853
+ _buildEngineIfReady() {
8854
+ if (this._externalAdapter && this.isConnected && !this._engine) this._buildEngineReporting();
8855
+ }
8329
8856
  /** Reject the `addClip()` calls waiting for clips that match `which`. */
8330
8857
  _rejectAwaitedClips(which, message) {
8331
8858
  for (const [clipId, awaited] of [...this._awaitedClips]) {
@@ -8434,7 +8961,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
8434
8961
  {
8435
8962
  effectiveSampleRate: this.effectiveSampleRate,
8436
8963
  duration: this._duration,
8437
- tracks: [...this._engineTracks.values()],
8964
+ tracks: this._loadedTracks(),
8438
8965
  masterVolume: this._engine?.getState().masterVolume ?? 1,
8439
8966
  getMasterEffectsState: () => this.getEffectsState(),
8440
8967
  getTrackEffectsState: (trackId) => this.getTrackEffectsState(trackId)
@@ -8559,11 +9086,26 @@ var DawEditorElement = class extends import_lit19.LitElement {
8559
9086
  * Returns false for unknown track/clip IDs (defensive).
8560
9087
  */
8561
9088
  isMidiClip(trackId, clipId) {
8562
- const track = this._engineTracks.get(trackId);
8563
- if (!track) return false;
8564
- const clip = track.clips.find((c) => c.id === clipId);
9089
+ const clip = this._loadedClip(trackId, clipId);
8565
9090
  return clip?.midiNotes != null;
8566
9091
  }
9092
+ /** The arrangement's tracks as they are played: loaded clips, the current mix (#848). */
9093
+ _loadedTracks() {
9094
+ const arrangement = this._arrangement;
9095
+ return arrangement.getTracks().map(
9096
+ (t) => loadedTrack(
9097
+ t,
9098
+ arrangement.getMixer().get(t.id) ?? mixOfTrack(t),
9099
+ arrangement.recordingTrackIds.has(t.id)
9100
+ )
9101
+ );
9102
+ }
9103
+ /** A loaded clip of a track of the arrangement, or undefined. */
9104
+ _loadedClip(trackId, clipId) {
9105
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9106
+ const clip = track?.clips.find((c) => c.id === clipId);
9107
+ return clip && !(0, import_core21.isLoadingClip)(clip) ? clip : void 0;
9108
+ }
8567
9109
  get effectiveSampleRate() {
8568
9110
  return this.sampleRate;
8569
9111
  }
@@ -8642,11 +9184,80 @@ var DawEditorElement = class extends import_lit19.LitElement {
8642
9184
  * the arrangement is not listed (its descriptor stays for a Redo).
8643
9185
  */
8644
9186
  get tracks() {
8645
- const ids = [...this._arrangement.getTracks().map((t) => t.id), ...this._entryQueue];
8646
- return ids.flatMap((trackId) => {
8647
- const descriptor = this._tracks.get(trackId);
9187
+ const listed = this._arrangement.getTracks().map((track) => this._listTrack(track));
9188
+ const queue = this._handedIn ? this._entryQueue.filter((id) => !this._trackElements.has(id)) : this._entryQueue;
9189
+ const waiting = queue.flatMap((trackId) => {
9190
+ const descriptor = this._pendingDescriptor(trackId);
8648
9191
  return descriptor ? [{ trackId, ...descriptor, ...this._mixOf(trackId) }] : [];
8649
9192
  });
9193
+ return [...listed, ...waiting];
9194
+ }
9195
+ /** A track of the arrangement as `editor.tracks` lists it: everything read from the arrangement. */
9196
+ _listTrack(track) {
9197
+ const extras = this._extras.get(track.id);
9198
+ const clipEls = new Map(
9199
+ [...this.querySelectorAll("daw-clip")].map((el) => [
9200
+ el.clipId,
9201
+ el
9202
+ ])
9203
+ );
9204
+ const sr = this.effectiveSampleRate;
9205
+ const clips = track.clips.map((clip) => {
9206
+ const el = clipEls.get(clip.id);
9207
+ const times = clipSeconds(clip, sr);
9208
+ const midi = (0, import_core21.isLoadingClip)(clip) ? null : clip;
9209
+ const base = {
9210
+ src: typeof clip.src === "string" ? clip.src : "",
9211
+ peaksSrc: extras?.peaksSrc.get(clip.id) ?? this._takenPeaksSrc(clip.id) ?? "",
9212
+ ...times,
9213
+ gain: clip.gain ?? 1,
9214
+ name: clip.name ?? "",
9215
+ fadeIn: el?.fadeIn ?? 0,
9216
+ fadeOut: el?.fadeOut ?? 0,
9217
+ fadeType: el?.fadeType ?? "linear",
9218
+ midiNotes: midi?.midiNotes ?? null,
9219
+ midiChannel: midi?.midiChannel ?? null,
9220
+ midiProgram: midi?.midiProgram ?? null
9221
+ };
9222
+ return el ? { kind: "dom", clipId: clip.id, ...base } : { kind: "drop", clipId: clip.id, ...base };
9223
+ });
9224
+ return {
9225
+ trackId: track.id,
9226
+ name: track.name ?? "",
9227
+ src: extras?.src ?? "",
9228
+ kind: (0, import_core21.trackKind)(track),
9229
+ renderMode: this._renderModeOf(track.id),
9230
+ spectrogramConfig: extras?.spectrogramConfig ?? null,
9231
+ clips,
9232
+ ...this._mixOf(track.id)
9233
+ };
9234
+ }
9235
+ /** A pending track's declaration: its element's attributes and clips now, or its descriptor. */
9236
+ _pendingDescriptor(trackId) {
9237
+ const pending = this._pending.get(trackId);
9238
+ if (!pending) return null;
9239
+ if (!("element" in pending)) return pending.descriptor;
9240
+ const read = this._readTrackDescriptor(pending.element);
9241
+ return pending.extraClips.length > 0 ? { ...read, clips: [...read.clips, ...pending.extraClips] } : read;
9242
+ }
9243
+ /** The extras a track of the arrangement takes when the editor has none for it. */
9244
+ _defaultExtras(trackId) {
9245
+ const track = this._arrangementOf(trackId).getTracks().find((t) => t.id === trackId);
9246
+ if (!track) return null;
9247
+ const kind = (0, import_core21.trackKind)(track);
9248
+ return {
9249
+ kind,
9250
+ renderMode: trackDescriptorRenderMode(kind, "waveform"),
9251
+ src: "",
9252
+ peaksSrc: /* @__PURE__ */ new Map()
9253
+ };
9254
+ }
9255
+ /** How a track is drawn: its extras, else from its kind (an undo-restored track has none). */
9256
+ _renderModeOf(trackId) {
9257
+ const extras = this._extras.get(trackId);
9258
+ if (extras) return extras.renderMode;
9259
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9260
+ return trackDescriptorRenderMode(track ? (0, import_core21.trackKind)(track) : "audio", "waveform");
8650
9261
  }
8651
9262
  /**
8652
9263
  * A track's mix, from its one owner, the arrangement (#843), as the engine
@@ -8655,13 +9266,162 @@ var DawEditorElement = class extends import_lit19.LitElement {
8655
9266
  * waiting to enter shows what its element declares.
8656
9267
  */
8657
9268
  _mixOf(trackId) {
8658
- const played = this._engineTracks.get(trackId);
8659
- if (played) return mixOfTrack(played);
8660
- const mix = this._arrangement.getMixer().get(trackId);
9269
+ const mix = mixOf(this._arrangement, trackId);
8661
9270
  if (mix) return mix;
9271
+ const pending = this._pending.get(trackId);
9272
+ if (pending && "mix" in pending) return pending.mix;
8662
9273
  const el = this._trackElements.get(trackId);
8663
9274
  return el ? mixOfElement(el) : DEFAULT_TRACK_MIX;
8664
9275
  }
9276
+ // --- Element links (#848, interactions/element-links.ts) ---
9277
+ /** @internal */
9278
+ _trackLinkState(trackId) {
9279
+ if (this._handedIn && this._trackElements.has(trackId)) return "detached";
9280
+ if (this._isEntered(trackId)) return "live";
9281
+ return this._extras.has(trackId) && !this._pending.has(trackId) ? "detached" : "pending";
9282
+ }
9283
+ /** @internal */
9284
+ _clipLinkState(trackId, clipId) {
9285
+ const track = this._trackLinkState(trackId);
9286
+ if (track !== "live") return track;
9287
+ const held = this._arrangement.getTracks().some((t) => t.clips.some((c) => c.id === clipId));
9288
+ if (held) return "live";
9289
+ return this._extras.get(trackId)?.peaksSrc.has(clipId) ? "detached" : "pending";
9290
+ }
9291
+ /** @internal The stored mix (not a take's mute) and the name. */
9292
+ _trackValues(trackId) {
9293
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9294
+ const mix = this._arrangement.getMixer().get(trackId);
9295
+ if (!track || !mix) return null;
9296
+ return { ...mix, name: track.name ?? "" };
9297
+ }
9298
+ /** @internal */
9299
+ _clipValues(trackId, clipId) {
9300
+ const clip = this._arrangement.getTracks().find((t) => t.id === this._clipHolderId(trackId, clipId))?.clips.find((c) => c.id === clipId);
9301
+ if (!clip) return null;
9302
+ const midi = (0, import_core21.isLoadingClip)(clip) ? null : clip;
9303
+ return {
9304
+ ...clipSeconds(clip, this.effectiveSampleRate),
9305
+ gain: clip.gain ?? 1,
9306
+ name: clip.name ?? "",
9307
+ midiNotes: midi?.midiNotes ?? null,
9308
+ midiChannel: midi?.midiChannel ?? null,
9309
+ midiProgram: midi?.midiProgram ?? null
9310
+ };
9311
+ }
9312
+ /** @internal A property or attribute set on a live `<daw-track>`: one undo step per field kind. */
9313
+ _requestTrackChange(trackId, partial) {
9314
+ const { name, ...mix } = partial;
9315
+ if (Object.keys(mix).length > 0) this._writeMixFields(trackId, mix, this._taskGesture(trackId));
9316
+ if (name !== void 0) this._renameTrack(trackId, name || "Untitled");
9317
+ }
9318
+ _taskGesture(trackId) {
9319
+ let id = this._taskGestures.get(trackId);
9320
+ if (!id) {
9321
+ id = (0, import_core21.createMixerGesture)().id;
9322
+ this._taskGestures.set(trackId, id);
9323
+ if (this._taskGestures.size === 1) queueMicrotask(() => this._taskGestures.clear());
9324
+ }
9325
+ return id;
9326
+ }
9327
+ /** @internal A property or attribute set on a live `<daw-clip>`: one undo step. */
9328
+ _requestClipChange(trackId, clipId, partial) {
9329
+ const current = this._clipValues(trackId, clipId);
9330
+ if (!current) return;
9331
+ const holderId = this._clipHolderId(trackId, clipId);
9332
+ const clip = this._arrangement.getTracks().find((t) => t.id === holderId)?.clips.find((c) => c.id === clipId);
9333
+ const src = clip && typeof clip.src === "string" ? clip.src : "";
9334
+ this._applyClipUpdate(holderId, clipId, { ...current, ...partial, src });
9335
+ }
9336
+ /**
9337
+ * The clips of an entering track that another track of the arrangement
9338
+ * holds (the page moved their `<daw-clip>` here while the track waited):
9339
+ * the track takes the held clip as it is, and `from` names what leaves
9340
+ * where. A held clip of the other kind is refused and stays.
9341
+ */
9342
+ _takeOverMovedClips(trackId, track) {
9343
+ const from = /* @__PURE__ */ new Map();
9344
+ const movedIds = /* @__PURE__ */ new Set();
9345
+ const refused = [];
9346
+ const others = this._arrangement.getTracks().filter((t) => t.id !== trackId);
9347
+ const kind = (0, import_core21.trackKind)(track);
9348
+ const clips = [];
9349
+ for (const clip of track.clips) {
9350
+ const holder = others.find((t) => t.clips.some((c) => c.id === clip.id));
9351
+ const held = holder?.clips.find((c) => c.id === clip.id);
9352
+ if (!holder || !held) {
9353
+ clips.push(clip);
9354
+ continue;
9355
+ }
9356
+ const isMidi = "midiNotes" in held && held.midiNotes != null;
9357
+ const error = clipKindError(track.name ?? "", kind, isMidi, held.name || held.id);
9358
+ if (error) {
9359
+ refused.push({ clipId: clip.id, error });
9360
+ continue;
9361
+ }
9362
+ clips.push(held);
9363
+ movedIds.add(clip.id);
9364
+ const ids = from.get(holder.id) ?? /* @__PURE__ */ new Set();
9365
+ from.set(holder.id, ids.add(clip.id));
9366
+ }
9367
+ return {
9368
+ track: movedIds.size || refused.length ? { ...track, clips } : track,
9369
+ from,
9370
+ movedIds,
9371
+ refused
9372
+ };
9373
+ }
9374
+ /** Run `fn` as one undo step of each arrangement it changes. */
9375
+ _inOneStep(arrangements, fn) {
9376
+ for (const a of arrangements) a.beginTransaction();
9377
+ try {
9378
+ fn();
9379
+ } finally {
9380
+ for (const a of arrangements) a.commitTransaction();
9381
+ }
9382
+ }
9383
+ /** The `peaks-src` some track took for a clip element, if any. */
9384
+ _takenPeaksSrc(clipId) {
9385
+ for (const extras of this._extras.values()) {
9386
+ const peaksSrc = extras.peaksSrc.get(clipId);
9387
+ if (peaksSrc !== void 0) return peaksSrc;
9388
+ }
9389
+ return void 0;
9390
+ }
9391
+ /**
9392
+ * The arrangement whose history holds a track: the one that holds it now,
9393
+ * or else, for a page track, the own one (an Undo took it out there; a
9394
+ * handed-in arrangement may be played meanwhile), or else the one played.
9395
+ */
9396
+ _historyOf(trackId, isPageTrack = this._trackElements.has(trackId)) {
9397
+ const holder = this._arrangementOf(trackId);
9398
+ if (holder.getTracks().some((t) => t.id === trackId)) return holder;
9399
+ return isPageTrack ? this._ownArrangement : holder;
9400
+ }
9401
+ /** The track of the arrangement played that holds a clip: `trackId` when it does, or else the one that does. */
9402
+ _clipHolderId(trackId, clipId) {
9403
+ const tracks = this._arrangement.getTracks();
9404
+ if (tracks.some((t) => t.id === trackId && t.clips.some((c) => c.id === clipId)))
9405
+ return trackId;
9406
+ return tracks.find((t) => t.clips.some((c) => c.id === clipId))?.id ?? trackId;
9407
+ }
9408
+ /** @internal */
9409
+ _trackKind(trackId) {
9410
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9411
+ return track ? (0, import_core21.trackKind)(track) : null;
9412
+ }
9413
+ /** @internal */
9414
+ _trackIndex(trackId) {
9415
+ return this._arrangement.getTracks().findIndex((t) => t.id === trackId);
9416
+ }
9417
+ /** @internal */
9418
+ _detachedReason() {
9419
+ return this._handedIn ? "a handed-in arrangement is set (editor.arrangement)" : "its track or clip is not in the arrangement the editor plays";
9420
+ }
9421
+ /** Set or clear `:state(detached)` on every registered element (#848). */
9422
+ _refreshLinkStates() {
9423
+ refreshLinkStates(this, this._trackElements);
9424
+ }
8665
9425
  /**
8666
9426
  * Change one mixer field of a track: the arrangement's setter with
8667
9427
  * `options` (an undo step; changes with one `gesture` id are one step). A
@@ -8678,8 +9438,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
8678
9438
  * Change the given mixer fields of a track as ONE undo step (#843): all
8679
9439
  * of them carry one fresh gesture id. A field left out is not sent.
8680
9440
  */
8681
- _writeMixFields(trackId, mix) {
8682
- const options = { gesture: (0, import_core19.createMixerGesture)().id };
9441
+ _writeMixFields(trackId, mix, gesture = (0, import_core21.createMixerGesture)().id) {
9442
+ const options = { gesture };
8683
9443
  if (mix.volume !== void 0) this._writeMix(trackId, "volume", mix.volume, options);
8684
9444
  if (mix.pan !== void 0) this._writeMix(trackId, "pan", mix.pan, options);
8685
9445
  if (mix.muted !== void 0) this._writeMix(trackId, "muted", mix.muted, options);
@@ -8710,23 +9470,38 @@ var DawEditorElement = class extends import_lit19.LitElement {
8710
9470
  // --- Lifecycle ---
8711
9471
  connectedCallback() {
8712
9472
  super.connectedCallback();
8713
- window.addEventListener("keydown", this._onDragEscape, { capture: true });
8714
- this.addEventListener("daw-track-connected", this._onTrackConnected);
8715
- this.addEventListener("daw-track-update", this._onTrackUpdate);
8716
- this.addEventListener("daw-track-control", this._onTrackControl);
8717
- this.addEventListener("daw-track-remove", this._onTrackRemoveRequest);
8718
- this.addEventListener("daw-clip-connected", this._onClipConnected);
8719
- this.addEventListener("daw-clip-update", this._onClipUpdate);
9473
+ if (this._connection.signal.aborted) this._connection = new AbortController();
9474
+ this._follow(this._arrangement);
9475
+ this._refreshLinkStates();
9476
+ const { signal } = this._connection;
9477
+ window.addEventListener("keydown", this._onDragEscape, { capture: true, signal });
9478
+ this.addEventListener("daw-track-connected", this._onTrackConnected, {
9479
+ signal
9480
+ });
9481
+ this.addEventListener("daw-track-update", this._onTrackUpdate, { signal });
9482
+ this.addEventListener("daw-track-control", this._onTrackControl, { signal });
9483
+ this.addEventListener("daw-track-remove", this._onTrackRemoveRequest, {
9484
+ signal
9485
+ });
9486
+ this.addEventListener("daw-clip-connected", this._onClipConnected, {
9487
+ signal
9488
+ });
8720
9489
  this.addEventListener(
8721
9490
  "daw-annotation-track-connected",
8722
- this._onAnnotationTrackConnected
9491
+ this._onAnnotationTrackConnected,
9492
+ { signal }
8723
9493
  );
8724
- this.addEventListener("daw-annotation-select", this._onAnnotationSelect);
8725
- this.addEventListener("daw-track-reorder", this._onTrackReorder);
8726
- this.addEventListener("daw-track-reorder-grab", this._onTrackReorderGrab);
9494
+ this.addEventListener("daw-annotation-select", this._onAnnotationSelect, {
9495
+ signal
9496
+ });
9497
+ this.addEventListener("daw-track-reorder", this._onTrackReorder, { signal });
9498
+ this.addEventListener("daw-track-reorder-grab", this._onTrackReorderGrab, {
9499
+ signal
9500
+ });
8727
9501
  this._childObserver = new MutationObserver((mutations) => {
8728
9502
  const removedTracks = /* @__PURE__ */ new Map();
8729
9503
  const removedClips = /* @__PURE__ */ new Set();
9504
+ const clipsOfRemoved = /* @__PURE__ */ new Map();
8730
9505
  const addedTrackIds = /* @__PURE__ */ new Set();
8731
9506
  for (const mutation of mutations) {
8732
9507
  for (const node of mutation.addedNodes) {
@@ -8751,53 +9526,68 @@ var DawEditorElement = class extends import_lit19.LitElement {
8751
9526
  node.querySelectorAll?.("daw-clip").forEach((c) => {
8752
9527
  removedClips.add(c);
8753
9528
  });
9529
+ for (const t of node.tagName === "DAW-TRACK" ? [node] : [...node.querySelectorAll?.("daw-track") ?? []]) {
9530
+ clipsOfRemoved.set(t.trackId, [
9531
+ ...t.querySelectorAll("daw-clip")
9532
+ ]);
9533
+ }
8754
9534
  }
8755
9535
  }
8756
- let orderMayHaveChanged = addedTrackIds.size > 0;
9536
+ const movedTrackIds = /* @__PURE__ */ new Set();
8757
9537
  for (const [trackId] of removedTracks) {
8758
9538
  if (addedTrackIds.has(trackId)) {
8759
- orderMayHaveChanged = true;
9539
+ movedTrackIds.add(trackId);
8760
9540
  continue;
8761
9541
  }
8762
- this._onTrackRemoved(trackId);
9542
+ const children = (clipsOfRemoved.get(trackId) ?? []).filter((c) => !c.isConnected);
9543
+ this._inOneStep([this._historyOf(trackId)], () => {
9544
+ this._onTrackRemoved(trackId);
9545
+ for (const clip of children) {
9546
+ removedClips.delete(clip);
9547
+ this._onClipRemovedFromDom(clip);
9548
+ }
9549
+ });
8763
9550
  }
8764
9551
  for (const clip of removedClips) {
8765
- if (clip.isConnected) continue;
9552
+ if (clip.isConnected && this.contains(clip)) continue;
8766
9553
  this._onClipRemovedFromDom(clip);
8767
9554
  }
8768
- if (orderMayHaveChanged) this._syncEngineOrderToDom();
9555
+ if (movedTrackIds.size > 0) this._placeMovedTracks(movedTrackIds);
8769
9556
  });
8770
9557
  this._childObserver.observe(this, { childList: true, subtree: true });
8771
9558
  for (const [trackId, el] of [...this._trackElements]) {
8772
9559
  if (!this.contains(el)) this._onTrackRemoved(trackId);
8773
9560
  }
9561
+ const present = new Set(
9562
+ [...this.querySelectorAll("daw-clip")].map((c) => c.clipId)
9563
+ );
9564
+ for (const [trackId] of this._trackElements) {
9565
+ for (const clipId of this._extras.get(trackId)?.peaksSrc.keys() ?? []) {
9566
+ if (present.has(clipId)) continue;
9567
+ const holder = this._historyOf(trackId).getTracks().find((t) => t.clips.some((c) => c.id === clipId));
9568
+ if (holder) {
9569
+ this._removeClipFromTrack(holder.id, clipId);
9570
+ this._forgetClip(trackId, clipId);
9571
+ } else this._dropUnheldClip(trackId, clipId);
9572
+ }
9573
+ }
8774
9574
  if (this._externalAdapter && !this._engine) this._buildEngineReporting();
8775
9575
  }
8776
9576
  disconnectedCallback() {
8777
9577
  super.disconnectedCallback();
8778
- window.removeEventListener("keydown", this._onDragEscape, { capture: true });
9578
+ this._unfollow();
9579
+ this._unfollow = () => {
9580
+ };
9581
+ this._connection.abort(abortError("<daw-editor> was disconnected"));
8779
9582
  this._effectsManager?.disposeAll();
8780
9583
  this._effectsManager = null;
8781
- this.removeEventListener("daw-track-connected", this._onTrackConnected);
8782
- this.removeEventListener("daw-track-update", this._onTrackUpdate);
8783
- this.removeEventListener("daw-track-control", this._onTrackControl);
8784
- this.removeEventListener("daw-track-remove", this._onTrackRemoveRequest);
8785
- this.removeEventListener("daw-clip-connected", this._onClipConnected);
8786
- this.removeEventListener("daw-clip-update", this._onClipUpdate);
8787
- this.removeEventListener(
8788
- "daw-annotation-track-connected",
8789
- this._onAnnotationTrackConnected
8790
- );
8791
- this.removeEventListener("daw-annotation-select", this._onAnnotationSelect);
8792
- this.removeEventListener("daw-track-reorder", this._onTrackReorder);
8793
- this.removeEventListener("daw-track-reorder-grab", this._onTrackReorderGrab);
8794
9584
  this._cancelDrags(true);
8795
- for (const end of [...this._loadWaitEnds]) end();
8796
9585
  for (const trackId of this._entryQueue) {
8797
- if (this._trackElements.has(trackId) || !this._entryWaiters.has(trackId)) continue;
8798
- const nextTracks = new Map(this._tracks);
8799
- nextTracks.delete(trackId);
8800
- this._tracks = nextTracks;
9586
+ const pending = this._pending.get(trackId);
9587
+ if (!pending || "element" in pending || !this._entryWaiters.has(trackId)) continue;
9588
+ const nextPending = new Map(this._pending);
9589
+ nextPending.delete(trackId);
9590
+ this._pending = nextPending;
8801
9591
  this._entryQueue = this._entryQueue.filter((id) => id !== trackId);
8802
9592
  this._settleEntry(
8803
9593
  trackId,
@@ -8872,14 +9662,19 @@ var DawEditorElement = class extends import_lit19.LitElement {
8872
9662
  }
8873
9663
  }
8874
9664
  _onTrackRemoved(trackId) {
8875
- const existed = this._tracks.has(trackId);
9665
+ const existed = this._pending.has(trackId) || this._extras.has(trackId) || this._isEntered(trackId);
9666
+ const isPageTrack = this._trackElements.has(trackId);
9667
+ const history = this._historyOf(trackId, isPageTrack);
9668
+ const detached = this._extras.has(trackId) && !this._pending.has(trackId) && !history.getTracks().some((t) => t.id === trackId);
9669
+ const detachedClipIds = detached ? [...this._extras.get(trackId)?.peaksSrc.keys() ?? []] : [];
8876
9670
  this._rejectAwaitedClips(
8877
9671
  (_, awaitedTrackId) => awaitedTrackId === trackId,
8878
9672
  "the track of the clip was removed before the clip loaded"
8879
9673
  );
8880
9674
  this._entryQueue = this._entryQueue.filter((id) => id !== trackId);
8881
9675
  this._settleEntry(trackId, new Error('track "' + trackId + '" was removed before it entered'));
8882
- const arrangementTrack = this._arrangement.getTracks().find((t) => t.id === trackId);
9676
+ const holder = this._arrangementOf(trackId);
9677
+ const arrangementTrack = holder.getTracks().find((t) => t.id === trackId);
8883
9678
  const clipIds = arrangementTrack?.clips.map((c) => c.id) ?? [];
8884
9679
  this._announcer.forget(trackId, clipIds);
8885
9680
  if (clipIds.some((id) => this._previewPeaks.has(id))) {
@@ -8890,10 +9685,9 @@ var DawEditorElement = class extends import_lit19.LitElement {
8890
9685
  for (const id of clipIds) this._previewWaveforms.delete(id);
8891
9686
  this._trackElements.delete(trackId);
8892
9687
  this._effectsManager?.disposeTrackChain(trackId);
8893
- const removedTrack = this._engineTracks.get(trackId);
8894
- if (removedTrack) {
9688
+ if (arrangementTrack) {
8895
9689
  const nextPeaks = new Map(this._peaksData);
8896
- for (const clip of removedTrack.clips) {
9690
+ for (const clip of arrangementTrack.clips) {
8897
9691
  this._clipBuffers.delete(clip.id);
8898
9692
  this._clipOffsets.delete(clip.id);
8899
9693
  nextPeaks.delete(clip.id);
@@ -8901,17 +9695,24 @@ var DawEditorElement = class extends import_lit19.LitElement {
8901
9695
  }
8902
9696
  this._peaksData = nextPeaks;
8903
9697
  }
8904
- const nextTracks = new Map(this._tracks);
8905
- nextTracks.delete(trackId);
8906
- this._tracks = nextTracks;
8907
- const nextEngine = new Map(this._engineTracks);
8908
- nextEngine.delete(trackId);
8909
- this._engineTracks = nextEngine;
9698
+ const nextPending = new Map(this._pending);
9699
+ nextPending.delete(trackId);
9700
+ this._pending = nextPending;
9701
+ const nextExtras = new Map(this._extras);
9702
+ nextExtras.delete(trackId);
9703
+ this._extras = nextExtras;
9704
+ if (arrangementTrack) holder.removeTrack(trackId);
9705
+ else if (detached) {
9706
+ history.removeTrack(trackId, { undoable: false });
9707
+ for (const id of detachedClipIds) {
9708
+ this._purgeClipCaches(id);
9709
+ this._previewWaveforms.delete(id);
9710
+ }
9711
+ }
8910
9712
  this._recomputeDuration();
8911
- this._arrangement.removeTrack(trackId);
8912
9713
  this._recomputeZoomFloor();
8913
9714
  this._disposeSpectrogramControllerIfEmpty();
8914
- if (existed && nextEngine.size === 0) {
9715
+ if (existed && this._arrangement.getTracks().length === 0) {
8915
9716
  if (this._engine) {
8916
9717
  if (this._isPlaying) {
8917
9718
  this._withSeekSuppression(() => this._engine.stop());
@@ -8932,10 +9733,21 @@ var DawEditorElement = class extends import_lit19.LitElement {
8932
9733
  );
8933
9734
  }
8934
9735
  }
9736
+ /** The arrangement that holds a track: the one played, else the own one (a page track while handed in). */
9737
+ _arrangementOf(trackId) {
9738
+ const has = (a) => a.getTracks().some((t) => t.id === trackId);
9739
+ return has(this._arrangement) || !has(this._ownArrangement) ? this._arrangement : this._ownArrangement;
9740
+ }
9741
+ /** Rename a track in the arrangement (an undo step); the same name changes nothing. */
9742
+ _renameTrack(trackId, name) {
9743
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9744
+ if (!track || track.name === name) return;
9745
+ this._arrangement.updateTrack(trackId, (current) => ({ ...current, name }));
9746
+ }
8935
9747
  /** Drop the controller when no spectrogram tracks remain. */
8936
9748
  _disposeSpectrogramControllerIfEmpty() {
8937
9749
  if (!this._spectrogramController) return;
8938
- const stillNeeded = Array.from(this._tracks.values()).some(
9750
+ const stillNeeded = Array.from(this._extras.values()).some(
8939
9751
  (d) => d.renderMode === "spectrogram"
8940
9752
  );
8941
9753
  if (!stillNeeded) {
@@ -8944,96 +9756,92 @@ var DawEditorElement = class extends import_lit19.LitElement {
8944
9756
  this._lastSpectrogramViewport = null;
8945
9757
  }
8946
9758
  }
8947
- /** Reconcile `_tracks` descriptors with the engine's track list.
8948
- *
8949
- * ADD: engine.undo() restores removed tracks in ENGINE state only —
8950
- * without a synthesized descriptor the track plays and renders but shows
8951
- * "Untitled" controls and is missing from `editor.tracks`.
8952
- * PRUNE (the symmetric half): redo removes the track from engine state
8953
- * again — without pruning, the synthesized descriptor is a permanent
8954
- * ghost that even removeTrack() can't clean (no element, no engine
8955
- * entry). Never prunes tracks that are mid-load or element-backed —
8956
- * their descriptors legitimately precede their engine entries. */
8957
- _reconcileDescriptorsWithEngineTracks(tracks) {
8958
- const engineIds = new Set(tracks.map((t) => t.id));
8959
- let next = null;
8960
- for (const track of tracks) {
8961
- if (this._tracks.has(track.id)) continue;
8962
- next ?? (next = new Map(this._tracks));
8963
- next.set(track.id, {
8964
- name: track.name ?? "",
8965
- src: "",
8966
- kind: (0, import_core19.trackKind)(track),
8967
- renderMode: trackDescriptorRenderMode((0, import_core19.trackKind)(track), "waveform"),
8968
- clips: []
8969
- });
9759
+ /**
9760
+ * A `<daw-clip>` now under `trackId` whose clip another track holds: the
9761
+ * clip moves to this track (one undo step) when both have entered the same
9762
+ * arrangement; a clip of the other kind stays with `daw-clip-error`.
9763
+ * Otherwise the old track lets it go and the element goes on as a new
9764
+ * arrival. Returns true when nothing more is to be done.
9765
+ */
9766
+ _rehomeClip(trackId, clipEl) {
9767
+ const clipId = clipEl.clipId;
9768
+ if (this._extras.get(trackId)?.peaksSrc.has(clipId)) return true;
9769
+ const arrangement = this._historyOf(trackId);
9770
+ if (arrangement.getTracks().some((t) => t.id === trackId && t.clips.some((c) => c.id === clipId))) {
9771
+ let peaksSrc2 = clipEl.peaksSrc || "";
9772
+ for (const [id, extras] of this._extras) {
9773
+ if (id === trackId || !extras.peaksSrc.has(clipId)) continue;
9774
+ peaksSrc2 = extras.peaksSrc.get(clipId) ?? peaksSrc2;
9775
+ this._forgetClip(id, clipId);
9776
+ }
9777
+ this._takeClip(trackId, clipId, peaksSrc2);
9778
+ return true;
8970
9779
  }
8971
- for (const trackId of this._tracks.keys()) {
8972
- if (engineIds.has(trackId) || this._entryQueue.includes(trackId) || this._trackElements.has(trackId)) {
8973
- continue;
9780
+ const fromTrackId = trackHoldingClip(arrangement, clipId, trackId);
9781
+ if (!fromTrackId) {
9782
+ for (const [id, extras] of this._extras) {
9783
+ if (id !== trackId && extras.peaksSrc.has(clipId)) this._forgetClip(id, clipId);
8974
9784
  }
8975
- next ?? (next = new Map(this._tracks));
8976
- next.delete(trackId);
9785
+ return false;
8977
9786
  }
8978
- for (const track of tracks) {
8979
- const desc = (next ?? this._tracks).get(track.id);
8980
- if (!desc || !desc.clips.some((c) => !isDomClip(c) && c.clipId !== void 0)) continue;
8981
- const reconciled = this._reconcileIdentifiedDropClips(desc.clips, track);
8982
- if (reconciled === desc.clips) continue;
8983
- next ?? (next = new Map(this._tracks));
8984
- next.set(track.id, { ...desc, clips: reconciled });
8985
- }
8986
- if (next) {
8987
- this._tracks = next;
8988
- }
8989
- }
8990
- /** Prune id-bearing drop descriptors the engine no longer has, and refresh
8991
- * the rest from their engine clip. Returns the SAME array when nothing
8992
- * changed, so an unchanged track never triggers a re-render. */
8993
- _reconcileIdentifiedDropClips(clips, track) {
8994
- const engineClips = new Map(track.clips.map((c) => [c.id, c]));
8995
- let changed = false;
8996
- const result = [];
8997
- for (const desc of clips) {
8998
- if (isDomClip(desc) || desc.clipId === void 0) {
8999
- result.push(desc);
9000
- continue;
9001
- }
9002
- const clip = engineClips.get(desc.clipId);
9003
- if (!clip) {
9004
- changed = true;
9005
- continue;
9006
- }
9007
- const sr = clip.sampleRate ?? this.effectiveSampleRate;
9008
- const start = clip.startSample / sr;
9009
- const duration = clip.durationSamples / sr;
9010
- const offset = clip.offsetSamples / sr;
9011
- const gain = clip.gain ?? desc.gain;
9012
- const name = clip.name ?? desc.name;
9013
- if (desc.start === start && desc.duration === duration && desc.offset === offset && desc.gain === gain && desc.name === name) {
9014
- result.push(desc);
9015
- continue;
9016
- }
9017
- changed = true;
9018
- result.push({ ...desc, start, duration, offset, gain, name });
9787
+ const entered = arrangement.getTracks().some((t) => t.id === trackId);
9788
+ if (!entered && this._pending.has(trackId)) return true;
9789
+ const toExtras = this._extras.get(trackId) ?? this._defaultExtras(trackId);
9790
+ if (!entered || !toExtras) {
9791
+ this._takeClip(trackId, clipId, this._takenPeaksSrc(clipId) ?? clipEl.peaksSrc ?? "");
9792
+ console.warn(
9793
+ '[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.'
9794
+ );
9795
+ this.dispatchEvent(
9796
+ new CustomEvent("daw-clip-error", {
9797
+ bubbles: true,
9798
+ composed: true,
9799
+ detail: {
9800
+ trackId,
9801
+ clipId,
9802
+ error: new Error('track "' + trackId + '" is not in the arrangement')
9803
+ }
9804
+ })
9805
+ );
9806
+ this._refreshLinkStates();
9807
+ return true;
9808
+ }
9809
+ const error = moveClipToTrack(arrangement, fromTrackId, trackId, clipId, toExtras.kind);
9810
+ if (error) {
9811
+ this._takeClip(trackId, clipId, this._extras.get(fromTrackId)?.peaksSrc.get(clipId) ?? "");
9812
+ console.warn(
9813
+ '[dawcore] <daw-clip> cannot move to track "' + (this._trackElements.get(trackId)?.name || "Untitled") + '" (' + String(error) + "): its clip stays in its track."
9814
+ );
9815
+ this.dispatchEvent(
9816
+ new CustomEvent("daw-clip-error", {
9817
+ bubbles: true,
9818
+ composed: true,
9819
+ detail: { trackId, clipId, error }
9820
+ })
9821
+ );
9822
+ return true;
9823
+ }
9824
+ const peaksSrc = this._takenPeaksSrc(clipId) ?? clipEl.peaksSrc ?? "";
9825
+ for (const [id, extras] of this._extras) {
9826
+ if (id !== trackId && extras.peaksSrc.has(clipId)) this._forgetClip(id, clipId);
9019
9827
  }
9020
- return changed ? result : clips;
9828
+ if (!this._extras.has(trackId)) this._extras = new Map(this._extras).set(trackId, toExtras);
9829
+ this._takeClip(trackId, clipId, peaksSrc);
9830
+ return true;
9021
9831
  }
9022
9832
  _onClipRemovedFromDom(clipEl) {
9023
9833
  const clipId = clipEl.clipId;
9024
- for (const t of this._arrangement.getTracks()) {
9025
- if (t.clips.some((c) => c.id === clipId)) {
9026
- this._removeClipFromTrack(t.id, clipId);
9027
- return;
9834
+ for (const arrangement of /* @__PURE__ */ new Set([this._arrangement, this._ownArrangement])) {
9835
+ for (const t of arrangement.getTracks()) {
9836
+ if (t.clips.some((c) => c.id === clipId)) {
9837
+ this._removeClipFromTrack(t.id, clipId);
9838
+ return;
9839
+ }
9028
9840
  }
9029
9841
  }
9030
- for (const [trackId, desc] of this._tracks) {
9031
- if (this._isEntered(trackId) || !desc.clips.some((c) => c.clipId === clipId)) continue;
9032
- this._tracks = new Map(this._tracks).set(trackId, {
9033
- ...desc,
9034
- clips: desc.clips.filter((c) => c.clipId !== clipId)
9035
- });
9036
- this._rejectAwaitedClips((id) => id === clipId, "the clip was removed before it loaded");
9842
+ for (const [trackId, extras] of this._extras) {
9843
+ if (!extras.peaksSrc.has(clipId)) continue;
9844
+ this._dropUnheldClip(trackId, clipId);
9037
9845
  return;
9038
9846
  }
9039
9847
  this._rejectAwaitedClips((id) => id === clipId, "the clip was removed before it loaded");
@@ -9050,12 +9858,15 @@ var DawEditorElement = class extends import_lit19.LitElement {
9050
9858
  * like any other; `daw-clip-ready` or `daw-clip-error` follows (#848).
9051
9859
  */
9052
9860
  _loadAndAppendClip(trackId, clipDesc) {
9053
- const trackDesc = this._tracks.get(trackId);
9054
- if (!trackDesc) return;
9861
+ const arrangement = this._arrangementOf(trackId);
9862
+ const track = arrangement.getTracks().find((t) => t.id === trackId);
9863
+ const extras = this._extras.get(trackId) ?? this._defaultExtras(trackId);
9864
+ if (!extras || !track) return;
9865
+ if (isDomClip(clipDesc)) this._takeClip(trackId, clipDesc.clipId, clipDesc.peaksSrc);
9055
9866
  const clipIsMidi = isMidiDescriptor(clipDesc);
9056
9867
  const kindError = clipKindError(
9057
- trackDesc.name,
9058
- trackDesc.kind,
9868
+ track.name ?? "",
9869
+ extras.kind,
9059
9870
  clipIsMidi,
9060
9871
  clipDesc.name || clipDesc.src || clipDesc.clipId
9061
9872
  );
@@ -9063,7 +9874,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9063
9874
  if (!clipIsMidi) this._announcer.expectClip(clipDesc.clipId);
9064
9875
  try {
9065
9876
  if (kindError) throw kindError;
9066
- this._arrangement.updateTrack(trackId, (current) => ({
9877
+ arrangement.updateTrack(trackId, (current) => ({
9067
9878
  ...current,
9068
9879
  clips: [...current.clips, clip]
9069
9880
  }));
@@ -9078,10 +9889,6 @@ var DawEditorElement = class extends import_lit19.LitElement {
9078
9889
  );
9079
9890
  return;
9080
9891
  }
9081
- this._tracks = new Map(this._tracks).set(trackId, {
9082
- ...trackDesc,
9083
- clips: [...trackDesc.clips, clipDesc]
9084
- });
9085
9892
  if (!clipIsMidi && clipDesc.peaksSrc) this._requestPreview(clipDesc.clipId, clipDesc.peaksSrc);
9086
9893
  }
9087
9894
  /**
@@ -9101,6 +9908,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9101
9908
  );
9102
9909
  return null;
9103
9910
  } catch (err) {
9911
+ if (isAbortError(err)) return null;
9104
9912
  console.warn(
9105
9913
  "[dawcore] Failed to load peaks from " + peaksSrc + ": " + String(err) + " \u2014 falling back to AudioBuffer generation"
9106
9914
  );
@@ -9129,24 +9937,28 @@ var DawEditorElement = class extends import_lit19.LitElement {
9129
9937
  }));
9130
9938
  }
9131
9939
  _applyClipUpdate(trackId, clipId, clipEl) {
9132
- const t = this._engineTracks.get(trackId);
9940
+ const t = this._arrangement.getTracks().find((track) => track.id === trackId);
9133
9941
  if (!t) {
9134
- console.warn('[dawcore] _applyClipUpdate: no engine track for id "' + trackId + '"');
9942
+ console.warn('[dawcore] _applyClipUpdate: no track for id "' + trackId + '"');
9135
9943
  return;
9136
9944
  }
9137
- const idx = t.clips.findIndex((c) => c.id === clipId);
9138
- if (idx === -1) {
9139
- const loading = this._arrangement.getTracks().find((track) => track.id === trackId)?.clips.some((c) => c.id === clipId);
9945
+ const loadedClip = this._loadedClip(trackId, clipId);
9946
+ if (!loadedClip) {
9947
+ const loading = t.clips.find((c) => c.id === clipId);
9948
+ if (loading && (0, import_core21.isLoadingClip)(loading)) {
9949
+ this._updateLoadingClip(trackId, loading, clipEl);
9950
+ return;
9951
+ }
9140
9952
  console.warn(
9141
- '[dawcore] _applyClipUpdate: clip "' + clipId + '" ' + (loading ? "is still loading; the change is dropped" : 'not found in track "' + trackId + '" (DOM/engine clip-id misalignment?)')
9953
+ '[dawcore] _applyClipUpdate: clip "' + clipId + '" not found in track "' + trackId + '" (DOM/engine clip-id misalignment?)'
9142
9954
  );
9143
9955
  return;
9144
9956
  }
9145
- const oldClip = t.clips[idx];
9957
+ const oldClip = loadedClip;
9146
9958
  const sr = oldClip.sampleRate ?? this.effectiveSampleRate;
9147
9959
  const isMidiNow = clipEl.midiNotes != null && !clipEl.src;
9148
9960
  const wasMidi = oldClip.midiNotes != null;
9149
- if (isMidiNow && (0, import_core19.trackKind)(t) !== "midi") {
9961
+ if (isMidiNow && (0, import_core21.trackKind)(t) !== "midi") {
9150
9962
  const kindError = clipKindError(t.name ?? "", "audio", true, clipEl.name || clipId);
9151
9963
  console.warn("[dawcore] _applyClipUpdate: " + kindError?.message);
9152
9964
  this.dispatchEvent(
@@ -9159,6 +9971,9 @@ var DawEditorElement = class extends import_lit19.LitElement {
9159
9971
  return;
9160
9972
  }
9161
9973
  if (isMidiNow || wasMidi) {
9974
+ 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) {
9975
+ return;
9976
+ }
9162
9977
  const notes = validMidiNotes(clipEl.midiNotes ?? []);
9163
9978
  const noteSpanSeconds = notes.length ? notes.reduce((max, n) => Math.max(max, n.time + n.duration), 0) : 0;
9164
9979
  const sourceDurationSamples = Math.ceil(Math.max(noteSpanSeconds, clipEl.duration, 1) * sr);
@@ -9191,6 +10006,9 @@ var DawEditorElement = class extends import_lit19.LitElement {
9191
10006
  gain: clipEl.gain,
9192
10007
  name: clipEl.name || oldClip.name
9193
10008
  };
10009
+ if (newStartSample === oldClip.startSample && newDurationSamples === oldClip.durationSamples && newOffsetSamples === oldClip.offsetSamples && updatedClip.gain === (oldClip.gain ?? 1) && updatedClip.name === oldClip.name) {
10010
+ return;
10011
+ }
9194
10012
  const boundsChanged = oldClip.offsetSamples !== newOffsetSamples || oldClip.durationSamples !== newDurationSamples;
9195
10013
  if (boundsChanged) {
9196
10014
  this._clipOffsets.set(clipId, {
@@ -9204,9 +10022,55 @@ var DawEditorElement = class extends import_lit19.LitElement {
9204
10022
  }
9205
10023
  this._replaceClip(trackId, clipId, updatedClip);
9206
10024
  }
10025
+ /**
10026
+ * A change to a clip still loading (#848 P10): its times, gain and name in
10027
+ * seconds on the `LoadingClip`, one undo step; the audio loads into it.
10028
+ */
10029
+ _updateLoadingClip(trackId, clip, values) {
10030
+ const next = {
10031
+ ...clip,
10032
+ start: values.start,
10033
+ ...values.duration > 0 ? { duration: values.duration } : {},
10034
+ offset: values.offset,
10035
+ gain: values.gain,
10036
+ ...values.name ? { name: values.name } : {}
10037
+ };
10038
+ 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) {
10039
+ return;
10040
+ }
10041
+ this._arrangement.updateTrack(trackId, (current) => ({
10042
+ ...current,
10043
+ clips: current.clips.map((c) => c.id === clip.id ? next : c)
10044
+ }));
10045
+ }
9207
10046
  /** Remove a clip (loaded or still loading) from a track of the arrangement: an undo step. */
9208
- _removeClipFromTrack(trackId, clipId) {
9209
- const track = this._arrangement.getTracks().find((t) => t.id === trackId);
10047
+ /**
10048
+ * An aborted addClip (D3): its clip leaves for good, from the track it
10049
+ * entered or from what a waiting track will enter with.
10050
+ */
10051
+ _discardAddedClip(trackId, clipId) {
10052
+ const pending = this._pending.get(trackId);
10053
+ if (pending) {
10054
+ this._pending = new Map(this._pending).set(
10055
+ trackId,
10056
+ "element" in pending ? { ...pending, extraClips: pending.extraClips.filter((c) => c.clipId !== clipId) } : {
10057
+ ...pending,
10058
+ descriptor: {
10059
+ ...pending.descriptor,
10060
+ clips: pending.descriptor.clips.filter((c) => c.clipId !== clipId)
10061
+ }
10062
+ }
10063
+ );
10064
+ return;
10065
+ }
10066
+ const holder = this._arrangementOf(trackId).getTracks().find((t) => t.id === trackId);
10067
+ if (holder?.clips.some((c) => c.id === clipId)) {
10068
+ this._removeClipFromTrack(trackId, clipId, { undoable: false });
10069
+ }
10070
+ }
10071
+ _removeClipFromTrack(trackId, clipId, options = {}) {
10072
+ const arrangement = this._arrangementOf(trackId);
10073
+ const track = arrangement.getTracks().find((t) => t.id === trackId);
9210
10074
  if (!track) {
9211
10075
  console.warn('[dawcore] _removeClipFromTrack: no track for id "' + trackId + '"');
9212
10076
  return;
@@ -9224,20 +10088,43 @@ var DawEditorElement = class extends import_lit19.LitElement {
9224
10088
  nextPreview.delete(clipId);
9225
10089
  this._previewPeaks = nextPreview;
9226
10090
  }
9227
- const desc = this._tracks.get(trackId);
9228
- if (desc) {
9229
- this._tracks = new Map(this._tracks).set(trackId, {
9230
- ...desc,
9231
- clips: desc.clips.filter((c) => c.clipId !== clipId)
9232
- });
9233
- }
9234
- const wasLoading = track.clips.some((c) => c.id === clipId && (0, import_core19.isLoadingClip)(c));
9235
- this._arrangement.updateTrack(trackId, (current) => ({
9236
- ...current,
9237
- clips: current.clips.filter((c) => c.id !== clipId)
9238
- }));
10091
+ this._forgetClip(trackId, clipId);
10092
+ const wasLoading = track.clips.some((c) => c.id === clipId && (0, import_core21.isLoadingClip)(c));
10093
+ if (options.undoable === false) arrangement.removeClip(trackId, clipId, { undoable: false });
10094
+ else
10095
+ arrangement.updateTrack(trackId, (current) => ({
10096
+ ...current,
10097
+ clips: current.clips.filter((c) => c.id !== clipId)
10098
+ }));
9239
10099
  if (wasLoading) this._announcer.forgetClip(clipId);
9240
10100
  }
10101
+ /** Record that the editor took a clip of a track (with its `peaks-src`, '' when none). */
10102
+ _takeClip(trackId, clipId, peaksSrc) {
10103
+ const extras = this._extras.get(trackId);
10104
+ if (!extras || extras.peaksSrc.get(clipId) === peaksSrc) return;
10105
+ const next = new Map(extras.peaksSrc).set(clipId, peaksSrc);
10106
+ this._extras = new Map(this._extras).set(trackId, { ...extras, peaksSrc: next });
10107
+ }
10108
+ /**
10109
+ * A `<daw-clip>` the editor took is removed while the arrangement does not
10110
+ * hold its clip (its track or its own arrival undone, or refused): it is
10111
+ * gone for good, also from the undo and redo states, so no Redo brings it
10112
+ * back (maintainer's choice, #848).
10113
+ */
10114
+ _dropUnheldClip(trackId, clipId) {
10115
+ this._historyOf(trackId).removeClip(trackId, clipId, { undoable: false });
10116
+ this._purgeClipCaches(clipId);
10117
+ this._previewWaveforms.delete(clipId);
10118
+ this._forgetClip(trackId, clipId);
10119
+ }
10120
+ /** The editor no longer holds anything for a clip of a track. */
10121
+ _forgetClip(trackId, clipId) {
10122
+ const extras = this._extras.get(trackId);
10123
+ if (!extras?.peaksSrc.has(clipId)) return;
10124
+ const next = new Map(extras.peaksSrc);
10125
+ next.delete(clipId);
10126
+ this._extras = new Map(this._extras).set(trackId, { ...extras, peaksSrc: next });
10127
+ }
9241
10128
  _readTrackDescriptor(trackEl) {
9242
10129
  const clipEls = trackEl.querySelectorAll("daw-clip");
9243
10130
  const clips = [];
@@ -9313,12 +10200,9 @@ var DawEditorElement = class extends import_lit19.LitElement {
9313
10200
  _flushTrackEntries() {
9314
10201
  if (this._entryQueue.length === 0) return;
9315
10202
  if (!this._engine) return;
9316
- if (this._dragInProgress) {
9317
- this._flushAfterDrag();
9318
- return;
9319
- }
9320
- const queued = this._entryQueue;
9321
- this._entryQueue = [];
10203
+ const isPageTrack = (id) => this._trackElements.has(id);
10204
+ const queued = this._handedIn ? this._entryQueue.filter((id) => !isPageTrack(id)) : this._entryQueue;
10205
+ this._entryQueue = this._handedIn ? this._entryQueue.filter(isPageTrack) : [];
9322
10206
  const domOrder = [...this.querySelectorAll("daw-track")].map(
9323
10207
  (el) => el.trackId
9324
10208
  );
@@ -9327,12 +10211,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
9327
10211
  return at === -1 ? domOrder.length : at;
9328
10212
  };
9329
10213
  const ordered = [...queued].sort((a, b) => position(a) - position(b));
9330
- const isPageTrack = (id) => {
9331
- const el = this._trackElements.get(id);
9332
- return el !== void 0 && !this._editorMadeTracks.has(el);
9333
- };
9334
10214
  const arrangement = this._arrangement;
9335
- const historyWasEmpty = !arrangement.canUndo && !arrangement.canRedo && !this._dragInProgress;
10215
+ const historyWasEmpty = !arrangement.canUndo && !arrangement.canRedo;
9336
10216
  let pageEntered = false;
9337
10217
  for (const id of ordered.filter(isPageTrack)) {
9338
10218
  if (this._enterTrack(id)) pageEntered = true;
@@ -9340,32 +10220,21 @@ var DawEditorElement = class extends import_lit19.LitElement {
9340
10220
  if (historyWasEmpty && pageEntered) arrangement.clearHistory();
9341
10221
  for (const id of ordered.filter((id2) => !isPageTrack(id2))) this._enterTrack(id);
9342
10222
  }
9343
- /** Flush the queue once the drag in progress has ended (its pointer or key is released). */
9344
- _flushAfterDrag() {
9345
- if (this._waitingForDragEnd) return;
9346
- this._waitingForDragEnd = true;
9347
- const events = ["pointerup", "pointercancel", "keyup"];
9348
- const retry = () => {
9349
- for (const type of events) window.removeEventListener(type, retry);
9350
- this._waitingForDragEnd = false;
9351
- setTimeout(() => this._flushTrackEntries(), 0);
9352
- };
9353
- for (const type of events) window.addEventListener(type, retry);
9354
- }
9355
10223
  /** Enter one registered track. False when it is gone, already in, or refused. */
9356
10224
  _enterTrack(trackId) {
9357
- const descriptor = this._tracks.get(trackId);
10225
+ const descriptor = this._pendingDescriptor(trackId);
9358
10226
  if (!descriptor || this._isEntered(trackId)) return false;
9359
10227
  const el = this._trackElements.get(trackId);
9360
10228
  const built = buildArrangementTrack(
9361
10229
  trackId,
9362
10230
  descriptor,
9363
- el ? mixOfElement(el) : DEFAULT_TRACK_MIX,
10231
+ this._mixOf(trackId),
9364
10232
  this.effectiveSampleRate
9365
10233
  );
9366
- if (built.descriptor !== descriptor) {
9367
- this._tracks = new Map(this._tracks).set(trackId, built.descriptor);
9368
- }
10234
+ const nextPending = new Map(this._pending);
10235
+ nextPending.delete(trackId);
10236
+ this._pending = nextPending;
10237
+ this._extras = new Map(this._extras).set(trackId, extrasOf(built.descriptor));
9369
10238
  for (const { clipId, error } of built.refused) {
9370
10239
  console.warn("[dawcore] " + error.message);
9371
10240
  this.dispatchEvent(
@@ -9381,14 +10250,45 @@ var DawEditorElement = class extends import_lit19.LitElement {
9381
10250
  trackId,
9382
10251
  this._arrangement.getTracks().map((t) => t.id)
9383
10252
  ) : void 0;
9384
- this._announcer.expect(trackId, built.refused.length);
9385
- for (const clip of built.track.clips) {
9386
- if ((0, import_core19.isLoadingClip)(clip)) this._announcer.expectClip(clip.id);
10253
+ const moved = this._takeOverMovedClips(trackId, built.track);
10254
+ const entering = moved.track;
10255
+ for (const { clipId, error } of moved.refused) {
10256
+ console.warn("[dawcore] " + error.message);
10257
+ this.dispatchEvent(
10258
+ new CustomEvent("daw-clip-error", {
10259
+ bubbles: true,
10260
+ composed: true,
10261
+ detail: { trackId, clipId, error }
10262
+ })
10263
+ );
10264
+ }
10265
+ this._announcer.expect(trackId, built.refused.length + moved.refused.length);
10266
+ for (const clip of entering.clips) {
10267
+ if ((0, import_core21.isLoadingClip)(clip)) this._announcer.expectClip(clip.id);
9387
10268
  }
9388
10269
  try {
9389
- this._arrangement.addTrack(built.track, index === void 0 ? void 0 : { index });
10270
+ if (moved.from.size === 0) {
10271
+ this._arrangement.addTrack(entering, index === void 0 ? void 0 : { index });
10272
+ } else {
10273
+ this._inOneStep([this._arrangement], () => {
10274
+ for (const [fromId, clipIds] of moved.from) {
10275
+ this._arrangement.updateTrack(fromId, (t) => ({
10276
+ ...t,
10277
+ clips: t.clips.filter((c) => !clipIds.has(c.id))
10278
+ }));
10279
+ for (const clipId of clipIds) this._forgetClip(fromId, clipId);
10280
+ }
10281
+ this._arrangement.addTrack(entering, index === void 0 ? void 0 : { index });
10282
+ });
10283
+ }
9390
10284
  } catch (err) {
9391
10285
  console.warn('[dawcore] Failed to add track "' + trackId + '": ' + String(err));
10286
+ if (!el) {
10287
+ const nextExtras = new Map(this._extras);
10288
+ nextExtras.delete(trackId);
10289
+ this._extras = nextExtras;
10290
+ }
10291
+ this._refreshLinkStates();
9392
10292
  this._settleEntry(trackId, err instanceof Error ? err : new Error(String(err)));
9393
10293
  this.dispatchEvent(
9394
10294
  new CustomEvent("daw-track-error", {
@@ -9399,8 +10299,9 @@ var DawEditorElement = class extends import_lit19.LitElement {
9399
10299
  );
9400
10300
  return false;
9401
10301
  }
9402
- this._settleEntry(trackId, null);
10302
+ this._settleEntry(trackId, ENTERED);
9403
10303
  for (const clipDesc of built.descriptor.clips) {
10304
+ if (clipDesc.clipId && moved.movedIds.has(clipDesc.clipId)) continue;
9404
10305
  if (clipDesc.peaksSrc && clipDesc.clipId && clipSourceOf(clipDesc)) {
9405
10306
  this._requestPreview(clipDesc.clipId, clipDesc.peaksSrc);
9406
10307
  }
@@ -9413,7 +10314,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
9413
10314
  * `<daw-clip>` children keeps them. A track still queued reads the new
9414
10315
  * descriptor when it enters.
9415
10316
  */
9416
- _replaceShorthandClips(trackId, descriptor) {
10317
+ _replaceShorthandClips(trackId, trackEl) {
10318
+ const descriptor = this._readTrackDescriptor(trackEl);
9417
10319
  if (!this._isEntered(trackId) || descriptor.clips.some(isDomClip)) return;
9418
10320
  const built = buildArrangementTrack(
9419
10321
  trackId,
@@ -9421,7 +10323,13 @@ var DawEditorElement = class extends import_lit19.LitElement {
9421
10323
  DEFAULT_TRACK_MIX,
9422
10324
  this.effectiveSampleRate
9423
10325
  );
9424
- this._tracks = new Map(this._tracks).set(trackId, built.descriptor);
10326
+ const extras = this._extras.get(trackId);
10327
+ if (extras) {
10328
+ this._extras = new Map(this._extras).set(trackId, {
10329
+ ...extras,
10330
+ peaksSrc: extrasOf(built.descriptor).peaksSrc
10331
+ });
10332
+ }
9425
10333
  this._arrangement.updateTrack(trackId, (current) => ({ ...current, clips: built.track.clips }));
9426
10334
  }
9427
10335
  /** Run the load announcements over the arrangement's current state. */
@@ -9440,7 +10348,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9440
10348
  const waveformData = await this._resolvePeaks(peaksSrc);
9441
10349
  if (!waveformData) return;
9442
10350
  const clip = this._arrangement.getTracks().flatMap((t) => t.clips).find((c) => c.id === clipId);
9443
- if (!clip || !(0, import_core19.isLoadingClip)(clip)) return;
10351
+ if (!clip || !(0, import_core21.isLoadingClip)(clip)) return;
9444
10352
  const rate = waveformData.sample_rate;
9445
10353
  const offset = clip.offset ?? 0;
9446
10354
  const seconds = clip.duration ?? Math.max(0, waveformData.duration - offset);
@@ -9469,13 +10377,13 @@ var DawEditorElement = class extends import_lit19.LitElement {
9469
10377
  this._entryWaiters.set(trackId, { resolve, reject });
9470
10378
  });
9471
10379
  }
9472
- /** Settle the wait for a track's entry: entered (`null`), or refused or gone. */
9473
- _settleEntry(trackId, error) {
10380
+ /** Settle the wait for a track's entry: entered (`ENTERED`), or refused or gone (the reason).*/
10381
+ _settleEntry(trackId, outcome) {
9474
10382
  const waiter = this._entryWaiters.get(trackId);
9475
10383
  if (!waiter) return;
9476
10384
  this._entryWaiters.delete(trackId);
9477
- if (error) waiter.reject(error);
9478
- else waiter.resolve(trackId);
10385
+ if (outcome === ENTERED) waiter.resolve(trackId);
10386
+ else waiter.reject(outcome);
9479
10387
  }
9480
10388
  /**
9481
10389
  * A dropped file as a track with no element (a File cannot be an attribute):
@@ -9485,7 +10393,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9485
10393
  _addDroppedFile(file) {
9486
10394
  const trackId = crypto.randomUUID();
9487
10395
  const name = file.name.replace(/\.\w+$/, "");
9488
- this._tracks = new Map(this._tracks).set(trackId, {
10396
+ const descriptor = {
9489
10397
  name,
9490
10398
  src: "",
9491
10399
  kind: "audio",
@@ -9509,8 +10417,10 @@ var DawEditorElement = class extends import_lit19.LitElement {
9509
10417
  midiProgram: null
9510
10418
  }
9511
10419
  ]
9512
- });
10420
+ };
10421
+ this._pending = new Map(this._pending).set(trackId, { descriptor, mix: DEFAULT_TRACK_MIX });
9513
10422
  const entered = this._waitForEntry(trackId);
10423
+ this._endEntryOnSwap(trackId, entered);
9514
10424
  this._queueEntry(trackId);
9515
10425
  return entered;
9516
10426
  }
@@ -9518,12 +10428,29 @@ var DawEditorElement = class extends import_lit19.LitElement {
9518
10428
  * Take a track out for good: no undo step, and no undo or redo brings it
9519
10429
  * back (a dropped file that could not be loaded was never a declaration).
9520
10430
  */
9521
- _discardTrack(trackId) {
9522
- const track = this._arrangement.getTracks().find((t) => t.id === trackId);
10431
+ _discardTrack(trackId, from = this._arrangement) {
10432
+ if (from !== this._arrangement) {
10433
+ from.removeTrack(trackId, { undoable: false });
10434
+ if (this._extras.has(trackId)) {
10435
+ const nextExtras = new Map(this._extras);
10436
+ nextExtras.delete(trackId);
10437
+ this._extras = nextExtras;
10438
+ }
10439
+ return;
10440
+ }
10441
+ const track = from.getTracks().find((t) => t.id === trackId);
9523
10442
  this._announcer.forget(trackId, track?.clips.map((c) => c.id) ?? []);
9524
- this._arrangement.removeTrack(trackId, { undoable: false });
10443
+ from.removeTrack(trackId, { undoable: false });
9525
10444
  this._onTrackRemoved(trackId);
9526
10445
  }
10446
+ /** The signal of the arrangement played now: aborted when it is swapped out. */
10447
+ get _playSignal() {
10448
+ return this._playSignals.signalOf(this._arrangement);
10449
+ }
10450
+ /** @internal A caller's signal combined with the arrangement played now (loadMidi, D6). */
10451
+ _operationSignal(signal) {
10452
+ return signal ? AbortSignal.any([signal, this._playSignal]) : this._playSignal;
10453
+ }
9527
10454
  /**
9528
10455
  * Resolves once the track has loaded (`daw-track-ready`), or when the
9529
10456
  * editor is disconnected meanwhile (the track is kept and loads after a
@@ -9533,30 +10460,31 @@ var DawEditorElement = class extends import_lit19.LitElement {
9533
10460
  const state9 = this._announcer.stateOf(trackId);
9534
10461
  if (state9 === "ready") return Promise.resolve();
9535
10462
  if (state9 === "failed") return Promise.reject(this._announcer.errorOf(trackId));
10463
+ const ended = AbortSignal.any([this._playSignal, this._connection.signal]);
10464
+ if (ended.aborted) return Promise.resolve();
9536
10465
  return new Promise((resolve, reject) => {
9537
- const cleanup = () => {
9538
- this.removeEventListener("daw-track-ready", onReady);
9539
- this.removeEventListener("daw-track-error", onError);
9540
- this._loadWaitEnds.delete(end);
9541
- };
9542
- const onReady = (e) => {
9543
- if (e.detail.trackId !== trackId) return;
9544
- cleanup();
9545
- resolve();
9546
- };
9547
- const onError = (e) => {
9548
- const detail = e.detail;
9549
- if (detail.trackId !== trackId) return;
9550
- cleanup();
9551
- reject(detail.error instanceof Error ? detail.error : new Error(String(detail.error)));
9552
- };
9553
- const end = () => {
9554
- cleanup();
9555
- resolve();
9556
- };
9557
- this.addEventListener("daw-track-ready", onReady);
9558
- this.addEventListener("daw-track-error", onError);
9559
- this._loadWaitEnds.add(end);
10466
+ const done = new AbortController();
10467
+ const signal = AbortSignal.any([ended, done.signal]);
10468
+ this.addEventListener(
10469
+ "daw-track-ready",
10470
+ (e) => {
10471
+ if (e.detail.trackId !== trackId) return;
10472
+ done.abort();
10473
+ resolve();
10474
+ },
10475
+ { signal }
10476
+ );
10477
+ this.addEventListener(
10478
+ "daw-track-error",
10479
+ (e) => {
10480
+ const detail = e.detail;
10481
+ if (detail.trackId !== trackId) return;
10482
+ done.abort();
10483
+ reject(detail.error instanceof Error ? detail.error : new Error(String(detail.error)));
10484
+ },
10485
+ { signal }
10486
+ );
10487
+ ended.addEventListener("abort", () => resolve(), { signal: done.signal });
9560
10488
  });
9561
10489
  }
9562
10490
  /**
@@ -9572,14 +10500,14 @@ var DawEditorElement = class extends import_lit19.LitElement {
9572
10500
  }
9573
10501
  const sources = this._arrangement.sources.getSnapshot().sources;
9574
10502
  const failed = new Set(
9575
- track.clips.filter(import_core19.isLoadingClip).map((clip) => clip.src).filter((src) => sources.get(src)?.status === "failed")
10503
+ track.clips.filter(import_core21.isLoadingClip).map((clip) => clip.src).filter((src) => sources.get(src)?.status === "failed")
9576
10504
  );
9577
10505
  for (const src of failed) this._arrangement.retry(src);
9578
10506
  }
9579
10507
  _fetchPeaks(src) {
9580
10508
  const cached = this._peaksCache.get(src);
9581
10509
  if (cached) return cached;
9582
- const promise = loadWaveformDataFromUrl(src).catch((err) => {
10510
+ const promise = loadWaveformDataFromUrl(src, this._playSignal).catch((err) => {
9583
10511
  this._peaksCache.delete(src);
9584
10512
  throw err;
9585
10513
  });
@@ -9594,7 +10522,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9594
10522
  _recomputeDuration() {
9595
10523
  const sr = this.effectiveSampleRate;
9596
10524
  let maxSample = 0;
9597
- for (const track of this._engineTracks.values()) {
10525
+ for (const track of this._loadedTracks()) {
9598
10526
  for (const clip of track.clips) {
9599
10527
  const endSample = clip.startSample + clip.durationSamples;
9600
10528
  if (endSample > maxSample) maxSample = endSample;
@@ -9602,7 +10530,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9602
10530
  }
9603
10531
  for (const track of this._arrangement.getTracks()) {
9604
10532
  for (const clip of track.clips) {
9605
- if (!(0, import_core19.isLoadingClip)(clip)) continue;
10533
+ if (!(0, import_core21.isLoadingClip)(clip)) continue;
9606
10534
  const seconds = this._placeholderSeconds(clip);
9607
10535
  if (seconds === null) continue;
9608
10536
  maxSample = Math.max(maxSample, Math.round(((clip.start ?? 0) + seconds) * sr));
@@ -9641,6 +10569,16 @@ var DawEditorElement = class extends import_lit19.LitElement {
9641
10569
  this._buildEngine();
9642
10570
  } catch (err) {
9643
10571
  console.warn("[dawcore] Failed to build the engine: " + String(err));
10572
+ const error = err instanceof Error ? err : new Error(String(err));
10573
+ for (const trackId of [...this._entryQueue]) {
10574
+ const pending = this._pending.get(trackId);
10575
+ if (!pending || "element" in pending || !this._entryWaiters.has(trackId)) continue;
10576
+ const nextPending = new Map(this._pending);
10577
+ nextPending.delete(trackId);
10578
+ this._pending = nextPending;
10579
+ this._entryQueue = this._entryQueue.filter((id) => id !== trackId);
10580
+ this._settleEntry(trackId, error);
10581
+ }
9644
10582
  this.dispatchEvent(
9645
10583
  new CustomEvent("daw-error", {
9646
10584
  bubbles: true,
@@ -9666,7 +10604,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9666
10604
  }
9667
10605
  adapter.setPpqn?.(this._ppqn);
9668
10606
  this.ppqn = adapter.ppqn;
9669
- const engine = new import_engine.PlaylistEngine({
10607
+ const engine = new import_engine3.PlaylistEngine({
9670
10608
  adapter,
9671
10609
  arrangement: this._arrangement,
9672
10610
  sampleRate: adapter.audioContext.sampleRate,
@@ -9682,8 +10620,11 @@ var DawEditorElement = class extends import_lit19.LitElement {
9682
10620
  });
9683
10621
  engine.on("stop", () => this._onEngineStop(engine));
9684
10622
  this._engine = engine;
10623
+ if (this._selectionStartTime !== 0 || this._selectionEndTime !== 0) {
10624
+ engine.setSelection(this._selectionStartTime, this._selectionEndTime);
10625
+ }
9685
10626
  this._onEngineState(engine.getState());
9686
- for (const track of this._engineTracks.values()) {
10627
+ for (const track of this._loadedTracks()) {
9687
10628
  for (const clip of track.clips) this._maybeRegisterSpectrogramClipAudio(track.id, clip);
9688
10629
  }
9689
10630
  this._flushTrackEntries();
@@ -9709,7 +10650,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9709
10650
  }
9710
10651
  }
9711
10652
  }
9712
- /** The engine's state changed: follow it (the one writer of `_engineTracks`). */
10653
+ /** The engine's state changed: draw it (the rows are read from the arrangement). */
9713
10654
  _onEngineState(engineState) {
9714
10655
  this._isPlaying = engineState.isPlaying;
9715
10656
  this._selectedTrackId = engineState.selectedTrackId;
@@ -9718,20 +10659,12 @@ var DawEditorElement = class extends import_lit19.LitElement {
9718
10659
  if (structuralChange || mixerChange) {
9719
10660
  this._lastTracksVersion = engineState.tracksVersion;
9720
10661
  this._lastMixerVersion = engineState.mixerVersion;
9721
- const nextTracks = /* @__PURE__ */ new Map();
9722
- for (const track of engineState.tracks) {
9723
- nextTracks.set(track.id, track);
9724
- }
9725
- this._engineTracks = nextTracks;
9726
- this._reconcileDescriptorsWithEngineTracks(engineState.tracks);
10662
+ this.requestUpdate();
9727
10663
  }
9728
10664
  if (structuralChange) {
9729
10665
  this._recomputeDuration();
9730
- if (!this._inOrderSync) {
9731
- this._syncDomToEngineOrder(engineState.tracks);
9732
- }
9733
10666
  this._effectsManager?.rewireTrackChains();
9734
- const audioTracks = engineState.tracks.filter((t) => (0, import_core19.trackKind)(t) !== "midi");
10667
+ const audioTracks = engineState.tracks.filter((t) => (0, import_core21.trackKind)(t) !== "midi");
9735
10668
  this._adoptLoadedClips(audioTracks);
9736
10669
  syncPeaksForChangedClips(this, audioTracks);
9737
10670
  this._announceLoading();
@@ -9755,17 +10688,18 @@ var DawEditorElement = class extends import_lit19.LitElement {
9755
10688
  this._engine = null;
9756
10689
  }
9757
10690
  }
9758
- async loadFiles(files) {
9759
- return loadFiles(this, files);
10691
+ async loadFiles(files, options = {}) {
10692
+ return loadFiles(this, files, options);
9760
10693
  }
9761
10694
  /**
9762
- * Imperatively load a `.mid` file (URL or File) and create N `<daw-track>`
9763
- * elements — one per note-bearing MIDI track. On any per-track failure,
9764
- * every `<daw-track>` appended during the call is removed (both successful
9765
- * and failed) so the editor returns to its pre-call state.
10695
+ * Imperatively load a `.mid` file (URL or File) and add N tracks (no
10696
+ * element, #848), one per note-bearing MIDI track. On any per-track
10697
+ * failure, every track the call added is removed with no undo step, so the
10698
+ * editor is as before the call.
9766
10699
  *
9767
- * `options.signal` is forwarded to `fetch()` only for URL sources; aborting
9768
- * after parsing does not cancel in-flight `addTrack` calls.
10700
+ * `options.signal` cancels the fetch, the parse and the tracks still
10701
+ * waiting to enter (combined with the arrangement played: a swap cancels
10702
+ * too); the call rejects with its `reason` and removes the tracks it added.
9769
10703
  *
9770
10704
  * Requires the optional `@dawcore/midi` peer dep — throws with an install
9771
10705
  * hint (and `console.warn`s the original error) when the dynamic import
@@ -9784,25 +10718,41 @@ var DawEditorElement = class extends import_lit19.LitElement {
9784
10718
  return this._ensureEngine();
9785
10719
  }
9786
10720
  /**
9787
- * Append a `<daw-track>` element built from `config` and resolve with its
9788
- * track id once the track has entered the arrangement (#848), before its
9789
- * audio has loaded. To follow loading, add the `daw-track-ready` /
9790
- * `daw-track-error` listener BEFORE calling: for a track with nothing to
9791
- * fetch, or whose audio is already loaded, it fires before this resolves.
9792
- * Without `editor.adapter` it waits for one. Rejects when the track is
9793
- * refused by the arrangement or removed before it enters.
10721
+ * Add a track built from `config` to the arrangement the editor plays when
10722
+ * it is called, and resolve with its id once it has entered (#848), before
10723
+ * its audio has loaded. A swap of `editor.arrangement` before it enters
10724
+ * rejects with an `AbortError` and the track enters nowhere; to add to
10725
+ * another arrangement, call that arrangement's own `addTrack`. No element is created: the track is drawn and listed like any
10726
+ * other, and `<daw-track>` children stay the page's declaration. To follow
10727
+ * loading, add the `daw-track-ready` / `daw-track-error` listener BEFORE
10728
+ * calling: for a track with nothing to fetch it fires before this
10729
+ * resolves. Without `editor.adapter` it waits for one. Rejects when the
10730
+ * arrangement refuses the track, when it is removed before it enters, or
10731
+ * when the engine cannot be built.
10732
+ *
10733
+ * `options.signal` (#848): aborting it before the track has entered takes
10734
+ * it out of the queue (it never enters) and rejects with its `reason`;
10735
+ * after that it changes nothing (the audio goes on loading). A signal
10736
+ * already aborted rejects at once and queues nothing.
9794
10737
  */
9795
- addTrack(config = {}) {
9796
- const trackEl = document.createElement("daw-track");
9797
- this._editorMadeTracks.add(trackEl);
9798
- if (config.name !== void 0) trackEl.setAttribute("name", config.name);
9799
- if (config.volume !== void 0) trackEl.volume = config.volume;
9800
- if (config.pan !== void 0) trackEl.pan = config.pan;
9801
- if (config.muted) trackEl.setAttribute("muted", "");
9802
- if (config.soloed) trackEl.setAttribute("soloed", "");
9803
- const kind = config.kind ?? (config.midi ? "midi" : void 0);
9804
- if (kind !== void 0) trackEl.setAttribute("kind", kind);
9805
- if (config.renderMode !== void 0) trackEl.setAttribute("render-mode", config.renderMode);
10738
+ addTrack(config = {}, options = {}) {
10739
+ const signal = options.signal;
10740
+ if (signal?.aborted) return Promise.reject(reasonOf(signal));
10741
+ const trackId = crypto.randomUUID();
10742
+ let kind = config.kind ?? (config.midi ? "midi" : "audio");
10743
+ if (kind !== "audio" && kind !== "midi") {
10744
+ console.warn(
10745
+ '[dawcore] addTrack: kind "' + String(kind) + `" is not a track kind ('audio' or 'midi'); using "audio"`
10746
+ );
10747
+ kind = "audio";
10748
+ }
10749
+ let renderMode = normalizeRenderMode(config.renderMode);
10750
+ if (renderMode === "both") {
10751
+ console.warn(
10752
+ `[dawcore] render-mode="both" is not yet supported; falling back to 'spectrogram'`
10753
+ );
10754
+ renderMode = "spectrogram";
10755
+ }
9806
10756
  const clipConfigs = [...config.clips ?? []];
9807
10757
  if (config.midi) {
9808
10758
  clipConfigs.push({
@@ -9811,115 +10761,194 @@ var DawEditorElement = class extends import_lit19.LitElement {
9811
10761
  midiProgram: config.midi.program
9812
10762
  });
9813
10763
  }
9814
- for (const clipConfig of clipConfigs) {
9815
- trackEl.appendChild(this._buildClipElement(clipConfig));
9816
- }
9817
- const entered = this._waitForEntry(trackEl.trackId);
9818
- this.appendChild(trackEl);
9819
- return entered;
10764
+ const descriptor = {
10765
+ name: config.name || "Untitled",
10766
+ src: "",
10767
+ kind,
10768
+ renderMode: trackDescriptorRenderMode(kind, renderMode),
10769
+ spectrogramConfig: config.spectrogramConfig ?? null,
10770
+ clips: clipConfigs.map((c) => clipDescriptorOf(c))
10771
+ };
10772
+ const mix = {
10773
+ volume: config.volume ?? DEFAULT_TRACK_MIX.volume,
10774
+ pan: config.pan ?? DEFAULT_TRACK_MIX.pan,
10775
+ muted: config.muted ?? false,
10776
+ soloed: config.soloed ?? false
10777
+ };
10778
+ this._pending = new Map(this._pending).set(trackId, { descriptor, mix });
10779
+ const entered = this._waitForEntry(trackId);
10780
+ this._endEntryOnSwap(trackId, entered);
10781
+ this._queueEntry(trackId);
10782
+ if (!signal) return entered;
10783
+ const settled = new AbortController();
10784
+ signal.addEventListener("abort", () => this._abortEntry(trackId, reasonOf(signal)), {
10785
+ signal: settled.signal
10786
+ });
10787
+ return entered.finally(() => settled.abort());
10788
+ }
10789
+ /**
10790
+ * A queued track goes into the arrangement played when it was queued: when
10791
+ * that one is swapped out first, the track leaves the queue and its wait
10792
+ * rejects with the swap's AbortError (addTrack, a dropped file).
10793
+ */
10794
+ _endEntryOnSwap(trackId, entered) {
10795
+ const settled = new AbortController();
10796
+ this._playSignal.addEventListener(
10797
+ "abort",
10798
+ (e) => this._abortEntry(trackId, reasonOf(e.target)),
10799
+ { signal: settled.signal }
10800
+ );
10801
+ void entered.then(
10802
+ () => settled.abort(),
10803
+ () => settled.abort()
10804
+ );
10805
+ }
10806
+ /** A track that has not entered leaves the queue and its wait rejects with `reason` (D4). */
10807
+ _abortEntry(trackId, reason) {
10808
+ if (!this._pending.has(trackId) || this._isEntered(trackId)) return;
10809
+ const nextPending = new Map(this._pending);
10810
+ nextPending.delete(trackId);
10811
+ this._pending = nextPending;
10812
+ this._settleEntry(trackId, reason);
10813
+ this.requestUpdate();
9820
10814
  }
9821
10815
  /**
9822
- * Remove a track by id. Equivalent to `trackElement.remove()` —
9823
- * the editor's MutationObserver handles engine and cache cleanup.
9824
- * No-op if no matching track exists.
10816
+ * Remove a track by id: its `<daw-track>` element is removed (the
10817
+ * MutationObserver does the rest), or, for a track with no element
10818
+ * (`addTrack`, a dropped file, an Undo), the track itself. One undo step.
10819
+ * Warns when no track has the id.
9825
10820
  */
9826
10821
  removeTrack(trackId) {
9827
10822
  const trackEl = this._trackElements.get(trackId);
9828
10823
  if (trackEl) {
9829
10824
  trackEl.remove();
9830
10825
  if (!this.isConnected) this._onTrackRemoved(trackId);
9831
- } else if (this._tracks.has(trackId) || this._isEntered(trackId)) {
10826
+ } else if (this._pending.has(trackId) || this._extras.has(trackId) || this._isEntered(trackId)) {
9832
10827
  this._onTrackRemoved(trackId);
9833
10828
  } else {
9834
10829
  console.warn('[dawcore] removeTrack: no track found for id "' + trackId + '"');
9835
10830
  }
9836
10831
  }
9837
10832
  /**
9838
- * Move a track to a new position in the vertical order (0-based index among
9839
- * `<daw-track>` elements). Element-backed tracks move their DOM element —
9840
- * the MutationObserver syncs the engine (single write path). Element-less
9841
- * tracks (undo-resurrected) reorder the engine directly.
10833
+ * Move a track to a 0-based position in the arrangement's order (every
10834
+ * track counts, those with no element too; `trackEl.index` and
10835
+ * `editor.tracks` give the positions). One undo step; no element moves.
9842
10836
  */
9843
10837
  reorderTrack(trackId, toIndex) {
9844
10838
  if (!Number.isFinite(toIndex)) {
9845
10839
  console.warn("[dawcore] reorderTrack: invalid toIndex " + String(toIndex));
9846
10840
  return;
9847
10841
  }
9848
- const el = this._trackElements.get(trackId);
9849
- if (el) {
9850
- const els = [...this.querySelectorAll("daw-track")];
9851
- const from = els.indexOf(el);
9852
- if (from === -1) return;
9853
- const clamped = Math.max(0, Math.min(toIndex, els.length - 1));
9854
- if (from === clamped) return;
9855
- const anchor = els[clamped];
9856
- if (clamped > from) anchor.after(el);
9857
- else anchor.before(el);
9858
- } else if (this._isEntered(trackId)) {
9859
- this._arrangement.reorderTrack(trackId, toIndex);
9860
- this.requestUpdate();
9861
- } else {
10842
+ if (!this._isEntered(trackId)) {
9862
10843
  console.warn('[dawcore] reorderTrack: no track found for id "' + trackId + '"');
10844
+ return;
9863
10845
  }
10846
+ const last = this._arrangement.getTracks().length - 1;
10847
+ this._arrangement.reorderTrack(trackId, Math.max(0, Math.min(Math.trunc(toIndex), last)));
9864
10848
  }
9865
10849
  /**
9866
- * Update reflected attributes on a track. The mixer fields go to their
9867
- * owner, the arrangement, as one undo step (#843; also while the track
9868
- * loads, #848). For DOM-element tracks the
9869
- * changes are also written to the `<daw-track>` element; for tracks
9870
- * without a DOM element (file drops) the descriptor is updated in place.
10850
+ * Change a track: the mix (one undo step, #843), the name (an undo step),
10851
+ * the render mode and spectrogram config (the editor's). The arrangement
10852
+ * is changed, never an element's attributes (#848): a `<daw-track>`'s
10853
+ * properties show the change. A track that has not entered yet gets it as
10854
+ * the value it enters with.
9871
10855
  */
9872
10856
  updateTrack(trackId, partial) {
10857
+ if (!this._isEntered(trackId)) {
10858
+ this._updatePendingTrack(trackId, partial);
10859
+ return;
10860
+ }
9873
10861
  const mix = {
9874
10862
  volume: partial.volume,
9875
10863
  pan: partial.pan,
9876
10864
  muted: partial.muted,
9877
10865
  soloed: partial.soloed
9878
10866
  };
9879
- const trackEl = this._trackElements.get(trackId);
9880
- if (trackEl) {
9881
- this._writeMixFields(trackId, mix);
9882
- if (partial.name !== void 0) trackEl.setAttribute("name", partial.name);
9883
- if (partial.volume !== void 0) trackEl.volume = partial.volume;
9884
- if (partial.pan !== void 0) trackEl.pan = partial.pan;
9885
- if (partial.muted !== void 0) {
9886
- if (partial.muted) trackEl.setAttribute("muted", "");
9887
- else trackEl.removeAttribute("muted");
9888
- }
9889
- if (partial.soloed !== void 0) {
9890
- if (partial.soloed) trackEl.setAttribute("soloed", "");
9891
- else trackEl.removeAttribute("soloed");
9892
- }
9893
- if (partial.renderMode !== void 0) trackEl.setAttribute("render-mode", partial.renderMode);
9894
- return;
9895
- }
9896
- const oldDesc = this._tracks.get(trackId);
9897
- if (!oldDesc) return;
9898
- let normalizedRenderMode = partial.renderMode === void 0 ? void 0 : normalizeRenderMode(partial.renderMode);
9899
- if (normalizedRenderMode === "both") {
10867
+ this._writeMixFields(trackId, mix);
10868
+ if (partial.name !== void 0) this._renameTrack(trackId, partial.name);
10869
+ const extras = this._extras.get(trackId) ?? this._defaultExtras(trackId);
10870
+ if (!extras) return;
10871
+ let renderMode = partial.renderMode === void 0 ? void 0 : normalizeRenderMode(partial.renderMode);
10872
+ if (renderMode === "both") {
9900
10873
  console.warn(
9901
10874
  `[dawcore] render-mode="both" is not yet supported; falling back to 'spectrogram'`
9902
10875
  );
9903
- normalizedRenderMode = "spectrogram";
10876
+ renderMode = "spectrogram";
9904
10877
  }
9905
- const newDesc = {
9906
- ...oldDesc,
9907
- ...partial.name !== void 0 && { name: partial.name },
9908
- ...normalizedRenderMode !== void 0 && {
9909
- renderMode: trackDescriptorRenderMode(oldDesc.kind, normalizedRenderMode)
10878
+ if (renderMode === void 0 && partial.spectrogramConfig === void 0) return;
10879
+ const next = {
10880
+ ...extras,
10881
+ ...renderMode !== void 0 && {
10882
+ renderMode: trackDescriptorRenderMode(extras.kind, renderMode)
10883
+ },
10884
+ ...partial.spectrogramConfig !== void 0 && {
10885
+ spectrogramConfig: partial.spectrogramConfig
9910
10886
  }
9911
10887
  };
9912
- this._tracks = new Map(this._tracks).set(trackId, newDesc);
9913
- this._writeMixFields(trackId, mix);
10888
+ this._extras = new Map(this._extras).set(trackId, next);
10889
+ if (next.spectrogramConfig !== extras.spectrogramConfig) {
10890
+ this._spectrogramController?.setTrackConfig(trackId, next.spectrogramConfig ?? null);
10891
+ }
10892
+ }
10893
+ /** `updateTrack` on a track waiting to enter: the values it will enter with. */
10894
+ _updatePendingTrack(trackId, partial) {
10895
+ const pending = this._pending.get(trackId);
10896
+ if (!pending) {
10897
+ console.warn('[dawcore] updateTrack: no track found for id "' + trackId + '"');
10898
+ return;
10899
+ }
10900
+ if ("element" in pending) {
10901
+ const el = pending.element;
10902
+ if (partial.name !== void 0) el.name = partial.name;
10903
+ if (partial.volume !== void 0) el.volume = partial.volume;
10904
+ if (partial.pan !== void 0) el.pan = partial.pan;
10905
+ if (partial.muted !== void 0) el.muted = partial.muted;
10906
+ if (partial.soloed !== void 0) el.soloed = partial.soloed;
10907
+ if (partial.renderMode !== void 0) el.renderMode = partial.renderMode;
10908
+ if (partial.spectrogramConfig !== void 0) el.spectrogramConfig = partial.spectrogramConfig;
10909
+ return;
10910
+ }
10911
+ const { descriptor, mix } = pending;
10912
+ this._pending = new Map(this._pending).set(trackId, {
10913
+ descriptor: {
10914
+ ...descriptor,
10915
+ ...partial.spectrogramConfig !== void 0 && {
10916
+ spectrogramConfig: partial.spectrogramConfig
10917
+ },
10918
+ ...partial.name !== void 0 && { name: partial.name },
10919
+ ...partial.renderMode !== void 0 && {
10920
+ renderMode: trackDescriptorRenderMode(
10921
+ descriptor.kind,
10922
+ normalizeRenderMode(partial.renderMode)
10923
+ )
10924
+ }
10925
+ },
10926
+ mix: {
10927
+ volume: partial.volume ?? mix.volume,
10928
+ pan: partial.pan ?? mix.pan,
10929
+ muted: partial.muted ?? mix.muted,
10930
+ soloed: partial.soloed ?? mix.soloed
10931
+ }
10932
+ });
9914
10933
  }
9915
10934
  /**
9916
- * Append a clip to an existing track. Builds a `<daw-clip>` from `config`
9917
- * and appends it to the track's DOM element; resolves with the new clip's
10935
+ * Add a clip to a track (with or without an element) and resolve with its
9918
10936
  * id once its audio has loaded (`daw-clip-ready`, before its peaks are
9919
- * drawn); rejects when it fails to load, is refused, or leaves the
9920
- * arrangement before it loads (a removal, an Undo).
10937
+ * drawn). The clip enters the arrangement as a loading clip, one undo
10938
+ * step; no `<daw-clip>` is created (#848). Rejects when it fails to load,
10939
+ * is refused (its kind), or leaves the arrangement before it loads (a
10940
+ * removal, an Undo). A clip added while the editor is detached loads once
10941
+ * a fresh adapter is set.
10942
+ *
10943
+ * `options.signal` (#848): aborting it before the clip has loaded rejects
10944
+ * with its `reason` and removes the clip for good (no undo step); after it
10945
+ * has loaded it changes nothing. A signal already aborted rejects at once
10946
+ * and adds nothing. A swap of `editor.arrangement` rejects the call with an
10947
+ * `AbortError`; its loading clip stays in the arrangement swapped out.
9921
10948
  */
9922
- addClip(trackId, config) {
10949
+ addClip(trackId, config, options = {}) {
10950
+ const callerSignal = options.signal;
10951
+ if (callerSignal?.aborted) return Promise.reject(reasonOf(callerSignal));
9923
10952
  if (!config.src) {
9924
10953
  return Promise.reject(
9925
10954
  new Error(
@@ -9927,38 +10956,45 @@ var DawEditorElement = class extends import_lit19.LitElement {
9927
10956
  )
9928
10957
  );
9929
10958
  }
9930
- const trackEl = this._trackElements.get(trackId);
9931
- if (!trackEl) {
9932
- return Promise.reject(
9933
- new Error(
9934
- 'addClip: no <daw-track> element for trackId "' + trackId + '" \u2014 addClip currently requires a DOM-backed track. Use editor.addTrack(config) first.'
9935
- )
9936
- );
9937
- }
9938
- if (!this._isEntered(trackId) && !this._entryQueue.includes(trackId)) {
10959
+ const pending = this._pending.get(trackId);
10960
+ if (!this._isEntered(trackId) && !pending) {
9939
10961
  return Promise.reject(
9940
10962
  new Error(
9941
- 'addClip: track "' + trackId + '" is not in the editor (an Undo took it out, or the arrangement refused it)'
10963
+ 'addClip: track "' + trackId + '" is not in the editor (an Undo took it out, the arrangement refused it, or no track has this id)'
9942
10964
  )
9943
10965
  );
9944
10966
  }
9945
- const clipEl = this._buildClipElement(config);
9946
- const clipId = clipEl.clipId;
10967
+ const clipDesc = clipDescriptorOf(config);
10968
+ const clipId = clipDesc.clipId;
9947
10969
  return new Promise((resolve, reject) => {
9948
10970
  let seen = false;
9949
- const onReady = (e) => {
9950
- if (e.detail.clipId !== clipId) return;
9951
- cleanup();
9952
- resolve(clipId);
9953
- };
9954
- const onError = (e) => {
9955
- const detail = e.detail;
9956
- if (detail.clipId !== clipId) return;
9957
- cleanup();
9958
- reject(detail.error instanceof Error ? detail.error : new Error(String(detail.error)));
10971
+ const call = new AbortController();
10972
+ const cleanup = () => {
10973
+ call.abort();
10974
+ this._awaitedClips.delete(clipId);
9959
10975
  };
9960
- const stopWatching = this._arrangement.subscribe(() => {
9961
- const present = this._arrangement.getTracks().some((t) => t.clips.some((c) => c.id === clipId));
10976
+ this.addEventListener(
10977
+ "daw-clip-ready",
10978
+ (e) => {
10979
+ if (e.detail.clipId !== clipId) return;
10980
+ cleanup();
10981
+ resolve(clipId);
10982
+ },
10983
+ { signal: call.signal }
10984
+ );
10985
+ this.addEventListener(
10986
+ "daw-clip-error",
10987
+ (e) => {
10988
+ const detail = e.detail;
10989
+ if (detail.clipId !== clipId) return;
10990
+ cleanup();
10991
+ reject(detail.error instanceof Error ? detail.error : new Error(String(detail.error)));
10992
+ },
10993
+ { signal: call.signal }
10994
+ );
10995
+ const watched = pending && "element" in pending && !this._isEntered(trackId) ? this._ownArrangement : this._arrangement;
10996
+ const stopWatching = watched.subscribe(() => {
10997
+ const present = watched.getTracks().some((t) => t.clips.some((c) => c.id === clipId));
9962
10998
  if (present) {
9963
10999
  seen = true;
9964
11000
  } else if (seen) {
@@ -9966,14 +11002,24 @@ var DawEditorElement = class extends import_lit19.LitElement {
9966
11002
  reject(new Error('clip "' + clipId + '" was removed before its audio loaded'));
9967
11003
  }
9968
11004
  });
9969
- const cleanup = () => {
9970
- this.removeEventListener("daw-clip-ready", onReady);
9971
- this.removeEventListener("daw-clip-error", onError);
9972
- stopWatching();
9973
- this._awaitedClips.delete(clipId);
9974
- };
9975
- this.addEventListener("daw-clip-ready", onReady);
9976
- this.addEventListener("daw-clip-error", onError);
11005
+ call.signal.addEventListener("abort", stopWatching);
11006
+ this._playSignals.signalOf(watched).addEventListener(
11007
+ "abort",
11008
+ (e) => {
11009
+ cleanup();
11010
+ reject(reasonOf(e.target));
11011
+ },
11012
+ { signal: call.signal }
11013
+ );
11014
+ callerSignal?.addEventListener(
11015
+ "abort",
11016
+ () => {
11017
+ cleanup();
11018
+ this._discardAddedClip(trackId, clipId);
11019
+ reject(reasonOf(callerSignal));
11020
+ },
11021
+ { signal: call.signal }
11022
+ );
9977
11023
  this._awaitedClips.set(clipId, {
9978
11024
  trackId,
9979
11025
  reject: (error) => {
@@ -9981,122 +11027,91 @@ var DawEditorElement = class extends import_lit19.LitElement {
9981
11027
  reject(error);
9982
11028
  }
9983
11029
  });
9984
- trackEl.appendChild(clipEl);
11030
+ if (this._isEntered(trackId)) {
11031
+ seen = true;
11032
+ this._loadAndAppendClip(trackId, clipDesc);
11033
+ } else if (pending) {
11034
+ this._pending = new Map(this._pending).set(
11035
+ trackId,
11036
+ "element" in pending ? { ...pending, extraClips: [...pending.extraClips, clipDesc] } : {
11037
+ ...pending,
11038
+ descriptor: {
11039
+ ...pending.descriptor,
11040
+ clips: [...pending.descriptor.clips, clipDesc]
11041
+ }
11042
+ }
11043
+ );
11044
+ }
9985
11045
  });
9986
11046
  }
9987
11047
  /**
9988
- * Remove a clip by id. Removes the matching `<daw-clip>` DOM element when
9989
- * present (MutationObserver handles cleanup); otherwise updates engine
9990
- * state directly. No-op if no matching clip exists.
11048
+ * Remove a clip by id: its `<daw-clip>` when there is one (the observer
11049
+ * removes the clip, as `select.remove(i)` removes an option), otherwise
11050
+ * the clip itself, one undo step. Undo brings the clip back with no
11051
+ * element. No-op with a warning when there is no such clip.
9991
11052
  */
9992
11053
  removeClip(trackId, clipId) {
9993
11054
  const trackEl = this._trackElements.get(trackId);
9994
- if (trackEl) {
9995
- const clipEl = [...trackEl.querySelectorAll("daw-clip")].find(
9996
- (c) => c.clipId === clipId
9997
- );
9998
- if (clipEl) {
9999
- clipEl.remove();
10000
- return;
10001
- }
11055
+ const clipEl = trackEl ? [...trackEl.querySelectorAll("daw-clip")].find(
11056
+ (c) => c.clipId === clipId
11057
+ ) : void 0;
11058
+ if (clipEl) {
11059
+ clipEl.remove();
11060
+ if (!this.isConnected && this._isEntered(trackId)) this._removeClipFromTrack(trackId, clipId);
11061
+ return;
10002
11062
  }
10003
11063
  if (this._isEntered(trackId)) {
10004
11064
  this._removeClipFromTrack(trackId, clipId);
10005
11065
  return;
10006
11066
  }
11067
+ const pending = this._pending.get(trackId);
11068
+ if (pending) {
11069
+ const without = (clips) => clips.filter((c) => c.clipId !== clipId);
11070
+ this._pending = new Map(this._pending).set(
11071
+ trackId,
11072
+ "element" in pending ? { ...pending, extraClips: without(pending.extraClips) } : {
11073
+ ...pending,
11074
+ descriptor: { ...pending.descriptor, clips: without(pending.descriptor.clips) }
11075
+ }
11076
+ );
11077
+ this._rejectAwaitedClips((id) => id === clipId, "the clip was removed before it loaded");
11078
+ return;
11079
+ }
10007
11080
  console.warn(
10008
11081
  '[dawcore] removeClip: no track found for id "' + trackId + '" (clipId "' + clipId + '")'
10009
11082
  );
10010
11083
  }
10011
11084
  /**
10012
- * Update a clip's position (start/duration/offset) or properties (gain/name).
10013
- * For DOM-element clips, writes properties on the `<daw-clip>` element which
10014
- * fires `daw-clip-update`; otherwise applies directly via `_applyClipUpdate`.
11085
+ * Change a clip's position (start/duration/offset), gain or name: one undo
11086
+ * step on the arrangement (#848; a clip still loading changes its loading
11087
+ * clip). A `<daw-clip>`'s properties show the change, its attributes do
11088
+ * not. Fades are a `<daw-clip>` declaration only (engine-side fades are
11089
+ * #489): `fadeIn` / `fadeOut` / `fadeType` here change nothing.
10015
11090
  *
10016
11091
  * Re-decoding (changing `src`) is not supported via this method — remove and
10017
11092
  * re-add the clip instead.
10018
- *
10019
- * Note: `fadeIn` / `fadeOut` / `fadeType` on the partial are written to the
10020
- * `<daw-clip>` element (so they round-trip in the descriptor), but engine-side
10021
- * fade application from `<daw-clip>` properties is not yet implemented — see
10022
- * the broader fade-engine integration tracked separately.
10023
11093
  */
10024
11094
  updateClip(trackId, clipId, partial) {
10025
- const trackEl = this._trackElements.get(trackId);
10026
- if (trackEl) {
10027
- const clipEl = [...trackEl.querySelectorAll("daw-clip")].find(
10028
- (c) => c.clipId === clipId
10029
- );
10030
- if (clipEl) {
10031
- if (partial.start !== void 0) clipEl.start = partial.start;
10032
- if (partial.duration !== void 0) clipEl.duration = partial.duration;
10033
- if (partial.offset !== void 0) clipEl.offset = partial.offset;
10034
- if (partial.gain !== void 0) clipEl.gain = partial.gain;
10035
- if (partial.name !== void 0) clipEl.setAttribute("name", partial.name);
10036
- if (partial.fadeIn !== void 0) clipEl.fadeIn = partial.fadeIn;
10037
- if (partial.fadeOut !== void 0) clipEl.fadeOut = partial.fadeOut;
10038
- if (partial.fadeType !== void 0) clipEl.setAttribute("fade-type", partial.fadeType);
10039
- return;
10040
- }
10041
- }
10042
- const t = this._engineTracks.get(trackId);
10043
- if (!t) {
11095
+ if (!this._isEntered(trackId)) {
10044
11096
  console.warn('[dawcore] updateClip: no track found for id "' + trackId + '"');
10045
11097
  return;
10046
11098
  }
10047
- const idx = t.clips.findIndex((c) => c.id === clipId);
10048
- if (idx === -1) {
11099
+ if (!this._clipValues(trackId, clipId)) {
10049
11100
  console.warn(
10050
11101
  '[dawcore] updateClip: clip "' + clipId + '" not found in track "' + trackId + '"'
10051
11102
  );
10052
11103
  return;
10053
11104
  }
10054
- const oldClip = t.clips[idx];
10055
- const sr = oldClip.sampleRate ?? this.effectiveSampleRate;
10056
- const updatedClip = {
10057
- ...oldClip,
10058
- ...partial.start !== void 0 && { startSample: Math.round(partial.start * sr) },
10059
- ...partial.duration !== void 0 && partial.duration > 0 && { durationSamples: Math.round(partial.duration * sr) },
10060
- ...partial.offset !== void 0 && { offsetSamples: Math.round(partial.offset * sr) },
10061
- ...partial.gain !== void 0 && { gain: partial.gain },
10062
- ...partial.name !== void 0 && { name: partial.name }
10063
- };
10064
- const desc = this._tracks.get(trackId);
10065
- if (desc?.clips.some((c) => c.clipId === clipId)) {
10066
- this._tracks = new Map(this._tracks).set(trackId, {
10067
- ...desc,
10068
- clips: desc.clips.map(
10069
- (c) => c.clipId === clipId ? {
10070
- ...c,
10071
- start: updatedClip.startSample / sr,
10072
- duration: updatedClip.durationSamples / sr,
10073
- offset: updatedClip.offsetSamples / sr,
10074
- ...partial.gain !== void 0 && { gain: partial.gain },
10075
- ...partial.name !== void 0 && { name: partial.name }
10076
- } : c
10077
- )
10078
- });
10079
- }
10080
- this._replaceClip(trackId, clipId, updatedClip);
10081
- }
10082
- _buildClipElement(config) {
10083
- const clipEl = document.createElement("daw-clip");
10084
- if (config.src !== void 0) clipEl.setAttribute("src", config.src);
10085
- if (config.peaksSrc !== void 0) clipEl.setAttribute("peaks-src", config.peaksSrc);
10086
- if (config.start !== void 0) clipEl.start = config.start;
10087
- if (config.duration !== void 0) clipEl.duration = config.duration;
10088
- if (config.offset !== void 0) clipEl.offset = config.offset;
10089
- if (config.gain !== void 0) clipEl.gain = config.gain;
10090
- if (config.name !== void 0) clipEl.setAttribute("name", config.name);
10091
- if (config.fadeIn !== void 0) clipEl.fadeIn = config.fadeIn;
10092
- if (config.fadeOut !== void 0) clipEl.fadeOut = config.fadeOut;
10093
- if (config.fadeType !== void 0) clipEl.setAttribute("fade-type", config.fadeType);
10094
- if (config.midiNotes !== void 0) clipEl.midiNotes = config.midiNotes;
10095
- if (config.midiChannel !== void 0)
10096
- clipEl.setAttribute("midi-channel", String(config.midiChannel));
10097
- if (config.midiProgram !== void 0)
10098
- clipEl.setAttribute("midi-program", String(config.midiProgram));
10099
- return clipEl;
11105
+ const request = {};
11106
+ if (partial.start !== void 0) request.start = partial.start;
11107
+ if (partial.duration !== void 0) request.duration = partial.duration;
11108
+ if (partial.offset !== void 0) request.offset = partial.offset;
11109
+ if (partial.gain !== void 0) request.gain = partial.gain;
11110
+ if (partial.name !== void 0) request.name = partial.name;
11111
+ if (partial.midiNotes !== void 0) request.midiNotes = partial.midiNotes;
11112
+ if (partial.midiChannel !== void 0) request.midiChannel = partial.midiChannel;
11113
+ if (partial.midiProgram !== void 0) request.midiProgram = partial.midiProgram;
11114
+ this._requestClipChange(trackId, clipId, request);
10100
11115
  }
10101
11116
  // --- Playback ---
10102
11117
  /**
@@ -10363,8 +11378,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
10363
11378
  return;
10364
11379
  }
10365
11380
  const targetId = options?.trackId ?? this._selectedTrackId;
10366
- const target = targetId ? this._tracks.get(targetId) : void 0;
10367
- if (targetId && target?.kind === "midi") {
11381
+ const target = targetId ? this._arrangement.getTracks().find((t) => t.id === targetId) : void 0;
11382
+ if (targetId && target && (0, import_core21.trackKind)(target) === "midi") {
10368
11383
  const error = new Error(
10369
11384
  'Cannot record onto MIDI track "' + target.name + '": a recording is audio. Select or create an audio track first.'
10370
11385
  );
@@ -10471,67 +11486,25 @@ var DawEditorElement = class extends import_lit19.LitElement {
10471
11486
  return (this._getOrderedTracks().length > 0 || this.scaleMode === "beats" || this.indefinitePlayback || this.fillViewport) && this.timescale;
10472
11487
  }
10473
11488
  /**
10474
- * DOM → engine: make the engine's track order match the light-DOM
10475
- * `<daw-track>` order. Single write path for reorders — editor-initiated
10476
- * (buttons/drag move the element) and consumer-initiated (insertBefore)
10477
- * mutations both land here via the MutationObserver. Element-less tracks
10478
- * (undo-resurrected) keep their engine positions (stable sort).
10479
- * Write-only-on-change: a no-op when orders already match, so the
10480
- * engine→DOM direction (statechange handler) converges in one pass.
11489
+ * `<daw-track>` elements the page moved (one MutationObserver batch): each
11490
+ * is placed after the arrangement track of the nearest `<daw-track>` before
11491
+ * it, in DOM order, as one undo step (#848 P13). Elements whose track is
11492
+ * not in the arrangement are left alone (a queued one enters at its DOM
11493
+ * position). The arrangement's own order changes (an Undo) move no element.
10481
11494
  */
10482
- _syncEngineOrderToDom() {
10483
- const engine = this._engine;
10484
- if (!engine) return;
10485
- const domOrder = [...this.querySelectorAll("daw-track")].map(
10486
- (el) => el.trackId
10487
- );
10488
- const engineIds = engine.getState().tracks.map((t) => t.id);
10489
- const inDom = new Set(domOrder);
10490
- const slots = engineIds.flatMap((id, i) => inDom.has(id) ? [i] : []);
10491
- const domSorted = domOrder.filter((id) => engineIds.includes(id));
10492
- const target = [...engineIds];
10493
- slots.forEach((slot, k) => {
10494
- target[slot] = domSorted[k];
10495
- });
10496
- if (target.every((id, i) => id === engineIds[i])) return;
10497
- this._inOrderSync = true;
11495
+ _placeMovedTracks(movedIds) {
11496
+ const els = [...this.querySelectorAll("daw-track")];
11497
+ const moved = els.filter((el) => movedIds.has(el.trackId) && this._isEntered(el.trackId));
11498
+ if (moved.length === 0) return;
11499
+ const arrangement = this._arrangement;
11500
+ arrangement.beginTransaction();
10498
11501
  try {
10499
- engine.beginTransaction();
10500
- const current = [...engineIds];
10501
- for (let i = 0; i < target.length; i++) {
10502
- if (current[i] === target[i]) continue;
10503
- engine.reorderTrack(target[i], i);
10504
- const from = current.indexOf(target[i]);
10505
- current.splice(from, 1);
10506
- current.splice(i, 0, target[i]);
10507
- }
10508
- engine.commitTransaction();
11502
+ for (const el of moved) {
11503
+ const others = arrangement.getTracks().map((t) => t.id).filter((id) => id !== el.trackId);
11504
+ arrangement.reorderTrack(el.trackId, entryIndex(els, el.trackId, others));
11505
+ }
10509
11506
  } finally {
10510
- this._inOrderSync = false;
10511
- }
10512
- this.requestUpdate();
10513
- }
10514
- /**
10515
- * Engine → DOM: after an engine-initiated order change (undo/redo), move
10516
- * `<daw-track>` elements to match engine order. The resulting mutations fire
10517
- * the observer's _syncEngineOrderToDom, which finds the orders equal and
10518
- * no-ops — converges in one pass (write-only-on-change).
10519
- */
10520
- _syncDomToEngineOrder(tracks) {
10521
- const els = [...this.querySelectorAll("daw-track")];
10522
- if (els.length < 2) return;
10523
- const byId = new Map(els.map((el) => [el.trackId, el]));
10524
- const desired = tracks.map((t) => byId.get(t.id)).filter((el) => el != null);
10525
- if (desired.length < 2) return;
10526
- const desiredSet = new Set(desired);
10527
- const slots = els.filter((el) => desiredSet.has(el));
10528
- if (desired.every((el, i) => el === slots[i])) return;
10529
- for (let i = 0; i < desired.length; i++) {
10530
- if (slots[i] === desired[i]) continue;
10531
- slots[i].before(desired[i]);
10532
- const from = slots.indexOf(desired[i]);
10533
- slots.splice(from, 1);
10534
- slots.splice(i, 0, desired[i]);
11507
+ arrangement.commitTransaction();
10535
11508
  }
10536
11509
  }
10537
11510
  /**
@@ -10541,9 +11514,12 @@ var DawEditorElement = class extends import_lit19.LitElement {
10541
11514
  _getOrderedTracks() {
10542
11515
  const rows = [];
10543
11516
  for (const track of this._arrangement.getTracks()) {
10544
- const loaded = this._engineTracks.get(track.id);
10545
- if (!loaded) continue;
10546
- rows.push([track.id, loaded, track.clips.filter(import_core19.isLoadingClip)]);
11517
+ const loaded = loadedTrack(
11518
+ track,
11519
+ this._mixOf(track.id),
11520
+ this._arrangement.recordingTrackIds.has(track.id)
11521
+ );
11522
+ rows.push([track.id, loaded, track.clips.filter(import_core21.isLoadingClip)]);
10547
11523
  }
10548
11524
  return rows;
10549
11525
  }
@@ -10566,7 +11542,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
10566
11542
  } else {
10567
11543
  const startSample = Math.round(startSec * sr);
10568
11544
  left = Math.floor(startSample / spp);
10569
- width = (0, import_core19.clipPixelWidth)(startSample, Math.round(seconds * sr), spp);
11545
+ width = (0, import_core21.clipPixelWidth)(startSample, Math.round(seconds * sr), spp);
10570
11546
  }
10571
11547
  const failed = this._arrangement.sources.getSnapshot().sources.get(clip.src)?.status === "failed";
10572
11548
  const peakData = this._previewPeaks.get(clip.id);
@@ -10612,7 +11588,11 @@ var DawEditorElement = class extends import_lit19.LitElement {
10612
11588
  selEndPx = this._selectionEndTime * sr / spp;
10613
11589
  }
10614
11590
  const orderedTracks = this._getOrderedTracks().map(([trackId, track, loading]) => {
10615
- const descriptor = this._tracks.get(trackId);
11591
+ const descriptor = {
11592
+ name: track.name ?? "",
11593
+ kind: (0, import_core21.trackKind)(track),
11594
+ renderMode: this._renderModeOf(trackId)
11595
+ };
10616
11596
  const firstPeaks = [...track.clips, ...loading].map((c) => this._peaksData.get(c.id) ?? this._previewPeaks.get(c.id)).find((p) => p && p.data.length > 0);
10617
11597
  const recSession = this._recordingController.getSession(trackId);
10618
11598
  const numChannels = firstPeaks ? firstPeaks.data.length : recSession ? recSession.channelCount : 1;
@@ -10660,24 +11640,30 @@ var DawEditorElement = class extends import_lit19.LitElement {
10660
11640
  <span class="annotation-lane-name">${track.name}</span>
10661
11641
  </div>`
10662
11642
  )}
10663
- ${orderedTracks.map((t, i) => {
10664
- const mix = this._mixOf(t.trackId);
10665
- return import_lit19.html`
10666
- <daw-track-controls
10667
- style="height: ${t.trackHeight}px;"
10668
- .trackId=${t.trackId}
10669
- .trackName=${t.descriptor?.name ?? "Untitled"}
10670
- .volume=${mix.volume}
10671
- .pan=${mix.pan}
10672
- .muted=${mix.muted}
10673
- .recording=${this._engine?.recordingTrackIds.has(t.trackId) ?? false}
10674
- .soloed=${mix.soloed}
10675
- .reorderable=${this.trackReordering}
10676
- .trackIndex=${i}
10677
- .trackCount=${orderedTracks.length}
10678
- ></daw-track-controls>
10679
- `;
10680
- })}
11643
+ ${(0, import_repeat.repeat)(
11644
+ orderedTracks,
11645
+ // Keyed by track: a swap or an outside reorder must not hand
11646
+ // a row (and a slider gesture held in it) to another track.
11647
+ (t) => t.trackId,
11648
+ (t, i) => {
11649
+ const mix = this._mixOf(t.trackId);
11650
+ return import_lit19.html`
11651
+ <daw-track-controls
11652
+ style="height: ${t.trackHeight}px;"
11653
+ .trackId=${t.trackId}
11654
+ .trackName=${t.descriptor?.name ?? "Untitled"}
11655
+ .volume=${mix.volume}
11656
+ .pan=${mix.pan}
11657
+ .muted=${mix.muted}
11658
+ .recording=${this._engine?.recordingTrackIds.has(t.trackId) ?? false}
11659
+ .soloed=${mix.soloed}
11660
+ .reorderable=${this.trackReordering}
11661
+ .trackIndex=${i}
11662
+ .trackCount=${orderedTracks.length}
11663
+ ></daw-track-controls>
11664
+ `;
11665
+ }
11666
+ )}
10681
11667
  </div>
10682
11668
  </div>` : ""}
10683
11669
  <div class="scroll-area">
@@ -10708,149 +11694,158 @@ var DawEditorElement = class extends import_lit19.LitElement {
10708
11694
  ></daw-grid>` : ""}
10709
11695
  ${orderedTracks.length > 0 || this.scaleMode === "beats" || this.indefinitePlayback || this.fillViewport ? import_lit19.html`<daw-selection .startPx=${selStartPx} .endPx=${selEndPx}></daw-selection>
10710
11696
  <daw-playhead></daw-playhead>` : ""}
10711
- ${orderedTracks.map((t) => {
10712
- const channelHeight = this.waveHeight;
10713
- return import_lit19.html`
10714
- <div
10715
- class="track-row ${t.trackId === this._selectedTrackId ? "selected" : ""}"
10716
- style="height: ${t.trackHeight}px;"
10717
- data-track-id=${t.trackId}
10718
- >
10719
- ${t.track.clips.map((clip) => {
10720
- const peakData = this._peaksData.get(clip.id) ?? this._previewPeaks.get(clip.id);
10721
- let clipLeft;
10722
- let width;
10723
- if (this.scaleMode === "beats") {
10724
- const startTick = clip.startTick !== void 0 ? clip.startTick : this._secondsToTicks(clip.startSample / sr);
10725
- const durSec = clip.durationSamples / sr;
10726
- const startSec = clip.startTick !== void 0 ? this._ticksToSeconds(clip.startTick) : clip.startSample / sr;
10727
- const endTick = this._secondsToTicks(startSec + durSec);
10728
- clipLeft = Math.round(startTick / this.ticksPerPixel);
10729
- width = Math.round(endTick / this.ticksPerPixel) - clipLeft;
10730
- } else {
10731
- clipLeft = Math.floor(clip.startSample / spp);
10732
- width = (0, import_core19.clipPixelWidth)(clip.startSample, clip.durationSamples, spp);
10733
- }
10734
- let clipSegments;
10735
- let segmentChannels;
10736
- if (this.scaleMode === "beats" && this.secondsToTicks) {
10737
- const audioBuffer = this._clipBuffers.get(clip.id);
10738
- const basePeaks = audioBuffer ? this._peakPipeline.getBaseScalePeaks(
10739
- audioBuffer,
10740
- this.mono,
10741
- clip.offsetSamples,
10742
- clip.durationSamples
10743
- ) : null;
10744
- if (basePeaks) {
10745
- const baseScale = basePeaks.scale;
10746
- segmentChannels = basePeaks.peaks.data;
10747
- const MIN_RENDER_STEP = 80;
10748
- const stepTicks = Math.max(MIN_RENDER_STEP, Math.ceil(this.ticksPerPixel));
11697
+ ${(0, import_repeat.repeat)(
11698
+ orderedTracks,
11699
+ (t) => t.trackId,
11700
+ (t) => {
11701
+ const channelHeight = this.waveHeight;
11702
+ return import_lit19.html`
11703
+ <div
11704
+ class="track-row ${t.trackId === this._selectedTrackId ? "selected" : ""}"
11705
+ style="height: ${t.trackHeight}px;"
11706
+ data-track-id=${t.trackId}
11707
+ >
11708
+ ${t.track.clips.map((clip) => {
11709
+ const peakData = this._peaksData.get(clip.id) ?? this._previewPeaks.get(clip.id);
11710
+ let clipLeft;
11711
+ let width;
11712
+ if (this.scaleMode === "beats") {
11713
+ const startTick = clip.startTick !== void 0 ? clip.startTick : this._secondsToTicks(clip.startSample / sr);
11714
+ const durSec = clip.durationSamples / sr;
10749
11715
  const startSec = clip.startTick !== void 0 ? this._ticksToSeconds(clip.startTick) : clip.startSample / sr;
10750
- const clipOffsetSec = clip.offsetSamples / sr;
10751
- const segStartTick = clip.startTick !== void 0 ? clip.startTick : this._secondsToTicks(startSec);
10752
- const endTick = this._secondsToTicks(startSec + clip.durationSamples / sr);
10753
- clipSegments = [];
10754
- for (let tick = segStartTick; tick < endTick; tick += stepTicks) {
10755
- const segEndTick = Math.min(tick + stepTicks, endTick);
10756
- const segStartAudioSec = this._ticksToSeconds(tick) - startSec + clipOffsetSec;
10757
- const segEndAudioSec = this._ticksToSeconds(segEndTick) - startSec + clipOffsetSec;
10758
- const segStartSample = Math.round(segStartAudioSec * sr);
10759
- const segEndSample = Math.round(segEndAudioSec * sr);
10760
- const totalPeaks = clip.durationSamples / baseScale;
10761
- clipSegments.push({
10762
- peakStart: Math.max(
10763
- 0,
10764
- (segStartSample - clip.offsetSamples) / baseScale
10765
- ),
10766
- peakEnd: Math.min(
10767
- totalPeaks,
10768
- (segEndSample - clip.offsetSamples) / baseScale
10769
- ),
10770
- pixelStart: (tick - segStartTick) / this.ticksPerPixel,
10771
- pixelEnd: (segEndTick - segStartTick) / this.ticksPerPixel
10772
- });
11716
+ const endTick = this._secondsToTicks(startSec + durSec);
11717
+ clipLeft = Math.round(startTick / this.ticksPerPixel);
11718
+ width = Math.round(endTick / this.ticksPerPixel) - clipLeft;
11719
+ } else {
11720
+ clipLeft = Math.floor(clip.startSample / spp);
11721
+ width = (0, import_core21.clipPixelWidth)(clip.startSample, clip.durationSamples, spp);
11722
+ }
11723
+ let clipSegments;
11724
+ let segmentChannels;
11725
+ if (this.scaleMode === "beats" && this.secondsToTicks) {
11726
+ const audioBuffer = this._clipBuffers.get(clip.id);
11727
+ const basePeaks = audioBuffer ? this._peakPipeline.getBaseScalePeaks(
11728
+ audioBuffer,
11729
+ this.mono,
11730
+ clip.offsetSamples,
11731
+ clip.durationSamples
11732
+ ) : null;
11733
+ if (basePeaks) {
11734
+ const baseScale = basePeaks.scale;
11735
+ segmentChannels = basePeaks.peaks.data;
11736
+ const MIN_RENDER_STEP = 80;
11737
+ const stepTicks = Math.max(
11738
+ MIN_RENDER_STEP,
11739
+ Math.ceil(this.ticksPerPixel)
11740
+ );
11741
+ const startSec = clip.startTick !== void 0 ? this._ticksToSeconds(clip.startTick) : clip.startSample / sr;
11742
+ const clipOffsetSec = clip.offsetSamples / sr;
11743
+ const segStartTick = clip.startTick !== void 0 ? clip.startTick : this._secondsToTicks(startSec);
11744
+ const endTick = this._secondsToTicks(
11745
+ startSec + clip.durationSamples / sr
11746
+ );
11747
+ clipSegments = [];
11748
+ for (let tick = segStartTick; tick < endTick; tick += stepTicks) {
11749
+ const segEndTick = Math.min(tick + stepTicks, endTick);
11750
+ const segStartAudioSec = this._ticksToSeconds(tick) - startSec + clipOffsetSec;
11751
+ const segEndAudioSec = this._ticksToSeconds(segEndTick) - startSec + clipOffsetSec;
11752
+ const segStartSample = Math.round(segStartAudioSec * sr);
11753
+ const segEndSample = Math.round(segEndAudioSec * sr);
11754
+ const totalPeaks = clip.durationSamples / baseScale;
11755
+ clipSegments.push({
11756
+ peakStart: Math.max(
11757
+ 0,
11758
+ (segStartSample - clip.offsetSamples) / baseScale
11759
+ ),
11760
+ peakEnd: Math.min(
11761
+ totalPeaks,
11762
+ (segEndSample - clip.offsetSamples) / baseScale
11763
+ ),
11764
+ pixelStart: (tick - segStartTick) / this.ticksPerPixel,
11765
+ pixelEnd: (segEndTick - segStartTick) / this.ticksPerPixel
11766
+ });
11767
+ }
10773
11768
  }
10774
11769
  }
10775
- }
10776
- const channels = segmentChannels ?? peakData?.data ?? [new Int16Array(0)];
10777
- const hdrH = this.clipHeaders ? this.clipHeaderHeight : 0;
10778
- const chH = this.waveHeight;
10779
- return import_lit19.html` <div
10780
- class="clip-container"
10781
- style="left:${clipLeft}px;top:0;width:${width}px;height:${t.trackHeight}px;"
10782
- data-clip-id=${clip.id}
10783
- >
10784
- ${hdrH > 0 ? import_lit19.html`<div
10785
- class="clip-header"
10786
- data-clip-id=${clip.id}
10787
- data-track-id=${t.trackId}
10788
- ?data-interactive=${this.interactiveClips}
10789
- >
10790
- <span>${clip.name || t.descriptor?.name || ""}</span>
10791
- </div>` : ""}
10792
- ${t.descriptor?.kind === "midi" ? import_lit19.html`<daw-piano-roll
10793
- style="position:absolute;left:0;top:${hdrH}px;"
10794
- .midiNotes=${clip.midiNotes ?? []}
10795
- .length=${peakData?.length ?? width}
10796
- .waveHeight=${chH * channels.length}
10797
- .samplesPerPixel=${this._renderSpp}
10798
- .sampleRate=${this.effectiveSampleRate}
10799
- .clipOffsetSeconds=${(clip.offsetSamples ?? 0) / this.effectiveSampleRate}
10800
- .visibleStart=${this._viewport.visibleStart}
10801
- .visibleEnd=${this._viewport.visibleEnd}
10802
- .originX=${clipLeft}
10803
- ?selected=${t.trackId === this._selectedTrackId}
10804
- ></daw-piano-roll>` : t.descriptor?.renderMode === "spectrogram" ? channels.map(
10805
- (_chPeaks, chIdx) => import_lit19.html`<daw-spectrogram
10806
- style="position:absolute;left:0;top:${hdrH + chIdx * chH}px;height:${chH}px;width:${peakData?.length ?? width}px;"
10807
- .clipId=${clip.id}
10808
- .trackId=${t.trackId}
10809
- .channelIndex=${chIdx}
10810
- .length=${peakData?.length ?? width}
10811
- .waveHeight=${chH}
10812
- .samplesPerPixel=${this._renderSpp}
10813
- .sampleRate=${this.effectiveSampleRate}
10814
- .clipOffsetSeconds=${(clip.offsetSamples ?? 0) / this.effectiveSampleRate}
10815
- .visibleStart=${this._viewport.visibleStart}
10816
- .visibleEnd=${this._viewport.visibleEnd}
10817
- .originX=${clipLeft}
10818
- ></daw-spectrogram>`
10819
- ) : channels.map(
10820
- (chPeaks, chIdx) => import_lit19.html` <daw-waveform
10821
- style="position:absolute;left:0;top:${hdrH + chIdx * chH}px;"
10822
- .peaks=${chPeaks}
10823
- .length=${peakData?.length ?? width}
10824
- .waveHeight=${chH}
10825
- .barWidth=${this.barWidth}
10826
- .barGap=${this.barGap}
10827
- .roundedBars=${this.roundedBars}
10828
- .gain=${this.gainScaledWaveforms ? clip.gain ?? 1 : 1}
10829
- .visibleStart=${this._viewport.visibleStart}
10830
- .visibleEnd=${this._viewport.visibleEnd}
10831
- .originX=${clipLeft}
10832
- .segments=${clipSegments}
10833
- ></daw-waveform>`
10834
- )}
10835
- ${this.interactiveClips ? import_lit19.html` <div
10836
- class="clip-boundary"
10837
- data-boundary-edge="left"
11770
+ const channels = segmentChannels ?? peakData?.data ?? [new Int16Array(0)];
11771
+ const hdrH = this.clipHeaders ? this.clipHeaderHeight : 0;
11772
+ const chH = this.waveHeight;
11773
+ return import_lit19.html` <div
11774
+ class="clip-container"
11775
+ style="left:${clipLeft}px;top:0;width:${width}px;height:${t.trackHeight}px;"
11776
+ data-clip-id=${clip.id}
11777
+ >
11778
+ ${hdrH > 0 ? import_lit19.html`<div
11779
+ class="clip-header"
10838
11780
  data-clip-id=${clip.id}
10839
11781
  data-track-id=${t.trackId}
10840
- ></div>
10841
- <div
10842
- class="clip-boundary"
10843
- data-boundary-edge="right"
10844
- data-clip-id=${clip.id}
10845
- data-track-id=${t.trackId}
10846
- ></div>` : ""}
10847
- </div>`;
10848
- })}
10849
- ${t.loading.map((clip) => this._renderPlaceholder(clip, t))}
10850
- ${this._renderRecordingPreview(t.trackId, channelHeight)}
10851
- </div>
10852
- `;
10853
- })}
11782
+ ?data-interactive=${this.interactiveClips}
11783
+ >
11784
+ <span>${clip.name || t.descriptor?.name || ""}</span>
11785
+ </div>` : ""}
11786
+ ${t.descriptor?.kind === "midi" ? import_lit19.html`<daw-piano-roll
11787
+ style="position:absolute;left:0;top:${hdrH}px;"
11788
+ .midiNotes=${clip.midiNotes ?? []}
11789
+ .length=${peakData?.length ?? width}
11790
+ .waveHeight=${chH * channels.length}
11791
+ .samplesPerPixel=${this._renderSpp}
11792
+ .sampleRate=${this.effectiveSampleRate}
11793
+ .clipOffsetSeconds=${(clip.offsetSamples ?? 0) / this.effectiveSampleRate}
11794
+ .visibleStart=${this._viewport.visibleStart}
11795
+ .visibleEnd=${this._viewport.visibleEnd}
11796
+ .originX=${clipLeft}
11797
+ ?selected=${t.trackId === this._selectedTrackId}
11798
+ ></daw-piano-roll>` : t.descriptor?.renderMode === "spectrogram" ? channels.map(
11799
+ (_chPeaks, chIdx) => import_lit19.html`<daw-spectrogram
11800
+ style="position:absolute;left:0;top:${hdrH + chIdx * chH}px;height:${chH}px;width:${peakData?.length ?? width}px;"
11801
+ .clipId=${clip.id}
11802
+ .trackId=${t.trackId}
11803
+ .channelIndex=${chIdx}
11804
+ .length=${peakData?.length ?? width}
11805
+ .waveHeight=${chH}
11806
+ .samplesPerPixel=${this._renderSpp}
11807
+ .sampleRate=${this.effectiveSampleRate}
11808
+ .clipOffsetSeconds=${(clip.offsetSamples ?? 0) / this.effectiveSampleRate}
11809
+ .visibleStart=${this._viewport.visibleStart}
11810
+ .visibleEnd=${this._viewport.visibleEnd}
11811
+ .originX=${clipLeft}
11812
+ ></daw-spectrogram>`
11813
+ ) : channels.map(
11814
+ (chPeaks, chIdx) => import_lit19.html` <daw-waveform
11815
+ style="position:absolute;left:0;top:${hdrH + chIdx * chH}px;"
11816
+ .peaks=${chPeaks}
11817
+ .length=${peakData?.length ?? width}
11818
+ .waveHeight=${chH}
11819
+ .barWidth=${this.barWidth}
11820
+ .barGap=${this.barGap}
11821
+ .roundedBars=${this.roundedBars}
11822
+ .gain=${this.gainScaledWaveforms ? clip.gain ?? 1 : 1}
11823
+ .visibleStart=${this._viewport.visibleStart}
11824
+ .visibleEnd=${this._viewport.visibleEnd}
11825
+ .originX=${clipLeft}
11826
+ .segments=${clipSegments}
11827
+ ></daw-waveform>`
11828
+ )}
11829
+ ${this.interactiveClips ? import_lit19.html` <div
11830
+ class="clip-boundary"
11831
+ data-boundary-edge="left"
11832
+ data-clip-id=${clip.id}
11833
+ data-track-id=${t.trackId}
11834
+ ></div>
11835
+ <div
11836
+ class="clip-boundary"
11837
+ data-boundary-edge="right"
11838
+ data-clip-id=${clip.id}
11839
+ data-track-id=${t.trackId}
11840
+ ></div>` : ""}
11841
+ </div>`;
11842
+ })}
11843
+ ${t.loading.map((clip) => this._renderPlaceholder(clip, t))}
11844
+ ${this._renderRecordingPreview(t.trackId, channelHeight)}
11845
+ </div>
11846
+ `;
11847
+ }
11848
+ )}
10854
11849
  </div>
10855
11850
  </div>
10856
11851
  </div>
@@ -10861,6 +11856,10 @@ var DawEditorElement = class extends import_lit19.LitElement {
10861
11856
  DawEditorElement.styles = [
10862
11857
  hostStyles,
10863
11858
  import_lit19.css`
11859
+ /* The hidden attribute hides the element: :host sets display (modern-web-guidance custom-elements). */
11860
+ :host([hidden]) {
11861
+ display: none;
11862
+ }
10864
11863
  :host {
10865
11864
  display: flex;
10866
11865
  flex-direction: column;
@@ -11090,10 +12089,7 @@ __decorateClass([
11090
12089
  ], DawEditorElement.prototype, "_previewPeaks", 2);
11091
12090
  __decorateClass([
11092
12091
  (0, import_decorators16.state)()
11093
- ], DawEditorElement.prototype, "_tracks", 2);
11094
- __decorateClass([
11095
- (0, import_decorators16.state)()
11096
- ], DawEditorElement.prototype, "_engineTracks", 2);
12092
+ ], DawEditorElement.prototype, "_extras", 2);
11097
12093
  __decorateClass([
11098
12094
  (0, import_decorators16.state)()
11099
12095
  ], DawEditorElement.prototype, "_peaksData", 2);
@@ -11169,6 +12165,8 @@ var DawRecordButtonElement = class extends DawTransportButton {
11169
12165
  super(...arguments);
11170
12166
  this._isRecording = false;
11171
12167
  this._targetRef = null;
12168
+ /** The listeners on `_targetRef`, aborted when the target changes or the button disconnects. */
12169
+ this._targetListeners = null;
11172
12170
  this._onStart = () => {
11173
12171
  this._isRecording = true;
11174
12172
  };
@@ -11199,15 +12197,16 @@ var DawRecordButtonElement = class extends DawTransportButton {
11199
12197
  this._cleanupListeners();
11200
12198
  if (!target) return;
11201
12199
  this._targetRef = target;
11202
- target.addEventListener("daw-recording-start", this._onStart);
11203
- target.addEventListener("daw-recording-complete", this._onComplete);
11204
- target.addEventListener("daw-recording-error", this._onError);
12200
+ this._targetListeners = new AbortController();
12201
+ const { signal } = this._targetListeners;
12202
+ target.addEventListener("daw-recording-start", this._onStart, { signal });
12203
+ target.addEventListener("daw-recording-complete", this._onComplete, { signal });
12204
+ target.addEventListener("daw-recording-error", this._onError, { signal });
11205
12205
  }
11206
12206
  _cleanupListeners() {
11207
12207
  if (this._targetRef) {
11208
- this._targetRef.removeEventListener("daw-recording-start", this._onStart);
11209
- this._targetRef.removeEventListener("daw-recording-complete", this._onComplete);
11210
- this._targetRef.removeEventListener("daw-recording-error", this._onError);
12208
+ this._targetListeners?.abort();
12209
+ this._targetListeners = null;
11211
12210
  this._targetRef = null;
11212
12211
  }
11213
12212
  }
@@ -11258,7 +12257,7 @@ DawRecordButtonElement = __decorateClass([
11258
12257
  // src/elements/daw-keyboard-shortcuts.ts
11259
12258
  var import_lit22 = require("lit");
11260
12259
  var import_decorators19 = require("lit/decorators.js");
11261
- var import_core20 = require("@waveform-playlist/core");
12260
+ var import_core22 = require("@waveform-playlist/core");
11262
12261
  var DawKeyboardShortcutsElement = class extends import_lit22.LitElement {
11263
12262
  constructor() {
11264
12263
  super(...arguments);
@@ -11278,12 +12277,15 @@ var DawKeyboardShortcutsElement = class extends import_lit22.LitElement {
11278
12277
  this._customShortcuts = [];
11279
12278
  this._editor = null;
11280
12279
  this._cachedShortcuts = null;
12280
+ // --- Lifecycle ---
12281
+ /** The listeners of this connection, aborted in disconnectedCallback. */
12282
+ this._listeners = null;
11281
12283
  // --- Event handler ---
11282
12284
  this._onKeyDown = (e) => {
11283
12285
  const shortcuts = this.shortcuts;
11284
12286
  if (shortcuts.length === 0) return;
11285
12287
  try {
11286
- (0, import_core20.handleKeyboardEvent)(e, shortcuts, true);
12288
+ (0, import_core22.handleKeyboardEvent)(e, shortcuts, true);
11287
12289
  } catch (err) {
11288
12290
  console.warn("[dawcore] Keyboard shortcut failed (key=" + e.key + "): " + String(err));
11289
12291
  const target = this._editor ?? this;
@@ -11336,7 +12338,6 @@ var DawKeyboardShortcutsElement = class extends import_lit22.LitElement {
11336
12338
  updated() {
11337
12339
  this._cachedShortcuts = null;
11338
12340
  }
11339
- // --- Lifecycle ---
11340
12341
  connectedCallback() {
11341
12342
  super.connectedCallback();
11342
12343
  for (const prop of [
@@ -11357,11 +12358,15 @@ var DawKeyboardShortcutsElement = class extends import_lit22.LitElement {
11357
12358
  "[dawcore] <daw-keyboard-shortcuts> must be placed inside a <daw-editor>. Preset shortcuts (playback, splitting, undo) will be inactive; only customShortcuts will fire."
11358
12359
  );
11359
12360
  }
11360
- document.addEventListener("keydown", this._onKeyDown);
12361
+ this._listeners?.abort();
12362
+ this._listeners = new AbortController();
12363
+ const { signal } = this._listeners;
12364
+ document.addEventListener("keydown", this._onKeyDown, { signal });
11361
12365
  }
11362
12366
  disconnectedCallback() {
11363
12367
  super.disconnectedCallback();
11364
- document.removeEventListener("keydown", this._onKeyDown);
12368
+ this._listeners?.abort();
12369
+ this._listeners = null;
11365
12370
  this._editor = null;
11366
12371
  }
11367
12372
  // No shadow DOM — render-less element
@@ -11473,7 +12478,7 @@ DawKeyboardShortcutsElement = __decorateClass([
11473
12478
  // src/elements/daw-spectrogram.ts
11474
12479
  var import_lit23 = require("lit");
11475
12480
  var import_decorators20 = require("lit/decorators.js");
11476
- var import_core21 = require("@waveform-playlist/core");
12481
+ var import_core23 = require("@waveform-playlist/core");
11477
12482
  var DawSpectrogramElement = class extends import_lit23.LitElement {
11478
12483
  constructor() {
11479
12484
  super(...arguments);
@@ -11538,11 +12543,11 @@ var DawSpectrogramElement = class extends import_lit23.LitElement {
11538
12543
  this._unregisterAllCanvases();
11539
12544
  this._canvases = [];
11540
12545
  if (this.length <= 0) return;
11541
- const chunkCount = Math.ceil(this.length / import_core21.MAX_CANVAS_WIDTH);
12546
+ const chunkCount = Math.ceil(this.length / import_core23.MAX_CANVAS_WIDTH);
11542
12547
  for (let i = 0; i < chunkCount; i++) {
11543
- const widthPx = Math.min(import_core21.MAX_CANVAS_WIDTH, this.length - i * import_core21.MAX_CANVAS_WIDTH);
12548
+ const widthPx = Math.min(import_core23.MAX_CANVAS_WIDTH, this.length - i * import_core23.MAX_CANVAS_WIDTH);
11544
12549
  const canvas = document.createElement("canvas");
11545
- canvas.style.left = i * import_core21.MAX_CANVAS_WIDTH + "px";
12550
+ canvas.style.left = i * import_core23.MAX_CANVAS_WIDTH + "px";
11546
12551
  canvas.style.width = widthPx + "px";
11547
12552
  const dpr = window.devicePixelRatio || 1;
11548
12553
  canvas.width = widthPx * dpr;
@@ -11568,7 +12573,7 @@ var DawSpectrogramElement = class extends import_lit23.LitElement {
11568
12573
  }
11569
12574
  for (let i = 0; i < this._canvases.length; i++) {
11570
12575
  const canvas = this._canvases[i];
11571
- const canvasId = (0, import_core21.buildSpectrogramCanvasId)({
12576
+ const canvasId = (0, import_core23.buildSpectrogramCanvasId)({
11572
12577
  clipId: this.clipId,
11573
12578
  channelIndex: this.channelIndex,
11574
12579
  chunkIndex: i
@@ -11589,7 +12594,7 @@ var DawSpectrogramElement = class extends import_lit23.LitElement {
11589
12594
  trackId: this.trackId,
11590
12595
  channelIndex: this.channelIndex,
11591
12596
  chunkIndex: i,
11592
- globalPixelOffset: this.originX + i * import_core21.MAX_CANVAS_WIDTH,
12597
+ globalPixelOffset: this.originX + i * import_core23.MAX_CANVAS_WIDTH,
11593
12598
  widthPx: parseFloat(canvas.style.width),
11594
12599
  heightPx: this.waveHeight
11595
12600
  });
@@ -11687,20 +12692,25 @@ var DawTimeDisplayElement = class extends import_lit24.LitElement {
11687
12692
  this._format = detail.format;
11688
12693
  }
11689
12694
  };
12695
+ /** The listeners of this connection, aborted in disconnectedCallback. */
12696
+ this._listeners = null;
11690
12697
  }
11691
12698
  get target() {
11692
12699
  return resolveTransportTarget(this);
11693
12700
  }
11694
12701
  connectedCallback() {
11695
12702
  super.connectedCallback();
11696
- document.addEventListener("daw-timeupdate", this._onTimeUpdate);
11697
- document.addEventListener("daw-time-format-change", this._onFormatChange);
12703
+ this._listeners?.abort();
12704
+ this._listeners = new AbortController();
12705
+ const { signal } = this._listeners;
12706
+ document.addEventListener("daw-timeupdate", this._onTimeUpdate, { signal });
12707
+ document.addEventListener("daw-time-format-change", this._onFormatChange, { signal });
11698
12708
  requestAnimationFrame(() => this._syncFromTarget());
11699
12709
  }
11700
12710
  disconnectedCallback() {
11701
12711
  super.disconnectedCallback();
11702
- document.removeEventListener("daw-timeupdate", this._onTimeUpdate);
11703
- document.removeEventListener("daw-time-format-change", this._onFormatChange);
12712
+ this._listeners?.abort();
12713
+ this._listeners = null;
11704
12714
  }
11705
12715
  _syncFromTarget() {
11706
12716
  if (!this.isConnected) return;
@@ -11771,6 +12781,8 @@ var DawTimeFormatElement = class extends import_lit25.LitElement {
11771
12781
  warnUnsupportedOnce(this, ["setTimeFormat"]);
11772
12782
  }
11773
12783
  };
12784
+ /** The listeners of this connection, aborted in disconnectedCallback. */
12785
+ this._listeners = null;
11774
12786
  }
11775
12787
  get target() {
11776
12788
  return resolveTransportTarget(this);
@@ -11788,9 +12800,12 @@ var DawTimeFormatElement = class extends import_lit25.LitElement {
11788
12800
  }
11789
12801
  connectedCallback() {
11790
12802
  super.connectedCallback();
11791
- document.addEventListener("daw-time-format-change", this._onFormatChange);
11792
- this.addEventListener("pointerdown", this._onPointerDown);
11793
- this.addEventListener("pointerenter", this._onPointerEnter);
12803
+ this._listeners?.abort();
12804
+ this._listeners = new AbortController();
12805
+ const { signal } = this._listeners;
12806
+ document.addEventListener("daw-time-format-change", this._onFormatChange, { signal });
12807
+ this.addEventListener("pointerdown", this._onPointerDown, { signal });
12808
+ this.addEventListener("pointerenter", this._onPointerEnter, { signal });
11794
12809
  requestAnimationFrame(() => {
11795
12810
  if (!this.isConnected) return;
11796
12811
  const target = this.target;
@@ -11802,9 +12817,8 @@ var DawTimeFormatElement = class extends import_lit25.LitElement {
11802
12817
  }
11803
12818
  disconnectedCallback() {
11804
12819
  super.disconnectedCallback();
11805
- document.removeEventListener("daw-time-format-change", this._onFormatChange);
11806
- this.removeEventListener("pointerdown", this._onPointerDown);
11807
- this.removeEventListener("pointerenter", this._onPointerEnter);
12820
+ this._listeners?.abort();
12821
+ this._listeners = null;
11808
12822
  }
11809
12823
  updated() {
11810
12824
  const select = this.shadowRoot?.querySelector("select");
@@ -11859,7 +12873,7 @@ DawTimeFormatElement = __decorateClass([
11859
12873
  // src/elements/daw-player.ts
11860
12874
  var import_lit26 = require("lit");
11861
12875
  var import_decorators23 = require("lit/decorators.js");
11862
- var import_repeat = require("lit/directives/repeat.js");
12876
+ var import_repeat2 = require("lit/directives/repeat.js");
11863
12877
  var import_media_element_playout = require("@waveform-playlist/media-element-playout");
11864
12878
  var MIN_RATE = 0.25;
11865
12879
  var MAX_RATE = 4;
@@ -11889,6 +12903,8 @@ var DawPlayerElement = class extends import_lit26.LitElement {
11889
12903
  this._channelPeaks = [];
11890
12904
  this._sampleRate = 48e3;
11891
12905
  this._resizeObserver = null;
12906
+ /** The peaks fetch in flight: a newer peaks-src or a disconnect aborts it (#848, D7). */
12907
+ this._peaksFetch = null;
11892
12908
  this._onPointerDown = (e) => {
11893
12909
  const area = e.currentTarget;
11894
12910
  const width = area.clientWidth;
@@ -11962,6 +12978,7 @@ var DawPlayerElement = class extends import_lit26.LitElement {
11962
12978
  const area = this.shadowRoot?.querySelector(".waveform-area");
11963
12979
  if (area) this._resizeObserver?.observe(area);
11964
12980
  });
12981
+ if (rebuilt && this.peaksSrc && !this._peaksSettled) void this._loadPeaks();
11965
12982
  if (rebuilt && this.src) {
11966
12983
  this._loadSource();
11967
12984
  this._playhead?.setPosition(0);
@@ -11983,7 +13000,7 @@ var DawPlayerElement = class extends import_lit26.LitElement {
11983
13000
  style="height:${this.waveHeight}px"
11984
13001
  @pointerdown=${this._onPointerDown}
11985
13002
  >
11986
- ${(0, import_repeat.repeat)(
13003
+ ${(0, import_repeat2.repeat)(
11987
13004
  this._channelPeaks,
11988
13005
  (_p, i) => i,
11989
13006
  (peaks) => import_lit26.html`<daw-waveform
@@ -12006,6 +13023,8 @@ var DawPlayerElement = class extends import_lit26.LitElement {
12006
13023
  if (changed.has("mono")) this._renderWaveform();
12007
13024
  }
12008
13025
  async _loadPeaks() {
13026
+ this._peaksFetch?.abort();
13027
+ this._peaksFetch = null;
12009
13028
  this._waveformData = null;
12010
13029
  this._readyDispatched = false;
12011
13030
  this._peaksSettled = false;
@@ -12016,8 +13035,11 @@ var DawPlayerElement = class extends import_lit26.LitElement {
12016
13035
  return;
12017
13036
  }
12018
13037
  const requested = this.peaksSrc;
13038
+ const fetching = new AbortController();
13039
+ this._peaksFetch = fetching;
12019
13040
  try {
12020
- const wd = await loadWaveformDataFromUrl(requested);
13041
+ const wd = await loadWaveformDataFromUrl(requested, fetching.signal);
13042
+ if (this._peaksFetch === fetching) this._peaksFetch = null;
12021
13043
  if (this.peaksSrc !== requested) return;
12022
13044
  this._waveformData = wd;
12023
13045
  this._sampleRate = wd.sample_rate;
@@ -12025,6 +13047,7 @@ var DawPlayerElement = class extends import_lit26.LitElement {
12025
13047
  this._renderWaveform();
12026
13048
  this._maybeDispatchReady();
12027
13049
  } catch (err) {
13050
+ if (fetching.signal.aborted) return;
12028
13051
  if (this.peaksSrc !== requested) return;
12029
13052
  console.warn("[dawcore] <daw-player> failed to load peaks-src: " + String(err));
12030
13053
  this._peaksSettled = true;
@@ -12124,6 +13147,8 @@ var DawPlayerElement = class extends import_lit26.LitElement {
12124
13147
  this._engine.off("error", this._onError);
12125
13148
  this._engine.dispose();
12126
13149
  this._engineDisposed = true;
13150
+ this._peaksFetch?.abort();
13151
+ this._peaksFetch = null;
12127
13152
  }
12128
13153
  // --- Private event handlers (arrow fields for stable identity) ---
12129
13154
  _dispatch(name, detail) {
@@ -12150,6 +13175,10 @@ var DawPlayerElement = class extends import_lit26.LitElement {
12150
13175
  }
12151
13176
  };
12152
13177
  DawPlayerElement.styles = import_lit26.css`
13178
+ /* The hidden attribute hides the element: :host sets display (modern-web-guidance custom-elements). */
13179
+ :host([hidden]) {
13180
+ display: none;
13181
+ }
12153
13182
  :host {
12154
13183
  display: block;
12155
13184
  position: relative;