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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -10,7 +10,7 @@ var __decorateClass = (decorators, target, key, kind) => {
10
10
  };
11
11
 
12
12
  // <define:__INSTALL_SPECS__>
13
- var define_INSTALL_SPECS_default = { "@dawcore/faust": "@dawcore/faust@^0.0.2-next.1", "@dawcore/midi": "@dawcore/midi@^0.0.6-next.3", "@dawcore/transport": "@dawcore/transport@^0.0.16-next.3", "@dawcore/wam": "@dawcore/wam@^0.0.5-next.0", "@waveform-playlist/core": "@waveform-playlist/core@^13.0.0-next.3", "@waveform-playlist/engine": "@waveform-playlist/engine@^14.0.0-next.2", "@waveform-playlist/worklets": "@waveform-playlist/worklets@^13.0.1-next.0", "@waveform-playlist/playout": "@waveform-playlist/playout@^13.0.0-next.3" };
13
+ var define_INSTALL_SPECS_default = { "@dawcore/faust": "@dawcore/faust@^0.0.2-next.1", "@dawcore/midi": "@dawcore/midi@^0.0.6-next.4", "@dawcore/transport": "@dawcore/transport@^0.0.16-next.4", "@dawcore/wam": "@dawcore/wam@^0.0.5-next.0", "@waveform-playlist/core": "@waveform-playlist/core@^13.0.0-next.4", "@waveform-playlist/engine": "@waveform-playlist/engine@^14.0.0-next.3", "@waveform-playlist/worklets": "@waveform-playlist/worklets@^13.0.1-next.0", "@waveform-playlist/playout": "@waveform-playlist/playout@^13.0.0-next.4" };
14
14
 
15
15
  // src/elements/daw-annotation.ts
16
16
  import { LitElement } from "lit";
