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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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"));
@@ -2803,10 +3027,9 @@ function computeTemporalTicks(samplesPerPixel, sampleRate, duration, rulerHeight
2803
3027
  const { marker, bigStep, smallStep } = config;
2804
3028
  const canvasInfo = /* @__PURE__ */ new Map();
2805
3029
  const labels = [];
2806
- const pixPerSec = sampleRate / samplesPerPixel;
2807
3030
  for (let counter = 0; ; counter += smallStep) {
2808
- const pix = Math.floor(counter / 1e3 * pixPerSec);
2809
- if (pix >= widthX) break;
3031
+ const pix = Math.floor(counter * sampleRate / (1e3 * samplesPerPixel));
3032
+ if (!(pix < widthX)) break;
2810
3033
  if (counter % marker === 0) {
2811
3034
  canvasInfo.set(pix, rulerHeight);
2812
3035
  labels.push({ pix, text: formatTime(counter) });
@@ -3026,7 +3249,7 @@ DawRulerElement = __decorateClass([
3026
3249
  ], DawRulerElement);
3027
3250
 
3028
3251
  // src/elements/daw-editor.ts
3029
- var import_engine = require("@waveform-playlist/engine");
3252
+ var import_engine3 = require("@waveform-playlist/engine");
3030
3253
 
3031
3254
  // src/utils/track-mix.ts
3032
3255
  var DEFAULT_TRACK_MIX = Object.freeze({
@@ -3041,15 +3264,6 @@ function mixOfTrack(track) {
3041
3264
  function mixOfElement(el) {
3042
3265
  return { volume: el.volume, pan: el.pan, muted: el.muted, soloed: el.soloed };
3043
3266
  }
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
3267
  function clampNumber(value, min, max) {
3054
3268
  return Math.max(min, Math.min(max, Number(value)));
3055
3269
  }
@@ -3260,6 +3474,10 @@ var DawTrackControlsElement = class extends import_lit15.LitElement {
3260
3474
  }
3261
3475
  };
3262
3476
  DawTrackControlsElement.styles = import_lit15.css`
3477
+ /* The hidden attribute hides the element: :host sets display (modern-web-guidance custom-elements). */
3478
+ :host([hidden]) {
3479
+ display: none;
3480
+ }
3263
3481
  :host {
3264
3482
  display: flex;
3265
3483
  flex-direction: column;
@@ -3721,6 +3939,8 @@ var ViewportController = class {
3721
3939
  this._scrollContainer = null;
3722
3940
  this._lastScrollLeft = 0;
3723
3941
  this._resizeObserver = null;
3942
+ /** The scroll listener on `_scrollContainer`, aborted when it is replaced or the host disconnects. */
3943
+ this._scrollListener = null;
3724
3944
  // Permissive defaults: render everything until scroll container is attached
3725
3945
  this.visibleStart = -Infinity;
3726
3946
  this.visibleEnd = Infinity;
@@ -3752,16 +3972,21 @@ var ViewportController = class {
3752
3972
  });
3753
3973
  }
3754
3974
  hostDisconnected() {
3755
- this._scrollContainer?.removeEventListener("scroll", this._onScroll);
3975
+ this._scrollListener?.abort();
3976
+ this._scrollListener = null;
3756
3977
  this._resizeObserver?.disconnect();
3757
3978
  this._resizeObserver = null;
3758
3979
  this._scrollContainer = null;
3759
3980
  }
3760
3981
  _attachScrollContainer(container) {
3761
- this._scrollContainer?.removeEventListener("scroll", this._onScroll);
3982
+ this._scrollListener?.abort();
3762
3983
  this._resizeObserver?.disconnect();
3763
3984
  this._scrollContainer = container;
3764
- container.addEventListener("scroll", this._onScroll, { passive: true });
3985
+ this._scrollListener = new AbortController();
3986
+ container.addEventListener("scroll", this._onScroll, {
3987
+ passive: true,
3988
+ signal: this._scrollListener.signal
3989
+ });
3765
3990
  this._update(container.scrollLeft, container.clientWidth);
3766
3991
  if (typeof ResizeObserver !== "undefined") {
3767
3992
  this._resizeObserver = new ResizeObserver(() => {
@@ -3788,9 +4013,11 @@ var ViewportController = class {
3788
4013
  var AudioResumeController = class {
3789
4014
  constructor(host) {
3790
4015
  this._target = null;
4016
+ /** The gesture listeners on `_target`: one controller per attach. */
4017
+ this._listeners = null;
3791
4018
  this._attached = false;
3792
4019
  this._generation = 0;
3793
- this._onGesture = (e) => {
4020
+ this._onGesture = () => {
3794
4021
  let ctx;
3795
4022
  try {
3796
4023
  ctx = this._host.audioContext;
@@ -3814,11 +4041,7 @@ var AudioResumeController = class {
3814
4041
  );
3815
4042
  });
3816
4043
  }
3817
- const otherType = e.type === "pointerdown" ? "keydown" : "pointerdown";
3818
- this._target?.removeEventListener(otherType, this._onGesture, {
3819
- capture: true
3820
- });
3821
- this._target = null;
4044
+ this._removeListeners();
3822
4045
  };
3823
4046
  this._host = host;
3824
4047
  host.addController(this);
@@ -3840,13 +4063,17 @@ var AudioResumeController = class {
3840
4063
  if (!resolvedTarget) return;
3841
4064
  this._target = resolvedTarget;
3842
4065
  this._attached = true;
4066
+ this._listeners = new AbortController();
4067
+ const { signal } = this._listeners;
3843
4068
  resolvedTarget.addEventListener("pointerdown", this._onGesture, {
3844
4069
  once: true,
3845
- capture: true
4070
+ capture: true,
4071
+ signal
3846
4072
  });
3847
4073
  resolvedTarget.addEventListener("keydown", this._onGesture, {
3848
4074
  once: true,
3849
- capture: true
4075
+ capture: true,
4076
+ signal
3850
4077
  });
3851
4078
  });
3852
4079
  }
@@ -3870,12 +4097,8 @@ var AudioResumeController = class {
3870
4097
  }
3871
4098
  _removeListeners() {
3872
4099
  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
- });
4100
+ this._listeners?.abort();
4101
+ this._listeners = null;
3879
4102
  this._target = null;
3880
4103
  }
3881
4104
  };
@@ -3894,6 +4117,8 @@ var import_core6 = require("@waveform-playlist/core");
3894
4117
  var RecordingController = class {
3895
4118
  constructor(host) {
3896
4119
  this._sessions = /* @__PURE__ */ new Map();
4120
+ /** Each session's mic-unplug listener, aborted when the session ends. */
4121
+ this._trackEndedListeners = /* @__PURE__ */ new WeakMap();
3897
4122
  /** Track IDs with a startRecording in flight (session not yet in _sessions).
3898
4123
  * The session is only set after several awaits — without this, two rapid
3899
4124
  * start calls both pass the _sessions guard and build two capture
@@ -4022,8 +4247,6 @@ var RecordingController = class {
4022
4247
  latencySamples,
4023
4248
  clipName: options.clipName,
4024
4249
  wasOverdub: options.overdub ?? false,
4025
- _onTrackEnded: onTrackEnded,
4026
- _audioTrack: audioTrack,
4027
4250
  stopAckResolve: null,
4028
4251
  stopPromise: null,
4029
4252
  stopping: false
@@ -4035,7 +4258,9 @@ var RecordingController = class {
4035
4258
  source.connect(workletNode);
4036
4259
  workletNode.port.postMessage({ command: "start", channelCount });
4037
4260
  if (audioTrack && onTrackEnded) {
4038
- audioTrack.addEventListener("ended", onTrackEnded);
4261
+ const listener = new AbortController();
4262
+ this._trackEndedListeners.set(session, listener);
4263
+ audioTrack.addEventListener("ended", onTrackEnded, { signal: listener.signal });
4039
4264
  }
4040
4265
  this._host._engine?.setTrackRecording(trackId, true);
4041
4266
  this._host.dispatchEvent(
@@ -4297,9 +4522,8 @@ var RecordingController = class {
4297
4522
  }
4298
4523
  }
4299
4524
  _removeTrackEndedListener(session) {
4300
- if (session._audioTrack && session._onTrackEnded) {
4301
- session._audioTrack.removeEventListener("ended", session._onTrackEnded);
4302
- }
4525
+ this._trackEndedListeners.get(session)?.abort();
4526
+ this._trackEndedListeners.delete(session);
4303
4527
  }
4304
4528
  _dispatchRecordingError(trackId, error) {
4305
4529
  this._host.dispatchEvent(
@@ -4371,6 +4595,8 @@ var AnnotationController = class {
4371
4595
  * Driven by daw-timeupdate, cleared on daw-stop, retained on pause.
4372
4596
  * Replaced immutably (a fresh Map) on every change. */
4373
4597
  this._playingIds = /* @__PURE__ */ new Map();
4598
+ /** The host listeners of this connection, aborted in hostDisconnected. */
4599
+ this._listeners = null;
4374
4600
  this._onDataChange = () => {
4375
4601
  this.deriveSecondsCaches();
4376
4602
  this._host.requestUpdate();
@@ -4422,11 +4648,14 @@ var AnnotationController = class {
4422
4648
  );
4423
4649
  }
4424
4650
  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);
4651
+ this._listeners?.abort();
4652
+ this._listeners = new AbortController();
4653
+ const { signal } = this._listeners;
4654
+ this._host.addEventListener("daw-annotation-update", this._onDataChange, { signal });
4655
+ this._host.addEventListener("daw-annotation-select", this._onDataChange, { signal });
4656
+ this._host.addEventListener("daw-annotation-connected", this._onDataChange, { signal });
4657
+ this._host.addEventListener("daw-timeupdate", this._onTimeUpdate, { signal });
4658
+ this._host.addEventListener("daw-stop", this._onStop, { signal });
4430
4659
  this._removalObserver = new MutationObserver((mutations) => {
4431
4660
  let changed = false;
4432
4661
  for (const m of mutations) {
@@ -4456,11 +4685,8 @@ var AnnotationController = class {
4456
4685
  this._removalObserver.observe(this._host, { childList: true, subtree: true });
4457
4686
  }
4458
4687
  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);
4688
+ this._listeners?.abort();
4689
+ this._listeners = null;
4464
4690
  this._removalObserver?.disconnect();
4465
4691
  this._removalObserver = null;
4466
4692
  this._tracks = [];
@@ -4685,6 +4911,8 @@ var PointerHandler = class {
4685
4911
  // still holds; zeroing only the host would desync the two).
4686
4912
  this._preDragSelectionStart = 0;
4687
4913
  this._preDragSelectionEnd = 0;
4914
+ /** The timeline's listeners of the seek / selection press in progress. */
4915
+ this._seekGesture = null;
4688
4916
  /** Cancels the armed clip drag; set while one is armed (#848). */
4689
4917
  this._cancelArmedClipDrag = null;
4690
4918
  this.onPointerDown = (e) => {
@@ -4701,11 +4929,10 @@ var PointerHandler = class {
4701
4929
  console.warn("[dawcore] setPointerCapture failed: " + String(err));
4702
4930
  }
4703
4931
  const onMove = (me) => clipHandler.onPointerMove(me);
4932
+ const gesture = new AbortController();
4704
4933
  const detach = (pointerId) => {
4705
4934
  this._cancelArmedClipDrag = null;
4706
- this._timeline?.removeEventListener("pointermove", onMove);
4707
- this._timeline?.removeEventListener("pointerup", onUp);
4708
- this._timeline?.removeEventListener("pointercancel", onCancel);
4935
+ gesture.abort();
4709
4936
  try {
4710
4937
  this._timeline?.releasePointerCapture(pointerId);
4711
4938
  } catch (err) {
@@ -4731,9 +4958,10 @@ var PointerHandler = class {
4731
4958
  );
4732
4959
  detach(downPointerId);
4733
4960
  };
4734
- this._timeline.addEventListener("pointermove", onMove);
4735
- this._timeline.addEventListener("pointerup", onUp);
4736
- this._timeline.addEventListener("pointercancel", onCancel);
4961
+ const { signal: signal2 } = gesture;
4962
+ this._timeline.addEventListener("pointermove", onMove, { signal: signal2 });
4963
+ this._timeline.addEventListener("pointerup", onUp, { signal: signal2 });
4964
+ this._timeline.addEventListener("pointercancel", onCancel, { signal: signal2 });
4737
4965
  }
4738
4966
  return;
4739
4967
  }
@@ -4756,9 +4984,12 @@ var PointerHandler = class {
4756
4984
  } catch (err) {
4757
4985
  console.warn("[dawcore] setPointerCapture failed: " + String(err));
4758
4986
  }
4759
- this._timeline.addEventListener("pointermove", this._onPointerMove);
4760
- this._timeline.addEventListener("pointerup", this._onPointerUp);
4761
- this._timeline.addEventListener("pointercancel", this._onPointerCancel);
4987
+ this._seekGesture?.abort();
4988
+ this._seekGesture = new AbortController();
4989
+ const { signal } = this._seekGesture;
4990
+ this._timeline.addEventListener("pointermove", this._onPointerMove, { signal });
4991
+ this._timeline.addEventListener("pointerup", this._onPointerUp, { signal });
4992
+ this._timeline.addEventListener("pointercancel", this._onPointerCancel, { signal });
4762
4993
  };
4763
4994
  this._onPointerMove = (e) => {
4764
4995
  if (!this._timeline) return;
@@ -4865,9 +5096,8 @@ var PointerHandler = class {
4865
5096
  "[dawcore] releasePointerCapture failed (may already be released): " + String(err)
4866
5097
  );
4867
5098
  }
4868
- this._timeline.removeEventListener("pointermove", this._onPointerMove);
4869
- this._timeline.removeEventListener("pointerup", this._onPointerUp);
4870
- this._timeline.removeEventListener("pointercancel", this._onPointerCancel);
5099
+ this._seekGesture?.abort();
5100
+ this._seekGesture = null;
4871
5101
  }
4872
5102
  _resetInteractionState() {
4873
5103
  this._isDragging = false;
@@ -4963,6 +5193,7 @@ var PointerHandler = class {
4963
5193
 
4964
5194
  // src/interactions/clip-pointer-handler.ts
4965
5195
  var import_core9 = require("@waveform-playlist/core");
5196
+ var import_engine = require("@waveform-playlist/engine");
4966
5197
  var ClipPointerHandler = class {
4967
5198
  constructor(host) {
4968
5199
  this._mode = null;
@@ -4979,6 +5210,10 @@ var ClipPointerHandler = class {
4979
5210
  this._originalOffsetSamples = 0;
4980
5211
  this._originalDurationSamples = 0;
4981
5212
  this._originalStartSample = 0;
5213
+ // Move: the dragged clip and the track's loaded clips, sorted, at drag start
5214
+ this._moveClip = null;
5215
+ this._moveSorted = [];
5216
+ this._committing = false;
4982
5217
  this._host = host;
4983
5218
  }
4984
5219
  /**
@@ -5003,6 +5238,18 @@ var ClipPointerHandler = class {
5003
5238
  }
5004
5239
  return Math.round(totalDeltaPx * h.renderSamplesPerPixel);
5005
5240
  }
5241
+ /** A sample delta from `anchorSample` in pixels: in tick space in beats mode,
5242
+ * so the drawn position does not drift from the sample round-trip. */
5243
+ _samplesToPx(anchorSample, deltaSamples) {
5244
+ const h = this._host;
5245
+ if (h.scaleMode === "beats") {
5246
+ const anchorSec = anchorSample / h.effectiveSampleRate;
5247
+ const anchorTick = h._secondsToTicks(anchorSec);
5248
+ const newTick = h._secondsToTicks(anchorSec + deltaSamples / h.effectiveSampleRate);
5249
+ return Math.round((newTick - anchorTick) / h.ticksPerPixel);
5250
+ }
5251
+ return Math.round(deltaSamples / h.renderSamplesPerPixel);
5252
+ }
5006
5253
  /** Returns true if a drag interaction is currently in progress. */
5007
5254
  get isActive() {
5008
5255
  return this._mode !== null;
@@ -5012,6 +5259,21 @@ var ClipPointerHandler = class {
5012
5259
  get isDragging() {
5013
5260
  return this._isDragging;
5014
5261
  }
5262
+ /**
5263
+ * The clip being dragged (past the threshold) with its bounds at the drag's
5264
+ * start, or null; null too while the release makes its one arrangement
5265
+ * call, so that call is not taken for an outside change (#848).
5266
+ */
5267
+ get draggedClip() {
5268
+ if (!this._isDragging || this._committing) return null;
5269
+ return {
5270
+ trackId: this._trackId,
5271
+ clipId: this._clipId,
5272
+ startSample: this._originalStartSample,
5273
+ durationSamples: this._originalDurationSamples,
5274
+ offsetSamples: this._originalOffsetSamples
5275
+ };
5276
+ }
5015
5277
  /**
5016
5278
  * Attempts to handle a pointerdown event on the given target element.
5017
5279
  * Returns true if the target is a recognized clip interaction element.
@@ -5049,11 +5311,10 @@ var ClipPointerHandler = class {
5049
5311
  }
5050
5312
  /**
5051
5313
  * 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.
5314
+ * clip's bounds now, not at the press, so a drag after an undo made during
5315
+ * the press starts from the clip as the undo left it (#848, review of
5316
+ * #915). Returns false when the clip is gone (the undo removed it): the
5317
+ * press is dropped.
5057
5318
  */
5058
5319
  _startDrag() {
5059
5320
  const engine = this._host.engine;
@@ -5065,13 +5326,17 @@ var ClipPointerHandler = class {
5065
5326
  this._originalStartSample = bounds.startSample;
5066
5327
  this._originalOffsetSamples = bounds.offsetSamples;
5067
5328
  this._originalDurationSamples = bounds.durationSamples;
5068
- engine.beginTransaction();
5329
+ if (this._mode === "move") {
5330
+ const track = engine.getState().tracks.find((t) => t.id === trackId);
5331
+ const clip = track?.clips.find((c) => c.id === clipId) ?? null;
5332
+ if (!track || !clip) return false;
5333
+ this._moveClip = clip;
5334
+ this._moveSorted = [...track.clips].sort((a, b) => a.startSample - b.startSample);
5335
+ }
5069
5336
  } else {
5070
- console.warn(
5071
- "[dawcore] drag start: engine unavailable, drag mutations will not be grouped for undo"
5072
- );
5337
+ console.warn("[dawcore] drag start: engine unavailable, the drag will not be applied");
5073
5338
  }
5074
- if (this._mode === "trim-left" || this._mode === "trim-right") {
5339
+ {
5075
5340
  const container = this._host.shadowRoot?.querySelector(
5076
5341
  `.clip-container[data-clip-id="${clipId}"]`
5077
5342
  );
@@ -5080,7 +5345,7 @@ var ClipPointerHandler = class {
5080
5345
  this._originalLeft = parseFloat(container.style.left) || 0;
5081
5346
  this._originalWidth = parseFloat(container.style.width) || 0;
5082
5347
  } else {
5083
- console.warn("[dawcore] clip container not found for trim visual feedback: " + clipId);
5348
+ console.warn("[dawcore] clip container not found for drag visual feedback: " + clipId);
5084
5349
  }
5085
5350
  }
5086
5351
  return true;
@@ -5104,10 +5369,13 @@ var ClipPointerHandler = class {
5104
5369
  if (!engine) return;
5105
5370
  if (this._mode === "move") {
5106
5371
  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;
5372
+ const clip = this._moveClip;
5373
+ const index = clip ? this._moveSorted.indexOf(clip) : -1;
5374
+ const delta = clip && index !== -1 ? (0, import_engine.constrainClipDrag)(clip, totalSnappedDelta, this._moveSorted, index) : totalSnappedDelta;
5375
+ this._cumulativeDeltaSamples = delta;
5376
+ if (this._clipContainer) {
5377
+ const deltaPx = this._samplesToPx(this._originalStartSample, delta);
5378
+ this._clipContainer.style.left = this._originalLeft + deltaPx + "px";
5111
5379
  }
5112
5380
  } else {
5113
5381
  const boundary = this._mode === "trim-left" ? "left" : "right";
@@ -5119,17 +5387,7 @@ var ClipPointerHandler = class {
5119
5387
  boundary,
5120
5388
  rawDeltaSamples
5121
5389
  );
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
- }
5390
+ const deltaPx = this._samplesToPx(anchor, deltaSamples);
5133
5391
  this._cumulativeDeltaSamples = deltaSamples;
5134
5392
  if (this._clipContainer) {
5135
5393
  if (this._mode === "trim-left") {
@@ -5168,31 +5426,39 @@ var ClipPointerHandler = class {
5168
5426
  if (this._mode === null) return;
5169
5427
  try {
5170
5428
  if (!this._isDragging || this._cumulativeDeltaSamples === 0) {
5171
- this._restoreTrimVisual();
5429
+ this._restoreVisual();
5172
5430
  return;
5173
5431
  }
5174
5432
  const engine = this._host.engine;
5433
+ this._committing = true;
5175
5434
  if (this._mode === "move") {
5435
+ this._restoreVisual();
5176
5436
  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
- })
5437
+ const applied = engine.moveClip(
5438
+ this._trackId,
5439
+ this._clipId,
5440
+ this._cumulativeDeltaSamples
5188
5441
  );
5442
+ if (applied !== 0) {
5443
+ this._host.dispatchEvent(
5444
+ new CustomEvent("daw-clip-move", {
5445
+ bubbles: true,
5446
+ composed: true,
5447
+ detail: {
5448
+ trackId: this._trackId,
5449
+ clipId: this._clipId,
5450
+ deltaSamples: applied
5451
+ }
5452
+ })
5453
+ );
5454
+ }
5189
5455
  } else {
5190
5456
  console.warn(
5191
- "[dawcore] engine unavailable at move drop \u2014 audio may be out of sync for track " + this._trackId
5457
+ "[dawcore] engine unavailable at move drop \u2014 move not applied for clip " + this._clipId
5192
5458
  );
5193
5459
  }
5194
5460
  } else {
5195
- this._restoreTrimVisual();
5461
+ this._restoreVisual();
5196
5462
  const boundary = this._mode === "trim-left" ? "left" : "right";
5197
5463
  if (engine) {
5198
5464
  engine.trimClip(this._trackId, this._clipId, boundary, this._cumulativeDeltaSamples);
@@ -5215,13 +5481,7 @@ var ClipPointerHandler = class {
5215
5481
  }
5216
5482
  }
5217
5483
  } finally {
5218
- if (this._isDragging) {
5219
- if (this._cumulativeDeltaSamples !== 0) {
5220
- this._host.engine?.commitTransaction();
5221
- } else {
5222
- this._host.engine?.abortTransaction();
5223
- }
5224
- }
5484
+ this._committing = false;
5225
5485
  this._reset();
5226
5486
  }
5227
5487
  }
@@ -5229,16 +5489,13 @@ var ClipPointerHandler = class {
5229
5489
  *
5230
5490
  * pointercancel fires INSTEAD of pointerup on touch interruption, pen
5231
5491
  * 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). */
5492
+ * armed (hover keeps moving the clip). The drag wrote nothing to the
5493
+ * arrangement, so reverting is putting the view back. */
5236
5494
  onPointerCancel(_e) {
5237
5495
  if (this._mode === null) return;
5238
5496
  try {
5239
- this._restoreTrimVisual();
5497
+ this._restoreVisual();
5240
5498
  } finally {
5241
- if (this._isDragging) this._host.engine?.abortTransaction();
5242
5499
  this._reset();
5243
5500
  }
5244
5501
  }
@@ -5260,11 +5517,11 @@ var ClipPointerHandler = class {
5260
5517
  return true;
5261
5518
  }
5262
5519
  /** Restore clip container CSS AND waveform peaks to original values after
5263
- * a trim visual preview. Peaks matter: the drag wrote re-extracted peak
5520
+ * a drag's visual preview. Peaks matter: a trim wrote re-extracted peak
5264
5521
  * arrays imperatively onto the <daw-waveform> elements (bypassing Lit), and
5265
- * a cancelled/zero-delta trim makes no engine mutation — so no statechange
5522
+ * a cancelled/zero-delta drag makes no engine mutation — so no statechange
5266
5523
  * re-render will ever repair them. */
5267
- _restoreTrimVisual() {
5524
+ _restoreVisual() {
5268
5525
  if (this._clipContainer) {
5269
5526
  this._clipContainer.style.left = this._originalLeft + "px";
5270
5527
  this._clipContainer.style.width = this._originalWidth + "px";
@@ -5292,6 +5549,8 @@ var ClipPointerHandler = class {
5292
5549
  this._originalOffsetSamples = 0;
5293
5550
  this._originalDurationSamples = 0;
5294
5551
  this._originalStartSample = 0;
5552
+ this._moveClip = null;
5553
+ this._moveSorted = [];
5295
5554
  }
5296
5555
  };
5297
5556
 
@@ -5322,9 +5581,12 @@ var AnnotationDragHandler = class {
5322
5581
  if (index === -1) return;
5323
5582
  const edge = isBoundary ? boundary.getAttribute("data-edge") : null;
5324
5583
  const captureEl = isBoundary ? boundary : box;
5584
+ this._drag?.listeners.abort();
5585
+ const listeners = new AbortController();
5325
5586
  this._drag = {
5326
5587
  track,
5327
5588
  captureEl,
5589
+ listeners,
5328
5590
  pointerId: e.pointerId,
5329
5591
  startClientX: e.clientX,
5330
5592
  moved: false,
@@ -5339,9 +5601,10 @@ var AnnotationDragHandler = class {
5339
5601
  captureEl.setPointerCapture(e.pointerId);
5340
5602
  } catch {
5341
5603
  }
5342
- captureEl.addEventListener("pointermove", this._onPointerMove);
5343
- captureEl.addEventListener("pointerup", this._onPointerUp);
5344
- captureEl.addEventListener("pointercancel", this._onPointerCancel);
5604
+ const { signal } = listeners;
5605
+ captureEl.addEventListener("pointermove", this._onPointerMove, { signal });
5606
+ captureEl.addEventListener("pointerup", this._onPointerUp, { signal });
5607
+ captureEl.addEventListener("pointercancel", this._onPointerCancel, { signal });
5345
5608
  };
5346
5609
  /** Non-private (underscore convention) so tests can drive moves directly. */
5347
5610
  this._onPointerMove = (e) => {
@@ -5446,9 +5709,7 @@ var AnnotationDragHandler = class {
5446
5709
  drag.captureEl.releasePointerCapture(drag.pointerId);
5447
5710
  } catch {
5448
5711
  }
5449
- drag.captureEl.removeEventListener("pointermove", this._onPointerMove);
5450
- drag.captureEl.removeEventListener("pointerup", this._onPointerUp);
5451
- drag.captureEl.removeEventListener("pointercancel", this._onPointerCancel);
5712
+ drag.listeners.abort();
5452
5713
  this._drag = null;
5453
5714
  }
5454
5715
  };
@@ -5465,6 +5726,8 @@ var TrackReorderHandler = class _TrackReorderHandler {
5465
5726
  this._fromIndex = 0;
5466
5727
  this._targetIndex = 0;
5467
5728
  this._gripEl = null;
5729
+ /** The grip's listeners of the drag in progress: one controller per drag. */
5730
+ this._gesture = null;
5468
5731
  this.onGrab = (trackId, e, gripEl) => {
5469
5732
  if (this._trackId !== null) return;
5470
5733
  const column = this._host.shadowRoot?.querySelector(".controls-column");
@@ -5514,9 +5777,11 @@ var TrackReorderHandler = class _TrackReorderHandler {
5514
5777
  gripEl.setPointerCapture(e.pointerId);
5515
5778
  } catch {
5516
5779
  }
5517
- gripEl.addEventListener("pointermove", this._onPointerMove);
5518
- gripEl.addEventListener("pointerup", this._onPointerUp);
5519
- gripEl.addEventListener("pointercancel", this._onPointerCancel);
5780
+ this._gesture = new AbortController();
5781
+ const { signal } = this._gesture;
5782
+ gripEl.addEventListener("pointermove", this._onPointerMove, { signal });
5783
+ gripEl.addEventListener("pointerup", this._onPointerUp, { signal });
5784
+ gripEl.addEventListener("pointercancel", this._onPointerCancel, { signal });
5520
5785
  };
5521
5786
  this._onPointerMove = (e) => {
5522
5787
  if (e.pointerId !== this._pointerId || this._trackId === null) return;
@@ -5586,6 +5851,11 @@ var TrackReorderHandler = class _TrackReorderHandler {
5586
5851
  static _reducedMotion() {
5587
5852
  return typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
5588
5853
  }
5854
+ /** The dragged track and the order of the rows at the grab (#848), or null. */
5855
+ get draggedTrack() {
5856
+ if (this._trackId === null) return null;
5857
+ return { trackId: this._trackId, order: this._rows.map((r) => r.trackId) };
5858
+ }
5589
5859
  /** True from the grab until the drag ends or is cancelled. */
5590
5860
  get isActive() {
5591
5861
  return this._trackId !== null;
@@ -5615,9 +5885,8 @@ var TrackReorderHandler = class _TrackReorderHandler {
5615
5885
  this._lanes = [];
5616
5886
  const grip = this._gripEl;
5617
5887
  if (grip) {
5618
- grip.removeEventListener("pointermove", this._onPointerMove);
5619
- grip.removeEventListener("pointerup", this._onPointerUp);
5620
- grip.removeEventListener("pointercancel", this._onPointerCancel);
5888
+ this._gesture?.abort();
5889
+ this._gesture = null;
5621
5890
  try {
5622
5891
  grip.releasePointerCapture(this._pointerId);
5623
5892
  } catch {
@@ -5681,13 +5950,66 @@ function parseDisplayTime(value, format) {
5681
5950
  return Math.max(0, seconds);
5682
5951
  }
5683
5952
 
5953
+ // src/interactions/abort.ts
5954
+ function abortError(message) {
5955
+ return new DOMException(message, "AbortError");
5956
+ }
5957
+ function isAbortError(error) {
5958
+ return error?.name === "AbortError";
5959
+ }
5960
+ function reasonOf(signal) {
5961
+ return signal.reason;
5962
+ }
5963
+ var PlaySignals = class {
5964
+ constructor() {
5965
+ this._controllers = /* @__PURE__ */ new WeakMap();
5966
+ }
5967
+ /** The signal of an arrangement: aborted when it is next swapped out. */
5968
+ signalOf(arrangement) {
5969
+ let controller = this._controllers.get(arrangement);
5970
+ if (!controller) {
5971
+ controller = new AbortController();
5972
+ this._controllers.set(arrangement, controller);
5973
+ }
5974
+ return controller.signal;
5975
+ }
5976
+ /** The arrangement leaves play: its waits end with `reason`; a later play gets a new signal. */
5977
+ swappedOut(arrangement, reason) {
5978
+ const controller = this._controllers.get(arrangement);
5979
+ this._controllers.delete(arrangement);
5980
+ controller?.abort(reason);
5981
+ }
5982
+ };
5983
+ function untilAborted(promise, signal) {
5984
+ if (!signal) return promise;
5985
+ if (signal.aborted) return Promise.reject(reasonOf(signal));
5986
+ return new Promise((resolve, reject) => {
5987
+ const done = new AbortController();
5988
+ signal.addEventListener("abort", () => reject(reasonOf(signal)), { signal: done.signal });
5989
+ promise.then(
5990
+ (value) => {
5991
+ done.abort();
5992
+ resolve(value);
5993
+ },
5994
+ (error) => {
5995
+ done.abort();
5996
+ reject(error);
5997
+ }
5998
+ );
5999
+ });
6000
+ }
6001
+
5684
6002
  // src/interactions/file-loader.ts
5685
- async function loadFiles(host, files) {
6003
+ async function loadFiles(host, files, options = {}) {
6004
+ const signal = options.signal;
6005
+ if (signal?.aborted) throw reasonOf(signal);
5686
6006
  if (!files) {
5687
6007
  console.warn("[dawcore] loadFiles called with null/undefined");
5688
6008
  return { loaded: [], failed: [] };
5689
6009
  }
5690
6010
  const fileArray = Array.from(files);
6011
+ const target = host.arrangement;
6012
+ const played = host._operationSignal();
5691
6013
  const loaded = [];
5692
6014
  const failed = [];
5693
6015
  const dispatchLoadError = (file, error) => {
@@ -5707,6 +6029,10 @@ async function loadFiles(host, files) {
5707
6029
  dispatchLoadError(file, new Error("<daw-editor> was disconnected"));
5708
6030
  continue;
5709
6031
  }
6032
+ if (played.aborted) {
6033
+ dispatchLoadError(file, reasonOf(played));
6034
+ continue;
6035
+ }
5710
6036
  if (file.type && !file.type.startsWith("audio/")) {
5711
6037
  const error = new Error("Non-audio MIME type: " + file.type);
5712
6038
  console.warn("[dawcore] Skipping non-audio file: " + file.name + " (" + file.type + ")");
@@ -5715,12 +6041,26 @@ async function loadFiles(host, files) {
5715
6041
  }
5716
6042
  let trackId = null;
5717
6043
  try {
5718
- trackId = await host._addDroppedFile(file);
5719
- await host._whenTrackLoaded(trackId);
6044
+ const adding = host._addDroppedFile(file);
6045
+ trackId = await untilAborted(adding, signal).catch((err) => {
6046
+ if (signal?.aborted)
6047
+ void adding.then(
6048
+ (id) => host._discardTrack(id, target),
6049
+ () => {
6050
+ }
6051
+ );
6052
+ throw err;
6053
+ });
6054
+ await untilAborted(host._whenTrackLoaded(trackId), signal);
5720
6055
  loaded.push(trackId);
5721
6056
  } catch (err) {
6057
+ if (signal?.aborted) {
6058
+ for (const id of [...loaded, ...trackId !== null ? [trackId] : []])
6059
+ host._discardTrack(id, target);
6060
+ throw reasonOf(signal);
6061
+ }
5722
6062
  console.warn("[dawcore] Failed to load file: " + file.name + " \u2014 " + String(err));
5723
- if (trackId !== null) host._discardTrack(trackId);
6063
+ if (trackId !== null) host._discardTrack(trackId, target);
5724
6064
  dispatchLoadError(file, err);
5725
6065
  }
5726
6066
  }
@@ -5736,6 +6076,9 @@ async function loadMidiImpl(host, source, options = {}) {
5736
6076
  "loadMidi: startTime must be a non-negative finite number (got " + String(options.startTime) + ")"
5737
6077
  );
5738
6078
  }
6079
+ const signal = host._operationSignal(options.signal);
6080
+ const target = host.arrangement;
6081
+ if (signal.aborted) throw reasonOf(signal);
5739
6082
  let midiModule;
5740
6083
  try {
5741
6084
  midiModule = await import("@dawcore/midi");
@@ -5746,7 +6089,7 @@ async function loadMidiImpl(host, source, options = {}) {
5746
6089
  const { parseMidiUrl, parseMidiFile } = midiModule;
5747
6090
  let parsed;
5748
6091
  if (typeof source === "string") {
5749
- parsed = await parseMidiUrl(source, void 0, options.signal);
6092
+ parsed = await parseMidiUrl(source, void 0, signal);
5750
6093
  } else {
5751
6094
  let buffer;
5752
6095
  try {
@@ -5758,21 +6101,24 @@ async function loadMidiImpl(host, source, options = {}) {
5758
6101
  }
5759
6102
  parsed = parseMidiFile(buffer);
5760
6103
  }
5761
- const childrenBefore = new Set(host.querySelectorAll("daw-track"));
6104
+ if (signal.aborted) throw reasonOf(signal);
5762
6105
  const settlements = await Promise.allSettled(
5763
6106
  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
- })
6107
+ (t) => host.addTrack(
6108
+ {
6109
+ name: t.name,
6110
+ kind: "midi",
6111
+ clips: [
6112
+ {
6113
+ midiNotes: t.notes,
6114
+ midiChannel: t.channel,
6115
+ midiProgram: t.programNumber,
6116
+ start: startTime
6117
+ }
6118
+ ]
6119
+ },
6120
+ { signal }
6121
+ )
5776
6122
  )
5777
6123
  );
5778
6124
  const succeeded = [];
@@ -5785,17 +6131,14 @@ async function loadMidiImpl(host, source, options = {}) {
5785
6131
  }
5786
6132
  }
5787
6133
  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) {
6134
+ for (const trackId of succeeded) {
5792
6135
  try {
5793
- el.remove();
6136
+ host._discardTrack(trackId, target);
5794
6137
  } catch (cleanupErr) {
5795
6138
  console.warn("[dawcore] loadMidi cleanup failed for a track: " + String(cleanupErr));
5796
6139
  }
5797
6140
  }
5798
- await Promise.resolve();
6141
+ if (signal.aborted) throw reasonOf(signal);
5799
6142
  for (let i = 1; i < rejections.length; i++) {
5800
6143
  console.warn(
5801
6144
  "[dawcore] loadMidi: additional track failure (" + i + "): " + stringifyReason(rejections[i])
@@ -5875,33 +6218,6 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
5875
6218
  clip
5876
6219
  ]
5877
6220
  }));
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
6221
  if (host.isConnected) {
5906
6222
  host.dispatchEvent(
5907
6223
  new CustomEvent("daw-recording-clip-add", {
@@ -5984,18 +6300,18 @@ function performSplit(host, time) {
5984
6300
  );
5985
6301
  return false;
5986
6302
  }
6303
+ const leftClip = trackAfter.clips.find((c) => c.id === originalClipId);
5987
6304
  const newClips = trackAfter.clips.filter((c) => !clipIdsBefore.has(c.id));
5988
- if (newClips.length !== 2) {
6305
+ if (!leftClip || newClips.length !== 1) {
5989
6306
  if (newClips.length > 0) {
5990
6307
  console.warn(
5991
- "[dawcore] splitAtPlayhead: expected 2 new clips after split but got " + newClips.length
6308
+ "[dawcore] splitAtPlayhead: expected the original clip and 1 new clip after split but got " + newClips.length + " new"
5992
6309
  );
5993
6310
  }
5994
6311
  return false;
5995
6312
  }
5996
- const sorted = [...newClips].sort((a, b) => a.startSample - b.startSample);
5997
- const leftClipId = sorted[0].id;
5998
- const rightClipId = sorted[1].id;
6313
+ const leftClipId = leftClip.id;
6314
+ const rightClipId = newClips[0].id;
5999
6315
  host.dispatchEvent(
6000
6316
  new CustomEvent("daw-clip-split", {
6001
6317
  bubbles: true,
@@ -6295,6 +6611,113 @@ var LoadAnnouncer = class {
6295
6611
  }
6296
6612
  };
6297
6613
 
6614
+ // src/interactions/arrangement-view.ts
6615
+ var import_core15 = require("@waveform-playlist/core");
6616
+ var views = /* @__PURE__ */ new WeakMap();
6617
+ function sameMix(a, b) {
6618
+ return a.volume === b.volume && a.pan === b.pan && a.muted === b.muted && a.soloed === b.soloed;
6619
+ }
6620
+ function loadedTrack(track, mix, recording) {
6621
+ const cached = views.get(track);
6622
+ if (cached && cached.recording === recording && sameMix(cached.mix, mix)) return cached.view;
6623
+ const view = {
6624
+ ...track,
6625
+ clips: track.clips.filter((c) => !(0, import_core15.isLoadingClip)(c)),
6626
+ volume: mix.volume,
6627
+ pan: mix.pan,
6628
+ muted: mix.muted || recording,
6629
+ soloed: mix.soloed
6630
+ };
6631
+ views.set(track, { mix: { ...mix }, recording, view });
6632
+ return view;
6633
+ }
6634
+ function mixOf(arrangement, trackId) {
6635
+ const mix = arrangement.getMixer().get(trackId);
6636
+ if (!mix) return null;
6637
+ return arrangement.recordingTrackIds.has(trackId) ? { ...mix, muted: true } : mix;
6638
+ }
6639
+ function clipSeconds(clip, fallbackSampleRate) {
6640
+ if ((0, import_core15.isLoadingClip)(clip)) {
6641
+ return { start: clip.start ?? 0, duration: clip.duration ?? 0, offset: clip.offset ?? 0 };
6642
+ }
6643
+ const sr = clip.sampleRate ?? fallbackSampleRate;
6644
+ return {
6645
+ start: clip.startSample / sr,
6646
+ duration: clip.durationSamples / sr,
6647
+ offset: clip.offsetSamples / sr
6648
+ };
6649
+ }
6650
+
6651
+ // src/interactions/arrangement-swap.ts
6652
+ var import_engine2 = require("@waveform-playlist/engine");
6653
+ function normalizeHandedIn(value, own) {
6654
+ if (value === null || value === void 0 || value === own) return null;
6655
+ if (!(0, import_engine2.isArrangement)(value)) {
6656
+ throw new TypeError(
6657
+ "[dawcore] editor.arrangement must be an arrangement made by createArrangement() (@waveform-playlist/engine), or null for the editor's own."
6658
+ );
6659
+ }
6660
+ return value;
6661
+ }
6662
+ function swapArrangement(host, next) {
6663
+ if (next === host._handedIn) return;
6664
+ if (host.isRecording) {
6665
+ console.warn(
6666
+ "[dawcore] editor.arrangement was not changed: a take is recording. Set it after stopRecording() resolves."
6667
+ );
6668
+ return;
6669
+ }
6670
+ host._cancelDrags();
6671
+ if (host.isPlaying) host.stop();
6672
+ const before = host._arrangement.getTracks().map((t) => t.id);
6673
+ host._releaseEngine();
6674
+ host._playArrangement(next);
6675
+ const kept = new Set(host._arrangement.getTracks().map((t) => t.id));
6676
+ for (const id of before) if (!kept.has(id)) host._disposeTrackChain(id);
6677
+ host._buildEngineIfReady();
6678
+ }
6679
+
6680
+ // src/interactions/drag-watch.ts
6681
+ var import_core16 = require("@waveform-playlist/core");
6682
+ function clipDragChanged(arrangement, drag) {
6683
+ const clip = arrangement.getTracks().find((t) => t.id === drag.trackId)?.clips.find((c) => c.id === drag.clipId);
6684
+ if (!clip || (0, import_core16.isLoadingClip)(clip)) return true;
6685
+ return clip.startSample !== drag.startSample || clip.durationSamples !== drag.durationSamples || clip.offsetSamples !== drag.offsetSamples;
6686
+ }
6687
+ function trackDragChanged(arrangement, drag) {
6688
+ const ids = arrangement.getTracks().map((t) => t.id);
6689
+ if (!ids.includes(drag.trackId) || ids.length !== drag.order.length) return true;
6690
+ return ids.some((id, i) => id !== drag.order[i]);
6691
+ }
6692
+
6693
+ // src/interactions/clip-rehome.ts
6694
+ function trackHoldingClip(arrangement, clipId, exceptTrackId) {
6695
+ const track = arrangement.getTracks().find((t) => t.id !== exceptTrackId && t.clips.some((c) => c.id === clipId));
6696
+ return track?.id ?? null;
6697
+ }
6698
+ function moveClipToTrack(arrangement, fromTrackId, toTrackId, clipId, toKind) {
6699
+ const tracks = arrangement.getTracks();
6700
+ const clip = tracks.find((t) => t.id === fromTrackId)?.clips.find((c) => c.id === clipId);
6701
+ const to = tracks.find((t) => t.id === toTrackId);
6702
+ if (!clip || !to) return new Error('clip "' + clipId + '" or track "' + toTrackId + '" is gone');
6703
+ const isMidi = "midiNotes" in clip && clip.midiNotes != null;
6704
+ const kindError = clipKindError(to.name ?? "", toKind, isMidi, clip.name || clipId);
6705
+ if (kindError) return kindError;
6706
+ arrangement.beginTransaction();
6707
+ try {
6708
+ arrangement.updateTrack(fromTrackId, (t) => ({
6709
+ ...t,
6710
+ clips: t.clips.filter((c) => c.id !== clipId)
6711
+ }));
6712
+ arrangement.updateTrack(toTrackId, (t) => ({ ...t, clips: [...t.clips, clip] }));
6713
+ } catch (err) {
6714
+ arrangement.abortTransaction();
6715
+ return err instanceof Error ? err : new Error(String(err));
6716
+ }
6717
+ arrangement.commitTransaction();
6718
+ return null;
6719
+ }
6720
+
6298
6721
  // src/effects/effects-chain-controller.ts
6299
6722
  var idCounter = 0;
6300
6723
  var EffectsChainController = class {
@@ -6508,10 +6931,10 @@ function loadFaustModule(feature) {
6508
6931
  }
6509
6932
 
6510
6933
  // src/effects/effects-manager.ts
6511
- var import_core16 = require("@waveform-playlist/core");
6934
+ var import_core18 = require("@waveform-playlist/core");
6512
6935
 
6513
6936
  // src/effects/effect-registry.ts
6514
- var import_core15 = require("@waveform-playlist/core");
6937
+ var import_core17 = require("@waveform-playlist/core");
6515
6938
  var MAX_DELAY_SECONDS = 10;
6516
6939
  function singleNode(node, applyParams) {
6517
6940
  return { input: node, output: node, applyParams };
@@ -6587,8 +7010,8 @@ function biquadDefinition(spec) {
6587
7010
  };
6588
7011
  }
6589
7012
  function registerBuiltIn(type, definition) {
6590
- if (!(0, import_core15.getEffectDefinitions)().has(type)) {
6591
- (0, import_core15.registerEffect)(type, { ...definition, builtIn: true });
7013
+ if (!(0, import_core17.getEffectDefinitions)().has(type)) {
7014
+ (0, import_core17.registerEffect)(type, { ...definition, builtIn: true });
6592
7015
  }
6593
7016
  }
6594
7017
  function registerBuiltIns() {
@@ -6743,7 +7166,7 @@ var EffectsManager = class {
6743
7166
  /** Run a registered effect's async `prepare` hook on the adapter's
6744
7167
  * context, so the synchronous addEffect() can create it. */
6745
7168
  async prepareEffect(type) {
6746
- await (0, import_core16.prepareEffect)(type, this._requireWiring().audioContext);
7169
+ await (0, import_core18.prepareEffect)(type, this._requireWiring().audioContext);
6747
7170
  }
6748
7171
  // --- Track chains ---
6749
7172
  addTrackEffect(trackId, target, type, params) {
@@ -6948,7 +7371,7 @@ var EffectsManager = class {
6948
7371
  this._runOp(chain, target, "setParams", effectId, { [paramId]: value });
6949
7372
  };
6950
7373
  if (entry.kind === "native") {
6951
- const definition = (0, import_core16.getEffectDefinitions)().get(entry.type);
7374
+ const definition = (0, import_core18.getEffectDefinitions)().get(entry.type);
6952
7375
  if (!definition) {
6953
7376
  throw new Error(
6954
7377
  PREFIX2 + 'openEffectGui: no registry definition for effect type "' + entry.type + '"'
@@ -7007,7 +7430,7 @@ var EffectsManager = class {
7007
7430
  }
7008
7431
  _addToChain(chain, target, type, params) {
7009
7432
  const audioContext = this._requireWiring().audioContext;
7010
- const created = (0, import_core16.createEffectInstance)(type, audioContext, params);
7433
+ const created = (0, import_core18.createEffectInstance)(type, audioContext, params);
7011
7434
  const effectId = chain.add({
7012
7435
  kind: "native",
7013
7436
  type,
@@ -7179,8 +7602,8 @@ var EffectsManager = class {
7179
7602
  if (entry.kind === "native") {
7180
7603
  try {
7181
7604
  const liveContext = this._requireWiring().audioContext;
7182
- if ((0, import_core16.needsPrepare)(entry.type, liveContext)) {
7183
- await (0, import_core16.ensureEffectPrepared)(entry.type, liveContext);
7605
+ if ((0, import_core18.needsPrepare)(entry.type, liveContext)) {
7606
+ await (0, import_core18.ensureEffectPrepared)(entry.type, liveContext);
7184
7607
  if (superseded() || chain.disposed) return;
7185
7608
  }
7186
7609
  const id = this._addToChain(chain, target, entry.type, entry.params);
@@ -7355,8 +7778,8 @@ function toWamParameterMap(params) {
7355
7778
  }
7356
7779
 
7357
7780
  // src/interactions/export-audio.ts
7358
- var import_core17 = require("@waveform-playlist/core");
7359
- var import_core18 = require("@waveform-playlist/core");
7781
+ var import_core19 = require("@waveform-playlist/core");
7782
+ var import_core20 = require("@waveform-playlist/core");
7360
7783
  var PREFIX3 = "[waveform-playlist] ";
7361
7784
  async function exportAudioImpl(host, options = {}) {
7362
7785
  const sampleRate = options.sampleRate ?? host.effectiveSampleRate;
@@ -7391,7 +7814,7 @@ async function exportAudioImpl(host, options = {}) {
7391
7814
  cleanups.push(chain.dispose);
7392
7815
  const volume = ctx.createGain();
7393
7816
  volume.gain.value = track.volume;
7394
- const panStage = (0, import_core17.createPanStage)(ctx, track.pan, (0, import_core17.trackChannelCount)(track));
7817
+ const panStage = (0, import_core19.createPanStage)(ctx, track.pan, (0, import_core19.trackChannelCount)(track));
7395
7818
  cleanups.push(panStage.dispose);
7396
7819
  chain.output.connect(volume);
7397
7820
  volume.connect(panStage.input);
@@ -7473,12 +7896,12 @@ async function buildOfflineChain(ctx, entries) {
7473
7896
  continue;
7474
7897
  }
7475
7898
  if (entry.kind === "native") {
7476
- const definition = (0, import_core18.getEffectDefinitions)().get(entry.type);
7899
+ const definition = (0, import_core20.getEffectDefinitions)().get(entry.type);
7477
7900
  if (entry.bypassed && definition && !definition.wetParam) {
7478
7901
  continue;
7479
7902
  }
7480
- await (0, import_core18.ensureEffectPrepared)(entry.type, ctx);
7481
- const created = (0, import_core18.createEffectInstance)(entry.type, ctx, entry.params);
7903
+ await (0, import_core20.ensureEffectPrepared)(entry.type, ctx);
7904
+ const created = (0, import_core20.createEffectInstance)(entry.type, ctx, entry.params);
7482
7905
  if (entry.bypassed && created.wetParam) {
7483
7906
  created.instance.applyParams({ [created.wetParam]: 0 });
7484
7907
  }
@@ -7520,8 +7943,8 @@ async function buildOfflineChain(ctx, entries) {
7520
7943
 
7521
7944
  // src/interactions/peaks-loader.ts
7522
7945
  var import_waveform_data2 = __toESM(require("waveform-data"));
7523
- async function loadWaveformDataFromUrl(src) {
7524
- const response = await fetch(src);
7946
+ async function loadWaveformDataFromUrl(src, signal) {
7947
+ const response = await fetch(src, signal ? { signal } : void 0);
7525
7948
  if (!response.ok) {
7526
7949
  throw new Error("[dawcore] Failed to fetch peaks data: " + response.statusText);
7527
7950
  }
@@ -7541,7 +7964,10 @@ var LINE_HEIGHT_PX = 16;
7541
7964
  var ScrollSyncController = class {
7542
7965
  constructor(host) {
7543
7966
  this._scrollContainer = null;
7544
- this._wheelTargets = /* @__PURE__ */ new Set();
7967
+ /** The scroll listener on `_scrollContainer`, aborted when it is replaced or detached. */
7968
+ this._scrollListener = null;
7969
+ /** Each wheel target and the controller of its listener. */
7970
+ this._wheelTargets = /* @__PURE__ */ new Map();
7545
7971
  this._warnedX = false;
7546
7972
  this._warnedY = false;
7547
7973
  /** Selector (in host shadow DOM) for the scroll container. */
@@ -7586,11 +8012,14 @@ var ScrollSyncController = class {
7586
8012
  });
7587
8013
  }
7588
8014
  hostDisconnected() {
7589
- this._scrollContainer?.removeEventListener("scroll", this._onScroll);
8015
+ this._detachAll();
8016
+ }
8017
+ /** Remove the scroll and every wheel listener. */
8018
+ _detachAll() {
8019
+ this._scrollListener?.abort();
8020
+ this._scrollListener = null;
7590
8021
  this._scrollContainer = null;
7591
- for (const target of this._wheelTargets) {
7592
- target.removeEventListener("wheel", this._onWheel);
7593
- }
8022
+ for (const listener of this._wheelTargets.values()) listener.abort();
7594
8023
  this._wheelTargets.clear();
7595
8024
  }
7596
8025
  /**
@@ -7616,29 +8045,31 @@ var ScrollSyncController = class {
7616
8045
  console.warn(
7617
8046
  '[dawcore] ScrollSyncController: scroll container "' + this.scrollSelector + '" was removed from the DOM \u2014 detaching listeners until it reappears.'
7618
8047
  );
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();
8048
+ this._detachAll();
7623
8049
  }
7624
8050
  return;
7625
8051
  }
7626
8052
  if (container !== this._scrollContainer) {
7627
- this._scrollContainer?.removeEventListener("scroll", this._onScroll);
8053
+ this._scrollListener?.abort();
7628
8054
  this._scrollContainer = container;
7629
- container.addEventListener("scroll", this._onScroll, { passive: true });
8055
+ this._scrollListener = new AbortController();
8056
+ container.addEventListener("scroll", this._onScroll, {
8057
+ passive: true,
8058
+ signal: this._scrollListener.signal
8059
+ });
7630
8060
  }
7631
8061
  const nextTargets = new Set(this._queryAll(this.wheelForwardSelector));
7632
- for (const old of this._wheelTargets) {
8062
+ for (const [old, listener] of [...this._wheelTargets]) {
7633
8063
  if (!nextTargets.has(old)) {
7634
- old.removeEventListener("wheel", this._onWheel);
8064
+ listener.abort();
7635
8065
  this._wheelTargets.delete(old);
7636
8066
  }
7637
8067
  }
7638
8068
  for (const next of nextTargets) {
7639
8069
  if (!this._wheelTargets.has(next)) {
7640
- next.addEventListener("wheel", this._onWheel, { passive: false });
7641
- this._wheelTargets.add(next);
8070
+ const listener = new AbortController();
8071
+ next.addEventListener("wheel", this._onWheel, { passive: false, signal: listener.signal });
8072
+ this._wheelTargets.set(next, listener);
7642
8073
  }
7643
8074
  }
7644
8075
  this._apply();
@@ -7744,7 +8175,38 @@ var PlaybackAnimationController = class {
7744
8175
  // src/elements/daw-editor.ts
7745
8176
  var import_meta = {};
7746
8177
  var RULER_HEIGHT = 30;
8178
+ function clipDescriptorOf(config) {
8179
+ return {
8180
+ kind: "drop",
8181
+ clipId: crypto.randomUUID(),
8182
+ src: config.src ?? "",
8183
+ peaksSrc: config.peaksSrc ?? "",
8184
+ start: config.start ?? 0,
8185
+ duration: config.duration ?? 0,
8186
+ offset: config.offset ?? 0,
8187
+ gain: config.gain ?? 1,
8188
+ name: config.name ?? "",
8189
+ fadeIn: config.fadeIn ?? 0,
8190
+ fadeOut: config.fadeOut ?? 0,
8191
+ fadeType: config.fadeType ?? "linear",
8192
+ midiNotes: config.midiNotes ?? null,
8193
+ midiChannel: config.midiChannel ?? null,
8194
+ midiProgram: config.midiProgram ?? null
8195
+ };
8196
+ }
8197
+ function extrasOf(descriptor) {
8198
+ return {
8199
+ kind: descriptor.kind,
8200
+ renderMode: descriptor.renderMode,
8201
+ spectrogramConfig: descriptor.spectrogramConfig,
8202
+ src: descriptor.src,
8203
+ peaksSrc: new Map(
8204
+ descriptor.clips.flatMap((c) => c.clipId ? [[c.clipId, c.peaksSrc]] : [])
8205
+ )
8206
+ };
8207
+ }
7747
8208
  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();";
8209
+ var ENTERED = /* @__PURE__ */ Symbol("entered");
7748
8210
  var DawEditorElement = class extends import_lit19.LitElement {
7749
8211
  constructor() {
7750
8212
  super();
@@ -7773,13 +8235,18 @@ var DawEditorElement = class extends import_lit19.LitElement {
7773
8235
  this._ppqn = 960;
7774
8236
  this.snapTo = "off";
7775
8237
  /**
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.
8238
+ * The editor's own arrangement (#848): the one owner of the tracks, the
8239
+ * clips, the mix, the undo history and loading of what the `<daw-track>`
8240
+ * children declare. Made with the editor, kept across a disconnect.
7779
8241
  */
7780
- this._arrangement = (0, import_engine.createArrangement)();
7781
- /** Sends the load events, read from the arrangement (#848). */
8242
+ this._ownArrangement = (0, import_engine3.createArrangement)();
8243
+ /** An arrangement the app handed in (`editor.arrangement`), played alone; null: the own one. */
8244
+ this._handedIn = null;
8245
+ /** Sends the load events, read from the arrangement played (#848; a new one per swap). */
7782
8246
  this._announcer = new LoadAnnouncer((event) => this.dispatchEvent(event));
8247
+ /** Stops following the arrangement played (its sources and its tracks). */
8248
+ this._unfollow = () => {
8249
+ };
7783
8250
  /**
7784
8251
  * Ids of tracks registered (a `<daw-track>` connected, a file dropped) and
7785
8252
  * not yet in the arrangement: they enter at the next flush, once there is
@@ -7793,13 +8260,17 @@ var DawEditorElement = class extends import_lit19.LitElement {
7793
8260
  * loads settles it here, without a public event (#917).
7794
8261
  */
7795
8262
  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
8263
  this._previewPeaks = /* @__PURE__ */ new Map();
7799
8264
  /** The `.dat` data of those clips, handed to the peak pipeline when the audio arrives. */
7800
8265
  this._previewWaveforms = /* @__PURE__ */ new Map();
7801
- this._tracks = /* @__PURE__ */ new Map();
7802
- this._engineTracks = /* @__PURE__ */ new Map();
8266
+ /**
8267
+ * Tracks registered and not in the arrangement yet, with their declaration
8268
+ * (#848): a `<daw-track>` is read when it enters (its clips and attributes
8269
+ * as they are then); a dropped file carries its descriptor. The one place a
8270
+ * track's state lives until it enters.
8271
+ */
8272
+ this._pending = /* @__PURE__ */ new Map();
8273
+ this._extras = /* @__PURE__ */ new Map();
7803
8274
  this._peaksData = /* @__PURE__ */ new Map();
7804
8275
  this._isPlaying = false;
7805
8276
  this._duration = 0;
@@ -7873,6 +8344,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
7873
8344
  s.scrollSelector = ".scroll-area";
7874
8345
  return s;
7875
8346
  })();
8347
+ /** One gesture id per track for the rest of this task: mix sets made together are one step (#843). */
8348
+ this._taskGestures = /* @__PURE__ */ new Map();
7876
8349
  /**
7877
8350
  * Cache of the last ViewportState forwarded to the spectrogram controller.
7878
8351
  * Lit's `updated()` fires on every reactive state change (`_isPlaying`,
@@ -7905,12 +8378,14 @@ var DawEditorElement = class extends import_lit19.LitElement {
7905
8378
  console.warn("[dawcore] Invalid daw-track-connected event detail: " + String(e.detail));
7906
8379
  return;
7907
8380
  }
7908
- if (this._tracks.has(trackId)) {
8381
+ if (this._pending.has(trackId) || this._extras.has(trackId) || this._isEntered(trackId)) {
7909
8382
  this._trackElements.set(trackId, trackEl);
7910
8383
  return;
7911
8384
  }
7912
- const descriptor = this._readTrackDescriptor(trackEl);
7913
- this._tracks = new Map(this._tracks).set(trackId, descriptor);
8385
+ this._pending = new Map(this._pending).set(trackId, {
8386
+ element: trackEl,
8387
+ extraClips: []
8388
+ });
7914
8389
  this._trackElements.set(trackId, trackEl);
7915
8390
  this._queueEntry(trackId);
7916
8391
  };
@@ -7919,50 +8394,33 @@ var DawEditorElement = class extends import_lit19.LitElement {
7919
8394
  if (!trackId) return;
7920
8395
  const trackEl = e.target.closest("daw-track");
7921
8396
  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);
8397
+ const old = this._extras.get(trackId);
8398
+ if (!old || !this._isEntered(trackId)) return;
7942
8399
  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
- }
8400
+ const next = {
8401
+ ...old,
8402
+ ...changed.includes("renderMode") && {
8403
+ renderMode: trackDescriptorRenderMode(old.kind, trackEl.renderMode)
8404
+ },
8405
+ ...changed.includes("spectrogramConfig") && {
8406
+ spectrogramConfig: trackEl.spectrogramConfig
8407
+ },
8408
+ ...changed.includes("src") && { src: trackEl.src }
8409
+ };
8410
+ this._extras = new Map(this._extras).set(trackId, next);
8411
+ if (old.src !== next.src) this._replaceShorthandClips(trackId, trackEl);
8412
+ const loaded = this._loadedTracks().find((t) => t.id === trackId)?.clips ?? [];
8413
+ if (next.renderMode === "spectrogram" && old.renderMode !== "spectrogram") {
8414
+ for (const clip of loaded) this._maybeRegisterSpectrogramClipAudio(trackId, clip);
8415
+ }
8416
+ if (next.renderMode !== "spectrogram" && old.renderMode === "spectrogram") {
8417
+ if (this._spectrogramController) {
8418
+ for (const clip of loaded) this._spectrogramController.unregisterClipAudio(clip.id);
7961
8419
  }
7962
8420
  this._disposeSpectrogramControllerIfEmpty();
7963
8421
  }
7964
- if (descriptor.spectrogramConfig !== oldDescriptor?.spectrogramConfig) {
7965
- this._spectrogramController?.setTrackConfig(trackId, descriptor.spectrogramConfig ?? null);
8422
+ if (next.spectrogramConfig !== old.spectrogramConfig) {
8423
+ this._spectrogramController?.setTrackConfig(trackId, next.spectrogramConfig ?? null);
7966
8424
  }
7967
8425
  };
7968
8426
  this._onTrackControl = (e) => {
@@ -7981,7 +8439,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
7981
8439
  })
7982
8440
  );
7983
8441
  }
7984
- if (this._tracks.has(trackId)) {
8442
+ if (this._isEntered(trackId)) {
7985
8443
  const options = typeof gesture === "string" ? { gesture } : void 0;
7986
8444
  if (prop === "volume") this._writeMix(trackId, "volume", clampNumber(value, 0, 1), options);
7987
8445
  if (prop === "pan") this._writeMix(trackId, "pan", clampNumber(value, -1, 1), options);
@@ -8007,56 +8465,42 @@ var DawEditorElement = class extends import_lit19.LitElement {
8007
8465
  const trackEl = clipEl.closest("daw-track");
8008
8466
  if (!trackEl) return;
8009
8467
  const trackId = trackEl.trackId;
8010
- if (!this._isEntered(trackId)) {
8468
+ if (this._rehomeClip(trackId, clipEl)) return;
8469
+ const entered = this._arrangementOf(trackId).getTracks().some((t) => t.id === trackId);
8470
+ if (!entered && !this._pending.has(trackId) && this._trackLinkState(trackId) === "detached") {
8471
+ this._takeClip(trackId, clipEl.clipId, clipEl.peaksSrc || "");
8472
+ console.warn(
8473
+ detachedWarning(
8474
+ '<daw-track> "' + (trackEl.name || "Untitled") + '"',
8475
+ "a <daw-clip> added to it",
8476
+ this._detachedReason()
8477
+ )
8478
+ );
8479
+ this._rejectAwaitedClips(
8480
+ (id) => id === clipEl.clipId,
8481
+ 'addClip: track "' + trackId + '" is detached'
8482
+ );
8483
+ this._refreshLinkStates();
8484
+ return;
8485
+ }
8486
+ if (!entered) {
8011
8487
  if (!this._entryQueue.includes(trackId)) {
8012
8488
  this._rejectAwaitedClips(
8013
8489
  (id) => id === clipEl.clipId,
8014
8490
  'addClip: track "' + trackId + '" is not in the editor (an Undo took it out)'
8015
8491
  );
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
8492
  }
8025
8493
  return;
8026
8494
  }
8027
- const loadedDesc = this._tracks.get(trackId);
8028
- if (loadedDesc && loadedDesc.clips.some((c) => isDomClip(c) && c.clipId === clipEl.clipId)) {
8029
- return;
8030
- }
8495
+ if (this._extras.get(trackId)?.peaksSrc.has(clipEl.clipId)) return;
8031
8496
  this._loadAndAppendClip(trackId, this._readClipDescriptor(clipEl));
8032
8497
  };
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
8498
  /** Who waits for a track to enter (addTrack, a dropped file). */
8057
8499
  this._entryWaiters = /* @__PURE__ */ new Map();
8058
- /** Ends the waits of `_whenTrackLoaded` (as loaded) when the editor is disconnected. */
8059
- this._loadWaitEnds = /* @__PURE__ */ new Set();
8500
+ /** One AbortController per arrangement while it is played (D2, interactions/abort.ts). */
8501
+ this._playSignals = new PlaySignals();
8502
+ /** One AbortController per connection: aborted in disconnectedCallback (D8). */
8503
+ this._connection = new AbortController();
8060
8504
  /** Last versions the statechange handler worked from; reset for each engine. */
8061
8505
  this._lastTracksVersion = -1;
8062
8506
  this._lastMixerVersion = -1;
@@ -8123,15 +8567,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
8123
8567
  }
8124
8568
  return time * this.effectiveSampleRate / this.samplesPerPixel;
8125
8569
  };
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
- });
8570
+ this._follow(this._ownArrangement);
8135
8571
  }
8136
8572
  get samplesPerPixel() {
8137
8573
  return this._samplesPerPixel;
@@ -8253,8 +8689,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
8253
8689
  * render — even if no canvases have been registered yet.
8254
8690
  */
8255
8691
  _maybeRegisterSpectrogramClipAudio(trackId, clip) {
8256
- const descriptor = this._tracks.get(trackId);
8257
- if (descriptor?.renderMode !== "spectrogram") return;
8692
+ if (this._renderModeOf(trackId) !== "spectrogram") return;
8258
8693
  const buffer = clip.audioBuffer ?? this._clipBuffers.get(clip.id);
8259
8694
  if (!buffer) return;
8260
8695
  const channelData = [];
@@ -8326,6 +8761,97 @@ var DawEditorElement = class extends import_lit19.LitElement {
8326
8761
  }
8327
8762
  return null;
8328
8763
  }
8764
+ /** The arrangement played now: a handed-in one, else the editor's own. */
8765
+ get _arrangement() {
8766
+ return this._handedIn ?? this._ownArrangement;
8767
+ }
8768
+ /**
8769
+ * The arrangement the editor plays (#848 PR 3): one handed in by the app,
8770
+ * or else the editor's own, whose content the `<daw-track>` children
8771
+ * declare. Setting one plays it alone, like `video.srcObject`: the
8772
+ * children are not added to it and show `:state(detached)` while it is
8773
+ * set; `null` (or the editor's own) goes back to the own arrangement with
8774
+ * what it held. A swap keeps the adapter: playback stops, a new engine is
8775
+ * built on the new arrangement. Refused (with a warning) during a take.
8776
+ * The editor never disposes or clears an arrangement it was handed.
8777
+ * Throws a `TypeError` for a value that is not an arrangement.
8778
+ */
8779
+ get arrangement() {
8780
+ return this._arrangement;
8781
+ }
8782
+ set arrangement(value) {
8783
+ swapArrangement(this, normalizeHandedIn(value, this._ownArrangement));
8784
+ }
8785
+ /**
8786
+ * Follow the arrangement played: a source that fails changes no track,
8787
+ * only `sources` tells of it (the events, the failed look); the elements'
8788
+ * link states follow its tracks (a structural change only, not every
8789
+ * mixer frame).
8790
+ */
8791
+ _follow(arrangement) {
8792
+ this._unfollow();
8793
+ const stopSources = arrangement.sources.subscribe(() => {
8794
+ this._announceLoading();
8795
+ this.requestUpdate();
8796
+ });
8797
+ let tracksVersion = arrangement.tracksVersion;
8798
+ const stopTracks = arrangement.subscribe(() => {
8799
+ this._watchDrags();
8800
+ if (arrangement.tracksVersion === tracksVersion) return;
8801
+ tracksVersion = arrangement.tracksVersion;
8802
+ this._refreshLinkStates();
8803
+ });
8804
+ this._unfollow = () => {
8805
+ stopSources();
8806
+ stopTracks();
8807
+ };
8808
+ }
8809
+ /**
8810
+ * A change to the arrangement while a drag is in progress came from
8811
+ * elsewhere (a drag writes nothing until its release): cancel the drag
8812
+ * when it changed what is dragged (#848 P2, interactions/drag-watch.ts).
8813
+ */
8814
+ _watchDrags() {
8815
+ const clip = this._clipPointer.draggedClip;
8816
+ if (clip && clipDragChanged(this._arrangement, clip)) this._pointer.cancelClipDrag();
8817
+ const track = this._trackReorderDrag.draggedTrack;
8818
+ if (track && trackDragChanged(this._arrangement, track)) this._trackReorderDrag.cancel();
8819
+ }
8820
+ // --- The swap (interactions/arrangement-swap.ts) ---
8821
+ /** @internal */
8822
+ _releaseEngine() {
8823
+ if (!this._engine) return;
8824
+ try {
8825
+ this._engine.dispose({ keepAdapter: true });
8826
+ } catch (err) {
8827
+ console.warn("[dawcore] Error releasing the engine: " + String(err));
8828
+ }
8829
+ this._engine = null;
8830
+ }
8831
+ /** @internal */
8832
+ _disposeTrackChain(trackId) {
8833
+ this._effectsManager?.disposeTrackChain(trackId);
8834
+ }
8835
+ /** @internal */
8836
+ _playArrangement(next) {
8837
+ this._playSignals.swappedOut(
8838
+ this._arrangement,
8839
+ abortError("the arrangement was swapped out (editor.arrangement) before it finished")
8840
+ );
8841
+ this._handedIn = next;
8842
+ this._announcer = new LoadAnnouncer((event) => this.dispatchEvent(event));
8843
+ this._follow(this._arrangement);
8844
+ this._currentTime = 0;
8845
+ this._stopPlayhead();
8846
+ this._recomputeDuration();
8847
+ this._refreshLinkStates();
8848
+ this._announceLoading();
8849
+ this.requestUpdate();
8850
+ }
8851
+ /** @internal */
8852
+ _buildEngineIfReady() {
8853
+ if (this._externalAdapter && this.isConnected && !this._engine) this._buildEngineReporting();
8854
+ }
8329
8855
  /** Reject the `addClip()` calls waiting for clips that match `which`. */
8330
8856
  _rejectAwaitedClips(which, message) {
8331
8857
  for (const [clipId, awaited] of [...this._awaitedClips]) {
@@ -8434,7 +8960,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
8434
8960
  {
8435
8961
  effectiveSampleRate: this.effectiveSampleRate,
8436
8962
  duration: this._duration,
8437
- tracks: [...this._engineTracks.values()],
8963
+ tracks: this._loadedTracks(),
8438
8964
  masterVolume: this._engine?.getState().masterVolume ?? 1,
8439
8965
  getMasterEffectsState: () => this.getEffectsState(),
8440
8966
  getTrackEffectsState: (trackId) => this.getTrackEffectsState(trackId)
@@ -8559,11 +9085,26 @@ var DawEditorElement = class extends import_lit19.LitElement {
8559
9085
  * Returns false for unknown track/clip IDs (defensive).
8560
9086
  */
8561
9087
  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);
9088
+ const clip = this._loadedClip(trackId, clipId);
8565
9089
  return clip?.midiNotes != null;
8566
9090
  }
9091
+ /** The arrangement's tracks as they are played: loaded clips, the current mix (#848). */
9092
+ _loadedTracks() {
9093
+ const arrangement = this._arrangement;
9094
+ return arrangement.getTracks().map(
9095
+ (t) => loadedTrack(
9096
+ t,
9097
+ arrangement.getMixer().get(t.id) ?? mixOfTrack(t),
9098
+ arrangement.recordingTrackIds.has(t.id)
9099
+ )
9100
+ );
9101
+ }
9102
+ /** A loaded clip of a track of the arrangement, or undefined. */
9103
+ _loadedClip(trackId, clipId) {
9104
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9105
+ const clip = track?.clips.find((c) => c.id === clipId);
9106
+ return clip && !(0, import_core21.isLoadingClip)(clip) ? clip : void 0;
9107
+ }
8567
9108
  get effectiveSampleRate() {
8568
9109
  return this.sampleRate;
8569
9110
  }
@@ -8642,11 +9183,80 @@ var DawEditorElement = class extends import_lit19.LitElement {
8642
9183
  * the arrangement is not listed (its descriptor stays for a Redo).
8643
9184
  */
8644
9185
  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);
9186
+ const listed = this._arrangement.getTracks().map((track) => this._listTrack(track));
9187
+ const queue = this._handedIn ? this._entryQueue.filter((id) => !this._trackElements.has(id)) : this._entryQueue;
9188
+ const waiting = queue.flatMap((trackId) => {
9189
+ const descriptor = this._pendingDescriptor(trackId);
8648
9190
  return descriptor ? [{ trackId, ...descriptor, ...this._mixOf(trackId) }] : [];
8649
9191
  });
9192
+ return [...listed, ...waiting];
9193
+ }
9194
+ /** A track of the arrangement as `editor.tracks` lists it: everything read from the arrangement. */
9195
+ _listTrack(track) {
9196
+ const extras = this._extras.get(track.id);
9197
+ const clipEls = new Map(
9198
+ [...this.querySelectorAll("daw-clip")].map((el) => [
9199
+ el.clipId,
9200
+ el
9201
+ ])
9202
+ );
9203
+ const sr = this.effectiveSampleRate;
9204
+ const clips = track.clips.map((clip) => {
9205
+ const el = clipEls.get(clip.id);
9206
+ const times = clipSeconds(clip, sr);
9207
+ const midi = (0, import_core21.isLoadingClip)(clip) ? null : clip;
9208
+ const base = {
9209
+ src: typeof clip.src === "string" ? clip.src : "",
9210
+ peaksSrc: extras?.peaksSrc.get(clip.id) ?? this._takenPeaksSrc(clip.id) ?? "",
9211
+ ...times,
9212
+ gain: clip.gain ?? 1,
9213
+ name: clip.name ?? "",
9214
+ fadeIn: el?.fadeIn ?? 0,
9215
+ fadeOut: el?.fadeOut ?? 0,
9216
+ fadeType: el?.fadeType ?? "linear",
9217
+ midiNotes: midi?.midiNotes ?? null,
9218
+ midiChannel: midi?.midiChannel ?? null,
9219
+ midiProgram: midi?.midiProgram ?? null
9220
+ };
9221
+ return el ? { kind: "dom", clipId: clip.id, ...base } : { kind: "drop", clipId: clip.id, ...base };
9222
+ });
9223
+ return {
9224
+ trackId: track.id,
9225
+ name: track.name ?? "",
9226
+ src: extras?.src ?? "",
9227
+ kind: (0, import_core21.trackKind)(track),
9228
+ renderMode: this._renderModeOf(track.id),
9229
+ spectrogramConfig: extras?.spectrogramConfig ?? null,
9230
+ clips,
9231
+ ...this._mixOf(track.id)
9232
+ };
9233
+ }
9234
+ /** A pending track's declaration: its element's attributes and clips now, or its descriptor. */
9235
+ _pendingDescriptor(trackId) {
9236
+ const pending = this._pending.get(trackId);
9237
+ if (!pending) return null;
9238
+ if (!("element" in pending)) return pending.descriptor;
9239
+ const read = this._readTrackDescriptor(pending.element);
9240
+ return pending.extraClips.length > 0 ? { ...read, clips: [...read.clips, ...pending.extraClips] } : read;
9241
+ }
9242
+ /** The extras a track of the arrangement takes when the editor has none for it. */
9243
+ _defaultExtras(trackId) {
9244
+ const track = this._arrangementOf(trackId).getTracks().find((t) => t.id === trackId);
9245
+ if (!track) return null;
9246
+ const kind = (0, import_core21.trackKind)(track);
9247
+ return {
9248
+ kind,
9249
+ renderMode: trackDescriptorRenderMode(kind, "waveform"),
9250
+ src: "",
9251
+ peaksSrc: /* @__PURE__ */ new Map()
9252
+ };
9253
+ }
9254
+ /** How a track is drawn: its extras, else from its kind (an undo-restored track has none). */
9255
+ _renderModeOf(trackId) {
9256
+ const extras = this._extras.get(trackId);
9257
+ if (extras) return extras.renderMode;
9258
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9259
+ return trackDescriptorRenderMode(track ? (0, import_core21.trackKind)(track) : "audio", "waveform");
8650
9260
  }
8651
9261
  /**
8652
9262
  * A track's mix, from its one owner, the arrangement (#843), as the engine
@@ -8655,13 +9265,162 @@ var DawEditorElement = class extends import_lit19.LitElement {
8655
9265
  * waiting to enter shows what its element declares.
8656
9266
  */
8657
9267
  _mixOf(trackId) {
8658
- const played = this._engineTracks.get(trackId);
8659
- if (played) return mixOfTrack(played);
8660
- const mix = this._arrangement.getMixer().get(trackId);
9268
+ const mix = mixOf(this._arrangement, trackId);
8661
9269
  if (mix) return mix;
9270
+ const pending = this._pending.get(trackId);
9271
+ if (pending && "mix" in pending) return pending.mix;
8662
9272
  const el = this._trackElements.get(trackId);
8663
9273
  return el ? mixOfElement(el) : DEFAULT_TRACK_MIX;
8664
9274
  }
9275
+ // --- Element links (#848, interactions/element-links.ts) ---
9276
+ /** @internal */
9277
+ _trackLinkState(trackId) {
9278
+ if (this._handedIn && this._trackElements.has(trackId)) return "detached";
9279
+ if (this._isEntered(trackId)) return "live";
9280
+ return this._extras.has(trackId) && !this._pending.has(trackId) ? "detached" : "pending";
9281
+ }
9282
+ /** @internal */
9283
+ _clipLinkState(trackId, clipId) {
9284
+ const track = this._trackLinkState(trackId);
9285
+ if (track !== "live") return track;
9286
+ const held = this._arrangement.getTracks().some((t) => t.clips.some((c) => c.id === clipId));
9287
+ if (held) return "live";
9288
+ return this._extras.get(trackId)?.peaksSrc.has(clipId) ? "detached" : "pending";
9289
+ }
9290
+ /** @internal The stored mix (not a take's mute) and the name. */
9291
+ _trackValues(trackId) {
9292
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9293
+ const mix = this._arrangement.getMixer().get(trackId);
9294
+ if (!track || !mix) return null;
9295
+ return { ...mix, name: track.name ?? "" };
9296
+ }
9297
+ /** @internal */
9298
+ _clipValues(trackId, clipId) {
9299
+ const clip = this._arrangement.getTracks().find((t) => t.id === this._clipHolderId(trackId, clipId))?.clips.find((c) => c.id === clipId);
9300
+ if (!clip) return null;
9301
+ const midi = (0, import_core21.isLoadingClip)(clip) ? null : clip;
9302
+ return {
9303
+ ...clipSeconds(clip, this.effectiveSampleRate),
9304
+ gain: clip.gain ?? 1,
9305
+ name: clip.name ?? "",
9306
+ midiNotes: midi?.midiNotes ?? null,
9307
+ midiChannel: midi?.midiChannel ?? null,
9308
+ midiProgram: midi?.midiProgram ?? null
9309
+ };
9310
+ }
9311
+ /** @internal A property or attribute set on a live `<daw-track>`: one undo step per field kind. */
9312
+ _requestTrackChange(trackId, partial) {
9313
+ const { name, ...mix } = partial;
9314
+ if (Object.keys(mix).length > 0) this._writeMixFields(trackId, mix, this._taskGesture(trackId));
9315
+ if (name !== void 0) this._renameTrack(trackId, name || "Untitled");
9316
+ }
9317
+ _taskGesture(trackId) {
9318
+ let id = this._taskGestures.get(trackId);
9319
+ if (!id) {
9320
+ id = (0, import_core21.createMixerGesture)().id;
9321
+ this._taskGestures.set(trackId, id);
9322
+ if (this._taskGestures.size === 1) queueMicrotask(() => this._taskGestures.clear());
9323
+ }
9324
+ return id;
9325
+ }
9326
+ /** @internal A property or attribute set on a live `<daw-clip>`: one undo step. */
9327
+ _requestClipChange(trackId, clipId, partial) {
9328
+ const current = this._clipValues(trackId, clipId);
9329
+ if (!current) return;
9330
+ const holderId = this._clipHolderId(trackId, clipId);
9331
+ const clip = this._arrangement.getTracks().find((t) => t.id === holderId)?.clips.find((c) => c.id === clipId);
9332
+ const src = clip && typeof clip.src === "string" ? clip.src : "";
9333
+ this._applyClipUpdate(holderId, clipId, { ...current, ...partial, src });
9334
+ }
9335
+ /**
9336
+ * The clips of an entering track that another track of the arrangement
9337
+ * holds (the page moved their `<daw-clip>` here while the track waited):
9338
+ * the track takes the held clip as it is, and `from` names what leaves
9339
+ * where. A held clip of the other kind is refused and stays.
9340
+ */
9341
+ _takeOverMovedClips(trackId, track) {
9342
+ const from = /* @__PURE__ */ new Map();
9343
+ const movedIds = /* @__PURE__ */ new Set();
9344
+ const refused = [];
9345
+ const others = this._arrangement.getTracks().filter((t) => t.id !== trackId);
9346
+ const kind = (0, import_core21.trackKind)(track);
9347
+ const clips = [];
9348
+ for (const clip of track.clips) {
9349
+ const holder = others.find((t) => t.clips.some((c) => c.id === clip.id));
9350
+ const held = holder?.clips.find((c) => c.id === clip.id);
9351
+ if (!holder || !held) {
9352
+ clips.push(clip);
9353
+ continue;
9354
+ }
9355
+ const isMidi = "midiNotes" in held && held.midiNotes != null;
9356
+ const error = clipKindError(track.name ?? "", kind, isMidi, held.name || held.id);
9357
+ if (error) {
9358
+ refused.push({ clipId: clip.id, error });
9359
+ continue;
9360
+ }
9361
+ clips.push(held);
9362
+ movedIds.add(clip.id);
9363
+ const ids = from.get(holder.id) ?? /* @__PURE__ */ new Set();
9364
+ from.set(holder.id, ids.add(clip.id));
9365
+ }
9366
+ return {
9367
+ track: movedIds.size || refused.length ? { ...track, clips } : track,
9368
+ from,
9369
+ movedIds,
9370
+ refused
9371
+ };
9372
+ }
9373
+ /** Run `fn` as one undo step of each arrangement it changes. */
9374
+ _inOneStep(arrangements, fn) {
9375
+ for (const a of arrangements) a.beginTransaction();
9376
+ try {
9377
+ fn();
9378
+ } finally {
9379
+ for (const a of arrangements) a.commitTransaction();
9380
+ }
9381
+ }
9382
+ /** The `peaks-src` some track took for a clip element, if any. */
9383
+ _takenPeaksSrc(clipId) {
9384
+ for (const extras of this._extras.values()) {
9385
+ const peaksSrc = extras.peaksSrc.get(clipId);
9386
+ if (peaksSrc !== void 0) return peaksSrc;
9387
+ }
9388
+ return void 0;
9389
+ }
9390
+ /**
9391
+ * The arrangement whose history holds a track: the one that holds it now,
9392
+ * or else, for a page track, the own one (an Undo took it out there; a
9393
+ * handed-in arrangement may be played meanwhile), or else the one played.
9394
+ */
9395
+ _historyOf(trackId, isPageTrack = this._trackElements.has(trackId)) {
9396
+ const holder = this._arrangementOf(trackId);
9397
+ if (holder.getTracks().some((t) => t.id === trackId)) return holder;
9398
+ return isPageTrack ? this._ownArrangement : holder;
9399
+ }
9400
+ /** The track of the arrangement played that holds a clip: `trackId` when it does, or else the one that does. */
9401
+ _clipHolderId(trackId, clipId) {
9402
+ const tracks = this._arrangement.getTracks();
9403
+ if (tracks.some((t) => t.id === trackId && t.clips.some((c) => c.id === clipId)))
9404
+ return trackId;
9405
+ return tracks.find((t) => t.clips.some((c) => c.id === clipId))?.id ?? trackId;
9406
+ }
9407
+ /** @internal */
9408
+ _trackKind(trackId) {
9409
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9410
+ return track ? (0, import_core21.trackKind)(track) : null;
9411
+ }
9412
+ /** @internal */
9413
+ _trackIndex(trackId) {
9414
+ return this._arrangement.getTracks().findIndex((t) => t.id === trackId);
9415
+ }
9416
+ /** @internal */
9417
+ _detachedReason() {
9418
+ return this._handedIn ? "a handed-in arrangement is set (editor.arrangement)" : "its track or clip is not in the arrangement the editor plays";
9419
+ }
9420
+ /** Set or clear `:state(detached)` on every registered element (#848). */
9421
+ _refreshLinkStates() {
9422
+ refreshLinkStates(this, this._trackElements);
9423
+ }
8665
9424
  /**
8666
9425
  * Change one mixer field of a track: the arrangement's setter with
8667
9426
  * `options` (an undo step; changes with one `gesture` id are one step). A
@@ -8678,8 +9437,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
8678
9437
  * Change the given mixer fields of a track as ONE undo step (#843): all
8679
9438
  * of them carry one fresh gesture id. A field left out is not sent.
8680
9439
  */
8681
- _writeMixFields(trackId, mix) {
8682
- const options = { gesture: (0, import_core19.createMixerGesture)().id };
9440
+ _writeMixFields(trackId, mix, gesture = (0, import_core21.createMixerGesture)().id) {
9441
+ const options = { gesture };
8683
9442
  if (mix.volume !== void 0) this._writeMix(trackId, "volume", mix.volume, options);
8684
9443
  if (mix.pan !== void 0) this._writeMix(trackId, "pan", mix.pan, options);
8685
9444
  if (mix.muted !== void 0) this._writeMix(trackId, "muted", mix.muted, options);
@@ -8710,23 +9469,38 @@ var DawEditorElement = class extends import_lit19.LitElement {
8710
9469
  // --- Lifecycle ---
8711
9470
  connectedCallback() {
8712
9471
  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);
9472
+ if (this._connection.signal.aborted) this._connection = new AbortController();
9473
+ this._follow(this._arrangement);
9474
+ this._refreshLinkStates();
9475
+ const { signal } = this._connection;
9476
+ window.addEventListener("keydown", this._onDragEscape, { capture: true, signal });
9477
+ this.addEventListener("daw-track-connected", this._onTrackConnected, {
9478
+ signal
9479
+ });
9480
+ this.addEventListener("daw-track-update", this._onTrackUpdate, { signal });
9481
+ this.addEventListener("daw-track-control", this._onTrackControl, { signal });
9482
+ this.addEventListener("daw-track-remove", this._onTrackRemoveRequest, {
9483
+ signal
9484
+ });
9485
+ this.addEventListener("daw-clip-connected", this._onClipConnected, {
9486
+ signal
9487
+ });
8720
9488
  this.addEventListener(
8721
9489
  "daw-annotation-track-connected",
8722
- this._onAnnotationTrackConnected
9490
+ this._onAnnotationTrackConnected,
9491
+ { signal }
8723
9492
  );
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);
9493
+ this.addEventListener("daw-annotation-select", this._onAnnotationSelect, {
9494
+ signal
9495
+ });
9496
+ this.addEventListener("daw-track-reorder", this._onTrackReorder, { signal });
9497
+ this.addEventListener("daw-track-reorder-grab", this._onTrackReorderGrab, {
9498
+ signal
9499
+ });
8727
9500
  this._childObserver = new MutationObserver((mutations) => {
8728
9501
  const removedTracks = /* @__PURE__ */ new Map();
8729
9502
  const removedClips = /* @__PURE__ */ new Set();
9503
+ const clipsOfRemoved = /* @__PURE__ */ new Map();
8730
9504
  const addedTrackIds = /* @__PURE__ */ new Set();
8731
9505
  for (const mutation of mutations) {
8732
9506
  for (const node of mutation.addedNodes) {
@@ -8751,53 +9525,68 @@ var DawEditorElement = class extends import_lit19.LitElement {
8751
9525
  node.querySelectorAll?.("daw-clip").forEach((c) => {
8752
9526
  removedClips.add(c);
8753
9527
  });
9528
+ for (const t of node.tagName === "DAW-TRACK" ? [node] : [...node.querySelectorAll?.("daw-track") ?? []]) {
9529
+ clipsOfRemoved.set(t.trackId, [
9530
+ ...t.querySelectorAll("daw-clip")
9531
+ ]);
9532
+ }
8754
9533
  }
8755
9534
  }
8756
- let orderMayHaveChanged = addedTrackIds.size > 0;
9535
+ const movedTrackIds = /* @__PURE__ */ new Set();
8757
9536
  for (const [trackId] of removedTracks) {
8758
9537
  if (addedTrackIds.has(trackId)) {
8759
- orderMayHaveChanged = true;
9538
+ movedTrackIds.add(trackId);
8760
9539
  continue;
8761
9540
  }
8762
- this._onTrackRemoved(trackId);
9541
+ const children = (clipsOfRemoved.get(trackId) ?? []).filter((c) => !c.isConnected);
9542
+ this._inOneStep([this._historyOf(trackId)], () => {
9543
+ this._onTrackRemoved(trackId);
9544
+ for (const clip of children) {
9545
+ removedClips.delete(clip);
9546
+ this._onClipRemovedFromDom(clip);
9547
+ }
9548
+ });
8763
9549
  }
8764
9550
  for (const clip of removedClips) {
8765
- if (clip.isConnected) continue;
9551
+ if (clip.isConnected && this.contains(clip)) continue;
8766
9552
  this._onClipRemovedFromDom(clip);
8767
9553
  }
8768
- if (orderMayHaveChanged) this._syncEngineOrderToDom();
9554
+ if (movedTrackIds.size > 0) this._placeMovedTracks(movedTrackIds);
8769
9555
  });
8770
9556
  this._childObserver.observe(this, { childList: true, subtree: true });
8771
9557
  for (const [trackId, el] of [...this._trackElements]) {
8772
9558
  if (!this.contains(el)) this._onTrackRemoved(trackId);
8773
9559
  }
9560
+ const present = new Set(
9561
+ [...this.querySelectorAll("daw-clip")].map((c) => c.clipId)
9562
+ );
9563
+ for (const [trackId] of this._trackElements) {
9564
+ for (const clipId of this._extras.get(trackId)?.peaksSrc.keys() ?? []) {
9565
+ if (present.has(clipId)) continue;
9566
+ const holder = this._historyOf(trackId).getTracks().find((t) => t.clips.some((c) => c.id === clipId));
9567
+ if (holder) {
9568
+ this._removeClipFromTrack(holder.id, clipId);
9569
+ this._forgetClip(trackId, clipId);
9570
+ } else this._dropUnheldClip(trackId, clipId);
9571
+ }
9572
+ }
8774
9573
  if (this._externalAdapter && !this._engine) this._buildEngineReporting();
8775
9574
  }
8776
9575
  disconnectedCallback() {
8777
9576
  super.disconnectedCallback();
8778
- window.removeEventListener("keydown", this._onDragEscape, { capture: true });
9577
+ this._unfollow();
9578
+ this._unfollow = () => {
9579
+ };
9580
+ this._connection.abort(abortError("<daw-editor> was disconnected"));
8779
9581
  this._effectsManager?.disposeAll();
8780
9582
  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
9583
  this._cancelDrags(true);
8795
- for (const end of [...this._loadWaitEnds]) end();
8796
9584
  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;
9585
+ const pending = this._pending.get(trackId);
9586
+ if (!pending || "element" in pending || !this._entryWaiters.has(trackId)) continue;
9587
+ const nextPending = new Map(this._pending);
9588
+ nextPending.delete(trackId);
9589
+ this._pending = nextPending;
8801
9590
  this._entryQueue = this._entryQueue.filter((id) => id !== trackId);
8802
9591
  this._settleEntry(
8803
9592
  trackId,
@@ -8872,14 +9661,19 @@ var DawEditorElement = class extends import_lit19.LitElement {
8872
9661
  }
8873
9662
  }
8874
9663
  _onTrackRemoved(trackId) {
8875
- const existed = this._tracks.has(trackId);
9664
+ const existed = this._pending.has(trackId) || this._extras.has(trackId) || this._isEntered(trackId);
9665
+ const isPageTrack = this._trackElements.has(trackId);
9666
+ const history = this._historyOf(trackId, isPageTrack);
9667
+ const detached = this._extras.has(trackId) && !this._pending.has(trackId) && !history.getTracks().some((t) => t.id === trackId);
9668
+ const detachedClipIds = detached ? [...this._extras.get(trackId)?.peaksSrc.keys() ?? []] : [];
8876
9669
  this._rejectAwaitedClips(
8877
9670
  (_, awaitedTrackId) => awaitedTrackId === trackId,
8878
9671
  "the track of the clip was removed before the clip loaded"
8879
9672
  );
8880
9673
  this._entryQueue = this._entryQueue.filter((id) => id !== trackId);
8881
9674
  this._settleEntry(trackId, new Error('track "' + trackId + '" was removed before it entered'));
8882
- const arrangementTrack = this._arrangement.getTracks().find((t) => t.id === trackId);
9675
+ const holder = this._arrangementOf(trackId);
9676
+ const arrangementTrack = holder.getTracks().find((t) => t.id === trackId);
8883
9677
  const clipIds = arrangementTrack?.clips.map((c) => c.id) ?? [];
8884
9678
  this._announcer.forget(trackId, clipIds);
8885
9679
  if (clipIds.some((id) => this._previewPeaks.has(id))) {
@@ -8890,10 +9684,9 @@ var DawEditorElement = class extends import_lit19.LitElement {
8890
9684
  for (const id of clipIds) this._previewWaveforms.delete(id);
8891
9685
  this._trackElements.delete(trackId);
8892
9686
  this._effectsManager?.disposeTrackChain(trackId);
8893
- const removedTrack = this._engineTracks.get(trackId);
8894
- if (removedTrack) {
9687
+ if (arrangementTrack) {
8895
9688
  const nextPeaks = new Map(this._peaksData);
8896
- for (const clip of removedTrack.clips) {
9689
+ for (const clip of arrangementTrack.clips) {
8897
9690
  this._clipBuffers.delete(clip.id);
8898
9691
  this._clipOffsets.delete(clip.id);
8899
9692
  nextPeaks.delete(clip.id);
@@ -8901,17 +9694,24 @@ var DawEditorElement = class extends import_lit19.LitElement {
8901
9694
  }
8902
9695
  this._peaksData = nextPeaks;
8903
9696
  }
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;
9697
+ const nextPending = new Map(this._pending);
9698
+ nextPending.delete(trackId);
9699
+ this._pending = nextPending;
9700
+ const nextExtras = new Map(this._extras);
9701
+ nextExtras.delete(trackId);
9702
+ this._extras = nextExtras;
9703
+ if (arrangementTrack) holder.removeTrack(trackId);
9704
+ else if (detached) {
9705
+ history.removeTrack(trackId, { undoable: false });
9706
+ for (const id of detachedClipIds) {
9707
+ this._purgeClipCaches(id);
9708
+ this._previewWaveforms.delete(id);
9709
+ }
9710
+ }
8910
9711
  this._recomputeDuration();
8911
- this._arrangement.removeTrack(trackId);
8912
9712
  this._recomputeZoomFloor();
8913
9713
  this._disposeSpectrogramControllerIfEmpty();
8914
- if (existed && nextEngine.size === 0) {
9714
+ if (existed && this._arrangement.getTracks().length === 0) {
8915
9715
  if (this._engine) {
8916
9716
  if (this._isPlaying) {
8917
9717
  this._withSeekSuppression(() => this._engine.stop());
@@ -8932,10 +9732,21 @@ var DawEditorElement = class extends import_lit19.LitElement {
8932
9732
  );
8933
9733
  }
8934
9734
  }
9735
+ /** The arrangement that holds a track: the one played, else the own one (a page track while handed in). */
9736
+ _arrangementOf(trackId) {
9737
+ const has = (a) => a.getTracks().some((t) => t.id === trackId);
9738
+ return has(this._arrangement) || !has(this._ownArrangement) ? this._arrangement : this._ownArrangement;
9739
+ }
9740
+ /** Rename a track in the arrangement (an undo step); the same name changes nothing. */
9741
+ _renameTrack(trackId, name) {
9742
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9743
+ if (!track || track.name === name) return;
9744
+ this._arrangement.updateTrack(trackId, (current) => ({ ...current, name }));
9745
+ }
8935
9746
  /** Drop the controller when no spectrogram tracks remain. */
8936
9747
  _disposeSpectrogramControllerIfEmpty() {
8937
9748
  if (!this._spectrogramController) return;
8938
- const stillNeeded = Array.from(this._tracks.values()).some(
9749
+ const stillNeeded = Array.from(this._extras.values()).some(
8939
9750
  (d) => d.renderMode === "spectrogram"
8940
9751
  );
8941
9752
  if (!stillNeeded) {
@@ -8944,96 +9755,92 @@ var DawEditorElement = class extends import_lit19.LitElement {
8944
9755
  this._lastSpectrogramViewport = null;
8945
9756
  }
8946
9757
  }
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
- });
9758
+ /**
9759
+ * A `<daw-clip>` now under `trackId` whose clip another track holds: the
9760
+ * clip moves to this track (one undo step) when both have entered the same
9761
+ * arrangement; a clip of the other kind stays with `daw-clip-error`.
9762
+ * Otherwise the old track lets it go and the element goes on as a new
9763
+ * arrival. Returns true when nothing more is to be done.
9764
+ */
9765
+ _rehomeClip(trackId, clipEl) {
9766
+ const clipId = clipEl.clipId;
9767
+ if (this._extras.get(trackId)?.peaksSrc.has(clipId)) return true;
9768
+ const arrangement = this._historyOf(trackId);
9769
+ if (arrangement.getTracks().some((t) => t.id === trackId && t.clips.some((c) => c.id === clipId))) {
9770
+ let peaksSrc2 = clipEl.peaksSrc || "";
9771
+ for (const [id, extras] of this._extras) {
9772
+ if (id === trackId || !extras.peaksSrc.has(clipId)) continue;
9773
+ peaksSrc2 = extras.peaksSrc.get(clipId) ?? peaksSrc2;
9774
+ this._forgetClip(id, clipId);
9775
+ }
9776
+ this._takeClip(trackId, clipId, peaksSrc2);
9777
+ return true;
8970
9778
  }
8971
- for (const trackId of this._tracks.keys()) {
8972
- if (engineIds.has(trackId) || this._entryQueue.includes(trackId) || this._trackElements.has(trackId)) {
8973
- continue;
9779
+ const fromTrackId = trackHoldingClip(arrangement, clipId, trackId);
9780
+ if (!fromTrackId) {
9781
+ for (const [id, extras] of this._extras) {
9782
+ if (id !== trackId && extras.peaksSrc.has(clipId)) this._forgetClip(id, clipId);
8974
9783
  }
8975
- next ?? (next = new Map(this._tracks));
8976
- next.delete(trackId);
9784
+ return false;
8977
9785
  }
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 });
9786
+ const entered = arrangement.getTracks().some((t) => t.id === trackId);
9787
+ if (!entered && this._pending.has(trackId)) return true;
9788
+ const toExtras = this._extras.get(trackId) ?? this._defaultExtras(trackId);
9789
+ if (!entered || !toExtras) {
9790
+ this._takeClip(trackId, clipId, this._takenPeaksSrc(clipId) ?? clipEl.peaksSrc ?? "");
9791
+ console.warn(
9792
+ '[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.'
9793
+ );
9794
+ this.dispatchEvent(
9795
+ new CustomEvent("daw-clip-error", {
9796
+ bubbles: true,
9797
+ composed: true,
9798
+ detail: {
9799
+ trackId,
9800
+ clipId,
9801
+ error: new Error('track "' + trackId + '" is not in the arrangement')
9802
+ }
9803
+ })
9804
+ );
9805
+ this._refreshLinkStates();
9806
+ return true;
9807
+ }
9808
+ const error = moveClipToTrack(arrangement, fromTrackId, trackId, clipId, toExtras.kind);
9809
+ if (error) {
9810
+ this._takeClip(trackId, clipId, this._extras.get(fromTrackId)?.peaksSrc.get(clipId) ?? "");
9811
+ console.warn(
9812
+ '[dawcore] <daw-clip> cannot move to track "' + (this._trackElements.get(trackId)?.name || "Untitled") + '" (' + String(error) + "): its clip stays in its track."
9813
+ );
9814
+ this.dispatchEvent(
9815
+ new CustomEvent("daw-clip-error", {
9816
+ bubbles: true,
9817
+ composed: true,
9818
+ detail: { trackId, clipId, error }
9819
+ })
9820
+ );
9821
+ return true;
9822
+ }
9823
+ const peaksSrc = this._takenPeaksSrc(clipId) ?? clipEl.peaksSrc ?? "";
9824
+ for (const [id, extras] of this._extras) {
9825
+ if (id !== trackId && extras.peaksSrc.has(clipId)) this._forgetClip(id, clipId);
9019
9826
  }
9020
- return changed ? result : clips;
9827
+ if (!this._extras.has(trackId)) this._extras = new Map(this._extras).set(trackId, toExtras);
9828
+ this._takeClip(trackId, clipId, peaksSrc);
9829
+ return true;
9021
9830
  }
9022
9831
  _onClipRemovedFromDom(clipEl) {
9023
9832
  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;
9833
+ for (const arrangement of /* @__PURE__ */ new Set([this._arrangement, this._ownArrangement])) {
9834
+ for (const t of arrangement.getTracks()) {
9835
+ if (t.clips.some((c) => c.id === clipId)) {
9836
+ this._removeClipFromTrack(t.id, clipId);
9837
+ return;
9838
+ }
9028
9839
  }
9029
9840
  }
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");
9841
+ for (const [trackId, extras] of this._extras) {
9842
+ if (!extras.peaksSrc.has(clipId)) continue;
9843
+ this._dropUnheldClip(trackId, clipId);
9037
9844
  return;
9038
9845
  }
9039
9846
  this._rejectAwaitedClips((id) => id === clipId, "the clip was removed before it loaded");
@@ -9050,12 +9857,15 @@ var DawEditorElement = class extends import_lit19.LitElement {
9050
9857
  * like any other; `daw-clip-ready` or `daw-clip-error` follows (#848).
9051
9858
  */
9052
9859
  _loadAndAppendClip(trackId, clipDesc) {
9053
- const trackDesc = this._tracks.get(trackId);
9054
- if (!trackDesc) return;
9860
+ const arrangement = this._arrangementOf(trackId);
9861
+ const track = arrangement.getTracks().find((t) => t.id === trackId);
9862
+ const extras = this._extras.get(trackId) ?? this._defaultExtras(trackId);
9863
+ if (!extras || !track) return;
9864
+ if (isDomClip(clipDesc)) this._takeClip(trackId, clipDesc.clipId, clipDesc.peaksSrc);
9055
9865
  const clipIsMidi = isMidiDescriptor(clipDesc);
9056
9866
  const kindError = clipKindError(
9057
- trackDesc.name,
9058
- trackDesc.kind,
9867
+ track.name ?? "",
9868
+ extras.kind,
9059
9869
  clipIsMidi,
9060
9870
  clipDesc.name || clipDesc.src || clipDesc.clipId
9061
9871
  );
@@ -9063,7 +9873,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9063
9873
  if (!clipIsMidi) this._announcer.expectClip(clipDesc.clipId);
9064
9874
  try {
9065
9875
  if (kindError) throw kindError;
9066
- this._arrangement.updateTrack(trackId, (current) => ({
9876
+ arrangement.updateTrack(trackId, (current) => ({
9067
9877
  ...current,
9068
9878
  clips: [...current.clips, clip]
9069
9879
  }));
@@ -9078,10 +9888,6 @@ var DawEditorElement = class extends import_lit19.LitElement {
9078
9888
  );
9079
9889
  return;
9080
9890
  }
9081
- this._tracks = new Map(this._tracks).set(trackId, {
9082
- ...trackDesc,
9083
- clips: [...trackDesc.clips, clipDesc]
9084
- });
9085
9891
  if (!clipIsMidi && clipDesc.peaksSrc) this._requestPreview(clipDesc.clipId, clipDesc.peaksSrc);
9086
9892
  }
9087
9893
  /**
@@ -9101,6 +9907,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9101
9907
  );
9102
9908
  return null;
9103
9909
  } catch (err) {
9910
+ if (isAbortError(err)) return null;
9104
9911
  console.warn(
9105
9912
  "[dawcore] Failed to load peaks from " + peaksSrc + ": " + String(err) + " \u2014 falling back to AudioBuffer generation"
9106
9913
  );
@@ -9129,24 +9936,28 @@ var DawEditorElement = class extends import_lit19.LitElement {
9129
9936
  }));
9130
9937
  }
9131
9938
  _applyClipUpdate(trackId, clipId, clipEl) {
9132
- const t = this._engineTracks.get(trackId);
9939
+ const t = this._arrangement.getTracks().find((track) => track.id === trackId);
9133
9940
  if (!t) {
9134
- console.warn('[dawcore] _applyClipUpdate: no engine track for id "' + trackId + '"');
9941
+ console.warn('[dawcore] _applyClipUpdate: no track for id "' + trackId + '"');
9135
9942
  return;
9136
9943
  }
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);
9944
+ const loadedClip = this._loadedClip(trackId, clipId);
9945
+ if (!loadedClip) {
9946
+ const loading = t.clips.find((c) => c.id === clipId);
9947
+ if (loading && (0, import_core21.isLoadingClip)(loading)) {
9948
+ this._updateLoadingClip(trackId, loading, clipEl);
9949
+ return;
9950
+ }
9140
9951
  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?)')
9952
+ '[dawcore] _applyClipUpdate: clip "' + clipId + '" not found in track "' + trackId + '" (DOM/engine clip-id misalignment?)'
9142
9953
  );
9143
9954
  return;
9144
9955
  }
9145
- const oldClip = t.clips[idx];
9956
+ const oldClip = loadedClip;
9146
9957
  const sr = oldClip.sampleRate ?? this.effectiveSampleRate;
9147
9958
  const isMidiNow = clipEl.midiNotes != null && !clipEl.src;
9148
9959
  const wasMidi = oldClip.midiNotes != null;
9149
- if (isMidiNow && (0, import_core19.trackKind)(t) !== "midi") {
9960
+ if (isMidiNow && (0, import_core21.trackKind)(t) !== "midi") {
9150
9961
  const kindError = clipKindError(t.name ?? "", "audio", true, clipEl.name || clipId);
9151
9962
  console.warn("[dawcore] _applyClipUpdate: " + kindError?.message);
9152
9963
  this.dispatchEvent(
@@ -9159,6 +9970,9 @@ var DawEditorElement = class extends import_lit19.LitElement {
9159
9970
  return;
9160
9971
  }
9161
9972
  if (isMidiNow || wasMidi) {
9973
+ 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) {
9974
+ return;
9975
+ }
9162
9976
  const notes = validMidiNotes(clipEl.midiNotes ?? []);
9163
9977
  const noteSpanSeconds = notes.length ? notes.reduce((max, n) => Math.max(max, n.time + n.duration), 0) : 0;
9164
9978
  const sourceDurationSamples = Math.ceil(Math.max(noteSpanSeconds, clipEl.duration, 1) * sr);
@@ -9191,6 +10005,9 @@ var DawEditorElement = class extends import_lit19.LitElement {
9191
10005
  gain: clipEl.gain,
9192
10006
  name: clipEl.name || oldClip.name
9193
10007
  };
10008
+ if (newStartSample === oldClip.startSample && newDurationSamples === oldClip.durationSamples && newOffsetSamples === oldClip.offsetSamples && updatedClip.gain === (oldClip.gain ?? 1) && updatedClip.name === oldClip.name) {
10009
+ return;
10010
+ }
9194
10011
  const boundsChanged = oldClip.offsetSamples !== newOffsetSamples || oldClip.durationSamples !== newDurationSamples;
9195
10012
  if (boundsChanged) {
9196
10013
  this._clipOffsets.set(clipId, {
@@ -9204,9 +10021,55 @@ var DawEditorElement = class extends import_lit19.LitElement {
9204
10021
  }
9205
10022
  this._replaceClip(trackId, clipId, updatedClip);
9206
10023
  }
10024
+ /**
10025
+ * A change to a clip still loading (#848 P10): its times, gain and name in
10026
+ * seconds on the `LoadingClip`, one undo step; the audio loads into it.
10027
+ */
10028
+ _updateLoadingClip(trackId, clip, values) {
10029
+ const next = {
10030
+ ...clip,
10031
+ start: values.start,
10032
+ ...values.duration > 0 ? { duration: values.duration } : {},
10033
+ offset: values.offset,
10034
+ gain: values.gain,
10035
+ ...values.name ? { name: values.name } : {}
10036
+ };
10037
+ 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) {
10038
+ return;
10039
+ }
10040
+ this._arrangement.updateTrack(trackId, (current) => ({
10041
+ ...current,
10042
+ clips: current.clips.map((c) => c.id === clip.id ? next : c)
10043
+ }));
10044
+ }
9207
10045
  /** 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);
10046
+ /**
10047
+ * An aborted addClip (D3): its clip leaves for good, from the track it
10048
+ * entered or from what a waiting track will enter with.
10049
+ */
10050
+ _discardAddedClip(trackId, clipId) {
10051
+ const pending = this._pending.get(trackId);
10052
+ if (pending) {
10053
+ this._pending = new Map(this._pending).set(
10054
+ trackId,
10055
+ "element" in pending ? { ...pending, extraClips: pending.extraClips.filter((c) => c.clipId !== clipId) } : {
10056
+ ...pending,
10057
+ descriptor: {
10058
+ ...pending.descriptor,
10059
+ clips: pending.descriptor.clips.filter((c) => c.clipId !== clipId)
10060
+ }
10061
+ }
10062
+ );
10063
+ return;
10064
+ }
10065
+ const holder = this._arrangementOf(trackId).getTracks().find((t) => t.id === trackId);
10066
+ if (holder?.clips.some((c) => c.id === clipId)) {
10067
+ this._removeClipFromTrack(trackId, clipId, { undoable: false });
10068
+ }
10069
+ }
10070
+ _removeClipFromTrack(trackId, clipId, options = {}) {
10071
+ const arrangement = this._arrangementOf(trackId);
10072
+ const track = arrangement.getTracks().find((t) => t.id === trackId);
9210
10073
  if (!track) {
9211
10074
  console.warn('[dawcore] _removeClipFromTrack: no track for id "' + trackId + '"');
9212
10075
  return;
@@ -9224,20 +10087,43 @@ var DawEditorElement = class extends import_lit19.LitElement {
9224
10087
  nextPreview.delete(clipId);
9225
10088
  this._previewPeaks = nextPreview;
9226
10089
  }
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
- }));
10090
+ this._forgetClip(trackId, clipId);
10091
+ const wasLoading = track.clips.some((c) => c.id === clipId && (0, import_core21.isLoadingClip)(c));
10092
+ if (options.undoable === false) arrangement.removeClip(trackId, clipId, { undoable: false });
10093
+ else
10094
+ arrangement.updateTrack(trackId, (current) => ({
10095
+ ...current,
10096
+ clips: current.clips.filter((c) => c.id !== clipId)
10097
+ }));
9239
10098
  if (wasLoading) this._announcer.forgetClip(clipId);
9240
10099
  }
10100
+ /** Record that the editor took a clip of a track (with its `peaks-src`, '' when none). */
10101
+ _takeClip(trackId, clipId, peaksSrc) {
10102
+ const extras = this._extras.get(trackId);
10103
+ if (!extras || extras.peaksSrc.get(clipId) === peaksSrc) return;
10104
+ const next = new Map(extras.peaksSrc).set(clipId, peaksSrc);
10105
+ this._extras = new Map(this._extras).set(trackId, { ...extras, peaksSrc: next });
10106
+ }
10107
+ /**
10108
+ * A `<daw-clip>` the editor took is removed while the arrangement does not
10109
+ * hold its clip (its track or its own arrival undone, or refused): it is
10110
+ * gone for good, also from the undo and redo states, so no Redo brings it
10111
+ * back (maintainer's choice, #848).
10112
+ */
10113
+ _dropUnheldClip(trackId, clipId) {
10114
+ this._historyOf(trackId).removeClip(trackId, clipId, { undoable: false });
10115
+ this._purgeClipCaches(clipId);
10116
+ this._previewWaveforms.delete(clipId);
10117
+ this._forgetClip(trackId, clipId);
10118
+ }
10119
+ /** The editor no longer holds anything for a clip of a track. */
10120
+ _forgetClip(trackId, clipId) {
10121
+ const extras = this._extras.get(trackId);
10122
+ if (!extras?.peaksSrc.has(clipId)) return;
10123
+ const next = new Map(extras.peaksSrc);
10124
+ next.delete(clipId);
10125
+ this._extras = new Map(this._extras).set(trackId, { ...extras, peaksSrc: next });
10126
+ }
9241
10127
  _readTrackDescriptor(trackEl) {
9242
10128
  const clipEls = trackEl.querySelectorAll("daw-clip");
9243
10129
  const clips = [];
@@ -9313,12 +10199,9 @@ var DawEditorElement = class extends import_lit19.LitElement {
9313
10199
  _flushTrackEntries() {
9314
10200
  if (this._entryQueue.length === 0) return;
9315
10201
  if (!this._engine) return;
9316
- if (this._dragInProgress) {
9317
- this._flushAfterDrag();
9318
- return;
9319
- }
9320
- const queued = this._entryQueue;
9321
- this._entryQueue = [];
10202
+ const isPageTrack = (id) => this._trackElements.has(id);
10203
+ const queued = this._handedIn ? this._entryQueue.filter((id) => !isPageTrack(id)) : this._entryQueue;
10204
+ this._entryQueue = this._handedIn ? this._entryQueue.filter(isPageTrack) : [];
9322
10205
  const domOrder = [...this.querySelectorAll("daw-track")].map(
9323
10206
  (el) => el.trackId
9324
10207
  );
@@ -9327,12 +10210,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
9327
10210
  return at === -1 ? domOrder.length : at;
9328
10211
  };
9329
10212
  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
10213
  const arrangement = this._arrangement;
9335
- const historyWasEmpty = !arrangement.canUndo && !arrangement.canRedo && !this._dragInProgress;
10214
+ const historyWasEmpty = !arrangement.canUndo && !arrangement.canRedo;
9336
10215
  let pageEntered = false;
9337
10216
  for (const id of ordered.filter(isPageTrack)) {
9338
10217
  if (this._enterTrack(id)) pageEntered = true;
@@ -9340,32 +10219,21 @@ var DawEditorElement = class extends import_lit19.LitElement {
9340
10219
  if (historyWasEmpty && pageEntered) arrangement.clearHistory();
9341
10220
  for (const id of ordered.filter((id2) => !isPageTrack(id2))) this._enterTrack(id);
9342
10221
  }
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
10222
  /** Enter one registered track. False when it is gone, already in, or refused. */
9356
10223
  _enterTrack(trackId) {
9357
- const descriptor = this._tracks.get(trackId);
10224
+ const descriptor = this._pendingDescriptor(trackId);
9358
10225
  if (!descriptor || this._isEntered(trackId)) return false;
9359
10226
  const el = this._trackElements.get(trackId);
9360
10227
  const built = buildArrangementTrack(
9361
10228
  trackId,
9362
10229
  descriptor,
9363
- el ? mixOfElement(el) : DEFAULT_TRACK_MIX,
10230
+ this._mixOf(trackId),
9364
10231
  this.effectiveSampleRate
9365
10232
  );
9366
- if (built.descriptor !== descriptor) {
9367
- this._tracks = new Map(this._tracks).set(trackId, built.descriptor);
9368
- }
10233
+ const nextPending = new Map(this._pending);
10234
+ nextPending.delete(trackId);
10235
+ this._pending = nextPending;
10236
+ this._extras = new Map(this._extras).set(trackId, extrasOf(built.descriptor));
9369
10237
  for (const { clipId, error } of built.refused) {
9370
10238
  console.warn("[dawcore] " + error.message);
9371
10239
  this.dispatchEvent(
@@ -9381,14 +10249,45 @@ var DawEditorElement = class extends import_lit19.LitElement {
9381
10249
  trackId,
9382
10250
  this._arrangement.getTracks().map((t) => t.id)
9383
10251
  ) : 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);
10252
+ const moved = this._takeOverMovedClips(trackId, built.track);
10253
+ const entering = moved.track;
10254
+ for (const { clipId, error } of moved.refused) {
10255
+ console.warn("[dawcore] " + error.message);
10256
+ this.dispatchEvent(
10257
+ new CustomEvent("daw-clip-error", {
10258
+ bubbles: true,
10259
+ composed: true,
10260
+ detail: { trackId, clipId, error }
10261
+ })
10262
+ );
10263
+ }
10264
+ this._announcer.expect(trackId, built.refused.length + moved.refused.length);
10265
+ for (const clip of entering.clips) {
10266
+ if ((0, import_core21.isLoadingClip)(clip)) this._announcer.expectClip(clip.id);
9387
10267
  }
9388
10268
  try {
9389
- this._arrangement.addTrack(built.track, index === void 0 ? void 0 : { index });
10269
+ if (moved.from.size === 0) {
10270
+ this._arrangement.addTrack(entering, index === void 0 ? void 0 : { index });
10271
+ } else {
10272
+ this._inOneStep([this._arrangement], () => {
10273
+ for (const [fromId, clipIds] of moved.from) {
10274
+ this._arrangement.updateTrack(fromId, (t) => ({
10275
+ ...t,
10276
+ clips: t.clips.filter((c) => !clipIds.has(c.id))
10277
+ }));
10278
+ for (const clipId of clipIds) this._forgetClip(fromId, clipId);
10279
+ }
10280
+ this._arrangement.addTrack(entering, index === void 0 ? void 0 : { index });
10281
+ });
10282
+ }
9390
10283
  } catch (err) {
9391
10284
  console.warn('[dawcore] Failed to add track "' + trackId + '": ' + String(err));
10285
+ if (!el) {
10286
+ const nextExtras = new Map(this._extras);
10287
+ nextExtras.delete(trackId);
10288
+ this._extras = nextExtras;
10289
+ }
10290
+ this._refreshLinkStates();
9392
10291
  this._settleEntry(trackId, err instanceof Error ? err : new Error(String(err)));
9393
10292
  this.dispatchEvent(
9394
10293
  new CustomEvent("daw-track-error", {
@@ -9399,8 +10298,9 @@ var DawEditorElement = class extends import_lit19.LitElement {
9399
10298
  );
9400
10299
  return false;
9401
10300
  }
9402
- this._settleEntry(trackId, null);
10301
+ this._settleEntry(trackId, ENTERED);
9403
10302
  for (const clipDesc of built.descriptor.clips) {
10303
+ if (clipDesc.clipId && moved.movedIds.has(clipDesc.clipId)) continue;
9404
10304
  if (clipDesc.peaksSrc && clipDesc.clipId && clipSourceOf(clipDesc)) {
9405
10305
  this._requestPreview(clipDesc.clipId, clipDesc.peaksSrc);
9406
10306
  }
@@ -9413,7 +10313,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
9413
10313
  * `<daw-clip>` children keeps them. A track still queued reads the new
9414
10314
  * descriptor when it enters.
9415
10315
  */
9416
- _replaceShorthandClips(trackId, descriptor) {
10316
+ _replaceShorthandClips(trackId, trackEl) {
10317
+ const descriptor = this._readTrackDescriptor(trackEl);
9417
10318
  if (!this._isEntered(trackId) || descriptor.clips.some(isDomClip)) return;
9418
10319
  const built = buildArrangementTrack(
9419
10320
  trackId,
@@ -9421,7 +10322,13 @@ var DawEditorElement = class extends import_lit19.LitElement {
9421
10322
  DEFAULT_TRACK_MIX,
9422
10323
  this.effectiveSampleRate
9423
10324
  );
9424
- this._tracks = new Map(this._tracks).set(trackId, built.descriptor);
10325
+ const extras = this._extras.get(trackId);
10326
+ if (extras) {
10327
+ this._extras = new Map(this._extras).set(trackId, {
10328
+ ...extras,
10329
+ peaksSrc: extrasOf(built.descriptor).peaksSrc
10330
+ });
10331
+ }
9425
10332
  this._arrangement.updateTrack(trackId, (current) => ({ ...current, clips: built.track.clips }));
9426
10333
  }
9427
10334
  /** Run the load announcements over the arrangement's current state. */
@@ -9440,7 +10347,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9440
10347
  const waveformData = await this._resolvePeaks(peaksSrc);
9441
10348
  if (!waveformData) return;
9442
10349
  const clip = this._arrangement.getTracks().flatMap((t) => t.clips).find((c) => c.id === clipId);
9443
- if (!clip || !(0, import_core19.isLoadingClip)(clip)) return;
10350
+ if (!clip || !(0, import_core21.isLoadingClip)(clip)) return;
9444
10351
  const rate = waveformData.sample_rate;
9445
10352
  const offset = clip.offset ?? 0;
9446
10353
  const seconds = clip.duration ?? Math.max(0, waveformData.duration - offset);
@@ -9469,13 +10376,13 @@ var DawEditorElement = class extends import_lit19.LitElement {
9469
10376
  this._entryWaiters.set(trackId, { resolve, reject });
9470
10377
  });
9471
10378
  }
9472
- /** Settle the wait for a track's entry: entered (`null`), or refused or gone. */
9473
- _settleEntry(trackId, error) {
10379
+ /** Settle the wait for a track's entry: entered (`ENTERED`), or refused or gone (the reason).*/
10380
+ _settleEntry(trackId, outcome) {
9474
10381
  const waiter = this._entryWaiters.get(trackId);
9475
10382
  if (!waiter) return;
9476
10383
  this._entryWaiters.delete(trackId);
9477
- if (error) waiter.reject(error);
9478
- else waiter.resolve(trackId);
10384
+ if (outcome === ENTERED) waiter.resolve(trackId);
10385
+ else waiter.reject(outcome);
9479
10386
  }
9480
10387
  /**
9481
10388
  * A dropped file as a track with no element (a File cannot be an attribute):
@@ -9485,7 +10392,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9485
10392
  _addDroppedFile(file) {
9486
10393
  const trackId = crypto.randomUUID();
9487
10394
  const name = file.name.replace(/\.\w+$/, "");
9488
- this._tracks = new Map(this._tracks).set(trackId, {
10395
+ const descriptor = {
9489
10396
  name,
9490
10397
  src: "",
9491
10398
  kind: "audio",
@@ -9509,8 +10416,10 @@ var DawEditorElement = class extends import_lit19.LitElement {
9509
10416
  midiProgram: null
9510
10417
  }
9511
10418
  ]
9512
- });
10419
+ };
10420
+ this._pending = new Map(this._pending).set(trackId, { descriptor, mix: DEFAULT_TRACK_MIX });
9513
10421
  const entered = this._waitForEntry(trackId);
10422
+ this._endEntryOnSwap(trackId, entered);
9514
10423
  this._queueEntry(trackId);
9515
10424
  return entered;
9516
10425
  }
@@ -9518,12 +10427,29 @@ var DawEditorElement = class extends import_lit19.LitElement {
9518
10427
  * Take a track out for good: no undo step, and no undo or redo brings it
9519
10428
  * back (a dropped file that could not be loaded was never a declaration).
9520
10429
  */
9521
- _discardTrack(trackId) {
9522
- const track = this._arrangement.getTracks().find((t) => t.id === trackId);
10430
+ _discardTrack(trackId, from = this._arrangement) {
10431
+ if (from !== this._arrangement) {
10432
+ from.removeTrack(trackId, { undoable: false });
10433
+ if (this._extras.has(trackId)) {
10434
+ const nextExtras = new Map(this._extras);
10435
+ nextExtras.delete(trackId);
10436
+ this._extras = nextExtras;
10437
+ }
10438
+ return;
10439
+ }
10440
+ const track = from.getTracks().find((t) => t.id === trackId);
9523
10441
  this._announcer.forget(trackId, track?.clips.map((c) => c.id) ?? []);
9524
- this._arrangement.removeTrack(trackId, { undoable: false });
10442
+ from.removeTrack(trackId, { undoable: false });
9525
10443
  this._onTrackRemoved(trackId);
9526
10444
  }
10445
+ /** The signal of the arrangement played now: aborted when it is swapped out. */
10446
+ get _playSignal() {
10447
+ return this._playSignals.signalOf(this._arrangement);
10448
+ }
10449
+ /** @internal A caller's signal combined with the arrangement played now (loadMidi, D6). */
10450
+ _operationSignal(signal) {
10451
+ return signal ? AbortSignal.any([signal, this._playSignal]) : this._playSignal;
10452
+ }
9527
10453
  /**
9528
10454
  * Resolves once the track has loaded (`daw-track-ready`), or when the
9529
10455
  * editor is disconnected meanwhile (the track is kept and loads after a
@@ -9533,30 +10459,31 @@ var DawEditorElement = class extends import_lit19.LitElement {
9533
10459
  const state9 = this._announcer.stateOf(trackId);
9534
10460
  if (state9 === "ready") return Promise.resolve();
9535
10461
  if (state9 === "failed") return Promise.reject(this._announcer.errorOf(trackId));
10462
+ const ended = AbortSignal.any([this._playSignal, this._connection.signal]);
10463
+ if (ended.aborted) return Promise.resolve();
9536
10464
  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);
10465
+ const done = new AbortController();
10466
+ const signal = AbortSignal.any([ended, done.signal]);
10467
+ this.addEventListener(
10468
+ "daw-track-ready",
10469
+ (e) => {
10470
+ if (e.detail.trackId !== trackId) return;
10471
+ done.abort();
10472
+ resolve();
10473
+ },
10474
+ { signal }
10475
+ );
10476
+ this.addEventListener(
10477
+ "daw-track-error",
10478
+ (e) => {
10479
+ const detail = e.detail;
10480
+ if (detail.trackId !== trackId) return;
10481
+ done.abort();
10482
+ reject(detail.error instanceof Error ? detail.error : new Error(String(detail.error)));
10483
+ },
10484
+ { signal }
10485
+ );
10486
+ ended.addEventListener("abort", () => resolve(), { signal: done.signal });
9560
10487
  });
9561
10488
  }
9562
10489
  /**
@@ -9572,14 +10499,14 @@ var DawEditorElement = class extends import_lit19.LitElement {
9572
10499
  }
9573
10500
  const sources = this._arrangement.sources.getSnapshot().sources;
9574
10501
  const failed = new Set(
9575
- track.clips.filter(import_core19.isLoadingClip).map((clip) => clip.src).filter((src) => sources.get(src)?.status === "failed")
10502
+ track.clips.filter(import_core21.isLoadingClip).map((clip) => clip.src).filter((src) => sources.get(src)?.status === "failed")
9576
10503
  );
9577
10504
  for (const src of failed) this._arrangement.retry(src);
9578
10505
  }
9579
10506
  _fetchPeaks(src) {
9580
10507
  const cached = this._peaksCache.get(src);
9581
10508
  if (cached) return cached;
9582
- const promise = loadWaveformDataFromUrl(src).catch((err) => {
10509
+ const promise = loadWaveformDataFromUrl(src, this._playSignal).catch((err) => {
9583
10510
  this._peaksCache.delete(src);
9584
10511
  throw err;
9585
10512
  });
@@ -9594,7 +10521,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9594
10521
  _recomputeDuration() {
9595
10522
  const sr = this.effectiveSampleRate;
9596
10523
  let maxSample = 0;
9597
- for (const track of this._engineTracks.values()) {
10524
+ for (const track of this._loadedTracks()) {
9598
10525
  for (const clip of track.clips) {
9599
10526
  const endSample = clip.startSample + clip.durationSamples;
9600
10527
  if (endSample > maxSample) maxSample = endSample;
@@ -9602,7 +10529,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9602
10529
  }
9603
10530
  for (const track of this._arrangement.getTracks()) {
9604
10531
  for (const clip of track.clips) {
9605
- if (!(0, import_core19.isLoadingClip)(clip)) continue;
10532
+ if (!(0, import_core21.isLoadingClip)(clip)) continue;
9606
10533
  const seconds = this._placeholderSeconds(clip);
9607
10534
  if (seconds === null) continue;
9608
10535
  maxSample = Math.max(maxSample, Math.round(((clip.start ?? 0) + seconds) * sr));
@@ -9641,6 +10568,16 @@ var DawEditorElement = class extends import_lit19.LitElement {
9641
10568
  this._buildEngine();
9642
10569
  } catch (err) {
9643
10570
  console.warn("[dawcore] Failed to build the engine: " + String(err));
10571
+ const error = err instanceof Error ? err : new Error(String(err));
10572
+ for (const trackId of [...this._entryQueue]) {
10573
+ const pending = this._pending.get(trackId);
10574
+ if (!pending || "element" in pending || !this._entryWaiters.has(trackId)) continue;
10575
+ const nextPending = new Map(this._pending);
10576
+ nextPending.delete(trackId);
10577
+ this._pending = nextPending;
10578
+ this._entryQueue = this._entryQueue.filter((id) => id !== trackId);
10579
+ this._settleEntry(trackId, error);
10580
+ }
9644
10581
  this.dispatchEvent(
9645
10582
  new CustomEvent("daw-error", {
9646
10583
  bubbles: true,
@@ -9666,7 +10603,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9666
10603
  }
9667
10604
  adapter.setPpqn?.(this._ppqn);
9668
10605
  this.ppqn = adapter.ppqn;
9669
- const engine = new import_engine.PlaylistEngine({
10606
+ const engine = new import_engine3.PlaylistEngine({
9670
10607
  adapter,
9671
10608
  arrangement: this._arrangement,
9672
10609
  sampleRate: adapter.audioContext.sampleRate,
@@ -9682,8 +10619,11 @@ var DawEditorElement = class extends import_lit19.LitElement {
9682
10619
  });
9683
10620
  engine.on("stop", () => this._onEngineStop(engine));
9684
10621
  this._engine = engine;
10622
+ if (this._selectionStartTime !== 0 || this._selectionEndTime !== 0) {
10623
+ engine.setSelection(this._selectionStartTime, this._selectionEndTime);
10624
+ }
9685
10625
  this._onEngineState(engine.getState());
9686
- for (const track of this._engineTracks.values()) {
10626
+ for (const track of this._loadedTracks()) {
9687
10627
  for (const clip of track.clips) this._maybeRegisterSpectrogramClipAudio(track.id, clip);
9688
10628
  }
9689
10629
  this._flushTrackEntries();
@@ -9709,7 +10649,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9709
10649
  }
9710
10650
  }
9711
10651
  }
9712
- /** The engine's state changed: follow it (the one writer of `_engineTracks`). */
10652
+ /** The engine's state changed: draw it (the rows are read from the arrangement). */
9713
10653
  _onEngineState(engineState) {
9714
10654
  this._isPlaying = engineState.isPlaying;
9715
10655
  this._selectedTrackId = engineState.selectedTrackId;
@@ -9718,20 +10658,12 @@ var DawEditorElement = class extends import_lit19.LitElement {
9718
10658
  if (structuralChange || mixerChange) {
9719
10659
  this._lastTracksVersion = engineState.tracksVersion;
9720
10660
  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);
10661
+ this.requestUpdate();
9727
10662
  }
9728
10663
  if (structuralChange) {
9729
10664
  this._recomputeDuration();
9730
- if (!this._inOrderSync) {
9731
- this._syncDomToEngineOrder(engineState.tracks);
9732
- }
9733
10665
  this._effectsManager?.rewireTrackChains();
9734
- const audioTracks = engineState.tracks.filter((t) => (0, import_core19.trackKind)(t) !== "midi");
10666
+ const audioTracks = engineState.tracks.filter((t) => (0, import_core21.trackKind)(t) !== "midi");
9735
10667
  this._adoptLoadedClips(audioTracks);
9736
10668
  syncPeaksForChangedClips(this, audioTracks);
9737
10669
  this._announceLoading();
@@ -9755,17 +10687,18 @@ var DawEditorElement = class extends import_lit19.LitElement {
9755
10687
  this._engine = null;
9756
10688
  }
9757
10689
  }
9758
- async loadFiles(files) {
9759
- return loadFiles(this, files);
10690
+ async loadFiles(files, options = {}) {
10691
+ return loadFiles(this, files, options);
9760
10692
  }
9761
10693
  /**
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.
10694
+ * Imperatively load a `.mid` file (URL or File) and add N tracks (no
10695
+ * element, #848), one per note-bearing MIDI track. On any per-track
10696
+ * failure, every track the call added is removed with no undo step, so the
10697
+ * editor is as before the call.
9766
10698
  *
9767
- * `options.signal` is forwarded to `fetch()` only for URL sources; aborting
9768
- * after parsing does not cancel in-flight `addTrack` calls.
10699
+ * `options.signal` cancels the fetch, the parse and the tracks still
10700
+ * waiting to enter (combined with the arrangement played: a swap cancels
10701
+ * too); the call rejects with its `reason` and removes the tracks it added.
9769
10702
  *
9770
10703
  * Requires the optional `@dawcore/midi` peer dep — throws with an install
9771
10704
  * hint (and `console.warn`s the original error) when the dynamic import
@@ -9784,25 +10717,41 @@ var DawEditorElement = class extends import_lit19.LitElement {
9784
10717
  return this._ensureEngine();
9785
10718
  }
9786
10719
  /**
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.
10720
+ * Add a track built from `config` to the arrangement the editor plays when
10721
+ * it is called, and resolve with its id once it has entered (#848), before
10722
+ * its audio has loaded. A swap of `editor.arrangement` before it enters
10723
+ * rejects with an `AbortError` and the track enters nowhere; to add to
10724
+ * another arrangement, call that arrangement's own `addTrack`. No element is created: the track is drawn and listed like any
10725
+ * other, and `<daw-track>` children stay the page's declaration. To follow
10726
+ * loading, add the `daw-track-ready` / `daw-track-error` listener BEFORE
10727
+ * calling: for a track with nothing to fetch it fires before this
10728
+ * resolves. Without `editor.adapter` it waits for one. Rejects when the
10729
+ * arrangement refuses the track, when it is removed before it enters, or
10730
+ * when the engine cannot be built.
10731
+ *
10732
+ * `options.signal` (#848): aborting it before the track has entered takes
10733
+ * it out of the queue (it never enters) and rejects with its `reason`;
10734
+ * after that it changes nothing (the audio goes on loading). A signal
10735
+ * already aborted rejects at once and queues nothing.
9794
10736
  */
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);
10737
+ addTrack(config = {}, options = {}) {
10738
+ const signal = options.signal;
10739
+ if (signal?.aborted) return Promise.reject(reasonOf(signal));
10740
+ const trackId = crypto.randomUUID();
10741
+ let kind = config.kind ?? (config.midi ? "midi" : "audio");
10742
+ if (kind !== "audio" && kind !== "midi") {
10743
+ console.warn(
10744
+ '[dawcore] addTrack: kind "' + String(kind) + `" is not a track kind ('audio' or 'midi'); using "audio"`
10745
+ );
10746
+ kind = "audio";
10747
+ }
10748
+ let renderMode = normalizeRenderMode(config.renderMode);
10749
+ if (renderMode === "both") {
10750
+ console.warn(
10751
+ `[dawcore] render-mode="both" is not yet supported; falling back to 'spectrogram'`
10752
+ );
10753
+ renderMode = "spectrogram";
10754
+ }
9806
10755
  const clipConfigs = [...config.clips ?? []];
9807
10756
  if (config.midi) {
9808
10757
  clipConfigs.push({
@@ -9811,115 +10760,194 @@ var DawEditorElement = class extends import_lit19.LitElement {
9811
10760
  midiProgram: config.midi.program
9812
10761
  });
9813
10762
  }
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;
10763
+ const descriptor = {
10764
+ name: config.name || "Untitled",
10765
+ src: "",
10766
+ kind,
10767
+ renderMode: trackDescriptorRenderMode(kind, renderMode),
10768
+ spectrogramConfig: config.spectrogramConfig ?? null,
10769
+ clips: clipConfigs.map((c) => clipDescriptorOf(c))
10770
+ };
10771
+ const mix = {
10772
+ volume: config.volume ?? DEFAULT_TRACK_MIX.volume,
10773
+ pan: config.pan ?? DEFAULT_TRACK_MIX.pan,
10774
+ muted: config.muted ?? false,
10775
+ soloed: config.soloed ?? false
10776
+ };
10777
+ this._pending = new Map(this._pending).set(trackId, { descriptor, mix });
10778
+ const entered = this._waitForEntry(trackId);
10779
+ this._endEntryOnSwap(trackId, entered);
10780
+ this._queueEntry(trackId);
10781
+ if (!signal) return entered;
10782
+ const settled = new AbortController();
10783
+ signal.addEventListener("abort", () => this._abortEntry(trackId, reasonOf(signal)), {
10784
+ signal: settled.signal
10785
+ });
10786
+ return entered.finally(() => settled.abort());
10787
+ }
10788
+ /**
10789
+ * A queued track goes into the arrangement played when it was queued: when
10790
+ * that one is swapped out first, the track leaves the queue and its wait
10791
+ * rejects with the swap's AbortError (addTrack, a dropped file).
10792
+ */
10793
+ _endEntryOnSwap(trackId, entered) {
10794
+ const settled = new AbortController();
10795
+ this._playSignal.addEventListener(
10796
+ "abort",
10797
+ (e) => this._abortEntry(trackId, reasonOf(e.target)),
10798
+ { signal: settled.signal }
10799
+ );
10800
+ void entered.then(
10801
+ () => settled.abort(),
10802
+ () => settled.abort()
10803
+ );
10804
+ }
10805
+ /** A track that has not entered leaves the queue and its wait rejects with `reason` (D4). */
10806
+ _abortEntry(trackId, reason) {
10807
+ if (!this._pending.has(trackId) || this._isEntered(trackId)) return;
10808
+ const nextPending = new Map(this._pending);
10809
+ nextPending.delete(trackId);
10810
+ this._pending = nextPending;
10811
+ this._settleEntry(trackId, reason);
10812
+ this.requestUpdate();
9820
10813
  }
9821
10814
  /**
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.
10815
+ * Remove a track by id: its `<daw-track>` element is removed (the
10816
+ * MutationObserver does the rest), or, for a track with no element
10817
+ * (`addTrack`, a dropped file, an Undo), the track itself. One undo step.
10818
+ * Warns when no track has the id.
9825
10819
  */
9826
10820
  removeTrack(trackId) {
9827
10821
  const trackEl = this._trackElements.get(trackId);
9828
10822
  if (trackEl) {
9829
10823
  trackEl.remove();
9830
10824
  if (!this.isConnected) this._onTrackRemoved(trackId);
9831
- } else if (this._tracks.has(trackId) || this._isEntered(trackId)) {
10825
+ } else if (this._pending.has(trackId) || this._extras.has(trackId) || this._isEntered(trackId)) {
9832
10826
  this._onTrackRemoved(trackId);
9833
10827
  } else {
9834
10828
  console.warn('[dawcore] removeTrack: no track found for id "' + trackId + '"');
9835
10829
  }
9836
10830
  }
9837
10831
  /**
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.
10832
+ * Move a track to a 0-based position in the arrangement's order (every
10833
+ * track counts, those with no element too; `trackEl.index` and
10834
+ * `editor.tracks` give the positions). One undo step; no element moves.
9842
10835
  */
9843
10836
  reorderTrack(trackId, toIndex) {
9844
10837
  if (!Number.isFinite(toIndex)) {
9845
10838
  console.warn("[dawcore] reorderTrack: invalid toIndex " + String(toIndex));
9846
10839
  return;
9847
10840
  }
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 {
10841
+ if (!this._isEntered(trackId)) {
9862
10842
  console.warn('[dawcore] reorderTrack: no track found for id "' + trackId + '"');
10843
+ return;
9863
10844
  }
10845
+ const last = this._arrangement.getTracks().length - 1;
10846
+ this._arrangement.reorderTrack(trackId, Math.max(0, Math.min(Math.trunc(toIndex), last)));
9864
10847
  }
9865
10848
  /**
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.
10849
+ * Change a track: the mix (one undo step, #843), the name (an undo step),
10850
+ * the render mode and spectrogram config (the editor's). The arrangement
10851
+ * is changed, never an element's attributes (#848): a `<daw-track>`'s
10852
+ * properties show the change. A track that has not entered yet gets it as
10853
+ * the value it enters with.
9871
10854
  */
9872
10855
  updateTrack(trackId, partial) {
10856
+ if (!this._isEntered(trackId)) {
10857
+ this._updatePendingTrack(trackId, partial);
10858
+ return;
10859
+ }
9873
10860
  const mix = {
9874
10861
  volume: partial.volume,
9875
10862
  pan: partial.pan,
9876
10863
  muted: partial.muted,
9877
10864
  soloed: partial.soloed
9878
10865
  };
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") {
10866
+ this._writeMixFields(trackId, mix);
10867
+ if (partial.name !== void 0) this._renameTrack(trackId, partial.name);
10868
+ const extras = this._extras.get(trackId) ?? this._defaultExtras(trackId);
10869
+ if (!extras) return;
10870
+ let renderMode = partial.renderMode === void 0 ? void 0 : normalizeRenderMode(partial.renderMode);
10871
+ if (renderMode === "both") {
9900
10872
  console.warn(
9901
10873
  `[dawcore] render-mode="both" is not yet supported; falling back to 'spectrogram'`
9902
10874
  );
9903
- normalizedRenderMode = "spectrogram";
10875
+ renderMode = "spectrogram";
9904
10876
  }
9905
- const newDesc = {
9906
- ...oldDesc,
9907
- ...partial.name !== void 0 && { name: partial.name },
9908
- ...normalizedRenderMode !== void 0 && {
9909
- renderMode: trackDescriptorRenderMode(oldDesc.kind, normalizedRenderMode)
10877
+ if (renderMode === void 0 && partial.spectrogramConfig === void 0) return;
10878
+ const next = {
10879
+ ...extras,
10880
+ ...renderMode !== void 0 && {
10881
+ renderMode: trackDescriptorRenderMode(extras.kind, renderMode)
10882
+ },
10883
+ ...partial.spectrogramConfig !== void 0 && {
10884
+ spectrogramConfig: partial.spectrogramConfig
9910
10885
  }
9911
10886
  };
9912
- this._tracks = new Map(this._tracks).set(trackId, newDesc);
9913
- this._writeMixFields(trackId, mix);
10887
+ this._extras = new Map(this._extras).set(trackId, next);
10888
+ if (next.spectrogramConfig !== extras.spectrogramConfig) {
10889
+ this._spectrogramController?.setTrackConfig(trackId, next.spectrogramConfig ?? null);
10890
+ }
10891
+ }
10892
+ /** `updateTrack` on a track waiting to enter: the values it will enter with. */
10893
+ _updatePendingTrack(trackId, partial) {
10894
+ const pending = this._pending.get(trackId);
10895
+ if (!pending) {
10896
+ console.warn('[dawcore] updateTrack: no track found for id "' + trackId + '"');
10897
+ return;
10898
+ }
10899
+ if ("element" in pending) {
10900
+ const el = pending.element;
10901
+ if (partial.name !== void 0) el.name = partial.name;
10902
+ if (partial.volume !== void 0) el.volume = partial.volume;
10903
+ if (partial.pan !== void 0) el.pan = partial.pan;
10904
+ if (partial.muted !== void 0) el.muted = partial.muted;
10905
+ if (partial.soloed !== void 0) el.soloed = partial.soloed;
10906
+ if (partial.renderMode !== void 0) el.renderMode = partial.renderMode;
10907
+ if (partial.spectrogramConfig !== void 0) el.spectrogramConfig = partial.spectrogramConfig;
10908
+ return;
10909
+ }
10910
+ const { descriptor, mix } = pending;
10911
+ this._pending = new Map(this._pending).set(trackId, {
10912
+ descriptor: {
10913
+ ...descriptor,
10914
+ ...partial.spectrogramConfig !== void 0 && {
10915
+ spectrogramConfig: partial.spectrogramConfig
10916
+ },
10917
+ ...partial.name !== void 0 && { name: partial.name },
10918
+ ...partial.renderMode !== void 0 && {
10919
+ renderMode: trackDescriptorRenderMode(
10920
+ descriptor.kind,
10921
+ normalizeRenderMode(partial.renderMode)
10922
+ )
10923
+ }
10924
+ },
10925
+ mix: {
10926
+ volume: partial.volume ?? mix.volume,
10927
+ pan: partial.pan ?? mix.pan,
10928
+ muted: partial.muted ?? mix.muted,
10929
+ soloed: partial.soloed ?? mix.soloed
10930
+ }
10931
+ });
9914
10932
  }
9915
10933
  /**
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
10934
+ * Add a clip to a track (with or without an element) and resolve with its
9918
10935
  * 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).
10936
+ * drawn). The clip enters the arrangement as a loading clip, one undo
10937
+ * step; no `<daw-clip>` is created (#848). Rejects when it fails to load,
10938
+ * is refused (its kind), or leaves the arrangement before it loads (a
10939
+ * removal, an Undo). A clip added while the editor is detached loads once
10940
+ * a fresh adapter is set.
10941
+ *
10942
+ * `options.signal` (#848): aborting it before the clip has loaded rejects
10943
+ * with its `reason` and removes the clip for good (no undo step); after it
10944
+ * has loaded it changes nothing. A signal already aborted rejects at once
10945
+ * and adds nothing. A swap of `editor.arrangement` rejects the call with an
10946
+ * `AbortError`; its loading clip stays in the arrangement swapped out.
9921
10947
  */
9922
- addClip(trackId, config) {
10948
+ addClip(trackId, config, options = {}) {
10949
+ const callerSignal = options.signal;
10950
+ if (callerSignal?.aborted) return Promise.reject(reasonOf(callerSignal));
9923
10951
  if (!config.src) {
9924
10952
  return Promise.reject(
9925
10953
  new Error(
@@ -9927,38 +10955,45 @@ var DawEditorElement = class extends import_lit19.LitElement {
9927
10955
  )
9928
10956
  );
9929
10957
  }
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)) {
10958
+ const pending = this._pending.get(trackId);
10959
+ if (!this._isEntered(trackId) && !pending) {
9939
10960
  return Promise.reject(
9940
10961
  new Error(
9941
- 'addClip: track "' + trackId + '" is not in the editor (an Undo took it out, or the arrangement refused it)'
10962
+ 'addClip: track "' + trackId + '" is not in the editor (an Undo took it out, the arrangement refused it, or no track has this id)'
9942
10963
  )
9943
10964
  );
9944
10965
  }
9945
- const clipEl = this._buildClipElement(config);
9946
- const clipId = clipEl.clipId;
10966
+ const clipDesc = clipDescriptorOf(config);
10967
+ const clipId = clipDesc.clipId;
9947
10968
  return new Promise((resolve, reject) => {
9948
10969
  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)));
10970
+ const call = new AbortController();
10971
+ const cleanup = () => {
10972
+ call.abort();
10973
+ this._awaitedClips.delete(clipId);
9959
10974
  };
9960
- const stopWatching = this._arrangement.subscribe(() => {
9961
- const present = this._arrangement.getTracks().some((t) => t.clips.some((c) => c.id === clipId));
10975
+ this.addEventListener(
10976
+ "daw-clip-ready",
10977
+ (e) => {
10978
+ if (e.detail.clipId !== clipId) return;
10979
+ cleanup();
10980
+ resolve(clipId);
10981
+ },
10982
+ { signal: call.signal }
10983
+ );
10984
+ this.addEventListener(
10985
+ "daw-clip-error",
10986
+ (e) => {
10987
+ const detail = e.detail;
10988
+ if (detail.clipId !== clipId) return;
10989
+ cleanup();
10990
+ reject(detail.error instanceof Error ? detail.error : new Error(String(detail.error)));
10991
+ },
10992
+ { signal: call.signal }
10993
+ );
10994
+ const watched = pending && "element" in pending && !this._isEntered(trackId) ? this._ownArrangement : this._arrangement;
10995
+ const stopWatching = watched.subscribe(() => {
10996
+ const present = watched.getTracks().some((t) => t.clips.some((c) => c.id === clipId));
9962
10997
  if (present) {
9963
10998
  seen = true;
9964
10999
  } else if (seen) {
@@ -9966,14 +11001,24 @@ var DawEditorElement = class extends import_lit19.LitElement {
9966
11001
  reject(new Error('clip "' + clipId + '" was removed before its audio loaded'));
9967
11002
  }
9968
11003
  });
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);
11004
+ call.signal.addEventListener("abort", stopWatching);
11005
+ this._playSignals.signalOf(watched).addEventListener(
11006
+ "abort",
11007
+ (e) => {
11008
+ cleanup();
11009
+ reject(reasonOf(e.target));
11010
+ },
11011
+ { signal: call.signal }
11012
+ );
11013
+ callerSignal?.addEventListener(
11014
+ "abort",
11015
+ () => {
11016
+ cleanup();
11017
+ this._discardAddedClip(trackId, clipId);
11018
+ reject(reasonOf(callerSignal));
11019
+ },
11020
+ { signal: call.signal }
11021
+ );
9977
11022
  this._awaitedClips.set(clipId, {
9978
11023
  trackId,
9979
11024
  reject: (error) => {
@@ -9981,122 +11026,91 @@ var DawEditorElement = class extends import_lit19.LitElement {
9981
11026
  reject(error);
9982
11027
  }
9983
11028
  });
9984
- trackEl.appendChild(clipEl);
11029
+ if (this._isEntered(trackId)) {
11030
+ seen = true;
11031
+ this._loadAndAppendClip(trackId, clipDesc);
11032
+ } else if (pending) {
11033
+ this._pending = new Map(this._pending).set(
11034
+ trackId,
11035
+ "element" in pending ? { ...pending, extraClips: [...pending.extraClips, clipDesc] } : {
11036
+ ...pending,
11037
+ descriptor: {
11038
+ ...pending.descriptor,
11039
+ clips: [...pending.descriptor.clips, clipDesc]
11040
+ }
11041
+ }
11042
+ );
11043
+ }
9985
11044
  });
9986
11045
  }
9987
11046
  /**
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.
11047
+ * Remove a clip by id: its `<daw-clip>` when there is one (the observer
11048
+ * removes the clip, as `select.remove(i)` removes an option), otherwise
11049
+ * the clip itself, one undo step. Undo brings the clip back with no
11050
+ * element. No-op with a warning when there is no such clip.
9991
11051
  */
9992
11052
  removeClip(trackId, clipId) {
9993
11053
  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
- }
11054
+ const clipEl = trackEl ? [...trackEl.querySelectorAll("daw-clip")].find(
11055
+ (c) => c.clipId === clipId
11056
+ ) : void 0;
11057
+ if (clipEl) {
11058
+ clipEl.remove();
11059
+ if (!this.isConnected && this._isEntered(trackId)) this._removeClipFromTrack(trackId, clipId);
11060
+ return;
10002
11061
  }
10003
11062
  if (this._isEntered(trackId)) {
10004
11063
  this._removeClipFromTrack(trackId, clipId);
10005
11064
  return;
10006
11065
  }
11066
+ const pending = this._pending.get(trackId);
11067
+ if (pending) {
11068
+ const without = (clips) => clips.filter((c) => c.clipId !== clipId);
11069
+ this._pending = new Map(this._pending).set(
11070
+ trackId,
11071
+ "element" in pending ? { ...pending, extraClips: without(pending.extraClips) } : {
11072
+ ...pending,
11073
+ descriptor: { ...pending.descriptor, clips: without(pending.descriptor.clips) }
11074
+ }
11075
+ );
11076
+ this._rejectAwaitedClips((id) => id === clipId, "the clip was removed before it loaded");
11077
+ return;
11078
+ }
10007
11079
  console.warn(
10008
11080
  '[dawcore] removeClip: no track found for id "' + trackId + '" (clipId "' + clipId + '")'
10009
11081
  );
10010
11082
  }
10011
11083
  /**
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`.
11084
+ * Change a clip's position (start/duration/offset), gain or name: one undo
11085
+ * step on the arrangement (#848; a clip still loading changes its loading
11086
+ * clip). A `<daw-clip>`'s properties show the change, its attributes do
11087
+ * not. Fades are a `<daw-clip>` declaration only (engine-side fades are
11088
+ * #489): `fadeIn` / `fadeOut` / `fadeType` here change nothing.
10015
11089
  *
10016
11090
  * Re-decoding (changing `src`) is not supported via this method — remove and
10017
11091
  * 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
11092
  */
10024
11093
  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) {
11094
+ if (!this._isEntered(trackId)) {
10044
11095
  console.warn('[dawcore] updateClip: no track found for id "' + trackId + '"');
10045
11096
  return;
10046
11097
  }
10047
- const idx = t.clips.findIndex((c) => c.id === clipId);
10048
- if (idx === -1) {
11098
+ if (!this._clipValues(trackId, clipId)) {
10049
11099
  console.warn(
10050
11100
  '[dawcore] updateClip: clip "' + clipId + '" not found in track "' + trackId + '"'
10051
11101
  );
10052
11102
  return;
10053
11103
  }
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;
11104
+ const request = {};
11105
+ if (partial.start !== void 0) request.start = partial.start;
11106
+ if (partial.duration !== void 0) request.duration = partial.duration;
11107
+ if (partial.offset !== void 0) request.offset = partial.offset;
11108
+ if (partial.gain !== void 0) request.gain = partial.gain;
11109
+ if (partial.name !== void 0) request.name = partial.name;
11110
+ if (partial.midiNotes !== void 0) request.midiNotes = partial.midiNotes;
11111
+ if (partial.midiChannel !== void 0) request.midiChannel = partial.midiChannel;
11112
+ if (partial.midiProgram !== void 0) request.midiProgram = partial.midiProgram;
11113
+ this._requestClipChange(trackId, clipId, request);
10100
11114
  }
10101
11115
  // --- Playback ---
10102
11116
  /**
@@ -10363,8 +11377,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
10363
11377
  return;
10364
11378
  }
10365
11379
  const targetId = options?.trackId ?? this._selectedTrackId;
10366
- const target = targetId ? this._tracks.get(targetId) : void 0;
10367
- if (targetId && target?.kind === "midi") {
11380
+ const target = targetId ? this._arrangement.getTracks().find((t) => t.id === targetId) : void 0;
11381
+ if (targetId && target && (0, import_core21.trackKind)(target) === "midi") {
10368
11382
  const error = new Error(
10369
11383
  'Cannot record onto MIDI track "' + target.name + '": a recording is audio. Select or create an audio track first.'
10370
11384
  );
@@ -10471,67 +11485,25 @@ var DawEditorElement = class extends import_lit19.LitElement {
10471
11485
  return (this._getOrderedTracks().length > 0 || this.scaleMode === "beats" || this.indefinitePlayback || this.fillViewport) && this.timescale;
10472
11486
  }
10473
11487
  /**
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.
11488
+ * `<daw-track>` elements the page moved (one MutationObserver batch): each
11489
+ * is placed after the arrangement track of the nearest `<daw-track>` before
11490
+ * it, in DOM order, as one undo step (#848 P13). Elements whose track is
11491
+ * not in the arrangement are left alone (a queued one enters at its DOM
11492
+ * position). The arrangement's own order changes (an Undo) move no element.
10481
11493
  */
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;
11494
+ _placeMovedTracks(movedIds) {
11495
+ const els = [...this.querySelectorAll("daw-track")];
11496
+ const moved = els.filter((el) => movedIds.has(el.trackId) && this._isEntered(el.trackId));
11497
+ if (moved.length === 0) return;
11498
+ const arrangement = this._arrangement;
11499
+ arrangement.beginTransaction();
10498
11500
  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();
11501
+ for (const el of moved) {
11502
+ const others = arrangement.getTracks().map((t) => t.id).filter((id) => id !== el.trackId);
11503
+ arrangement.reorderTrack(el.trackId, entryIndex(els, el.trackId, others));
11504
+ }
10509
11505
  } 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]);
11506
+ arrangement.commitTransaction();
10535
11507
  }
10536
11508
  }
10537
11509
  /**
@@ -10541,9 +11513,12 @@ var DawEditorElement = class extends import_lit19.LitElement {
10541
11513
  _getOrderedTracks() {
10542
11514
  const rows = [];
10543
11515
  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)]);
11516
+ const loaded = loadedTrack(
11517
+ track,
11518
+ this._mixOf(track.id),
11519
+ this._arrangement.recordingTrackIds.has(track.id)
11520
+ );
11521
+ rows.push([track.id, loaded, track.clips.filter(import_core21.isLoadingClip)]);
10547
11522
  }
10548
11523
  return rows;
10549
11524
  }
@@ -10566,7 +11541,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
10566
11541
  } else {
10567
11542
  const startSample = Math.round(startSec * sr);
10568
11543
  left = Math.floor(startSample / spp);
10569
- width = (0, import_core19.clipPixelWidth)(startSample, Math.round(seconds * sr), spp);
11544
+ width = (0, import_core21.clipPixelWidth)(startSample, Math.round(seconds * sr), spp);
10570
11545
  }
10571
11546
  const failed = this._arrangement.sources.getSnapshot().sources.get(clip.src)?.status === "failed";
10572
11547
  const peakData = this._previewPeaks.get(clip.id);
@@ -10612,7 +11587,11 @@ var DawEditorElement = class extends import_lit19.LitElement {
10612
11587
  selEndPx = this._selectionEndTime * sr / spp;
10613
11588
  }
10614
11589
  const orderedTracks = this._getOrderedTracks().map(([trackId, track, loading]) => {
10615
- const descriptor = this._tracks.get(trackId);
11590
+ const descriptor = {
11591
+ name: track.name ?? "",
11592
+ kind: (0, import_core21.trackKind)(track),
11593
+ renderMode: this._renderModeOf(trackId)
11594
+ };
10616
11595
  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
11596
  const recSession = this._recordingController.getSession(trackId);
10618
11597
  const numChannels = firstPeaks ? firstPeaks.data.length : recSession ? recSession.channelCount : 1;
@@ -10660,24 +11639,30 @@ var DawEditorElement = class extends import_lit19.LitElement {
10660
11639
  <span class="annotation-lane-name">${track.name}</span>
10661
11640
  </div>`
10662
11641
  )}
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
- })}
11642
+ ${(0, import_repeat.repeat)(
11643
+ orderedTracks,
11644
+ // Keyed by track: a swap or an outside reorder must not hand
11645
+ // a row (and a slider gesture held in it) to another track.
11646
+ (t) => t.trackId,
11647
+ (t, i) => {
11648
+ const mix = this._mixOf(t.trackId);
11649
+ return import_lit19.html`
11650
+ <daw-track-controls
11651
+ style="height: ${t.trackHeight}px;"
11652
+ .trackId=${t.trackId}
11653
+ .trackName=${t.descriptor?.name ?? "Untitled"}
11654
+ .volume=${mix.volume}
11655
+ .pan=${mix.pan}
11656
+ .muted=${mix.muted}
11657
+ .recording=${this._engine?.recordingTrackIds.has(t.trackId) ?? false}
11658
+ .soloed=${mix.soloed}
11659
+ .reorderable=${this.trackReordering}
11660
+ .trackIndex=${i}
11661
+ .trackCount=${orderedTracks.length}
11662
+ ></daw-track-controls>
11663
+ `;
11664
+ }
11665
+ )}
10681
11666
  </div>
10682
11667
  </div>` : ""}
10683
11668
  <div class="scroll-area">
@@ -10708,149 +11693,158 @@ var DawEditorElement = class extends import_lit19.LitElement {
10708
11693
  ></daw-grid>` : ""}
10709
11694
  ${orderedTracks.length > 0 || this.scaleMode === "beats" || this.indefinitePlayback || this.fillViewport ? import_lit19.html`<daw-selection .startPx=${selStartPx} .endPx=${selEndPx}></daw-selection>
10710
11695
  <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));
11696
+ ${(0, import_repeat.repeat)(
11697
+ orderedTracks,
11698
+ (t) => t.trackId,
11699
+ (t) => {
11700
+ const channelHeight = this.waveHeight;
11701
+ return import_lit19.html`
11702
+ <div
11703
+ class="track-row ${t.trackId === this._selectedTrackId ? "selected" : ""}"
11704
+ style="height: ${t.trackHeight}px;"
11705
+ data-track-id=${t.trackId}
11706
+ >
11707
+ ${t.track.clips.map((clip) => {
11708
+ const peakData = this._peaksData.get(clip.id) ?? this._previewPeaks.get(clip.id);
11709
+ let clipLeft;
11710
+ let width;
11711
+ if (this.scaleMode === "beats") {
11712
+ const startTick = clip.startTick !== void 0 ? clip.startTick : this._secondsToTicks(clip.startSample / sr);
11713
+ const durSec = clip.durationSamples / sr;
10749
11714
  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
- });
11715
+ const endTick = this._secondsToTicks(startSec + durSec);
11716
+ clipLeft = Math.round(startTick / this.ticksPerPixel);
11717
+ width = Math.round(endTick / this.ticksPerPixel) - clipLeft;
11718
+ } else {
11719
+ clipLeft = Math.floor(clip.startSample / spp);
11720
+ width = (0, import_core21.clipPixelWidth)(clip.startSample, clip.durationSamples, spp);
11721
+ }
11722
+ let clipSegments;
11723
+ let segmentChannels;
11724
+ if (this.scaleMode === "beats" && this.secondsToTicks) {
11725
+ const audioBuffer = this._clipBuffers.get(clip.id);
11726
+ const basePeaks = audioBuffer ? this._peakPipeline.getBaseScalePeaks(
11727
+ audioBuffer,
11728
+ this.mono,
11729
+ clip.offsetSamples,
11730
+ clip.durationSamples
11731
+ ) : null;
11732
+ if (basePeaks) {
11733
+ const baseScale = basePeaks.scale;
11734
+ segmentChannels = basePeaks.peaks.data;
11735
+ const MIN_RENDER_STEP = 80;
11736
+ const stepTicks = Math.max(
11737
+ MIN_RENDER_STEP,
11738
+ Math.ceil(this.ticksPerPixel)
11739
+ );
11740
+ const startSec = clip.startTick !== void 0 ? this._ticksToSeconds(clip.startTick) : clip.startSample / sr;
11741
+ const clipOffsetSec = clip.offsetSamples / sr;
11742
+ const segStartTick = clip.startTick !== void 0 ? clip.startTick : this._secondsToTicks(startSec);
11743
+ const endTick = this._secondsToTicks(
11744
+ startSec + clip.durationSamples / sr
11745
+ );
11746
+ clipSegments = [];
11747
+ for (let tick = segStartTick; tick < endTick; tick += stepTicks) {
11748
+ const segEndTick = Math.min(tick + stepTicks, endTick);
11749
+ const segStartAudioSec = this._ticksToSeconds(tick) - startSec + clipOffsetSec;
11750
+ const segEndAudioSec = this._ticksToSeconds(segEndTick) - startSec + clipOffsetSec;
11751
+ const segStartSample = Math.round(segStartAudioSec * sr);
11752
+ const segEndSample = Math.round(segEndAudioSec * sr);
11753
+ const totalPeaks = clip.durationSamples / baseScale;
11754
+ clipSegments.push({
11755
+ peakStart: Math.max(
11756
+ 0,
11757
+ (segStartSample - clip.offsetSamples) / baseScale
11758
+ ),
11759
+ peakEnd: Math.min(
11760
+ totalPeaks,
11761
+ (segEndSample - clip.offsetSamples) / baseScale
11762
+ ),
11763
+ pixelStart: (tick - segStartTick) / this.ticksPerPixel,
11764
+ pixelEnd: (segEndTick - segStartTick) / this.ticksPerPixel
11765
+ });
11766
+ }
10773
11767
  }
10774
11768
  }
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"
11769
+ const channels = segmentChannels ?? peakData?.data ?? [new Int16Array(0)];
11770
+ const hdrH = this.clipHeaders ? this.clipHeaderHeight : 0;
11771
+ const chH = this.waveHeight;
11772
+ return import_lit19.html` <div
11773
+ class="clip-container"
11774
+ style="left:${clipLeft}px;top:0;width:${width}px;height:${t.trackHeight}px;"
11775
+ data-clip-id=${clip.id}
11776
+ >
11777
+ ${hdrH > 0 ? import_lit19.html`<div
11778
+ class="clip-header"
10838
11779
  data-clip-id=${clip.id}
10839
11780
  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
- })}
11781
+ ?data-interactive=${this.interactiveClips}
11782
+ >
11783
+ <span>${clip.name || t.descriptor?.name || ""}</span>
11784
+ </div>` : ""}
11785
+ ${t.descriptor?.kind === "midi" ? import_lit19.html`<daw-piano-roll
11786
+ style="position:absolute;left:0;top:${hdrH}px;"
11787
+ .midiNotes=${clip.midiNotes ?? []}
11788
+ .length=${peakData?.length ?? width}
11789
+ .waveHeight=${chH * channels.length}
11790
+ .samplesPerPixel=${this._renderSpp}
11791
+ .sampleRate=${this.effectiveSampleRate}
11792
+ .clipOffsetSeconds=${(clip.offsetSamples ?? 0) / this.effectiveSampleRate}
11793
+ .visibleStart=${this._viewport.visibleStart}
11794
+ .visibleEnd=${this._viewport.visibleEnd}
11795
+ .originX=${clipLeft}
11796
+ ?selected=${t.trackId === this._selectedTrackId}
11797
+ ></daw-piano-roll>` : t.descriptor?.renderMode === "spectrogram" ? channels.map(
11798
+ (_chPeaks, chIdx) => import_lit19.html`<daw-spectrogram
11799
+ style="position:absolute;left:0;top:${hdrH + chIdx * chH}px;height:${chH}px;width:${peakData?.length ?? width}px;"
11800
+ .clipId=${clip.id}
11801
+ .trackId=${t.trackId}
11802
+ .channelIndex=${chIdx}
11803
+ .length=${peakData?.length ?? width}
11804
+ .waveHeight=${chH}
11805
+ .samplesPerPixel=${this._renderSpp}
11806
+ .sampleRate=${this.effectiveSampleRate}
11807
+ .clipOffsetSeconds=${(clip.offsetSamples ?? 0) / this.effectiveSampleRate}
11808
+ .visibleStart=${this._viewport.visibleStart}
11809
+ .visibleEnd=${this._viewport.visibleEnd}
11810
+ .originX=${clipLeft}
11811
+ ></daw-spectrogram>`
11812
+ ) : channels.map(
11813
+ (chPeaks, chIdx) => import_lit19.html` <daw-waveform
11814
+ style="position:absolute;left:0;top:${hdrH + chIdx * chH}px;"
11815
+ .peaks=${chPeaks}
11816
+ .length=${peakData?.length ?? width}
11817
+ .waveHeight=${chH}
11818
+ .barWidth=${this.barWidth}
11819
+ .barGap=${this.barGap}
11820
+ .roundedBars=${this.roundedBars}
11821
+ .gain=${this.gainScaledWaveforms ? clip.gain ?? 1 : 1}
11822
+ .visibleStart=${this._viewport.visibleStart}
11823
+ .visibleEnd=${this._viewport.visibleEnd}
11824
+ .originX=${clipLeft}
11825
+ .segments=${clipSegments}
11826
+ ></daw-waveform>`
11827
+ )}
11828
+ ${this.interactiveClips ? import_lit19.html` <div
11829
+ class="clip-boundary"
11830
+ data-boundary-edge="left"
11831
+ data-clip-id=${clip.id}
11832
+ data-track-id=${t.trackId}
11833
+ ></div>
11834
+ <div
11835
+ class="clip-boundary"
11836
+ data-boundary-edge="right"
11837
+ data-clip-id=${clip.id}
11838
+ data-track-id=${t.trackId}
11839
+ ></div>` : ""}
11840
+ </div>`;
11841
+ })}
11842
+ ${t.loading.map((clip) => this._renderPlaceholder(clip, t))}
11843
+ ${this._renderRecordingPreview(t.trackId, channelHeight)}
11844
+ </div>
11845
+ `;
11846
+ }
11847
+ )}
10854
11848
  </div>
10855
11849
  </div>
10856
11850
  </div>
@@ -10861,6 +11855,10 @@ var DawEditorElement = class extends import_lit19.LitElement {
10861
11855
  DawEditorElement.styles = [
10862
11856
  hostStyles,
10863
11857
  import_lit19.css`
11858
+ /* The hidden attribute hides the element: :host sets display (modern-web-guidance custom-elements). */
11859
+ :host([hidden]) {
11860
+ display: none;
11861
+ }
10864
11862
  :host {
10865
11863
  display: flex;
10866
11864
  flex-direction: column;
@@ -11090,10 +12088,7 @@ __decorateClass([
11090
12088
  ], DawEditorElement.prototype, "_previewPeaks", 2);
11091
12089
  __decorateClass([
11092
12090
  (0, import_decorators16.state)()
11093
- ], DawEditorElement.prototype, "_tracks", 2);
11094
- __decorateClass([
11095
- (0, import_decorators16.state)()
11096
- ], DawEditorElement.prototype, "_engineTracks", 2);
12091
+ ], DawEditorElement.prototype, "_extras", 2);
11097
12092
  __decorateClass([
11098
12093
  (0, import_decorators16.state)()
11099
12094
  ], DawEditorElement.prototype, "_peaksData", 2);
@@ -11169,6 +12164,8 @@ var DawRecordButtonElement = class extends DawTransportButton {
11169
12164
  super(...arguments);
11170
12165
  this._isRecording = false;
11171
12166
  this._targetRef = null;
12167
+ /** The listeners on `_targetRef`, aborted when the target changes or the button disconnects. */
12168
+ this._targetListeners = null;
11172
12169
  this._onStart = () => {
11173
12170
  this._isRecording = true;
11174
12171
  };
@@ -11199,15 +12196,16 @@ var DawRecordButtonElement = class extends DawTransportButton {
11199
12196
  this._cleanupListeners();
11200
12197
  if (!target) return;
11201
12198
  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);
12199
+ this._targetListeners = new AbortController();
12200
+ const { signal } = this._targetListeners;
12201
+ target.addEventListener("daw-recording-start", this._onStart, { signal });
12202
+ target.addEventListener("daw-recording-complete", this._onComplete, { signal });
12203
+ target.addEventListener("daw-recording-error", this._onError, { signal });
11205
12204
  }
11206
12205
  _cleanupListeners() {
11207
12206
  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);
12207
+ this._targetListeners?.abort();
12208
+ this._targetListeners = null;
11211
12209
  this._targetRef = null;
11212
12210
  }