@@ -241,6 +241,7 @@ var DawAnnotationTrackElement = class extends LitElement2 {
241
241
  this._onKeyDownCapture = (e) => {
242
242
  if (!this.keyboardControls) return;
243
243
  if (e.repeat) return;
244
+ if (e.key === "Escape" && e.defaultPrevented) return;
244
245
  if (keyBelongsToFocusedControl(e)) return;
245
246
  const match = this._shortcutEntries().find((entry) => matchesKeyBinding(e, entry.binding));
246
247
  if (!match) return;
@@ -2216,11 +2217,9 @@ DawStopButtonElement = __decorateClass([
2216
2217
  import { LitElement as LitElement14, html as html12, css as css11 } from "lit";
2217
2218
  import { customElement as customElement16, property as property12, state as state4 } from "lit/decorators.js";
2218
2219
  import {
2219
- createClip as createClip2,
2220
- createClipFromSeconds,
2221
2220
  createMixerGesture as createMixerGesture2,
2222
- createTrack,
2223
2221
  clipPixelWidth,
2222
+ isLoadingClip as isLoadingClip3,
2224
2223
  trackKind
2225
2224
  } from "@waveform-playlist/core";
2226
2225
 
@@ -2966,6 +2965,9 @@ DawRulerElement = __decorateClass([
2966
2965
  customElement13("daw-ruler")
2967
2966
  ], DawRulerElement);
2968
2967
 
2968
+ // src/elements/daw-editor.ts
2969
+ import { createArrangement, PlaylistEngine } from "@waveform-playlist/engine";
2970
+
2969
2971
  // src/utils/track-mix.ts
2970
2972
  var DEFAULT_TRACK_MIX = Object.freeze({
2971
2973
  volume: 1,
@@ -2988,9 +2990,6 @@ function pickMix(mix, names) {
2988
2990
  ...named.has("soloed") && { soloed: mix.soloed }
2989
2991
  };
2990
2992
  }
2991
- function withMix(track, mix) {
2992
- return { ...track, ...mixOfElement(mix) };
2993
- }
2994
2993
  function clampNumber(value, min, max) {
2995
2994
  return Math.max(min, Math.min(max, Number(value)));
2996
2995
  }
@@ -3575,6 +3574,18 @@ var clipStyles = css10`
3575
3574
  position: absolute;
3576
3575
  overflow: hidden;
3577
3576
  }
3577
+ /* A clip whose audio is still loading (#848). */
3578
+ .clip-container.placeholder {
3579
+ opacity: var(--daw-placeholder-clip-opacity, 0.5);
3580
+ background: color-mix(in srgb, var(--daw-wave-color, #c49a6c) 35%, transparent);
3581
+ }
3582
+ /* A clip whose audio failed to load: it stays, like a broken <img>. */
3583
+ .clip-container.placeholder.failed {
3584
+ opacity: 1;
3585
+ background: color-mix(in srgb, var(--daw-clip-failed-color, #e06c75) 15%, transparent);
3586
+ outline: 2px dashed var(--daw-clip-failed-color, #e06c75);
3587
+ outline-offset: -2px;
3588
+ }
3578
3589
  .clip-header {
3579
3590
  position: relative;
3580
3591
  z-index: 1;
@@ -3884,7 +3895,6 @@ var RecordingController = class {
3884
3895
  const bits = options.bits ?? 16;
3885
3896
  try {
3886
3897
  const rawCtx = this._host.audioContext;
3887
- this._host.resolveAudioContextSampleRate(rawCtx.sampleRate);
3888
3898
  if (rawCtx.state === "suspended") {
3889
3899
  await rawCtx.resume();
3890
3900
  }
@@ -4625,6 +4635,8 @@ var PointerHandler = class {
4625
4635
  // still holds; zeroing only the host would desync the two).
4626
4636
  this._preDragSelectionStart = 0;
4627
4637
  this._preDragSelectionEnd = 0;
4638
+ /** Cancels the armed clip drag; set while one is armed (#848). */
4639
+ this._cancelArmedClipDrag = null;
4628
4640
  this.onPointerDown = (e) => {
4629
4641
  const clipHandler = this._host._clipHandler;
4630
4642
  if (clipHandler) {
@@ -4639,12 +4651,13 @@ var PointerHandler = class {
4639
4651
  console.warn("[dawcore] setPointerCapture failed: " + String(err));
4640
4652
  }
4641
4653
  const onMove = (me) => clipHandler.onPointerMove(me);
4642
- const detach = (pe) => {
4654
+ const detach = (pointerId) => {
4655
+ this._cancelArmedClipDrag = null;
4643
4656
  this._timeline?.removeEventListener("pointermove", onMove);
4644
4657
  this._timeline?.removeEventListener("pointerup", onUp);
4645
4658
  this._timeline?.removeEventListener("pointercancel", onCancel);
4646
4659
  try {
4647
- this._timeline?.releasePointerCapture(pe.pointerId);
4660
+ this._timeline?.releasePointerCapture(pointerId);
4648
4661
  } catch (err) {
4649
4662
  console.warn(
4650
4663
  "[dawcore] releasePointerCapture failed (may already be released): " + String(err)
@@ -4654,13 +4667,19 @@ var PointerHandler = class {
4654
4667
  };
4655
4668
  const onUp = (ue) => {
4656
4669
  clipHandler.onPointerUp(ue);
4657
- detach(ue);
4670
+ detach(ue.pointerId);
4658
4671
  };
4659
4672
  const downPointerId = e.pointerId;
4660
4673
  const onCancel = (ce) => {
4661
4674
  if (ce.pointerId !== downPointerId) return;
4662
4675
  clipHandler.onPointerCancel(ce);
4663
- detach(ce);
4676
+ detach(ce.pointerId);
4677
+ };
4678
+ this._cancelArmedClipDrag = () => {
4679
+ clipHandler.onPointerCancel(
4680
+ new PointerEvent("pointercancel", { pointerId: downPointerId })
4681
+ );
4682
+ detach(downPointerId);
4664
4683
  };
4665
4684
  this._timeline.addEventListener("pointermove", onMove);
4666
4685
  this._timeline.addEventListener("pointerup", onUp);
@@ -4773,6 +4792,17 @@ var PointerHandler = class {
4773
4792
  }
4774
4793
  return time * h.effectiveSampleRate / h.samplesPerPixel;
4775
4794
  }
4795
+ /**
4796
+ * Cancel an armed clip move or trim as a `pointercancel` would: the clip
4797
+ * handler reverts it and the timeline's listeners and pointer capture are
4798
+ * released. Returns whether a clip drag was armed.
4799
+ */
4800
+ cancelClipDrag() {
4801
+ const cancel = this._cancelArmedClipDrag;
4802
+ if (!cancel) return false;
4803
+ cancel();
4804
+ return true;
4805
+ }
4776
4806
  /** Detach the drag listeners and release capture — shared by the up and
4777
4807
  * cancel terminals so a new listener added to onPointerDown can't be
4778
4808
  * missed on one of them. */
@@ -4927,6 +4957,11 @@ var ClipPointerHandler = class {
4927
4957
  get isActive() {
4928
4958
  return this._mode !== null;
4929
4959
  }
4960
+ /** True once the pointer of the current press has moved past the drag
4961
+ * threshold: a press that has not moved is not a drag (#848). */
4962
+ get isDragging() {
4963
+ return this._isDragging;
4964
+ }
4930
4965
  /**
4931
4966
  * Attempts to handle a pointerdown event on the given target element.
4932
4967
  * Returns true if the target is a recognized clip interaction element.
@@ -4961,21 +4996,32 @@ var ClipPointerHandler = class {
4961
4996
  this._startPx = e.clientX;
4962
4997
  this._isDragging = false;
4963
4998
  this._cumulativeDeltaSamples = 0;
4999
+ }
5000
+ /**
5001
+ * The press has become a drag (the pointer passed the threshold): take the
5002
+ * clip's bounds and open the transaction now, not at the press. An undo
5003
+ * made during the press (it is not a drag, so undo works) then has no
5004
+ * transaction to abort, and the drag that follows starts from the clip as
5005
+ * the undo left it, one undo step (#848, review of #915). Returns false
5006
+ * when the clip is gone (the undo removed it): the press is dropped.
5007
+ */
5008
+ _startDrag() {
4964
5009
  const engine = this._host.engine;
5010
+ const trackId = this._trackId;
5011
+ const clipId = this._clipId;
4965
5012
  if (engine) {
4966
5013
  const bounds = engine.getClipBounds(trackId, clipId);
4967
- if (bounds) {
4968
- this._originalStartSample = bounds.startSample;
4969
- }
4970
- }
4971
- if (engine) {
5014
+ if (!bounds) return false;
5015
+ this._originalStartSample = bounds.startSample;
5016
+ this._originalOffsetSamples = bounds.offsetSamples;
5017
+ this._originalDurationSamples = bounds.durationSamples;
4972
5018
  engine.beginTransaction();
4973
5019
  } else {
4974
5020
  console.warn(
4975
- "[dawcore] beginDrag: engine unavailable, drag mutations will not be grouped for undo"
5021
+ "[dawcore] drag start: engine unavailable, drag mutations will not be grouped for undo"
4976
5022
  );
4977
5023
  }
4978
- if (mode === "trim-left" || mode === "trim-right") {
5024
+ if (this._mode === "trim-left" || this._mode === "trim-right") {
4979
5025
  const container = this._host.shadowRoot?.querySelector(
4980
5026
  `.clip-container[data-clip-id="${clipId}"]`
4981
5027
  );
@@ -4986,21 +5032,18 @@ var ClipPointerHandler = class {
4986
5032
  } else {
4987
5033
  console.warn("[dawcore] clip container not found for trim visual feedback: " + clipId);
4988
5034
  }
4989
- const engine2 = this._host.engine;
4990
- if (engine2) {
4991
- const bounds = engine2.getClipBounds(trackId, clipId);
4992
- if (bounds) {
4993
- this._originalOffsetSamples = bounds.offsetSamples;
4994
- this._originalDurationSamples = bounds.durationSamples;
4995
- }
4996
- }
4997
5035
  }
5036
+ return true;
4998
5037
  }
4999
5038
  /** Processes pointermove events during an active drag. */
5000
5039
  onPointerMove(e) {
5001
5040
  if (this._mode === null) return;
5002
5041
  const totalDeltaPx = e.clientX - this._startPx;
5003
5042
  if (!this._isDragging && Math.abs(totalDeltaPx) > DRAG_THRESHOLD) {
5043
+ if (!this._startDrag()) {
5044
+ this._reset();
5045
+ return;
5046
+ }
5004
5047
  this._isDragging = true;
5005
5048
  if (this._boundaryEl) {
5006
5049
  this._boundaryEl.classList.add("dragging");
@@ -5122,10 +5165,12 @@ var ClipPointerHandler = class {
5122
5165
  }
5123
5166
  }
5124
5167
  } finally {
5125
- if (this._isDragging && this._cumulativeDeltaSamples !== 0) {
5126
- this._host.engine?.commitTransaction();
5127
- } else {
5128
- this._host.engine?.abortTransaction();
5168
+ if (this._isDragging) {
5169
+ if (this._cumulativeDeltaSamples !== 0) {
5170
+ this._host.engine?.commitTransaction();
5171
+ } else {
5172
+ this._host.engine?.abortTransaction();
5173
+ }
5129
5174
  }
5130
5175
  this._reset();
5131
5176
  }
@@ -5143,7 +5188,7 @@ var ClipPointerHandler = class {
5143
5188
  try {
5144
5189
  this._restoreTrimVisual();
5145
5190
  } finally {
5146
- this._host.engine?.abortTransaction();
5191
+ if (this._isDragging) this._host.engine?.abortTransaction();
5147
5192
  this._reset();
5148
5193
  }
5149
5194
  }
@@ -5318,16 +5363,35 @@ var AnnotationDragHandler = class {
5318
5363
  this._onPointerCancel = (e) => {
5319
5364
  const drag = this._drag;
5320
5365
  if (!drag || e.pointerId !== drag.pointerId) return;
5321
- const elements = drag.track.annotationElements;
5322
- if (drag.mode === "ticks") {
5323
- applyTickBoundaryResults(elements, drag.snapshot, (t) => this._host._ticksToSeconds(t));
5324
- } else {
5325
- applyBoundaryResults(elements, drag.snapshot);
5326
- }
5327
- this._teardown();
5366
+ this._restoreAndTeardown(drag);
5328
5367
  };
5329
5368
  this._host = host;
5330
5369
  }
5370
+ /** True from pointerdown on an annotation until the drag ends or is cancelled. */
5371
+ get isActive() {
5372
+ return this._drag !== null;
5373
+ }
5374
+ /** True once the pointer has moved at least `DRAG_THRESHOLD` px (an edge
5375
+ * drag, or a box press that moved): a press that has not moved (a click on
5376
+ * the box) is not a drag (#848). */
5377
+ get isDragging() {
5378
+ return this._drag?.moved ?? false;
5379
+ }
5380
+ /** Cancel the drag in progress (Escape, editor disconnect): the boundaries
5381
+ * go back to where they were when it began (#848). */
5382
+ cancel() {
5383
+ if (this._drag) this._restoreAndTeardown(this._drag);
5384
+ }
5385
+ /** Restore the drag-start snapshot — a cancelled drag must not commit. */
5386
+ _restoreAndTeardown(drag) {
5387
+ const elements = drag.track.annotationElements;
5388
+ if (drag.mode === "ticks") {
5389
+ applyTickBoundaryResults(elements, drag.snapshot, (t) => this._host._ticksToSeconds(t));
5390
+ } else {
5391
+ applyBoundaryResults(elements, drag.snapshot);
5392
+ }
5393
+ this._teardown();
5394
+ }
5331
5395
  _teardown() {
5332
5396
  const drag = this._drag;
5333
5397
  if (!drag) return;
@@ -5475,6 +5539,10 @@ var TrackReorderHandler = class _TrackReorderHandler {
5475
5539
  static _reducedMotion() {
5476
5540
  return typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
5477
5541
  }
5542
+ /** True from the grab until the drag ends or is cancelled. */
5543
+ get isActive() {
5544
+ return this._trackId !== null;
5545
+ }
5478
5546
  /** Abort any in-progress drag and reset state. Called by the editor on
5479
5547
  * disconnect — without this, a drag interrupted by editor removal (with no
5480
5548
  * pointercancel delivered) would leave the handler wedged and silently
@@ -5588,23 +5656,25 @@ async function loadFiles(host, files) {
5588
5656
  }
5589
5657
  };
5590
5658
  for (const file of fileArray) {
5659
+ if (!host.isConnected) {
5660
+ dispatchLoadError(file, new Error("<daw-editor> was disconnected"));
5661
+ continue;
5662
+ }
5591
5663
  if (file.type && !file.type.startsWith("audio/")) {
5592
5664
  const error = new Error("Non-audio MIME type: " + file.type);
5593
5665
  console.warn("[dawcore] Skipping non-audio file: " + file.name + " (" + file.type + ")");
5594
5666
  dispatchLoadError(file, error);
5595
5667
  continue;
5596
5668
  }
5597
- const blobUrl = URL.createObjectURL(file);
5598
- const name = file.name.replace(/\.\w+$/, "");
5669
+ let trackId = null;
5599
5670
  try {
5600
- const trackEl = await host.addTrack({ name, clips: [{ src: blobUrl, name }] });
5601
- loaded.push(trackEl.trackId);
5671
+ trackId = await host._addDroppedFile(file);
5672
+ await host._whenTrackLoaded(trackId);
5673
+ loaded.push(trackId);
5602
5674
  } catch (err) {
5603
5675
  console.warn("[dawcore] Failed to load file: " + file.name + " \u2014 " + String(err));
5676
+ if (trackId !== null) host._discardTrack(trackId);
5604
5677
  dispatchLoadError(file, err);
5605
- } finally {
5606
- URL.revokeObjectURL(blobUrl);
5607
- host._audioCache.delete(blobUrl);
5608
5678
  }
5609
5679
  }
5610
5680
  return { loaded, failed };
@@ -5692,7 +5762,7 @@ async function loadMidiImpl(host, source, options = {}) {
5692
5762
  throw first instanceof Error ? first : new Error(stringifyReason(first));
5693
5763
  }
5694
5764
  return {
5695
- trackIds: succeeded.map((el) => el.trackId),
5765
+ trackIds: succeeded,
5696
5766
  bpm: parsed.bpm,
5697
5767
  timeSignature: parsed.timeSignature,
5698
5768
  duration: parsed.duration,
@@ -5713,7 +5783,7 @@ function stringifyReason(reason) {
5713
5783
  }
5714
5784
 
5715
5785
  // src/interactions/recording-clip.ts
5716
- import { carveClipRange, createClip } from "@waveform-playlist/core";
5786
+ import { carveClipRange, createClip, isLoadingClip } from "@waveform-playlist/core";
5717
5787
  function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamples = 0, clipName) {
5718
5788
  let trimmedBuf = buf;
5719
5789
  if (offsetSamples > 0 && offsetSamples < buf.length) {
@@ -5740,8 +5810,7 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
5740
5810
  host._clipBuffers = new Map(host._clipBuffers).set(clip.id, trimmedBuf);
5741
5811
  host._clipOffsets.set(clip.id, { offsetSamples: 0, durationSamples: durSamples });
5742
5812
  host._peakPipeline.generatePeaks(trimmedBuf, host.renderSamplesPerPixel, host.mono).then((pd) => {
5743
- const t = host._engineTracks.get(trackId);
5744
- if (!t) {
5813
+ if (!host._arrangement.getTracks().some((t) => t.id === trackId)) {
5745
5814
  const next = new Map(host._clipBuffers);
5746
5815
  next.delete(clip.id);
5747
5816
  host._clipBuffers = next;
@@ -5750,13 +5819,15 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
5750
5819
  }
5751
5820
  host._peaksData = new Map(host._peaksData).set(clip.id, pd);
5752
5821
  host._raiseZoomFloor(host._peakPipeline.getCachedScale(trimmedBuf));
5753
- host._engineTracks = new Map(host._engineTracks).set(trackId, {
5754
- ...t,
5755
- // Punch-in replace (#579): the recorded clip owns [startSample,
5756
- // startSample + durSamples) — carve overlapped content out of the
5757
- // existing clips before inserting (parity with the React provider).
5758
- clips: [...carveClipRange(t.clips, startSample, startSample + durSamples), clip]
5759
- });
5822
+ host._arrangement.updateTrack(trackId, (current) => ({
5823
+ ...current,
5824
+ clips: [
5825
+ ...current.clips.flatMap(
5826
+ (c) => isLoadingClip(c) ? [c] : carveClipRange([c], startSample, startSample + durSamples)
5827
+ ),
5828
+ clip
5829
+ ]
5830
+ }));
5760
5831
  const desc = host._tracks.get(trackId);
5761
5832
  if (desc) {
5762
5833
  const sr = host.effectiveSampleRate;
@@ -5784,13 +5855,6 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
5784
5855
  clips: [...desc.clips, clipDesc]
5785
5856
  });
5786
5857
  }
5787
- host._recomputeDuration();
5788
- const updatedTrack = host._engineTracks.get(trackId);
5789
- if (host._engine?.updateTrack && updatedTrack) {
5790
- host._engine.updateTrack(trackId, updatedTrack);
5791
- } else {
5792
- host._engine?.setTracks([...host._engineTracks.values()]);
5793
- }
5794
5858
  if (host.isConnected) {
5795
5859
  host.dispatchEvent(
5796
5860
  new CustomEvent("daw-recording-clip-add", {
@@ -5934,6 +5998,7 @@ function syncPeaksForChangedClips(host, tracks) {
5934
5998
  clip.durationSamples
5935
5999
  ).then((peakData) => {
5936
6000
  host._peaksData = new Map(host._peaksData).set(clip.id, peakData);
6001
+ host._clipPeaksReady?.(clip.id, audioBuffer);
5937
6002
  }).catch((err) => {
5938
6003
  console.warn(
5939
6004
  "[dawcore] Failed to generate peaks for clip " + clip.id + ": " + String(err)
@@ -5984,6 +6049,205 @@ function findAudioBufferForClip(host, clip, track) {
5984
6049
  return null;
5985
6050
  }
5986
6051
 
6052
+ // src/interactions/track-entry.ts
6053
+ import { createClip as createClip2, createTrack } from "@waveform-playlist/core";
6054
+ function validMidiNotes(notes) {
6055
+ return notes.filter((n) => {
6056
+ const ok = Number.isFinite(n.time) && n.time >= 0 && Number.isFinite(n.duration) && n.duration > 0 && Number.isInteger(n.midi) && n.midi >= 0 && n.midi <= 127 && Number.isFinite(n.velocity) && n.velocity >= 0 && n.velocity <= 1;
6057
+ if (!ok) {
6058
+ console.warn("[dawcore] dropping malformed MIDI note: " + JSON.stringify(n));
6059
+ }
6060
+ return ok;
6061
+ });
6062
+ }
6063
+ function clipSourceOf(clipDesc) {
6064
+ return !isDomClip(clipDesc) && clipDesc.file || clipDesc.src;
6065
+ }
6066
+ function isMidiDescriptor(clipDesc) {
6067
+ if (clipSourceOf(clipDesc)) {
6068
+ if (clipDesc.midiNotes != null) {
6069
+ console.warn(
6070
+ '[dawcore] clip "' + (clipDesc.name || (isDomClip(clipDesc) ? clipDesc.clipId : "?")) + '" has both src and midiNotes \u2014 treating as audio (notes will be ignored)'
6071
+ );
6072
+ }
6073
+ return false;
6074
+ }
6075
+ return true;
6076
+ }
6077
+ function clipKindError(trackName, kind, clipIsMidi, clipLabel) {
6078
+ if (clipIsMidi === (kind === "midi")) return null;
6079
+ return new Error(
6080
+ clipIsMidi ? 'clip "' + clipLabel + '" is a MIDI clip (no src) on audio track "' + trackName + `". A track holds one kind of clip: set kind="midi" on the <daw-track> (or kind: 'midi' in addTrack) for a track of MIDI clips.` : 'clip "' + clipLabel + '" is an audio clip on MIDI track "' + trackName + '". A track holds one kind of clip: put the clip on an audio track.'
6081
+ );
6082
+ }
6083
+ function buildMidiClip(clipDesc, sampleRate) {
6084
+ const notes = validMidiNotes(clipDesc.midiNotes ?? []);
6085
+ const noteSpanSeconds = notes.length ? notes.reduce((max, n) => Math.max(max, n.time + n.duration), 0) : 0;
6086
+ const sourceDurationSamples = Math.ceil(
6087
+ Math.max(noteSpanSeconds, clipDesc.duration, 1) * sampleRate
6088
+ );
6089
+ const requestedDurationSamples = clipDesc.duration > 0 ? Math.round(clipDesc.duration * sampleRate) : sourceDurationSamples;
6090
+ const clip = createClip2({
6091
+ startSample: Math.round(clipDesc.start * sampleRate),
6092
+ durationSamples: requestedDurationSamples,
6093
+ offsetSamples: Math.round(clipDesc.offset * sampleRate),
6094
+ sampleRate,
6095
+ sourceDurationSamples,
6096
+ gain: clipDesc.gain,
6097
+ name: clipDesc.name,
6098
+ midiNotes: notes,
6099
+ midiChannel: clipDesc.midiChannel ?? void 0,
6100
+ midiProgram: clipDesc.midiProgram ?? void 0
6101
+ });
6102
+ if (clipDesc.clipId) clip.id = clipDesc.clipId;
6103
+ return clip;
6104
+ }
6105
+ function buildLoadingClip(clipDesc) {
6106
+ return {
6107
+ id: clipDesc.clipId,
6108
+ src: clipSourceOf(clipDesc),
6109
+ start: clipDesc.start,
6110
+ offset: clipDesc.offset,
6111
+ gain: clipDesc.gain,
6112
+ ...clipDesc.duration > 0 && { duration: clipDesc.duration },
6113
+ ...clipDesc.name && { name: clipDesc.name }
6114
+ };
6115
+ }
6116
+ function withClipId(clipDesc) {
6117
+ if (clipDesc.clipId) return clipDesc;
6118
+ return { ...clipDesc, clipId: crypto.randomUUID() };
6119
+ }
6120
+ function buildArrangementTrack(trackId, descriptor, mix, sampleRate) {
6121
+ const clips = [];
6122
+ const refused = [];
6123
+ let changed = false;
6124
+ const descClips = descriptor.clips.map((clipDesc) => {
6125
+ const identified = withClipId(clipDesc);
6126
+ if (identified !== clipDesc) changed = true;
6127
+ const isMidi = isMidiDescriptor(identified);
6128
+ const source = clipSourceOf(identified);
6129
+ const sourceName = typeof source === "string" ? source : source instanceof File ? source.name : "";
6130
+ const label = identified.name || sourceName || identified.clipId;
6131
+ const kindError = clipKindError(descriptor.name, descriptor.kind, isMidi, label);
6132
+ if (kindError) refused.push({ clipId: identified.clipId, error: kindError });
6133
+ else clips.push(isMidi ? buildMidiClip(identified, sampleRate) : buildLoadingClip(identified));
6134
+ return identified;
6135
+ });
6136
+ const base = createTrack({ name: descriptor.name, kind: descriptor.kind, clips: [], ...mix });
6137
+ const track = { ...base, id: trackId, clips };
6138
+ return { track, descriptor: changed ? { ...descriptor, clips: descClips } : descriptor, refused };
6139
+ }
6140
+ function entryIndex(trackEls, trackId, arrangementIds) {
6141
+ const at = trackEls.findIndex((el) => el.trackId === trackId);
6142
+ for (let i = at - 1; i >= 0; i--) {
6143
+ const position = arrangementIds.indexOf(trackEls[i].trackId);
6144
+ if (position !== -1) return position + 1;
6145
+ }
6146
+ return 0;
6147
+ }
6148
+
6149
+ // src/interactions/load-announcer.ts
6150
+ import { isLoadingClip as isLoadingClip2 } from "@waveform-playlist/core";
6151
+ var LoadAnnouncer = class {
6152
+ constructor(_dispatch) {
6153
+ this._dispatch = _dispatch;
6154
+ this._tracks = /* @__PURE__ */ new Map();
6155
+ /** The failure each clip was last announced with. */
6156
+ this._clipErrors = /* @__PURE__ */ new Map();
6157
+ /** Clips seen while loading, and not yet announced as loaded. */
6158
+ this._loadingClips = /* @__PURE__ */ new Set();
6159
+ }
6160
+ /** A track is about to enter, with `refused` clips left out for their kind. */
6161
+ expect(trackId, refused) {
6162
+ this._tracks.set(trackId, { state: null, refused });
6163
+ }
6164
+ /**
6165
+ * A clip is about to enter while loading: it is announced ready when it
6166
+ * loads, also when its source was loaded already and it is never seen
6167
+ * loading.
6168
+ */
6169
+ expectClip(clipId) {
6170
+ this._loadingClips.add(clipId);
6171
+ }
6172
+ /** A loading clip was removed: its load will not be announced. */
6173
+ forgetClip(clipId) {
6174
+ this._loadingClips.delete(clipId);
6175
+ this._clipErrors.delete(clipId);
6176
+ }
6177
+ /** The error a failed track was announced with. */
6178
+ errorOf(trackId) {
6179
+ return this._tracks.get(trackId)?.error ?? new Error('track "' + trackId + '" failed to load');
6180
+ }
6181
+ /** A track was removed by the page or an editor method: nothing more is said of it. */
6182
+ forget(trackId, clipIds) {
6183
+ this._tracks.delete(trackId);
6184
+ for (const id of clipIds) {
6185
+ this._clipErrors.delete(id);
6186
+ this._loadingClips.delete(id);
6187
+ }
6188
+ }
6189
+ /** The state a track was last announced in (`null` before its first announcement). */
6190
+ stateOf(trackId) {
6191
+ return this._tracks.get(trackId)?.state ?? null;
6192
+ }
6193
+ update(tracks, sources) {
6194
+ for (const track of tracks) this._updateTrack(track, sources);
6195
+ }
6196
+ _updateTrack(track, sources) {
6197
+ const record = this._tracks.get(track.id) ?? { state: null, refused: 0 };
6198
+ this._tracks.set(track.id, record);
6199
+ let pending = 0;
6200
+ let failed = 0;
6201
+ let loaded = 0;
6202
+ let firstError = null;
6203
+ for (const clip of track.clips) {
6204
+ if (!isLoadingClip2(clip)) {
6205
+ loaded++;
6206
+ if (this._loadingClips.delete(clip.id)) {
6207
+ this._clipErrors.delete(clip.id);
6208
+ this._send("daw-clip-ready", { trackId: track.id, clipId: clip.id });
6209
+ }
6210
+ continue;
6211
+ }
6212
+ this._loadingClips.add(clip.id);
6213
+ const source = sources.get(clip.src);
6214
+ if (source?.status !== "failed") {
6215
+ pending++;
6216
+ this._clipErrors.delete(clip.id);
6217
+ continue;
6218
+ }
6219
+ failed++;
6220
+ const error = source.error ?? new Error('the audio of clip "' + clip.id + '" failed to load');
6221
+ firstError ?? (firstError = error);
6222
+ if (this._clipErrors.get(clip.id) !== error) {
6223
+ this._clipErrors.set(clip.id, error);
6224
+ this._send("daw-clip-error", {
6225
+ trackId: track.id,
6226
+ clipId: clip.id,
6227
+ error
6228
+ });
6229
+ }
6230
+ }
6231
+ const next = pending > 0 ? "pending" : loaded > 0 || failed + record.refused === 0 ? "ready" : "failed";
6232
+ if (next === record.state) return;
6233
+ record.state = next;
6234
+ record.error = void 0;
6235
+ if (next === "ready") {
6236
+ this._send("daw-track-ready", { trackId: track.id });
6237
+ } else if (next === "failed") {
6238
+ const requested = failed + record.refused;
6239
+ const error = requested === 1 && firstError ? firstError : new Error(
6240
+ "all " + requested + " clip(s) failed to load \u2014 see prior daw-clip-error events"
6241
+ );
6242
+ record.error = error;
6243
+ this._send("daw-track-error", { trackId: track.id, error });
6244
+ }
6245
+ }
6246
+ _send(type, detail) {
6247
+ this._dispatch(new CustomEvent(type, { bubbles: true, composed: true, detail }));
6248
+ }
6249
+ };
6250
+
5987
6251
  // src/effects/effects-chain-controller.ts
5988
6252
  var idCounter = 0;
5989
6253
  var EffectsChainController = class {
@@ -7447,16 +7711,9 @@ var PlaybackAnimationController = class {
7447
7711
  // src/elements/daw-editor.ts
7448
7712
  var RULER_HEIGHT = 30;
7449
7713
  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();";
7450
- var TrackLoadCancelledError = class extends Error {
7451
- constructor(message, reason) {
7452
- super(message);
7453
- this.reason = reason;
7454
- this.name = "TrackLoadCancelledError";
7455
- }
7456
- };
7457
7714
  var DawEditorElement = class extends LitElement14 {
7458
7715
  constructor() {
7459
- super(...arguments);
7716
+ super();
7460
7717
  this._samplesPerPixel = 1024;
7461
7718
  this._timeFormat = "hh:mm:ss.sss";
7462
7719
  this.waveHeight = 128;
@@ -7481,10 +7738,33 @@ var DawEditorElement = class extends LitElement14 {
7481
7738
  this.timeSignature = [4, 4];
7482
7739
  this._ppqn = 960;
7483
7740
  this.snapTo = "off";
7484
- /** Resolved sample rate — falls back to sampleRate property until first audio decode. */
7485
- this._resolvedSampleRate = null;
7741
+ /**
7742
+ * The one owner of the tracks, the clips, the mix, the undo history and
7743
+ * loading (#848). Made with the editor, kept across a disconnect; the
7744
+ * engine plays it once there is an adapter.
7745
+ */
7746
+ this._arrangement = createArrangement();
7747
+ /** Sends the load events, read from the arrangement (#848). */
7748
+ this._announcer = new LoadAnnouncer((event) => this.dispatchEvent(event));
7749
+ /**
7750
+ * Ids of tracks registered (a `<daw-track>` connected, a file dropped) and
7751
+ * not yet in the arrangement: they enter at the next flush, once there is
7752
+ * an engine (#848).
7753
+ */
7754
+ this._entryQueue = [];
7755
+ this._entryFlushScheduled = false;
7756
+ /**
7757
+ * Clips an `addClip()` is waiting for, with their track and the way to
7758
+ * reject the call: a removal of the clip or of its track before the clip
7759
+ * loads settles it here, without a public event (#917).
7760
+ */
7761
+ this._awaitedClips = /* @__PURE__ */ new Map();
7762
+ /** `<daw-track>` elements `addTrack()` made: every other one is the page's (the history rule). */
7763
+ this._editorMadeTracks = /* @__PURE__ */ new WeakSet();
7764
+ this._previewPeaks = /* @__PURE__ */ new Map();
7765
+ /** The `.dat` data of those clips, handed to the peak pipeline when the audio arrives. */
7766
+ this._previewWaveforms = /* @__PURE__ */ new Map();
7486
7767
  this._tracks = /* @__PURE__ */ new Map();
7487
- this._seedMix = /* @__PURE__ */ new Map();
7488
7768
  this._engineTracks = /* @__PURE__ */ new Map();
7489
7769
  this._peaksData = /* @__PURE__ */ new Map();
7490
7770
  this._isPlaying = false;
@@ -7503,16 +7783,11 @@ var DawEditorElement = class extends LitElement14 {
7503
7783
  // hook, same pattern as the whole-track _duration check.
7504
7784
  this._activePlayEndTime = null;
7505
7785
  this._externalAdapter = null;
7506
- /** True after a disconnect disposed the consumer's adapter via the engine
7507
- * — rebuild attempts fail loudly until a fresh adapter is set. */
7508
- this._adapterConsumedByDispose = false;
7509
7786
  // --- Effects (master chain; per-track chains delegated from <daw-track>) ---
7510
7787
  this._effectsManager = null;
7511
7788
  this._engine = null;
7512
7789
  this._warnedMissingTicksToSeconds = false;
7513
7790
  this._warnedMissingSecondsToTicks = false;
7514
- this._enginePromise = null;
7515
- this._audioCache = /* @__PURE__ */ new Map();
7516
7791
  this._peaksCache = /* @__PURE__ */ new Map();
7517
7792
  this._clipBuffers = /* @__PURE__ */ new Map();
7518
7793
  this._clipOffsets = /* @__PURE__ */ new Map();
@@ -7520,11 +7795,6 @@ var DawEditorElement = class extends LitElement14 {
7520
7795
  /** Coarsest scale from pre-computed peaks — zoom cannot go finer than this. 0 = no limit. */
7521
7796
  this._minSamplesPerPixel = 0;
7522
7797
  this._trackElements = /* @__PURE__ */ new Map();
7523
- /** Track ids with a _loadTrack in flight. Distinct from `_engineTracks`
7524
- * membership: the peaks-first path inserts a render-only PREVIEW track
7525
- * into _engineTracks mid-load, so `has()` alone cannot answer "is this
7526
- * track still loading?". */
7527
- this._loadingTracks = /* @__PURE__ */ new Set();
7528
7798
  this._childObserver = null;
7529
7799
  this._audioResume = new AudioResumeController(this);
7530
7800
  this._recordingController = new RecordingController(this);
@@ -7607,9 +7877,8 @@ var DawEditorElement = class extends LitElement14 {
7607
7877
  }
7608
7878
  const descriptor = this._readTrackDescriptor(trackEl);
7609
7879
  this._tracks = new Map(this._tracks).set(trackId, descriptor);
7610
- this._setSeedMix(trackId, mixOfElement(trackEl));
7611
7880
  this._trackElements.set(trackId, trackEl);
7612
- this._loadTrack(trackId, descriptor);
7881
+ this._queueEntry(trackId);
7613
7882
  };
7614
7883
  this._onTrackUpdate = (e) => {
7615
7884
  const trackId = e.detail?.trackId;
@@ -7632,11 +7901,14 @@ var DawEditorElement = class extends LitElement14 {
7632
7901
  trackEl.kind = keptKind;
7633
7902
  });
7634
7903
  }
7904
+ if (oldDescriptor && oldDescriptor.src === descriptor.src && !descriptor.clips.some(isDomClip) && !oldDescriptor.clips.some(isDomClip)) {
7905
+ descriptor = { ...descriptor, clips: oldDescriptor.clips };
7906
+ }
7635
7907
  this._tracks = new Map(this._tracks).set(trackId, descriptor);
7636
7908
  const changed = Array.isArray(e.detail.changed) ? e.detail.changed : [];
7637
7909
  this._writeMixFields(trackId, pickMix(mixOfElement(trackEl), changed));
7638
- if (oldDescriptor?.src !== descriptor.src) {
7639
- this._loadTrack(trackId, descriptor);
7910
+ if (oldDescriptor && oldDescriptor.src !== descriptor.src) {
7911
+ this._replaceShorthandClips(trackId, descriptor);
7640
7912
  }
7641
7913
  if (descriptor.renderMode === "spectrogram" && oldDescriptor?.renderMode !== "spectrogram") {
7642
7914
  const engineTrack = this._engineTracks.get(trackId);
@@ -7701,18 +7973,20 @@ var DawEditorElement = class extends LitElement14 {
7701
7973
  const trackEl = clipEl.closest("daw-track");
7702
7974
  if (!trackEl) return;
7703
7975
  const trackId = trackEl.trackId;
7704
- if (!this._engineTracks.has(trackId) || this._loadingTracks.has(trackId)) {
7976
+ if (!this._isEntered(trackId)) {
7977
+ if (!this._entryQueue.includes(trackId)) {
7978
+ this._rejectAwaitedClips(
7979
+ (id) => id === clipEl.clipId,
7980
+ 'addClip: track "' + trackId + '" is not in the editor (an Undo took it out)'
7981
+ );
7982
+ return;
7983
+ }
7705
7984
  const desc = this._tracks.get(trackId);
7706
7985
  if (desc && !desc.clips.some((c) => isDomClip(c) && c.clipId === clipEl.clipId)) {
7707
- const message = 'daw-clip-connected fired while parent track "' + trackId + '" is still loading \u2014 the clip will not be loaded. Wait for daw-track-ready before appending more <daw-clip> children, or use editor.addClip(trackId, config) after the track finishes loading.';
7708
- console.warn("[dawcore] " + message);
7709
- this.dispatchEvent(
7710
- new CustomEvent("daw-clip-error", {
7711
- bubbles: true,
7712
- composed: true,
7713
- detail: { trackId, clipId: clipEl.clipId, error: new Error(message) }
7714
- })
7715
- );
7986
+ this._tracks = new Map(this._tracks).set(trackId, {
7987
+ ...desc,
7988
+ clips: [...desc.clips, this._readClipDescriptor(clipEl)]
7989
+ });
7716
7990
  }
7717
7991
  return;
7718
7992
  }
@@ -7720,24 +7994,7 @@ var DawEditorElement = class extends LitElement14 {
7720
7994
  if (loadedDesc && loadedDesc.clips.some((c) => isDomClip(c) && c.clipId === clipEl.clipId)) {
7721
7995
  return;
7722
7996
  }
7723
- const clipDesc = {
7724
- kind: "dom",
7725
- clipId: clipEl.clipId,
7726
- src: clipEl.src,
7727
- peaksSrc: clipEl.peaksSrc,
7728
- start: clipEl.start,
7729
- duration: clipEl.duration,
7730
- offset: clipEl.offset,
7731
- gain: clipEl.gain,
7732
- name: clipEl.name,
7733
- fadeIn: clipEl.fadeIn,
7734
- fadeOut: clipEl.fadeOut,
7735
- fadeType: clipEl.fadeType,
7736
- midiNotes: clipEl.midiNotes,
7737
- midiChannel: clipEl.midiChannel,
7738
- midiProgram: clipEl.midiProgram
7739
- };
7740
- this._loadAndAppendClip(trackId, clipDesc);
7997
+ this._loadAndAppendClip(trackId, this._readClipDescriptor(clipEl));
7741
7998
  };
7742
7999
  this._onClipUpdate = (e) => {
7743
8000
  const clipEl = e.target;
@@ -7749,8 +8006,26 @@ var DawEditorElement = class extends LitElement14 {
7749
8006
  );
7750
8007
  return;
7751
8008
  }
8009
+ const desc = this._tracks.get(detail.trackId);
8010
+ if (desc && !this._isEntered(detail.trackId)) {
8011
+ this._tracks = new Map(this._tracks).set(detail.trackId, {
8012
+ ...desc,
8013
+ clips: desc.clips.map(
8014
+ (c) => isDomClip(c) && c.clipId === clipEl.clipId ? this._readClipDescriptor(clipEl) : c
8015
+ )
8016
+ });
8017
+ return;
8018
+ }
7752
8019
  this._applyClipUpdate(detail.trackId, detail.clipId, clipEl);
7753
8020
  };
8021
+ this._waitingForDragEnd = false;
8022
+ /** Who waits for a track to enter (addTrack, a dropped file). */
8023
+ this._entryWaiters = /* @__PURE__ */ new Map();
8024
+ /** Ends the waits of `_whenTrackLoaded` (as loaded) when the editor is disconnected. */
8025
+ this._loadWaitEnds = /* @__PURE__ */ new Set();
8026
+ /** Last versions the statechange handler worked from; reset for each engine. */
8027
+ this._lastTracksVersion = -1;
8028
+ this._lastMixerVersion = -1;
7754
8029
  // --- File Drop ---
7755
8030
  this._onDragOver = (e) => {
7756
8031
  if (!this.fileDrop) return;
@@ -7791,6 +8066,16 @@ var DawEditorElement = class extends LitElement14 {
7791
8066
  if (!this.trackReordering) return;
7792
8067
  this._trackReorderDrag.onGrab(e.detail.trackId, e.detail.pointerEvent, e.detail.gripElement);
7793
8068
  };
8069
+ /**
8070
+ * Escape during a drag cancels it and does nothing else: the default is
8071
+ * prevented, so `<daw-keyboard-shortcuts>` (core's `handleKeyboardEvent`)
8072
+ * does not also stop playback. No `stopPropagation`: an app's own listener
8073
+ * can read `defaultPrevented`.
8074
+ */
8075
+ this._onDragEscape = (e) => {
8076
+ if (e.key !== "Escape") return;
8077
+ if (this._cancelDrags()) e.preventDefault();
8078
+ };
7794
8079
  // --- Recording ---
7795
8080
  this.recordingStream = null;
7796
8081
  /** Set in togglePauseRecording when Transport is paused alongside the
@@ -7809,6 +8094,10 @@ var DawEditorElement = class extends LitElement14 {
7809
8094
  * statechange emissions during the transaction would otherwise bounce
7810
8095
  * half-applied orders back into the DOM. */
7811
8096
  this._inOrderSync = false;
8097
+ this._arrangement.sources.subscribe(() => {
8098
+ this._announceLoading();
8099
+ this.requestUpdate();
8100
+ });
7812
8101
  }
7813
8102
  get samplesPerPixel() {
7814
8103
  return this._samplesPerPixel;
@@ -7987,16 +8276,33 @@ var DawEditorElement = class extends LitElement14 {
7987
8276
  get _hasTickCallbacks() {
7988
8277
  return !!(this.secondsToTicks && this.ticksToSeconds);
7989
8278
  }
7990
- /** Sample rate — reads from adapter's AudioContext when available, otherwise falls back to 48000. */
8279
+ /**
8280
+ * Sample rate: the adapter's AudioContext rate. Without an adapter (after a
8281
+ * disconnect let it go), the rate of the loaded clips the arrangement holds,
8282
+ * else 48000. Decoded audio is at the context's rate, so the two agree.
8283
+ */
7991
8284
  get sampleRate() {
7992
- return this._resolvedSampleRate ?? this._externalAdapter?.audioContext.sampleRate ?? 48e3;
8285
+ return this._externalAdapter?.audioContext.sampleRate ?? this._loadedClipSampleRate() ?? 48e3;
8286
+ }
8287
+ _loadedClipSampleRate() {
8288
+ for (const track of this._arrangement.getTracks()) {
8289
+ for (const clip of track.clips) {
8290
+ if ("sampleRate" in clip && typeof clip.sampleRate === "number") return clip.sampleRate;
8291
+ }
8292
+ }
8293
+ return null;
8294
+ }
8295
+ /** Reject the `addClip()` calls waiting for clips that match `which`. */
8296
+ _rejectAwaitedClips(which, message) {
8297
+ for (const [clipId, awaited] of [...this._awaitedClips]) {
8298
+ if (which(clipId, awaited.trackId)) awaited.reject(new Error(message));
8299
+ }
7993
8300
  }
7994
8301
  set adapter(value) {
7995
8302
  if (value && value.audioContext.state === "closed") {
7996
8303
  console.warn("[dawcore] Adapter AudioContext is already closed. Ignoring.");
7997
8304
  return;
7998
8305
  }
7999
- this._adapterConsumedByDispose = false;
8000
8306
  if (this._engine) {
8001
8307
  console.warn(
8002
8308
  "[dawcore] adapter set after engine is built. The engine will continue using the previous adapter."
@@ -8010,6 +8316,7 @@ var DawEditorElement = class extends LitElement14 {
8010
8316
  this._effectsManager = null;
8011
8317
  }
8012
8318
  this._externalAdapter = value;
8319
+ if (value && this.isConnected && !this._engine) this._buildEngineReporting();
8013
8320
  }
8014
8321
  get adapter() {
8015
8322
  return this._externalAdapter;
@@ -8224,10 +8531,7 @@ var DawEditorElement = class extends LitElement14 {
8224
8531
  return clip?.midiNotes != null;
8225
8532
  }
8226
8533
  get effectiveSampleRate() {
8227
- return this._resolvedSampleRate ?? this.sampleRate;
8228
- }
8229
- resolveAudioContextSampleRate(rate) {
8230
- if (!this._resolvedSampleRate) this._resolvedSampleRate = rate;
8534
+ return this.sampleRate;
8231
8535
  }
8232
8536
  /**
8233
8537
  * In beats mode, derive samplesPerPixel from ticksPerPixel so that
@@ -8298,53 +8602,43 @@ var DawEditorElement = class extends LitElement14 {
8298
8602
  _setSelectedTrackId(trackId) {
8299
8603
  this._selectedTrackId = trackId;
8300
8604
  }
8605
+ /**
8606
+ * Every track: those in the arrangement, in its order, then those still
8607
+ * waiting to enter (#848). A `<daw-track>` whose track an Undo took out of
8608
+ * the arrangement is not listed (its descriptor stays for a Redo).
8609
+ */
8301
8610
  get tracks() {
8302
- return [...this._tracks.entries()].map(([trackId, descriptor]) => ({
8303
- trackId,
8304
- ...descriptor,
8305
- ...this._mixOf(trackId)
8306
- }));
8611
+ const ids = [...this._arrangement.getTracks().map((t) => t.id), ...this._entryQueue];
8612
+ return ids.flatMap((trackId) => {
8613
+ const descriptor = this._tracks.get(trackId);
8614
+ return descriptor ? [{ trackId, ...descriptor, ...this._mixOf(trackId) }] : [];
8615
+ });
8307
8616
  }
8308
8617
  /**
8309
- * A track's mix, from its one owner: the arrangement (through
8310
- * `_engineTracks`, which follows `mixerVersion`) for a track the engine
8311
- * holds, the seed for one still on its way in (#843).
8618
+ * A track's mix, from its one owner, the arrangement (#843), as the engine
8619
+ * plays it: its projection carries the take's mute, which `getMixer()`
8620
+ * leaves out (the stored mute comes back when the take ends). A track still
8621
+ * waiting to enter shows what its element declares.
8312
8622
  */
8313
8623
  _mixOf(trackId) {
8314
- const seed = this._seedMix.get(trackId);
8315
- if (seed) return seed;
8316
- const track = this._engineTracks.get(trackId);
8317
- return track ? mixOfTrack(track) : DEFAULT_TRACK_MIX;
8318
- }
8319
- /** Replace a track's seed (a new Map: `_seedMix` is reactive state). */
8320
- _setSeedMix(trackId, mix) {
8321
- this._seedMix = new Map(this._seedMix).set(trackId, mix);
8322
- }
8323
- _deleteSeedMix(trackIds) {
8324
- let next = null;
8325
- for (const id of trackIds) {
8326
- if (!this._seedMix.has(id)) continue;
8327
- next ?? (next = new Map(this._seedMix));
8328
- next.delete(id);
8329
- }
8330
- if (next) this._seedMix = next;
8624
+ const played = this._engineTracks.get(trackId);
8625
+ if (played) return mixOfTrack(played);
8626
+ const mix = this._arrangement.getMixer().get(trackId);
8627
+ if (mix) return mix;
8628
+ const el = this._trackElements.get(trackId);
8629
+ return el ? mixOfElement(el) : DEFAULT_TRACK_MIX;
8331
8630
  }
8332
8631
  /**
8333
- * Change one mixer field of a track: the seed while the track is loading
8334
- * (not an undo step, nothing sent), else the engine's setter with
8335
- * `options` (an undo step; changes with one `gesture` id are one step).
8632
+ * Change one mixer field of a track: the arrangement's setter with
8633
+ * `options` (an undo step; changes with one `gesture` id are one step). A
8634
+ * track that has not entered yet changes nothing.
8336
8635
  */
8337
8636
  _writeMix(trackId, field, value, options) {
8338
- const seed = this._seedMix.get(trackId);
8339
- if (seed) {
8340
- if (seed[field] !== value) this._setSeedMix(trackId, { ...seed, [field]: value });
8341
- return;
8342
- }
8343
- if (!this._engine) return;
8344
- if (field === "volume") this._engine.setTrackVolume(trackId, value, options);
8345
- else if (field === "pan") this._engine.setTrackPan(trackId, value, options);
8346
- else if (field === "muted") this._engine.setTrackMute(trackId, value, options);
8347
- else this._engine.setTrackSolo(trackId, value, options);
8637
+ const arrangement = this._arrangement;
8638
+ if (field === "volume") arrangement.setTrackVolume(trackId, value, options);
8639
+ else if (field === "pan") arrangement.setTrackPan(trackId, value, options);
8640
+ else if (field === "muted") arrangement.setTrackMute(trackId, value, options);
8641
+ else arrangement.setTrackSolo(trackId, value, options);
8348
8642
  }
8349
8643
  /**
8350
8644
  * Change the given mixer fields of a track as ONE undo step (#843): all
@@ -8357,13 +8651,6 @@ var DawEditorElement = class extends LitElement14 {
8357
8651
  if (mix.muted !== void 0) this._writeMix(trackId, "muted", mix.muted, options);
8358
8652
  if (mix.soloed !== void 0) this._writeMix(trackId, "soloed", mix.soloed, options);
8359
8653
  }
8360
- /** The ordered tracks for `engine.setTracks`, a loading track with its seed. */
8361
- _tracksForEngine() {
8362
- return this._getOrderedTracks().map(([trackId, track]) => {
8363
- const seed = this._seedMix.get(trackId);
8364
- return seed ? withMix(track, seed) : track;
8365
- });
8366
- }
8367
8654
  get selectedTrackId() {
8368
8655
  return this._selectedTrackId;
8369
8656
  }
@@ -8389,6 +8676,7 @@ var DawEditorElement = class extends LitElement14 {
8389
8676
  // --- Lifecycle ---
8390
8677
  connectedCallback() {
8391
8678
  super.connectedCallback();
8679
+ window.addEventListener("keydown", this._onDragEscape, { capture: true });
8392
8680
  this.addEventListener("daw-track-connected", this._onTrackConnected);
8393
8681
  this.addEventListener("daw-track-update", this._onTrackUpdate);
8394
8682
  this.addEventListener("daw-track-control", this._onTrackControl);
@@ -8446,9 +8734,14 @@ var DawEditorElement = class extends LitElement14 {
8446
8734
  if (orderMayHaveChanged) this._syncEngineOrderToDom();
8447
8735
  });
8448
8736
  this._childObserver.observe(this, { childList: true, subtree: true });
8737
+ for (const [trackId, el] of [...this._trackElements]) {
8738
+ if (!this.contains(el)) this._onTrackRemoved(trackId);
8739
+ }
8740
+ if (this._externalAdapter && !this._engine) this._buildEngineReporting();
8449
8741
  }
8450
8742
  disconnectedCallback() {
8451
8743
  super.disconnectedCallback();
8744
+ window.removeEventListener("keydown", this._onDragEscape, { capture: true });
8452
8745
  this._effectsManager?.disposeAll();
8453
8746
  this._effectsManager = null;
8454
8747
  this.removeEventListener("daw-track-connected", this._onTrackConnected);
@@ -8464,16 +8757,23 @@ var DawEditorElement = class extends LitElement14 {
8464
8757
  this.removeEventListener("daw-annotation-select", this._onAnnotationSelect);
8465
8758
  this.removeEventListener("daw-track-reorder", this._onTrackReorder);
8466
8759
  this.removeEventListener("daw-track-reorder-grab", this._onTrackReorderGrab);
8467
- this._trackReorderDrag.cancel();
8760
+ this._cancelDrags(true);
8761
+ for (const end of [...this._loadWaitEnds]) end();
8762
+ for (const trackId of this._entryQueue) {
8763
+ if (this._trackElements.has(trackId) || !this._entryWaiters.has(trackId)) continue;
8764
+ const nextTracks = new Map(this._tracks);
8765
+ nextTracks.delete(trackId);
8766
+ this._tracks = nextTracks;
8767
+ this._entryQueue = this._entryQueue.filter((id) => id !== trackId);
8768
+ this._settleEntry(
8769
+ trackId,
8770
+ new Error("<daw-editor> was disconnected before the file entered")
8771
+ );
8772
+ }
8468
8773
  this._childObserver?.disconnect();
8469
8774
  this._childObserver = null;
8470
- this._trackElements.clear();
8471
- this._audioCache.clear();
8472
8775
  this._peaksCache.clear();
8473
- this._clipBuffers.clear();
8474
- this._clipOffsets.clear();
8475
8776
  this._peakPipeline.terminate();
8476
- this._minSamplesPerPixel = 0;
8477
8777
  this._spectrogramController?.dispose();
8478
8778
  this._spectrogramController = null;
8479
8779
  this._lastSpectrogramViewport = null;
@@ -8484,14 +8784,8 @@ var DawEditorElement = class extends LitElement14 {
8484
8784
  console.warn("[dawcore] Error disposing engine: " + String(err));
8485
8785
  }
8486
8786
  if (hadEngine) {
8487
- this._adapterConsumedByDispose = true;
8787
+ this._externalAdapter = null;
8488
8788
  }
8489
- this._tracks = /* @__PURE__ */ new Map();
8490
- this._seedMix = /* @__PURE__ */ new Map();
8491
- this._engineTracks = /* @__PURE__ */ new Map();
8492
- this._peaksData = /* @__PURE__ */ new Map();
8493
- this._loadingTracks.clear();
8494
- this._recomputeDuration();
8495
8789
  }
8496
8790
  willUpdate(changedProperties) {
8497
8791
  if (changedProperties.has("eagerResume")) {
@@ -8545,6 +8839,21 @@ var DawEditorElement = class extends LitElement14 {
8545
8839
  }
8546
8840
  _onTrackRemoved(trackId) {
8547
8841
  const existed = this._tracks.has(trackId);
8842
+ this._rejectAwaitedClips(
8843
+ (_, awaitedTrackId) => awaitedTrackId === trackId,
8844
+ "the track of the clip was removed before the clip loaded"
8845
+ );
8846
+ this._entryQueue = this._entryQueue.filter((id) => id !== trackId);
8847
+ this._settleEntry(trackId, new Error('track "' + trackId + '" was removed before it entered'));
8848
+ const arrangementTrack = this._arrangement.getTracks().find((t) => t.id === trackId);
8849
+ const clipIds = arrangementTrack?.clips.map((c) => c.id) ?? [];
8850
+ this._announcer.forget(trackId, clipIds);
8851
+ if (clipIds.some((id) => this._previewPeaks.has(id))) {
8852
+ const nextPreview = new Map(this._previewPeaks);
8853
+ for (const id of clipIds) nextPreview.delete(id);
8854
+ this._previewPeaks = nextPreview;
8855
+ }
8856
+ for (const id of clipIds) this._previewWaveforms.delete(id);
8548
8857
  this._trackElements.delete(trackId);
8549
8858
  this._effectsManager?.disposeTrackChain(trackId);
8550
8859
  const removedTrack = this._engineTracks.get(trackId);
@@ -8561,14 +8870,11 @@ var DawEditorElement = class extends LitElement14 {
8561
8870
  const nextTracks = new Map(this._tracks);
8562
8871
  nextTracks.delete(trackId);
8563
8872
  this._tracks = nextTracks;
8564
- this._deleteSeedMix([trackId]);
8565
8873
  const nextEngine = new Map(this._engineTracks);
8566
8874
  nextEngine.delete(trackId);
8567
8875
  this._engineTracks = nextEngine;
8568
8876
  this._recomputeDuration();
8569
- if (this._engine) {
8570
- this._engine.removeTrack(trackId);
8571
- }
8877
+ this._arrangement.removeTrack(trackId);
8572
8878
  this._recomputeZoomFloor();
8573
8879
  this._disposeSpectrogramControllerIfEmpty();
8574
8880
  if (existed && nextEngine.size === 0) {
@@ -8629,7 +8935,7 @@ var DawEditorElement = class extends LitElement14 {
8629
8935
  });
8630
8936
  }
8631
8937
  for (const trackId of this._tracks.keys()) {
8632
- if (engineIds.has(trackId) || this._loadingTracks.has(trackId) || this._trackElements.has(trackId)) {
8938
+ if (engineIds.has(trackId) || this._entryQueue.includes(trackId) || this._trackElements.has(trackId)) {
8633
8939
  continue;
8634
8940
  }
8635
8941
  next ?? (next = new Map(this._tracks));
@@ -8681,12 +8987,22 @@ var DawEditorElement = class extends LitElement14 {
8681
8987
  }
8682
8988
  _onClipRemovedFromDom(clipEl) {
8683
8989
  const clipId = clipEl.clipId;
8684
- for (const [trackId, t] of this._engineTracks.entries()) {
8990
+ for (const t of this._arrangement.getTracks()) {
8685
8991
  if (t.clips.some((c) => c.id === clipId)) {
8686
- this._removeClipFromTrack(trackId, clipId);
8992
+ this._removeClipFromTrack(t.id, clipId);
8687
8993
  return;
8688
8994
  }
8689
8995
  }
8996
+ for (const [trackId, desc] of this._tracks) {
8997
+ if (this._isEntered(trackId) || !desc.clips.some((c) => c.clipId === clipId)) continue;
8998
+ this._tracks = new Map(this._tracks).set(trackId, {
8999
+ ...desc,
9000
+ clips: desc.clips.filter((c) => c.clipId !== clipId)
9001
+ });
9002
+ this._rejectAwaitedClips((id) => id === clipId, "the clip was removed before it loaded");
9003
+ return;
9004
+ }
9005
+ this._rejectAwaitedClips((id) => id === clipId, "the clip was removed before it loaded");
8690
9006
  if (this._clipBuffers.has(clipId) || this._clipOffsets.has(clipId) || this._peaksData.has(clipId)) {
8691
9007
  console.warn(
8692
9008
  '[dawcore] _onClipRemovedFromDom: orphaned cache entries for clip "' + clipId + '" \u2014 purging (DOM/engine id mismatch?)'
@@ -8694,62 +9010,52 @@ var DawEditorElement = class extends LitElement14 {
8694
9010
  this._purgeClipCaches(clipId);
8695
9011
  }
8696
9012
  }
8697
- async _loadAndAppendClip(trackId, clipDesc) {
8698
- if (!clipDesc.src) return;
8699
- const clipId = clipDesc.clipId;
8700
- let insertedClipId = null;
9013
+ /**
9014
+ * A `<daw-clip>` appended to a track that has entered: the clip goes in as
9015
+ * a loading clip (a loaded one for MIDI), one undo step. Its audio loads
9016
+ * like any other; `daw-clip-ready` or `daw-clip-error` follows (#848).
9017
+ */
9018
+ _loadAndAppendClip(trackId, clipDesc) {
9019
+ const trackDesc = this._tracks.get(trackId);
9020
+ if (!trackDesc) return;
9021
+ const clipIsMidi = isMidiDescriptor(clipDesc);
9022
+ const kindError = clipKindError(
9023
+ trackDesc.name,
9024
+ trackDesc.kind,
9025
+ clipIsMidi,
9026
+ clipDesc.name || clipDesc.src || clipDesc.clipId
9027
+ );
9028
+ const clip = clipIsMidi ? buildMidiClip(clipDesc, this.effectiveSampleRate) : buildLoadingClip(clipDesc);
9029
+ if (!clipIsMidi) this._announcer.expectClip(clipDesc.clipId);
8701
9030
  try {
8702
- const trackDesc = this._tracks.get(trackId);
8703
- const kindError = trackDesc ? this._clipKindError(trackDesc.name, trackDesc.kind, false, clipDesc.name || clipDesc.src) : null;
8704
9031
  if (kindError) throw kindError;
8705
- const waveformDataPromise = clipDesc.peaksSrc ? this._resolvePeaks(clipDesc.peaksSrc) : Promise.resolve(null);
8706
- const audioPromise = this._fetchAndDecode(clipDesc.src);
8707
- const [waveformData, audioBuffer] = await Promise.all([waveformDataPromise, audioPromise]);
8708
- this._resolvedSampleRate = audioBuffer.sampleRate;
8709
- const clip = await this._finalizeAudioClip(clipDesc, audioBuffer, waveformData);
8710
- insertedClipId = clip.id;
8711
- const t = this._engineTracks.get(trackId);
8712
- if (!t) {
8713
- this._purgeClipCaches(clip.id);
8714
- return;
8715
- }
8716
- const updatedTrack = { ...t, clips: [...t.clips, clip] };
8717
- this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);
8718
- const desc = this._tracks.get(trackId);
8719
- if (desc) {
8720
- this._tracks = new Map(this._tracks).set(trackId, {
8721
- ...desc,
8722
- clips: [...desc.clips, clipDesc]
8723
- });
8724
- }
8725
- this._commitTrackChange(trackId, updatedTrack);
8726
- this._maybeRegisterSpectrogramClipAudio(trackId, clip);
8727
- this.dispatchEvent(
8728
- new CustomEvent("daw-clip-ready", {
8729
- bubbles: true,
8730
- composed: true,
8731
- detail: { trackId, clipId: clip.id }
8732
- })
8733
- );
9032
+ this._arrangement.updateTrack(trackId, (current) => ({
9033
+ ...current,
9034
+ clips: [...current.clips, clip]
9035
+ }));
8734
9036
  } catch (err) {
8735
9037
  console.warn("[dawcore] _loadAndAppendClip failed: " + String(err));
8736
- if (insertedClipId) this._purgeClipCaches(insertedClipId);
8737
9038
  this.dispatchEvent(
8738
9039
  new CustomEvent("daw-clip-error", {
8739
9040
  bubbles: true,
8740
9041
  composed: true,
8741
- detail: { trackId, clipId: insertedClipId ?? clipId, error: err }
9042
+ detail: { trackId, clipId: clipDesc.clipId, error: err }
8742
9043
  })
8743
9044
  );
9045
+ return;
8744
9046
  }
9047
+ this._tracks = new Map(this._tracks).set(trackId, {
9048
+ ...trackDesc,
9049
+ clips: [...trackDesc.clips, clipDesc]
9050
+ });
9051
+ if (!clipIsMidi && clipDesc.peaksSrc) this._requestPreview(clipDesc.clipId, clipDesc.peaksSrc);
8745
9052
  }
8746
9053
  /**
8747
9054
  * Resolve pre-computed peaks for a clip: fetch the .dat/.json, validate the
8748
9055
  * sample rate matches the AudioContext, return the WaveformData or null.
8749
9056
  * Warns on fetch failure and on sample-rate mismatch — never silent.
8750
9057
  *
8751
- * Shared between `_loadTrack` (peaks-first preview path) and
8752
- * `_loadAndAppendClip` (incremental late-append).
9058
+ * Used by `_requestPreview` for a clip that is still loading.
8753
9059
  */
8754
9060
  async _resolvePeaks(peaksSrc) {
8755
9061
  try {
@@ -8767,127 +9073,6 @@ var DawEditorElement = class extends LitElement14 {
8767
9073
  return null;
8768
9074
  }
8769
9075
  }
8770
- /**
8771
- * Construct an AudioClip from a decoded buffer (and optional WaveformData),
8772
- * align its id with the source `<daw-clip>.clipId` when present, populate
8773
- * `_clipBuffers` / `_clipOffsets`, generate peaks via the worker pipeline,
8774
- * and populate `_peaksData`. Returns the finished AudioClip.
8775
- *
8776
- * Shared between `_loadTrack`'s standard path and `_loadAndAppendClip`.
8777
- * Not used by `_loadTrack`'s peaks-first preview path because that path
8778
- * uses sync `extractPeaks` and inserts a preview track BEFORE audio decode.
8779
- */
8780
- async _finalizeAudioClip(clipDesc, audioBuffer, waveformData) {
8781
- let clip;
8782
- if (waveformData) {
8783
- const wdRate = waveformData.sample_rate;
8784
- clip = createClip2({
8785
- audioBuffer,
8786
- waveformData,
8787
- startSample: Math.round(clipDesc.start * wdRate),
8788
- durationSamples: Math.round((clipDesc.duration || waveformData.duration) * wdRate),
8789
- offsetSamples: Math.round(clipDesc.offset * wdRate),
8790
- gain: clipDesc.gain,
8791
- name: clipDesc.name,
8792
- sampleRate: wdRate,
8793
- sourceDurationSamples: Math.ceil(waveformData.duration * wdRate)
8794
- });
8795
- this._peakPipeline.cacheWaveformData(audioBuffer, waveformData);
8796
- } else {
8797
- clip = createClipFromSeconds({
8798
- audioBuffer,
8799
- startTime: clipDesc.start,
8800
- duration: clipDesc.duration || audioBuffer.duration,
8801
- offset: clipDesc.offset,
8802
- gain: clipDesc.gain,
8803
- name: clipDesc.name,
8804
- sampleRate: audioBuffer.sampleRate,
8805
- sourceDuration: audioBuffer.duration
8806
- });
8807
- }
8808
- if (isDomClip(clipDesc)) clip.id = clipDesc.clipId;
8809
- this._clipBuffers = new Map(this._clipBuffers).set(clip.id, audioBuffer);
8810
- this._clipOffsets.set(clip.id, {
8811
- offsetSamples: clip.offsetSamples,
8812
- durationSamples: clip.durationSamples
8813
- });
8814
- let peakData;
8815
- try {
8816
- peakData = await this._peakPipeline.generatePeaks(
8817
- audioBuffer,
8818
- this._renderSpp,
8819
- this.mono,
8820
- clip.offsetSamples,
8821
- clip.durationSamples
8822
- );
8823
- } catch (err) {
8824
- this._purgeClipCaches(clip.id);
8825
- throw err;
8826
- }
8827
- this._peaksData = new Map(this._peaksData).set(clip.id, peakData);
8828
- const cachedScale = waveformData?.scale ?? this._peakPipeline.getCachedScale(audioBuffer);
8829
- this._raiseZoomFloor(cachedScale);
8830
- return clip;
8831
- }
8832
- /**
8833
- * Filter MIDI notes to only those with finite, in-range fields. Logs a
8834
- * warning for each dropped note. Used by _buildMidiClip and the
8835
- * _applyClipUpdate MIDI branch to prevent NaN propagation through the
8836
- * timeline.
8837
- */
8838
- _validMidiNotes(notes) {
8839
- return notes.filter((n) => {
8840
- const ok = Number.isFinite(n.time) && n.time >= 0 && Number.isFinite(n.duration) && n.duration > 0 && Number.isInteger(n.midi) && n.midi >= 0 && n.midi <= 127 && Number.isFinite(n.velocity) && n.velocity >= 0 && n.velocity <= 1;
8841
- if (!ok) {
8842
- console.warn("[dawcore] dropping malformed MIDI note: " + JSON.stringify(n));
8843
- }
8844
- return ok;
8845
- });
8846
- }
8847
- /**
8848
- * A clip descriptor is treated as MIDI when it has no audio src.
8849
- * Includes placeholder MIDI clips (no notes, no duration yet — registered
8850
- * with a 1s default span; notes upgrade via _applyClipUpdate). Warns when
8851
- * a clip ambiguously has both src and midiNotes — the audio path runs
8852
- * and notes would be silently ignored.
8853
- */
8854
- _isMidiDescriptor(clipDesc) {
8855
- if (clipDesc.src) {
8856
- if (clipDesc.midiNotes != null) {
8857
- console.warn(
8858
- '[dawcore] clip "' + (clipDesc.name || (isDomClip(clipDesc) ? clipDesc.clipId : "?")) + '" has both src and midiNotes \u2014 treating as audio (notes will be ignored)'
8859
- );
8860
- }
8861
- return false;
8862
- }
8863
- return true;
8864
- }
8865
- /**
8866
- * Build an engine clip from a MIDI clip descriptor. Always returns a clip
8867
- * — empty notes / no declared duration get a 1-second placeholder span so
8868
- * the clip is reachable via `engine.updateTrack` once notes arrive.
8869
- */
8870
- _buildMidiClip(clipDesc) {
8871
- const sr = this.effectiveSampleRate;
8872
- const notes = this._validMidiNotes(clipDesc.midiNotes ?? []);
8873
- const noteSpanSeconds = notes.length ? notes.reduce((max, n) => Math.max(max, n.time + n.duration), 0) : 0;
8874
- const sourceDurationSamples = Math.ceil(Math.max(noteSpanSeconds, clipDesc.duration, 1) * sr);
8875
- const requestedDurationSamples = clipDesc.duration > 0 ? Math.round(clipDesc.duration * sr) : sourceDurationSamples;
8876
- const clip = createClip2({
8877
- startSample: Math.round(clipDesc.start * sr),
8878
- durationSamples: requestedDurationSamples,
8879
- offsetSamples: Math.round(clipDesc.offset * sr),
8880
- sampleRate: sr,
8881
- sourceDurationSamples,
8882
- gain: clipDesc.gain,
8883
- name: clipDesc.name,
8884
- midiNotes: notes,
8885
- midiChannel: clipDesc.midiChannel ?? void 0,
8886
- midiProgram: clipDesc.midiProgram ?? void 0
8887
- });
8888
- if (isDomClip(clipDesc)) clip.id = clipDesc.clipId;
8889
- return clip;
8890
- }
8891
9076
  /** Remove a single clip from all per-clip caches. Used by error rollbacks. */
8892
9077
  _purgeClipCaches(clipId) {
8893
9078
  const nextBuffers = new Map(this._clipBuffers);
@@ -8900,16 +9085,14 @@ var DawEditorElement = class extends LitElement14 {
8900
9085
  this._spectrogramController?.unregisterClipAudio(clipId);
8901
9086
  }
8902
9087
  /**
8903
- * Recompute duration and forward an updated track to the engine. Single
8904
- * source of truth for the incremental-vs-full-rebuild policy used by every
8905
- * clip-level mutation (addClip, updateClip, removeClip, _applyClipUpdate).
8906
- * Use the engine's incremental updateTrack when available; otherwise fall
8907
- * back to full setTracks (legacy adapters).
9088
+ * Replace one loaded clip of a track in the arrangement: an undo step. The
9089
+ * function form, so the track's loading clips stay as they are (#848).
8908
9090
  */
8909
- _commitTrackChange(trackId, updatedTrack) {
8910
- this._recomputeDuration();
8911
- if (this._engine?.updateTrack) this._engine.updateTrack(trackId, updatedTrack);
8912
- else if (this._engine) this._engine.setTracks(this._tracksForEngine());
9091
+ _replaceClip(trackId, clipId, clip) {
9092
+ this._arrangement.updateTrack(trackId, (current) => ({
9093
+ ...current,
9094
+ clips: current.clips.map((c) => c.id === clipId ? clip : c)
9095
+ }));
8913
9096
  }
8914
9097
  _applyClipUpdate(trackId, clipId, clipEl) {
8915
9098
  const t = this._engineTracks.get(trackId);
@@ -8919,8 +9102,9 @@ var DawEditorElement = class extends LitElement14 {
8919
9102
  }
8920
9103
  const idx = t.clips.findIndex((c) => c.id === clipId);
8921
9104
  if (idx === -1) {
9105
+ const loading = this._arrangement.getTracks().find((track) => track.id === trackId)?.clips.some((c) => c.id === clipId);
8922
9106
  console.warn(
8923
- '[dawcore] _applyClipUpdate: clip "' + clipId + '" not found in track "' + trackId + '" (DOM/engine clip-id misalignment?)'
9107
+ '[dawcore] _applyClipUpdate: clip "' + clipId + '" ' + (loading ? "is still loading; the change is dropped" : 'not found in track "' + trackId + '" (DOM/engine clip-id misalignment?)')
8924
9108
  );
8925
9109
  return;
8926
9110
  }
@@ -8929,7 +9113,7 @@ var DawEditorElement = class extends LitElement14 {
8929
9113
  const isMidiNow = clipEl.midiNotes != null && !clipEl.src;
8930
9114
  const wasMidi = oldClip.midiNotes != null;
8931
9115
  if (isMidiNow && trackKind(t) !== "midi") {
8932
- const kindError = this._clipKindError(t.name, "audio", true, clipEl.name || clipId);
9116
+ const kindError = clipKindError(t.name ?? "", "audio", true, clipEl.name || clipId);
8933
9117
  console.warn("[dawcore] _applyClipUpdate: " + kindError?.message);
8934
9118
  this.dispatchEvent(
8935
9119
  new CustomEvent("daw-clip-error", {
@@ -8941,7 +9125,7 @@ var DawEditorElement = class extends LitElement14 {
8941
9125
  return;
8942
9126
  }
8943
9127
  if (isMidiNow || wasMidi) {
8944
- const notes = this._validMidiNotes(clipEl.midiNotes ?? []);
9128
+ const notes = validMidiNotes(clipEl.midiNotes ?? []);
8945
9129
  const noteSpanSeconds = notes.length ? notes.reduce((max, n) => Math.max(max, n.time + n.duration), 0) : 0;
8946
9130
  const sourceDurationSamples = Math.ceil(Math.max(noteSpanSeconds, clipEl.duration, 1) * sr);
8947
9131
  const requestedDurationSamples = clipEl.duration > 0 ? Math.round(clipEl.duration * sr) : sourceDurationSamples;
@@ -8958,12 +9142,8 @@ var DawEditorElement = class extends LitElement14 {
8958
9142
  midiChannel: clipEl.midiChannel ?? void 0,
8959
9143
  midiProgram: clipEl.midiProgram ?? void 0
8960
9144
  };
8961
- const updatedClips2 = [...t.clips];
8962
- updatedClips2[idx] = updatedClip2;
8963
- const updatedTrack2 = { ...t, clips: updatedClips2 };
8964
- this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack2);
8965
9145
  this._purgeClipCaches(clipId);
8966
- this._commitTrackChange(trackId, updatedTrack2);
9146
+ this._replaceClip(trackId, clipId, updatedClip2);
8967
9147
  return;
8968
9148
  }
8969
9149
  const newStartSample = Math.round(clipEl.start * sr);
@@ -8977,10 +9157,6 @@ var DawEditorElement = class extends LitElement14 {
8977
9157
  gain: clipEl.gain,
8978
9158
  name: clipEl.name || oldClip.name
8979
9159
  };
8980
- const updatedClips = [...t.clips];
8981
- updatedClips[idx] = updatedClip;
8982
- const updatedTrack = { ...t, clips: updatedClips };
8983
- this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);
8984
9160
  const boundsChanged = oldClip.offsetSamples !== newOffsetSamples || oldClip.durationSamples !== newDurationSamples;
8985
9161
  if (boundsChanged) {
8986
9162
  this._clipOffsets.set(clipId, {
@@ -8992,40 +9168,41 @@ var DawEditorElement = class extends LitElement14 {
8992
9168
  this._peaksData = new Map(this._peaksData).set(clipId, peaks);
8993
9169
  }
8994
9170
  }
8995
- this._commitTrackChange(trackId, updatedTrack);
9171
+ this._replaceClip(trackId, clipId, updatedClip);
8996
9172
  }
9173
+ /** Remove a clip (loaded or still loading) from a track of the arrangement: an undo step. */
8997
9174
  _removeClipFromTrack(trackId, clipId) {
8998
- const t = this._engineTracks.get(trackId);
8999
- if (!t) {
9000
- console.warn('[dawcore] _removeClipFromTrack: no engine track for id "' + trackId + '"');
9175
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9176
+ if (!track) {
9177
+ console.warn('[dawcore] _removeClipFromTrack: no track for id "' + trackId + '"');
9001
9178
  return;
9002
9179
  }
9003
- const updatedClips = t.clips.filter((c) => c.id !== clipId);
9004
- if (updatedClips.length === t.clips.length) {
9180
+ if (!track.clips.some((c) => c.id === clipId)) {
9005
9181
  console.warn(
9006
9182
  '[dawcore] _removeClipFromTrack: clip "' + clipId + '" not found in track "' + trackId + '"'
9007
9183
  );
9008
9184
  return;
9009
9185
  }
9010
- const updatedTrack = { ...t, clips: updatedClips };
9011
- this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);
9012
- const nextBuffers = new Map(this._clipBuffers);
9013
- nextBuffers.delete(clipId);
9014
- this._clipBuffers = nextBuffers;
9015
- this._clipOffsets.delete(clipId);
9016
- const nextPeaks = new Map(this._peaksData);
9017
- nextPeaks.delete(clipId);
9018
- this._peaksData = nextPeaks;
9186
+ this._purgeClipCaches(clipId);
9187
+ this._previewWaveforms.delete(clipId);
9188
+ if (this._previewPeaks.has(clipId)) {
9189
+ const nextPreview = new Map(this._previewPeaks);
9190
+ nextPreview.delete(clipId);
9191
+ this._previewPeaks = nextPreview;
9192
+ }
9019
9193
  const desc = this._tracks.get(trackId);
9020
9194
  if (desc) {
9021
9195
  this._tracks = new Map(this._tracks).set(trackId, {
9022
9196
  ...desc,
9023
- // Descriptors without an id (file drops, the <daw-track src>
9024
- // shorthand) are kept — their identity is the descriptor itself.
9025
9197
  clips: desc.clips.filter((c) => c.clipId !== clipId)
9026
9198
  });
9027
9199
  }
9028
- this._commitTrackChange(trackId, updatedTrack);
9200
+ const wasLoading = track.clips.some((c) => c.id === clipId && isLoadingClip3(c));
9201
+ this._arrangement.updateTrack(trackId, (current) => ({
9202
+ ...current,
9203
+ clips: current.clips.filter((c) => c.id !== clipId)
9204
+ }));
9205
+ if (wasLoading) this._announcer.forgetClip(clipId);
9029
9206
  }
9030
9207
  _readTrackDescriptor(trackEl) {
9031
9208
  const clipEls = trackEl.querySelectorAll("daw-clip");
@@ -9048,25 +9225,7 @@ var DawEditorElement = class extends LitElement14 {
9048
9225
  midiProgram: null
9049
9226
  });
9050
9227
  } else {
9051
- for (const clipEl of clipEls) {
9052
- clips.push({
9053
- kind: "dom",
9054
- clipId: clipEl.clipId,
9055
- src: clipEl.src,
9056
- peaksSrc: clipEl.peaksSrc,
9057
- start: clipEl.start,
9058
- duration: clipEl.duration,
9059
- offset: clipEl.offset,
9060
- gain: clipEl.gain,
9061
- name: clipEl.name,
9062
- fadeIn: clipEl.fadeIn,
9063
- fadeOut: clipEl.fadeOut,
9064
- fadeType: clipEl.fadeType,
9065
- midiNotes: clipEl.midiNotes,
9066
- midiChannel: clipEl.midiChannel,
9067
- midiProgram: clipEl.midiProgram
9068
- });
9069
- }
9228
+ for (const clipEl of clipEls) clips.push(this._readClipDescriptor(clipEl));
9070
9229
  }
9071
9230
  return {
9072
9231
  name: trackEl.name || "Untitled",
@@ -9076,228 +9235,312 @@ var DawEditorElement = class extends LitElement14 {
9076
9235
  clips
9077
9236
  };
9078
9237
  }
9238
+ _readClipDescriptor(clipEl) {
9239
+ return {
9240
+ kind: "dom",
9241
+ clipId: clipEl.clipId,
9242
+ src: clipEl.src,
9243
+ peaksSrc: clipEl.peaksSrc,
9244
+ start: clipEl.start,
9245
+ duration: clipEl.duration,
9246
+ offset: clipEl.offset,
9247
+ gain: clipEl.gain,
9248
+ name: clipEl.name,
9249
+ fadeIn: clipEl.fadeIn,
9250
+ fadeOut: clipEl.fadeOut,
9251
+ fadeType: clipEl.fadeType,
9252
+ midiNotes: clipEl.midiNotes,
9253
+ midiChannel: clipEl.midiChannel,
9254
+ midiProgram: clipEl.midiProgram
9255
+ };
9256
+ }
9257
+ // --- Entering the arrangement (#848) ---
9258
+ _isEntered(trackId) {
9259
+ return this._arrangement.getTracks().some((t) => t.id === trackId);
9260
+ }
9261
+ /** Queue a registered track for the next flush. */
9262
+ _queueEntry(trackId) {
9263
+ if (!this._entryQueue.includes(trackId)) this._entryQueue = [...this._entryQueue, trackId];
9264
+ if (this._entryFlushScheduled) return;
9265
+ this._entryFlushScheduled = true;
9266
+ queueMicrotask(() => {
9267
+ this._entryFlushScheduled = false;
9268
+ this._flushTrackEntries();
9269
+ });
9270
+ }
9079
9271
  /**
9080
- * The error for a clip whose kind is not its track's (#756), or null. A clip
9081
- * with no `src` is a MIDI clip (see _isMidiDescriptor).
9272
+ * Enter the queued tracks into the arrangement, in DOM order. Without an
9273
+ * engine they wait (the sample rate of a MIDI clip comes from the
9274
+ * adapter); the engine's build flushes again. The page's tracks entering
9275
+ * while the arrangement has no history are not undo steps: the history is
9276
+ * cleared after them, so Undo right after load removes nothing (and the
9277
+ * next page track finds it empty again).
9082
9278
  */
9083
- _clipKindError(trackName, kind, clipIsMidi, clipLabel) {
9084
- if (clipIsMidi === (kind === "midi")) return null;
9085
- return new Error(
9086
- clipIsMidi ? 'clip "' + clipLabel + '" is a MIDI clip (no src) on audio track "' + trackName + `". A track holds one kind of clip: set kind="midi" on the <daw-track> (or kind: 'midi' in addTrack) for a track of MIDI clips.` : 'clip "' + clipLabel + '" is an audio clip on MIDI track "' + trackName + '". A track holds one kind of clip: put the clip on an audio track.'
9279
+ _flushTrackEntries() {
9280
+ if (this._entryQueue.length === 0) return;
9281
+ if (!this._engine) return;
9282
+ if (this._dragInProgress) {
9283
+ this._flushAfterDrag();
9284
+ return;
9285
+ }
9286
+ const queued = this._entryQueue;
9287
+ this._entryQueue = [];
9288
+ const domOrder = [...this.querySelectorAll("daw-track")].map(
9289
+ (el) => el.trackId
9087
9290
  );
9291
+ const position = (id) => {
9292
+ const at = domOrder.indexOf(id);
9293
+ return at === -1 ? domOrder.length : at;
9294
+ };
9295
+ const ordered = [...queued].sort((a, b) => position(a) - position(b));
9296
+ const isPageTrack = (id) => {
9297
+ const el = this._trackElements.get(id);
9298
+ return el !== void 0 && !this._editorMadeTracks.has(el);
9299
+ };
9300
+ const arrangement = this._arrangement;
9301
+ const historyWasEmpty = !arrangement.canUndo && !arrangement.canRedo && !this._dragInProgress;
9302
+ let pageEntered = false;
9303
+ for (const id of ordered.filter(isPageTrack)) {
9304
+ if (this._enterTrack(id)) pageEntered = true;
9305
+ }
9306
+ if (historyWasEmpty && pageEntered) arrangement.clearHistory();
9307
+ for (const id of ordered.filter((id2) => !isPageTrack(id2))) this._enterTrack(id);
9308
+ }
9309
+ /** Flush the queue once the drag in progress has ended (its pointer or key is released). */
9310
+ _flushAfterDrag() {
9311
+ if (this._waitingForDragEnd) return;
9312
+ this._waitingForDragEnd = true;
9313
+ const events = ["pointerup", "pointercancel", "keyup"];
9314
+ const retry = () => {
9315
+ for (const type of events) window.removeEventListener(type, retry);
9316
+ this._waitingForDragEnd = false;
9317
+ setTimeout(() => this._flushTrackEntries(), 0);
9318
+ };
9319
+ for (const type of events) window.addEventListener(type, retry);
9088
9320
  }
9089
- // --- Audio Loading ---
9090
- async _loadTrack(trackId, descriptor) {
9091
- this._loadingTracks.add(trackId);
9092
- const sppAtLoadStart = this._samplesPerPixel;
9093
- try {
9094
- const clips = [];
9095
- let refusedMidiClips = 0;
9096
- for (const clipDesc of descriptor.clips) {
9097
- const clipIsMidi = this._isMidiDescriptor(clipDesc);
9098
- const kindError = this._clipKindError(
9099
- descriptor.name,
9100
- descriptor.kind,
9101
- clipIsMidi,
9102
- clipDesc.name || clipDesc.src || (isDomClip(clipDesc) ? clipDesc.clipId : "")
9103
- );
9104
- if (kindError) {
9105
- console.warn("[dawcore] _loadTrack: " + kindError.message);
9106
- if (this.isConnected) {
9107
- this.dispatchEvent(
9108
- new CustomEvent("daw-clip-error", {
9109
- bubbles: true,
9110
- composed: true,
9111
- detail: {
9112
- trackId,
9113
- clipId: isDomClip(clipDesc) ? clipDesc.clipId : "",
9114
- error: kindError
9115
- }
9116
- })
9117
- );
9118
- }
9119
- if (clipIsMidi) refusedMidiClips++;
9120
- continue;
9121
- }
9122
- if (clipIsMidi) {
9123
- clips.push(this._buildMidiClip(clipDesc));
9124
- continue;
9125
- }
9126
- try {
9127
- const waveformDataPromise = clipDesc.peaksSrc ? this._resolvePeaks(clipDesc.peaksSrc) : Promise.resolve(null);
9128
- const audioPromise = this._fetchAndDecode(clipDesc.src);
9129
- const waveformData = await waveformDataPromise;
9130
- if (waveformData) {
9131
- const wdRate = waveformData.sample_rate;
9132
- const clip2 = createClip2({
9133
- waveformData,
9134
- startSample: Math.round(clipDesc.start * wdRate),
9135
- durationSamples: Math.round((clipDesc.duration || waveformData.duration) * wdRate),
9136
- offsetSamples: Math.round(clipDesc.offset * wdRate),
9137
- gain: clipDesc.gain,
9138
- name: clipDesc.name,
9139
- sampleRate: wdRate,
9140
- sourceDurationSamples: Math.ceil(waveformData.duration * wdRate)
9141
- });
9142
- if (isDomClip(clipDesc)) clip2.id = clipDesc.clipId;
9143
- const effectiveScale = Math.max(this._renderSpp, waveformData.scale);
9144
- const peakData = extractPeaks(
9145
- waveformData,
9146
- effectiveScale,
9147
- this.mono,
9148
- clip2.offsetSamples,
9149
- clip2.durationSamples
9150
- );
9151
- this._clipOffsets.set(clip2.id, {
9152
- offsetSamples: clip2.offsetSamples,
9153
- durationSamples: clip2.durationSamples
9154
- });
9155
- this._peaksData = new Map(this._peaksData).set(clip2.id, peakData);
9156
- this._raiseZoomFloor(waveformData.scale);
9157
- if (this._tracks.has(trackId)) {
9158
- const previewTrack = createTrack({
9159
- name: descriptor.name,
9160
- kind: descriptor.kind,
9161
- clips: [clip2],
9162
- ...this._mixOf(trackId)
9163
- });
9164
- previewTrack.id = trackId;
9165
- this._engineTracks = new Map(this._engineTracks).set(trackId, previewTrack);
9166
- this._recomputeDuration();
9167
- }
9168
- let audioBuffer2;
9169
- try {
9170
- audioBuffer2 = await audioPromise;
9171
- } catch (audioErr) {
9172
- const nextPeaks = new Map(this._peaksData);
9173
- nextPeaks.delete(clip2.id);
9174
- this._peaksData = nextPeaks;
9175
- this._clipOffsets.delete(clip2.id);
9176
- const nextEngine = new Map(this._engineTracks);
9177
- nextEngine.delete(trackId);
9178
- this._engineTracks = nextEngine;
9179
- this._recomputeZoomFloor();
9180
- this._recomputeDuration();
9181
- throw audioErr;
9182
- }
9183
- this._resolvedSampleRate = audioBuffer2.sampleRate;
9184
- const updatedClip = { ...clip2, audioBuffer: audioBuffer2 };
9185
- this._clipBuffers = new Map(this._clipBuffers).set(clip2.id, audioBuffer2);
9186
- this._peakPipeline.cacheWaveformData(audioBuffer2, waveformData);
9187
- clips.push(updatedClip);
9188
- continue;
9189
- }
9190
- const audioBuffer = await audioPromise;
9191
- this._resolvedSampleRate = audioBuffer.sampleRate;
9192
- const clip = await this._finalizeAudioClip(clipDesc, audioBuffer, null);
9193
- clips.push(clip);
9194
- } catch (clipErr) {
9195
- console.warn(
9196
- '[dawcore] _loadTrack: clip "' + clipDesc.src + '" failed: ' + String(clipErr)
9197
- );
9198
- if (this.isConnected) {
9199
- this.dispatchEvent(
9200
- new CustomEvent("daw-clip-error", {
9201
- bubbles: true,
9202
- composed: true,
9203
- detail: {
9204
- trackId,
9205
- clipId: isDomClip(clipDesc) ? clipDesc.clipId : "",
9206
- error: clipErr
9207
- }
9208
- })
9209
- );
9210
- }
9211
- }
9212
- }
9213
- const trackWasRemoved = !this._tracks.has(trackId);
9214
- if (trackWasRemoved || !this.isConnected) {
9215
- for (const clip of clips) {
9216
- this._purgeClipCaches(clip.id);
9217
- }
9218
- if (this._engineTracks.has(trackId)) {
9219
- const nextEngine = new Map(this._engineTracks);
9220
- nextEngine.delete(trackId);
9221
- this._engineTracks = nextEngine;
9222
- this._recomputeDuration();
9223
- }
9224
- this._recomputeZoomFloor();
9225
- if (this._samplesPerPixel !== sppAtLoadStart && sppAtLoadStart >= this._minSamplesPerPixel) {
9226
- this.samplesPerPixel = sppAtLoadStart;
9227
- }
9228
- throw new TrackLoadCancelledError(
9229
- trackWasRemoved ? 'track "' + trackId + '" was removed while loading' : 'editor was disconnected while track "' + trackId + '" was loading',
9230
- trackWasRemoved ? "removed" : "disconnected"
9231
- );
9232
- }
9233
- const track = createTrack({
9234
- name: descriptor.name,
9235
- kind: descriptor.kind,
9236
- clips,
9237
- ...this._mixOf(trackId)
9238
- });
9239
- const requestedClips = descriptor.clips.filter((c) => c.src).length + refusedMidiClips;
9240
- if (requestedClips > 0 && clips.length === 0) {
9241
- throw new Error(
9242
- "all " + requestedClips + " clip(s) failed to load \u2014 see prior daw-clip-error events"
9243
- );
9244
- }
9245
- track.id = trackId;
9246
- this._engineTracks = new Map(this._engineTracks).set(trackId, track);
9247
- this._recomputeDuration();
9248
- for (const c of clips) {
9249
- this._maybeRegisterSpectrogramClipAudio(trackId, c);
9250
- }
9251
- const engine = await this._ensureEngine();
9252
- engine.setTracks(this._tracksForEngine());
9321
+ /** Enter one registered track. False when it is gone, already in, or refused. */
9322
+ _enterTrack(trackId) {
9323
+ const descriptor = this._tracks.get(trackId);
9324
+ if (!descriptor || this._isEntered(trackId)) return false;
9325
+ const el = this._trackElements.get(trackId);
9326
+ const built = buildArrangementTrack(
9327
+ trackId,
9328
+ descriptor,
9329
+ el ? mixOfElement(el) : DEFAULT_TRACK_MIX,
9330
+ this.effectiveSampleRate
9331
+ );
9332
+ if (built.descriptor !== descriptor) {
9333
+ this._tracks = new Map(this._tracks).set(trackId, built.descriptor);
9334
+ }
9335
+ for (const { clipId, error } of built.refused) {
9336
+ console.warn("[dawcore] " + error.message);
9253
9337
  this.dispatchEvent(
9254
- new CustomEvent("daw-track-ready", {
9338
+ new CustomEvent("daw-clip-error", {
9255
9339
  bubbles: true,
9256
9340
  composed: true,
9257
- detail: { trackId }
9341
+ detail: { trackId, clipId, error }
9258
9342
  })
9259
9343
  );
9344
+ }
9345
+ const index = el ? entryIndex(
9346
+ [...this.querySelectorAll("daw-track")],
9347
+ trackId,
9348
+ this._arrangement.getTracks().map((t) => t.id)
9349
+ ) : void 0;
9350
+ this._announcer.expect(trackId, built.refused.length);
9351
+ for (const clip of built.track.clips) {
9352
+ if (isLoadingClip3(clip)) this._announcer.expectClip(clip.id);
9353
+ }
9354
+ try {
9355
+ this._arrangement.addTrack(built.track, index === void 0 ? void 0 : { index });
9260
9356
  } catch (err) {
9261
- const cancelled = err instanceof TrackLoadCancelledError;
9262
- console.warn(
9263
- cancelled ? "[dawcore] Track load cancelled: " + err.message : '[dawcore] Failed to load track "' + trackId + '": ' + String(err)
9264
- );
9357
+ console.warn('[dawcore] Failed to add track "' + trackId + '": ' + String(err));
9358
+ this._settleEntry(trackId, err instanceof Error ? err : new Error(String(err)));
9265
9359
  this.dispatchEvent(
9266
9360
  new CustomEvent("daw-track-error", {
9267
9361
  bubbles: true,
9268
9362
  composed: true,
9269
- detail: {
9270
- trackId,
9271
- error: err,
9272
- ...cancelled ? { reason: err.reason } : {}
9273
- }
9363
+ detail: { trackId, error: err }
9274
9364
  })
9275
9365
  );
9276
- } finally {
9277
- this._loadingTracks.delete(trackId);
9278
- }
9279
- }
9280
- async _fetchAndDecode(src) {
9281
- if (this._audioCache.has(src)) {
9282
- return this._audioCache.get(src);
9366
+ return false;
9283
9367
  }
9284
- const promise = (async () => {
9285
- const response = await fetch(src);
9286
- if (!response.ok) {
9287
- throw new Error(
9288
- 'Failed to fetch audio "' + src + '": ' + response.status + " " + response.statusText
9289
- );
9368
+ this._settleEntry(trackId, null);
9369
+ for (const clipDesc of built.descriptor.clips) {
9370
+ if (clipDesc.peaksSrc && clipDesc.clipId && clipSourceOf(clipDesc)) {
9371
+ this._requestPreview(clipDesc.clipId, clipDesc.peaksSrc);
9290
9372
  }
9291
- const arrayBuffer = await response.arrayBuffer();
9292
- return this.audioContext.decodeAudioData(arrayBuffer);
9293
- })();
9294
- this._audioCache.set(src, promise);
9295
- try {
9296
- return await promise;
9297
- } catch (err) {
9298
- this._audioCache.delete(src);
9299
- throw err;
9300
9373
  }
9374
+ return true;
9375
+ }
9376
+ /**
9377
+ * The `<daw-track src>` shorthand changed its src: the entered track gets a
9378
+ * new loading clip for it, one undo step. A track whose clips are
9379
+ * `<daw-clip>` children keeps them. A track still queued reads the new
9380
+ * descriptor when it enters.
9381
+ */
9382
+ _replaceShorthandClips(trackId, descriptor) {
9383
+ if (!this._isEntered(trackId) || descriptor.clips.some(isDomClip)) return;
9384
+ const built = buildArrangementTrack(
9385
+ trackId,
9386
+ descriptor,
9387
+ DEFAULT_TRACK_MIX,
9388
+ this.effectiveSampleRate
9389
+ );
9390
+ this._tracks = new Map(this._tracks).set(trackId, built.descriptor);
9391
+ this._arrangement.updateTrack(trackId, (current) => ({ ...current, clips: built.track.clips }));
9392
+ }
9393
+ /** Run the load announcements over the arrangement's current state. */
9394
+ _announceLoading() {
9395
+ this._announcer.update(
9396
+ this._arrangement.getTracks(),
9397
+ this._arrangement.sources.getSnapshot().sources
9398
+ );
9399
+ }
9400
+ /**
9401
+ * Fetch a loading clip's `.dat` peaks and draw them until its audio
9402
+ * arrives (an editor-only cache, not the arrangement: writing the clip
9403
+ * after it entered would be an undo step).
9404
+ */
9405
+ async _requestPreview(clipId, peaksSrc) {
9406
+ const waveformData = await this._resolvePeaks(peaksSrc);
9407
+ if (!waveformData) return;
9408
+ const clip = this._arrangement.getTracks().flatMap((t) => t.clips).find((c) => c.id === clipId);
9409
+ if (!clip || !isLoadingClip3(clip)) return;
9410
+ const rate = waveformData.sample_rate;
9411
+ const offset = clip.offset ?? 0;
9412
+ const seconds = clip.duration ?? Math.max(0, waveformData.duration - offset);
9413
+ const peakData = extractPeaks(
9414
+ waveformData,
9415
+ Math.max(this._renderSpp, waveformData.scale),
9416
+ this.mono,
9417
+ Math.round(offset * rate),
9418
+ Math.round(seconds * rate)
9419
+ );
9420
+ this._previewPeaks = new Map(this._previewPeaks).set(clipId, peakData);
9421
+ this._previewWaveforms.set(clipId, waveformData);
9422
+ this._raiseZoomFloor(waveformData.scale);
9423
+ this._recomputeDuration();
9424
+ }
9425
+ /** The peak sync made a clip's peaks: its zoom floor holds, its preview goes. */
9426
+ _clipPeaksReady(clipId, audioBuffer) {
9427
+ this._raiseZoomFloor(this._peakPipeline.getCachedScale(audioBuffer));
9428
+ if (!this._previewPeaks.has(clipId)) return;
9429
+ const next = new Map(this._previewPeaks);
9430
+ next.delete(clipId);
9431
+ this._previewPeaks = next;
9432
+ }
9433
+ _waitForEntry(trackId) {
9434
+ return new Promise((resolve, reject) => {
9435
+ this._entryWaiters.set(trackId, { resolve, reject });
9436
+ });
9437
+ }
9438
+ /** Settle the wait for a track's entry: entered (`null`), or refused or gone. */
9439
+ _settleEntry(trackId, error) {
9440
+ const waiter = this._entryWaiters.get(trackId);
9441
+ if (!waiter) return;
9442
+ this._entryWaiters.delete(trackId);
9443
+ if (error) waiter.reject(error);
9444
+ else waiter.resolve(trackId);
9445
+ }
9446
+ /**
9447
+ * A dropped file as a track with no element (a File cannot be an attribute):
9448
+ * one loading clip whose source is the file. Resolves with the track id once
9449
+ * it has entered, an undo step like any track an editor method adds.
9450
+ */
9451
+ _addDroppedFile(file) {
9452
+ const trackId = crypto.randomUUID();
9453
+ const name = file.name.replace(/\.\w+$/, "");
9454
+ this._tracks = new Map(this._tracks).set(trackId, {
9455
+ name,
9456
+ src: "",
9457
+ kind: "audio",
9458
+ renderMode: trackDescriptorRenderMode("audio", "waveform"),
9459
+ clips: [
9460
+ {
9461
+ kind: "drop",
9462
+ file,
9463
+ src: "",
9464
+ peaksSrc: "",
9465
+ start: 0,
9466
+ duration: 0,
9467
+ offset: 0,
9468
+ gain: 1,
9469
+ name,
9470
+ fadeIn: 0,
9471
+ fadeOut: 0,
9472
+ fadeType: "linear",
9473
+ midiNotes: null,
9474
+ midiChannel: null,
9475
+ midiProgram: null
9476
+ }
9477
+ ]
9478
+ });
9479
+ const entered = this._waitForEntry(trackId);
9480
+ this._queueEntry(trackId);
9481
+ return entered;
9482
+ }
9483
+ /**
9484
+ * Take a track out for good: no undo step, and no undo or redo brings it
9485
+ * back (a dropped file that could not be loaded was never a declaration).
9486
+ */
9487
+ _discardTrack(trackId) {
9488
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9489
+ this._announcer.forget(trackId, track?.clips.map((c) => c.id) ?? []);
9490
+ this._arrangement.removeTrack(trackId, { undoable: false });
9491
+ this._onTrackRemoved(trackId);
9492
+ }
9493
+ /**
9494
+ * Resolves once the track has loaded (`daw-track-ready`), or when the
9495
+ * editor is disconnected meanwhile (the track is kept and loads after a
9496
+ * reparent); rejects when its audio failed (`daw-track-error`).
9497
+ */
9498
+ _whenTrackLoaded(trackId) {
9499
+ const state9 = this._announcer.stateOf(trackId);
9500
+ if (state9 === "ready") return Promise.resolve();
9501
+ if (state9 === "failed") return Promise.reject(this._announcer.errorOf(trackId));
9502
+ return new Promise((resolve, reject) => {
9503
+ const cleanup = () => {
9504
+ this.removeEventListener("daw-track-ready", onReady);
9505
+ this.removeEventListener("daw-track-error", onError);
9506
+ this._loadWaitEnds.delete(end);
9507
+ };
9508
+ const onReady = (e) => {
9509
+ if (e.detail.trackId !== trackId) return;
9510
+ cleanup();
9511
+ resolve();
9512
+ };
9513
+ const onError = (e) => {
9514
+ const detail = e.detail;
9515
+ if (detail.trackId !== trackId) return;
9516
+ cleanup();
9517
+ reject(detail.error instanceof Error ? detail.error : new Error(String(detail.error)));
9518
+ };
9519
+ const end = () => {
9520
+ cleanup();
9521
+ resolve();
9522
+ };
9523
+ this.addEventListener("daw-track-ready", onReady);
9524
+ this.addEventListener("daw-track-error", onError);
9525
+ this._loadWaitEnds.add(end);
9526
+ });
9527
+ }
9528
+ /**
9529
+ * Load again every failed source the track's clips name (#848). A track
9530
+ * whose audio failed stays in the editor, like a broken `<img>`;
9531
+ * `daw-track-ready` follows when it loads.
9532
+ */
9533
+ retryTrack(trackId) {
9534
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9535
+ if (!track) {
9536
+ console.warn('[dawcore] retryTrack: no track found for id "' + trackId + '"');
9537
+ return;
9538
+ }
9539
+ const sources = this._arrangement.sources.getSnapshot().sources;
9540
+ const failed = new Set(
9541
+ track.clips.filter(isLoadingClip3).map((clip) => clip.src).filter((src) => sources.get(src)?.status === "failed")
9542
+ );
9543
+ for (const src of failed) this._arrangement.retry(src);
9301
9544
  }
9302
9545
  _fetchPeaks(src) {
9303
9546
  const cached = this._peaksCache.get(src);
@@ -9309,7 +9552,13 @@ var DawEditorElement = class extends LitElement14 {
9309
9552
  this._peaksCache.set(src, promise);
9310
9553
  return promise;
9311
9554
  }
9555
+ /**
9556
+ * The timeline's duration, the one writer of `_duration`: the loaded clips,
9557
+ * and the clips still loading whose length is known (a duration, or `.dat`
9558
+ * peaks), so the timeline is as wide as what is drawn (#848).
9559
+ */
9312
9560
  _recomputeDuration() {
9561
+ const sr = this.effectiveSampleRate;
9313
9562
  let maxSample = 0;
9314
9563
  for (const track of this._engineTracks.values()) {
9315
9564
  for (const clip of track.clips) {
@@ -9317,28 +9566,60 @@ var DawEditorElement = class extends LitElement14 {
9317
9566
  if (endSample > maxSample) maxSample = endSample;
9318
9567
  }
9319
9568
  }
9320
- this._duration = maxSample / this.effectiveSampleRate;
9569
+ for (const track of this._arrangement.getTracks()) {
9570
+ for (const clip of track.clips) {
9571
+ if (!isLoadingClip3(clip)) continue;
9572
+ const seconds = this._placeholderSeconds(clip);
9573
+ if (seconds === null) continue;
9574
+ maxSample = Math.max(maxSample, Math.round(((clip.start ?? 0) + seconds) * sr));
9575
+ }
9576
+ }
9577
+ this._duration = maxSample / sr;
9578
+ }
9579
+ /** How long a loading clip is drawn: its duration, else what its `.dat` peaks cover; null when unknown. */
9580
+ _placeholderSeconds(clip) {
9581
+ if (clip.duration != null && clip.duration > 0) return clip.duration;
9582
+ const waveformData = this._previewWaveforms.get(clip.id);
9583
+ if (!waveformData) return null;
9584
+ const seconds = waveformData.duration - (clip.offset ?? 0);
9585
+ return seconds > 0 ? seconds : null;
9321
9586
  }
9322
9587
  // --- Engine ---
9588
+ /**
9589
+ * The engine, built now when the editor is connected with an adapter.
9590
+ * Rejects without an adapter, and on a detached editor (an engine built
9591
+ * there would hold the adapter's graph with nothing to dispose it).
9592
+ */
9323
9593
  _ensureEngine() {
9324
9594
  if (this._engine) return Promise.resolve(this._engine);
9325
- if (this._enginePromise) return this._enginePromise;
9326
- this._enginePromise = this._buildEngine().catch((err) => {
9327
- this._enginePromise = null;
9328
- throw err;
9329
- });
9330
- return this._enginePromise;
9595
+ try {
9596
+ if (!this.isConnected && this._externalAdapter) {
9597
+ throw new Error("[dawcore] <daw-editor> is not connected: no engine is built for it.");
9598
+ }
9599
+ return Promise.resolve(this._buildEngine());
9600
+ } catch (err) {
9601
+ return Promise.reject(err);
9602
+ }
9603
+ }
9604
+ /** Build the engine from the adapter setter or a connect: a failure is reported, not thrown. */
9605
+ _buildEngineReporting() {
9606
+ try {
9607
+ this._buildEngine();
9608
+ } catch (err) {
9609
+ console.warn("[dawcore] Failed to build the engine: " + String(err));
9610
+ this.dispatchEvent(
9611
+ new CustomEvent("daw-error", {
9612
+ bubbles: true,
9613
+ composed: true,
9614
+ detail: { operation: "engine", error: err }
9615
+ })
9616
+ );
9617
+ }
9331
9618
  }
9332
- async _buildEngine() {
9619
+ _buildEngine() {
9333
9620
  if (!this._externalAdapter) {
9334
9621
  throw new Error(noAdapterError());
9335
9622
  }
9336
- if (this._adapterConsumedByDispose) {
9337
- throw new Error(
9338
- "[dawcore] editor.adapter was disposed by a previous disconnect \u2014 set a fresh PlayoutAdapter after reparenting <daw-editor>."
9339
- );
9340
- }
9341
- const { PlaylistEngine } = await import("@waveform-playlist/engine");
9342
9623
  const adapter = this._externalAdapter;
9343
9624
  if (!this._hasTickCallbacks) {
9344
9625
  if (adapter.setTempo) {
@@ -9353,63 +9634,92 @@ var DawEditorElement = class extends LitElement14 {
9353
9634
  this.ppqn = adapter.ppqn;
9354
9635
  const engine = new PlaylistEngine({
9355
9636
  adapter,
9356
- sampleRate: this.effectiveSampleRate,
9637
+ arrangement: this._arrangement,
9638
+ sampleRate: adapter.audioContext.sampleRate,
9357
9639
  samplesPerPixel: this.samplesPerPixel,
9358
9640
  bpm: this._bpm,
9359
9641
  zoomLevels: [256, 512, 1024, 2048, 4096, 8192, this.samplesPerPixel].filter((v, i, a) => a.indexOf(v) === i).sort((a, b) => a - b)
9360
9642
  });
9361
- let lastTracksVersion = -1;
9362
- let lastMixerVersion = -1;
9363
- engine.on("statechange", (engineState) => {
9364
- this._isPlaying = engineState.isPlaying;
9365
- this._duration = engineState.duration;
9366
- this._selectedTrackId = engineState.selectedTrackId;
9367
- const structuralChange = engineState.tracksVersion !== lastTracksVersion;
9368
- const mixerChange = engineState.mixerVersion !== lastMixerVersion;
9369
- if (structuralChange || mixerChange) {
9370
- lastTracksVersion = engineState.tracksVersion;
9371
- lastMixerVersion = engineState.mixerVersion;
9372
- const nextTracks = /* @__PURE__ */ new Map();
9373
- for (const track of engineState.tracks) {
9374
- nextTracks.set(track.id, track);
9375
- }
9376
- this._engineTracks = nextTracks;
9377
- this._deleteSeedMix(nextTracks.keys());
9378
- this._reconcileDescriptorsWithEngineTracks(engineState.tracks);
9379
- }
9380
- if (structuralChange) {
9381
- if (!this._inOrderSync) {
9382
- this._syncDomToEngineOrder(engineState.tracks);
9383
- }
9384
- this._effectsManager?.rewireTrackChains();
9385
- const audioTracks = engineState.tracks.filter((t) => trackKind(t) !== "midi");
9386
- syncPeaksForChangedClips(this, audioTracks);
9387
- }
9388
- if (engineState.bpm !== this._lastAnnotationBpm) {
9389
- this._lastAnnotationBpm = engineState.bpm;
9390
- this._annotations.deriveSecondsCaches();
9391
- }
9392
- });
9643
+ this._lastTracksVersion = -1;
9644
+ this._lastMixerVersion = -1;
9645
+ engine.on("statechange", (engineState) => this._onEngineState(engineState));
9393
9646
  engine.on("pause", () => {
9394
9647
  this._currentTime = engine.getCurrentTime();
9395
9648
  });
9396
- engine.on("stop", () => {
9397
- this._currentTime = engine.getCurrentTime();
9398
- this._stopPlayhead();
9399
- this._activePlayEndTime = null;
9400
- if (!this._inConsumerStop && !this._inSeekTransition && this.isConnected) {
9401
- this.dispatchEvent(new CustomEvent("daw-stop", { bubbles: true, composed: true }));
9402
- }
9403
- });
9649
+ engine.on("stop", () => this._onEngineStop(engine));
9404
9650
  this._engine = engine;
9651
+ this._onEngineState(engine.getState());
9652
+ for (const track of this._engineTracks.values()) {
9653
+ for (const clip of track.clips) this._maybeRegisterSpectrogramClipAudio(track.id, clip);
9654
+ }
9655
+ this._flushTrackEntries();
9405
9656
  return engine;
9406
9657
  }
9658
+ /**
9659
+ * Clips whose audio has just arrived: a `.dat` preview's data goes to the
9660
+ * peak pipeline (no worker run), a spectrogram track gets the audio. The
9661
+ * peak sync then makes their peaks.
9662
+ */
9663
+ _adoptLoadedClips(tracks) {
9664
+ for (const track of tracks) {
9665
+ for (const clip of track.clips) {
9666
+ const waveformData = this._previewWaveforms.get(clip.id);
9667
+ if (waveformData && clip.audioBuffer) {
9668
+ if (waveformData.sample_rate === clip.audioBuffer.sampleRate) {
9669
+ this._peakPipeline.cacheWaveformData(clip.audioBuffer, waveformData);
9670
+ }
9671
+ this._previewWaveforms.delete(clip.id);
9672
+ }
9673
+ if (!this._clipBuffers.has(clip.id))
9674
+ this._maybeRegisterSpectrogramClipAudio(track.id, clip);
9675
+ }
9676
+ }
9677
+ }
9678
+ /** The engine's state changed: follow it (the one writer of `_engineTracks`). */
9679
+ _onEngineState(engineState) {
9680
+ this._isPlaying = engineState.isPlaying;
9681
+ this._selectedTrackId = engineState.selectedTrackId;
9682
+ const structuralChange = engineState.tracksVersion !== this._lastTracksVersion;
9683
+ const mixerChange = engineState.mixerVersion !== this._lastMixerVersion;
9684
+ if (structuralChange || mixerChange) {
9685
+ this._lastTracksVersion = engineState.tracksVersion;
9686
+ this._lastMixerVersion = engineState.mixerVersion;
9687
+ const nextTracks = /* @__PURE__ */ new Map();
9688
+ for (const track of engineState.tracks) {
9689
+ nextTracks.set(track.id, track);
9690
+ }
9691
+ this._engineTracks = nextTracks;
9692
+ this._reconcileDescriptorsWithEngineTracks(engineState.tracks);
9693
+ }
9694
+ if (structuralChange) {
9695
+ this._recomputeDuration();
9696
+ if (!this._inOrderSync) {
9697
+ this._syncDomToEngineOrder(engineState.tracks);
9698
+ }
9699
+ this._effectsManager?.rewireTrackChains();
9700
+ const audioTracks = engineState.tracks.filter((t) => trackKind(t) !== "midi");
9701
+ this._adoptLoadedClips(audioTracks);
9702
+ syncPeaksForChangedClips(this, audioTracks);
9703
+ this._announceLoading();
9704
+ }
9705
+ if (engineState.bpm !== this._lastAnnotationBpm) {
9706
+ this._lastAnnotationBpm = engineState.bpm;
9707
+ this._annotations.deriveSecondsCaches();
9708
+ }
9709
+ }
9710
+ _onEngineStop(engine) {
9711
+ this._currentTime = engine.getCurrentTime();
9712
+ this._stopPlayhead();
9713
+ this._activePlayEndTime = null;
9714
+ if (!this._inConsumerStop && !this._inSeekTransition && this.isConnected) {
9715
+ this.dispatchEvent(new CustomEvent("daw-stop", { bubbles: true, composed: true }));
9716
+ }
9717
+ }
9407
9718
  _disposeEngine() {
9408
9719
  if (this._engine) {
9409
9720
  this._engine.dispose();
9410
9721
  this._engine = null;
9411
9722
  }
9412
- this._enginePromise = null;
9413
9723
  }
9414
9724
  async loadFiles(files) {
9415
9725
  return loadFiles(this, files);
@@ -9440,43 +9750,17 @@ var DawEditorElement = class extends LitElement14 {
9440
9750
  return this._ensureEngine();
9441
9751
  }
9442
9752
  /**
9443
- * Wait for either `readyEvent` or `errorEvent` to fire on this editor for
9444
- * the entity matching `matchesId`. Listeners are wired synchronously, then
9445
- * `setup` is called (typical: appendChild). Resolves with `resolveValue`
9446
- * on ready; rejects with a normalized Error on error. Used by addTrack and
9447
- * addClip to share their Promise-with-listener-cleanup machinery.
9448
- */
9449
- _awaitId(readyEvent, errorEvent, matchesId, resolveValue, setup) {
9450
- return new Promise((resolve, reject) => {
9451
- const onReady = (e) => {
9452
- if (!matchesId(e.detail)) return;
9453
- cleanup();
9454
- resolve(resolveValue);
9455
- };
9456
- const onError = (e) => {
9457
- const detail = e.detail;
9458
- if (!matchesId(e.detail)) return;
9459
- cleanup();
9460
- const err = detail.error;
9461
- reject(err instanceof Error ? err : new Error(String(err)));
9462
- };
9463
- const cleanup = () => {
9464
- this.removeEventListener(readyEvent, onReady);
9465
- this.removeEventListener(errorEvent, onError);
9466
- };
9467
- this.addEventListener(readyEvent, onReady);
9468
- this.addEventListener(errorEvent, onError);
9469
- setup();
9470
- });
9471
- }
9472
- /**
9473
- * Append a `<daw-track>` element built from `config` and resolve once the
9474
- * track finishes loading (or reject on `daw-track-error`). Goes through
9475
- * the same `_loadTrack` pipeline as declarative tracks, so descriptors,
9476
- * peaks, and clip buffers are populated correctly.
9753
+ * Append a `<daw-track>` element built from `config` and resolve with its
9754
+ * track id once the track has entered the arrangement (#848), before its
9755
+ * audio has loaded. To follow loading, add the `daw-track-ready` /
9756
+ * `daw-track-error` listener BEFORE calling: for a track with nothing to
9757
+ * fetch, or whose audio is already loaded, it fires before this resolves.
9758
+ * Without `editor.adapter` it waits for one. Rejects when the track is
9759
+ * refused by the arrangement or removed before it enters.
9477
9760
  */
9478
9761
  addTrack(config = {}) {
9479
9762
  const trackEl = document.createElement("daw-track");
9763
+ this._editorMadeTracks.add(trackEl);
9480
9764
  if (config.name !== void 0) trackEl.setAttribute("name", config.name);
9481
9765
  if (config.volume !== void 0) trackEl.volume = config.volume;
9482
9766
  if (config.pan !== void 0) trackEl.pan = config.pan;
@@ -9496,13 +9780,9 @@ var DawEditorElement = class extends LitElement14 {
9496
9780
  for (const clipConfig of clipConfigs) {
9497
9781
  trackEl.appendChild(this._buildClipElement(clipConfig));
9498
9782
  }
9499
- return this._awaitId(
9500
- "daw-track-ready",
9501
- "daw-track-error",
9502
- (d) => d.trackId === trackEl.trackId,
9503
- trackEl,
9504
- () => this.appendChild(trackEl)
9505
- );
9783
+ const entered = this._waitForEntry(trackEl.trackId);
9784
+ this.appendChild(trackEl);
9785
+ return entered;
9506
9786
  }
9507
9787
  /**
9508
9788
  * Remove a track by id. Equivalent to `trackElement.remove()` —
@@ -9513,7 +9793,8 @@ var DawEditorElement = class extends LitElement14 {
9513
9793
  const trackEl = this._trackElements.get(trackId);
9514
9794
  if (trackEl) {
9515
9795
  trackEl.remove();
9516
- } else if (this._engineTracks.has(trackId)) {
9796
+ if (!this.isConnected) this._onTrackRemoved(trackId);
9797
+ } else if (this._tracks.has(trackId) || this._isEntered(trackId)) {
9517
9798
  this._onTrackRemoved(trackId);
9518
9799
  } else {
9519
9800
  console.warn('[dawcore] removeTrack: no track found for id "' + trackId + '"');
@@ -9540,8 +9821,8 @@ var DawEditorElement = class extends LitElement14 {
9540
9821
  const anchor = els[clamped];
9541
9822
  if (clamped > from) anchor.after(el);
9542
9823
  else anchor.before(el);
9543
- } else if (this._engineTracks.has(trackId)) {
9544
- this._engine.reorderTrack(trackId, toIndex);
9824
+ } else if (this._isEntered(trackId)) {
9825
+ this._arrangement.reorderTrack(trackId, toIndex);
9545
9826
  this.requestUpdate();
9546
9827
  } else {
9547
9828
  console.warn('[dawcore] reorderTrack: no track found for id "' + trackId + '"');
@@ -9549,8 +9830,8 @@ var DawEditorElement = class extends LitElement14 {
9549
9830
  }
9550
9831
  /**
9551
9832
  * Update reflected attributes on a track. The mixer fields go to their
9552
- * owner as one undo step (#843): the engine, or while the track is loading
9553
- * the values it will enter with (not a step). For DOM-element tracks the
9833
+ * owner, the arrangement, as one undo step (#843; also while the track
9834
+ * loads, #848). For DOM-element tracks the
9554
9835
  * changes are also written to the `<daw-track>` element; for tracks
9555
9836
  * without a DOM element (file drops) the descriptor is updated in place.
9556
9837
  */
@@ -9599,8 +9880,10 @@ var DawEditorElement = class extends LitElement14 {
9599
9880
  }
9600
9881
  /**
9601
9882
  * Append a clip to an existing track. Builds a `<daw-clip>` from `config`
9602
- * and appends it to the track's DOM element when one exists; resolves with
9603
- * the new clip's id once the audio decode + peak generation finish.
9883
+ * and appends it to the track's DOM element; resolves with the new clip's
9884
+ * id once its audio has loaded (`daw-clip-ready`, before its peaks are
9885
+ * drawn); rejects when it fails to load, is refused, or leaves the
9886
+ * arrangement before it loads (a removal, an Undo).
9604
9887
  */
9605
9888
  addClip(trackId, config) {
9606
9889
  if (!config.src) {
@@ -9618,14 +9901,54 @@ var DawEditorElement = class extends LitElement14 {
9618
9901
  )
9619
9902
  );
9620
9903
  }
9904
+ if (!this._isEntered(trackId) && !this._entryQueue.includes(trackId)) {
9905
+ return Promise.reject(
9906
+ new Error(
9907
+ 'addClip: track "' + trackId + '" is not in the editor (an Undo took it out, or the arrangement refused it)'
9908
+ )
9909
+ );
9910
+ }
9621
9911
  const clipEl = this._buildClipElement(config);
9622
- return this._awaitId(
9623
- "daw-clip-ready",
9624
- "daw-clip-error",
9625
- (d) => d.clipId === clipEl.clipId,
9626
- clipEl.clipId,
9627
- () => trackEl.appendChild(clipEl)
9628
- );
9912
+ const clipId = clipEl.clipId;
9913
+ return new Promise((resolve, reject) => {
9914
+ let seen = false;
9915
+ const onReady = (e) => {
9916
+ if (e.detail.clipId !== clipId) return;
9917
+ cleanup();
9918
+ resolve(clipId);
9919
+ };
9920
+ const onError = (e) => {
9921
+ const detail = e.detail;
9922
+ if (detail.clipId !== clipId) return;
9923
+ cleanup();
9924
+ reject(detail.error instanceof Error ? detail.error : new Error(String(detail.error)));
9925
+ };
9926
+ const stopWatching = this._arrangement.subscribe(() => {
9927
+ const present = this._arrangement.getTracks().some((t) => t.clips.some((c) => c.id === clipId));
9928
+ if (present) {
9929
+ seen = true;
9930
+ } else if (seen) {
9931
+ cleanup();
9932
+ reject(new Error('clip "' + clipId + '" was removed before its audio loaded'));
9933
+ }
9934
+ });
9935
+ const cleanup = () => {
9936
+ this.removeEventListener("daw-clip-ready", onReady);
9937
+ this.removeEventListener("daw-clip-error", onError);
9938
+ stopWatching();
9939
+ this._awaitedClips.delete(clipId);
9940
+ };
9941
+ this.addEventListener("daw-clip-ready", onReady);
9942
+ this.addEventListener("daw-clip-error", onError);
9943
+ this._awaitedClips.set(clipId, {
9944
+ trackId,
9945
+ reject: (error) => {
9946
+ cleanup();
9947
+ reject(error);
9948
+ }
9949
+ });
9950
+ trackEl.appendChild(clipEl);
9951
+ });
9629
9952
  }
9630
9953
  /**
9631
9954
  * Remove a clip by id. Removes the matching `<daw-clip>` DOM element when
@@ -9643,7 +9966,7 @@ var DawEditorElement = class extends LitElement14 {
9643
9966
  return;
9644
9967
  }
9645
9968
  }
9646
- if (this._engineTracks.has(trackId)) {
9969
+ if (this._isEntered(trackId)) {
9647
9970
  this._removeClipFromTrack(trackId, clipId);
9648
9971
  return;
9649
9972
  }
@@ -9704,10 +10027,6 @@ var DawEditorElement = class extends LitElement14 {
9704
10027
  ...partial.gain !== void 0 && { gain: partial.gain },
9705
10028
  ...partial.name !== void 0 && { name: partial.name }
9706
10029
  };
9707
- const updatedClips = [...t.clips];
9708
- updatedClips[idx] = updatedClip;
9709
- const updatedTrack = { ...t, clips: updatedClips };
9710
- this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);
9711
10030
  const desc = this._tracks.get(trackId);
9712
10031
  if (desc?.clips.some((c) => c.clipId === clipId)) {
9713
10032
  this._tracks = new Map(this._tracks).set(trackId, {
@@ -9724,7 +10043,7 @@ var DawEditorElement = class extends LitElement14 {
9724
10043
  )
9725
10044
  });
9726
10045
  }
9727
- this._commitTrackChange(trackId, updatedTrack);
10046
+ this._replaceClip(trackId, clipId, updatedClip);
9728
10047
  }
9729
10048
  _buildClipElement(config) {
9730
10049
  const clipEl = document.createElement("daw-clip");
@@ -9855,16 +10174,49 @@ var DawEditorElement = class extends LitElement14 {
9855
10174
  })
9856
10175
  );
9857
10176
  }
9858
- /** Undo the last structural edit. */
10177
+ /**
10178
+ * A clip or track drag is in progress: undo and redo do nothing until it
10179
+ * ends (#848). A clip counts once its pointer has moved past the drag
10180
+ * threshold; annotation drags do not count (annotations are not in the
10181
+ * undo history).
10182
+ */
10183
+ get _dragInProgress() {
10184
+ return this._clipPointer.isDragging || this._trackReorderDrag.isActive;
10185
+ }
10186
+ /**
10187
+ * Cancel every drag in progress, as a `pointercancel` would. Returns whether
10188
+ * one was. A clip or annotation press that has not moved is not a drag and
10189
+ * is left alone, unless `includePresses` (the editor's disconnect, which
10190
+ * ends every pointer interaction).
10191
+ */
10192
+ _cancelDrags(includePresses = false) {
10193
+ let cancelled = false;
10194
+ if (includePresses || this._clipPointer.isDragging) {
10195
+ cancelled = this._pointer.cancelClipDrag() || cancelled;
10196
+ }
10197
+ if (this._trackReorderDrag.isActive) {
10198
+ this._trackReorderDrag.cancel();
10199
+ cancelled = true;
10200
+ }
10201
+ const annotation = this._annotationDrag;
10202
+ if (includePresses ? annotation.isActive : annotation.isDragging) {
10203
+ annotation.cancel();
10204
+ cancelled = true;
10205
+ }
10206
+ return cancelled;
10207
+ }
10208
+ /** Undo the last edit. Does nothing while a drag is in progress. */
9859
10209
  undo() {
10210
+ if (this._dragInProgress) return;
9860
10211
  if (!this._engine) {
9861
10212
  console.warn("[dawcore] undo: engine not ready, call ignored");
9862
10213
  return;
9863
10214
  }
9864
10215
  this._engine.undo();
9865
10216
  }
9866
- /** Redo the last undone edit. */
10217
+ /** Redo the last undone edit. Does nothing while a drag is in progress. */
9867
10218
  redo() {
10219
+ if (this._dragInProgress) return;
9868
10220
  if (!this._engine) {
9869
10221
  console.warn("[dawcore] redo: engine not ready, call ignored");
9870
10222
  return;
@@ -10100,11 +10452,12 @@ var DawEditorElement = class extends LitElement14 {
10100
10452
  (el) => el.trackId
10101
10453
  );
10102
10454
  const engineIds = engine.getState().tracks.map((t) => t.id);
10103
- const target = [...engineIds].sort((a, b) => {
10104
- const ai = domOrder.indexOf(a);
10105
- const bi = domOrder.indexOf(b);
10106
- if (ai === -1 || bi === -1) return 0;
10107
- return ai - bi;
10455
+ const inDom = new Set(domOrder);
10456
+ const slots = engineIds.flatMap((id, i) => inDom.has(id) ? [i] : []);
10457
+ const domSorted = domOrder.filter((id) => engineIds.includes(id));
10458
+ const target = [...engineIds];
10459
+ slots.forEach((slot, k) => {
10460
+ target[slot] = domSorted[k];
10108
10461
  });
10109
10462
  if (target.every((id, i) => id === engineIds[i])) return;
10110
10463
  this._inOrderSync = true;
@@ -10147,18 +10500,67 @@ var DawEditorElement = class extends LitElement14 {
10147
10500
  slots.splice(i, 0, desired[i]);
10148
10501
  }
10149
10502
  }
10503
+ /**
10504
+ * The rows, in the arrangement's order (#848): each track's loaded clips
10505
+ * (the engine's projection, with the current mix) and the clips still loading.
10506
+ */
10150
10507
  _getOrderedTracks() {
10151
- const domOrder = [...this.querySelectorAll("daw-track")].map(
10152
- (el) => el.trackId
10153
- );
10154
- return [...this._engineTracks.entries()].sort((a, b) => {
10155
- const ai = domOrder.indexOf(a[0]);
10156
- const bi = domOrder.indexOf(b[0]);
10157
- if (ai === -1 && bi === -1) return 0;
10158
- if (ai === -1) return 1;
10159
- if (bi === -1) return -1;
10160
- return ai - bi;
10161
- });
10508
+ const rows = [];
10509
+ for (const track of this._arrangement.getTracks()) {
10510
+ const loaded = this._engineTracks.get(track.id);
10511
+ if (!loaded) continue;
10512
+ rows.push([track.id, loaded, track.clips.filter(isLoadingClip3)]);
10513
+ }
10514
+ return rows;
10515
+ }
10516
+ /**
10517
+ * A clip still loading: a placeholder box where its length is known, with
10518
+ * its `.dat` peaks when they came, drawn failed when its source failed. Its
10519
+ * header carries no clip id, so it cannot be dragged.
10520
+ */
10521
+ _renderPlaceholder(clip, row) {
10522
+ const seconds = this._placeholderSeconds(clip);
10523
+ if (seconds === null) return "";
10524
+ const sr = this.effectiveSampleRate;
10525
+ const spp = this._renderSpp;
10526
+ const startSec = clip.start ?? 0;
10527
+ let left;
10528
+ let width;
10529
+ if (this.scaleMode === "beats") {
10530
+ left = Math.round(this._secondsToTicks(startSec) / this.ticksPerPixel);
10531
+ width = Math.round(this._secondsToTicks(startSec + seconds) / this.ticksPerPixel) - left;
10532
+ } else {
10533
+ const startSample = Math.round(startSec * sr);
10534
+ left = Math.floor(startSample / spp);
10535
+ width = clipPixelWidth(startSample, Math.round(seconds * sr), spp);
10536
+ }
10537
+ const failed = this._arrangement.sources.getSnapshot().sources.get(clip.src)?.status === "failed";
10538
+ const peakData = this._previewPeaks.get(clip.id);
10539
+ const hdrH = this.clipHeaders ? this.clipHeaderHeight : 0;
10540
+ const chH = this.waveHeight;
10541
+ return html12`<div
10542
+ class="clip-container placeholder ${failed ? "failed" : ""}"
10543
+ style="left:${left}px;top:0;width:${width}px;height:${row.trackHeight}px;"
10544
+ data-clip-id=${clip.id}
10545
+ >
10546
+ ${hdrH > 0 ? html12`<div class="clip-header">
10547
+ <span>${clip.name || row.descriptor?.name || ""}</span>
10548
+ </div>` : ""}
10549
+ ${(peakData?.data ?? []).map(
10550
+ (chPeaks, chIdx) => html12`<daw-waveform
10551
+ style="position:absolute;left:0;top:${hdrH + chIdx * chH}px;"
10552
+ .peaks=${chPeaks}
10553
+ .length=${peakData?.length ?? width}
10554
+ .waveHeight=${chH}
10555
+ .barWidth=${this.barWidth}
10556
+ .barGap=${this.barGap}
10557
+ .roundedBars=${this.roundedBars}
10558
+ .visibleStart=${this._viewport.visibleStart}
10559
+ .visibleEnd=${this._viewport.visibleEnd}
10560
+ .originX=${left}
10561
+ ></daw-waveform>`
10562
+ )}
10563
+ </div>`;
10162
10564
  }
10163
10565
  // --- Render ---
10164
10566
  render() {
@@ -10175,14 +10577,15 @@ var DawEditorElement = class extends LitElement14 {
10175
10577
  selStartPx = this._selectionStartTime * sr / spp;
10176
10578
  selEndPx = this._selectionEndTime * sr / spp;
10177
10579
  }
10178
- const orderedTracks = this._getOrderedTracks().map(([trackId, track]) => {
10580
+ const orderedTracks = this._getOrderedTracks().map(([trackId, track, loading]) => {
10179
10581
  const descriptor = this._tracks.get(trackId);
10180
- const firstPeaks = track.clips.map((c) => this._peaksData.get(c.id)).find((p) => p && p.data.length > 0);
10582
+ const firstPeaks = [...track.clips, ...loading].map((c) => this._peaksData.get(c.id) ?? this._previewPeaks.get(c.id)).find((p) => p && p.data.length > 0);
10181
10583
  const recSession = this._recordingController.getSession(trackId);
10182
10584
  const numChannels = firstPeaks ? firstPeaks.data.length : recSession ? recSession.channelCount : 1;
10183
10585
  return {
10184
10586
  trackId,
10185
10587
  track,
10588
+ loading,
10186
10589
  descriptor,
10187
10590
  numChannels,
10188
10591
  trackHeight: this.waveHeight * numChannels + (this.clipHeaders ? this.clipHeaderHeight : 0)
@@ -10280,7 +10683,7 @@ var DawEditorElement = class extends LitElement14 {
10280
10683
  data-track-id=${t.trackId}
10281
10684
  >
10282
10685
  ${t.track.clips.map((clip) => {
10283
- const peakData = this._peaksData.get(clip.id);
10686
+ const peakData = this._peaksData.get(clip.id) ?? this._previewPeaks.get(clip.id);
10284
10687
  let clipLeft;
10285
10688
  let width;
10286
10689
  if (this.scaleMode === "beats") {
@@ -10409,6 +10812,7 @@ var DawEditorElement = class extends LitElement14 {
10409
10812
  ></div>` : ""}
10410
10813
  </div>`;
10411
10814
  })}
10815
+ ${t.loading.map((clip) => this._renderPlaceholder(clip, t))}
10412
10816
  ${this._renderRecordingPreview(t.trackId, channelHeight)}
10413
10817
  </div>
10414
10818
  `;
@@ -10649,10 +11053,10 @@ __decorateClass([
10649
11053
  ], DawEditorElement.prototype, "ticksToSeconds", 2);
10650
11054
  __decorateClass([
10651
11055
  state4()
10652
- ], DawEditorElement.prototype, "_tracks", 2);
11056
+ ], DawEditorElement.prototype, "_previewPeaks", 2);
10653
11057
  __decorateClass([
10654
11058
  state4()
10655
- ], DawEditorElement.prototype, "_seedMix", 2);
11059
+ ], DawEditorElement.prototype, "_tracks", 2);
10656
11060
  __decorateClass([
10657
11061
  state4()
10658
11062
  ], DawEditorElement.prototype, "_engineTracks", 2);