11213
12211
  }
@@ -11258,7 +12256,7 @@ DawRecordButtonElement = __decorateClass([
11258
12256
  // src/elements/daw-keyboard-shortcuts.ts
11259
12257
  var import_lit22 = require("lit");
11260
12258
  var import_decorators19 = require("lit/decorators.js");
11261
- var import_core20 = require("@waveform-playlist/core");
12259
+ var import_core22 = require("@waveform-playlist/core");
11262
12260
  var DawKeyboardShortcutsElement = class extends import_lit22.LitElement {
11263
12261
  constructor() {
11264
12262
  super(...arguments);
@@ -11278,12 +12276,15 @@ var DawKeyboardShortcutsElement = class extends import_lit22.LitElement {
11278
12276
  this._customShortcuts = [];
11279
12277
  this._editor = null;
11280
12278
  this._cachedShortcuts = null;
12279
+ // --- Lifecycle ---
12280
+ /** The listeners of this connection, aborted in disconnectedCallback. */
12281
+ this._listeners = null;
11281
12282
  // --- Event handler ---
11282
12283
  this._onKeyDown = (e) => {
11283
12284
  const shortcuts = this.shortcuts;
11284
12285
  if (shortcuts.length === 0) return;
11285
12286
  try {
11286
- (0, import_core20.handleKeyboardEvent)(e, shortcuts, true);
12287
+ (0, import_core22.handleKeyboardEvent)(e, shortcuts, true);
11287
12288
  } catch (err) {
11288
12289
  console.warn("[dawcore] Keyboard shortcut failed (key=" + e.key + "): " + String(err));
11289
12290
  const target = this._editor ?? this;
@@ -11336,7 +12337,6 @@ var DawKeyboardShortcutsElement = class extends import_lit22.LitElement {
11336
12337
  updated() {
11337
12338
  this._cachedShortcuts = null;
11338
12339
  }
11339
- // --- Lifecycle ---
11340
12340
  connectedCallback() {
11341
12341
  super.connectedCallback();
11342
12342
  for (const prop of [
@@ -11357,11 +12357,15 @@ var DawKeyboardShortcutsElement = class extends import_lit22.LitElement {
11357
12357
  "[dawcore] <daw-keyboard-shortcuts> must be placed inside a <daw-editor>. Preset shortcuts (playback, splitting, undo) will be inactive; only customShortcuts will fire."
11358
12358
  );
11359
12359
  }
11360
- document.addEventListener("keydown", this._onKeyDown);
12360
+ this._listeners?.abort();
12361
+ this._listeners = new AbortController();
12362
+ const { signal } = this._listeners;
12363
+ document.addEventListener("keydown", this._onKeyDown, { signal });
11361
12364
  }
11362
12365
  disconnectedCallback() {
11363
12366
  super.disconnectedCallback();
11364
- document.removeEventListener("keydown", this._onKeyDown);
12367
+ this._listeners?.abort();
12368
+ this._listeners = null;
11365
12369
  this._editor = null;
11366
12370
  }
11367
12371
  // No shadow DOM — render-less element
@@ -11473,7 +12477,7 @@ DawKeyboardShortcutsElement = __decorateClass([
11473
12477
  // src/elements/daw-spectrogram.ts
11474
12478
  var import_lit23 = require("lit");
11475
12479
  var import_decorators20 = require("lit/decorators.js");
11476
- var import_core21 = require("@waveform-playlist/core");
12480
+ var import_core23 = require("@waveform-playlist/core");
11477
12481
  var DawSpectrogramElement = class extends import_lit23.LitElement {
11478
12482
  constructor() {
11479
12483
  super(...arguments);
@@ -11538,11 +12542,11 @@ var DawSpectrogramElement = class extends import_lit23.LitElement {
11538
12542
  this._unregisterAllCanvases();
11539
12543
  this._canvases = [];
11540
12544
  if (this.length <= 0) return;
11541
- const chunkCount = Math.ceil(this.length / import_core21.MAX_CANVAS_WIDTH);
12545
+ const chunkCount = Math.ceil(this.length / import_core23.MAX_CANVAS_WIDTH);
11542
12546
  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);
12547
+ const widthPx = Math.min(import_core23.MAX_CANVAS_WIDTH, this.length - i * import_core23.MAX_CANVAS_WIDTH);
11544
12548
  const canvas = document.createElement("canvas");
11545
- canvas.style.left = i * import_core21.MAX_CANVAS_WIDTH + "px";
12549
+ canvas.style.left = i * import_core23.MAX_CANVAS_WIDTH + "px";
11546
12550
  canvas.style.width = widthPx + "px";
11547
12551
  const dpr = window.devicePixelRatio || 1;
11548
12552
  canvas.width = widthPx * dpr;
@@ -11568,7 +12572,7 @@ var DawSpectrogramElement = class extends import_lit23.LitElement {
11568
12572
  }
11569
12573
  for (let i = 0; i < this._canvases.length; i++) {
11570
12574
  const canvas = this._canvases[i];
11571
- const canvasId = (0, import_core21.buildSpectrogramCanvasId)({
12575
+ const canvasId = (0, import_core23.buildSpectrogramCanvasId)({
11572
12576
  clipId: this.clipId,
11573
12577
  channelIndex: this.channelIndex,
11574
12578
  chunkIndex: i
@@ -11589,7 +12593,7 @@ var DawSpectrogramElement = class extends import_lit23.LitElement {
11589
12593
  trackId: this.trackId,
11590
12594
  channelIndex: this.channelIndex,
11591
12595
  chunkIndex: i,
11592
- globalPixelOffset: this.originX + i * import_core21.MAX_CANVAS_WIDTH,
12596
+ globalPixelOffset: this.originX + i * import_core23.MAX_CANVAS_WIDTH,
11593
12597
  widthPx: parseFloat(canvas.style.width),
11594
12598
  heightPx: this.waveHeight
11595
12599
  });
@@ -11687,20 +12691,25 @@ var DawTimeDisplayElement = class extends import_lit24.LitElement {
11687
12691
  this._format = detail.format;
11688
12692
  }
11689
12693
  };
12694
+ /** The listeners of this connection, aborted in disconnectedCallback. */
12695
+ this._listeners = null;
11690
12696
  }
11691
12697
  get target() {
11692
12698
  return resolveTransportTarget(this);
11693
12699
  }
11694
12700
  connectedCallback() {
11695
12701
  super.connectedCallback();
11696
- document.addEventListener("daw-timeupdate", this._onTimeUpdate);
11697
- document.addEventListener("daw-time-format-change", this._onFormatChange);
12702
+ this._listeners?.abort();
12703
+ this._listeners = new AbortController();
12704
+ const { signal } = this._listeners;
12705
+ document.addEventListener("daw-timeupdate", this._onTimeUpdate, { signal });
12706
+ document.addEventListener("daw-time-format-change", this._onFormatChange, { signal });
11698
12707
  requestAnimationFrame(() => this._syncFromTarget());
11699
12708
  }
11700
12709
  disconnectedCallback() {
11701
12710
  super.disconnectedCallback();
11702
- document.removeEventListener("daw-timeupdate", this._onTimeUpdate);
11703
- document.removeEventListener("daw-time-format-change", this._onFormatChange);
12711
+ this._listeners?.abort();
12712
+ this._listeners = null;
11704
12713
  }
11705
12714
  _syncFromTarget() {
11706
12715
  if (!this.isConnected) return;
@@ -11771,6 +12780,8 @@ var DawTimeFormatElement = class extends import_lit25.LitElement {
11771
12780
  warnUnsupportedOnce(this, ["setTimeFormat"]);
11772
12781
  }
11773
12782
  };
12783
+ /** The listeners of this connection, aborted in disconnectedCallback. */
12784
+ this._listeners = null;
11774
12785
  }
11775
12786
  get target() {
11776
12787
  return resolveTransportTarget(this);
@@ -11788,9 +12799,12 @@ var DawTimeFormatElement = class extends import_lit25.LitElement {
11788
12799
  }
11789
12800
  connectedCallback() {
11790
12801
  super.connectedCallback();
11791
- document.addEventListener("daw-time-format-change", this._onFormatChange);
11792
- this.addEventListener("pointerdown", this._onPointerDown);
11793
- this.addEventListener("pointerenter", this._onPointerEnter);
12802
+ this._listeners?.abort();
12803
+ this._listeners = new AbortController();
12804
+ const { signal } = this._listeners;
12805
+ document.addEventListener("daw-time-format-change", this._onFormatChange, { signal });
12806
+ this.addEventListener("pointerdown", this._onPointerDown, { signal });
12807
+ this.addEventListener("pointerenter", this._onPointerEnter, { signal });
11794
12808
  requestAnimationFrame(() => {
11795
12809
  if (!this.isConnected) return;
11796
12810
  const target = this.target;
@@ -11802,9 +12816,8 @@ var DawTimeFormatElement = class extends import_lit25.LitElement {
11802
12816
  }
11803
12817
  disconnectedCallback() {
11804
12818
  super.disconnectedCallback();
11805
- document.removeEventListener("daw-time-format-change", this._onFormatChange);
11806
- this.removeEventListener("pointerdown", this._onPointerDown);
11807
- this.removeEventListener("pointerenter", this._onPointerEnter);
12819
+ this._listeners?.abort();
12820
+ this._listeners = null;
11808
12821
  }
11809
12822
  updated() {
11810
12823
  const select = this.shadowRoot?.querySelector("select");
@@ -11859,7 +12872,7 @@ DawTimeFormatElement = __decorateClass([
11859
12872
  // src/elements/daw-player.ts
11860
12873
  var import_lit26 = require("lit");
11861
12874
  var import_decorators23 = require("lit/decorators.js");
11862
- var import_repeat = require("lit/directives/repeat.js");
12875
+ var import_repeat2 = require("lit/directives/repeat.js");
11863
12876
  var import_media_element_playout = require("@waveform-playlist/media-element-playout");
11864
12877
  var MIN_RATE = 0.25;
11865
12878
  var MAX_RATE = 4;
@@ -11889,6 +12902,8 @@ var DawPlayerElement = class extends import_lit26.LitElement {
11889
12902
  this._channelPeaks = [];
11890
12903
  this._sampleRate = 48e3;
11891
12904
  this._resizeObserver = null;
12905
+ /** The peaks fetch in flight: a newer peaks-src or a disconnect aborts it (#848, D7). */
12906
+ this._peaksFetch = null;
11892
12907
  this._onPointerDown = (e) => {
11893
12908
  const area = e.currentTarget;
11894
12909
  const width = area.clientWidth;
@@ -11962,6 +12977,7 @@ var DawPlayerElement = class extends import_lit26.LitElement {
11962
12977
  const area = this.shadowRoot?.querySelector(".waveform-area");
11963
12978
  if (area) this._resizeObserver?.observe(area);
11964
12979
  });
12980
+ if (rebuilt && this.peaksSrc && !this._peaksSettled) void this._loadPeaks();
11965
12981
  if (rebuilt && this.src) {
11966
12982
  this._loadSource();
11967
12983
  this._playhead?.setPosition(0);
@@ -11983,7 +12999,7 @@ var DawPlayerElement = class extends import_lit26.LitElement {
11983
12999
  style="height:${this.waveHeight}px"
11984
13000
  @pointerdown=${this._onPointerDown}
11985
13001
  >
11986
- ${(0, import_repeat.repeat)(
13002
+ ${(0, import_repeat2.repeat)(
11987
13003
  this._channelPeaks,
11988
13004
  (_p, i) => i,
11989
13005
  (peaks) => import_lit26.html`<daw-waveform
@@ -12006,6 +13022,8 @@ var DawPlayerElement = class extends import_lit26.LitElement {
12006
13022
  if (changed.has("mono")) this._renderWaveform();
12007
13023
  }
12008
13024
  async _loadPeaks() {
13025
+ this._peaksFetch?.abort();
13026
+ this._peaksFetch = null;
12009
13027
  this._waveformData = null;
12010
13028
  this._readyDispatched = false;
12011
13029
  this._peaksSettled = false;
@@ -12016,8 +13034,11 @@ var DawPlayerElement = class extends import_lit26.LitElement {
12016
13034
  return;
12017
13035
  }
12018
13036
  const requested = this.peaksSrc;
13037
+ const fetching = new AbortController();
13038
+ this._peaksFetch = fetching;
12019
13039
  try {
12020
- const wd = await loadWaveformDataFromUrl(requested);
13040
+ const wd = await loadWaveformDataFromUrl(requested, fetching.signal);
13041
+ if (this._peaksFetch === fetching) this._peaksFetch = null;
12021
13042
  if (this.peaksSrc !== requested) return;
12022
13043
  this._waveformData = wd;
12023
13044
  this._sampleRate = wd.sample_rate;
@@ -12025,6 +13046,7 @@ var DawPlayerElement = class extends import_lit26.LitElement {
12025
13046
  this._renderWaveform();
12026
13047
  this._maybeDispatchReady();
12027
13048
  } catch (err) {
13049
+ if (fetching.signal.aborted) return;
12028
13050
  if (this.peaksSrc !== requested) return;
12029
13051
  console.warn("[dawcore] <daw-player> failed to load peaks-src: " + String(err));
12030
13052
  this._peaksSettled = true;
@@ -12124,6 +13146,8 @@ var DawPlayerElement = class extends import_lit26.LitElement {
12124
13146
  this._engine.off("error", this._onError);
12125
13147
  this._engine.dispose();
12126
13148
  this._engineDisposed = true;
13149
+ this._peaksFetch?.abort();
13150
+ this._peaksFetch = null;
12127
13151
  }
12128
13152
  // --- Private event handlers (arrow fields for stable identity) ---
12129
13153
  _dispatch(name, detail) {
@@ -12150,6 +13174,10 @@ var DawPlayerElement = class extends import_lit26.LitElement {
12150
13174
  }
12151
13175
  };
12152
13176
  DawPlayerElement.styles = import_lit26.css`
13177
+ /* The hidden attribute hides the element: :host sets display (modern-web-guidance custom-elements). */
13178
+ :host([hidden]) {
13179
+ display: none;
13180
+ }
12153
13181
  :host {
12154
13182
  display: block;
12155
13183
  position: relative;