@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.js CHANGED
@@ -82,7 +82,7 @@ __export(index_exports, {
82
82
  module.exports = __toCommonJS(index_exports);
83
83
 
84
84
  // <define:__INSTALL_SPECS__>
85
- var define_INSTALL_SPECS_default = { "@dawcore/faust": "@dawcore/faust@^0.0.2-next.1", "@dawcore/midi": "@dawcore/midi@^0.0.6-next.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" };
85
+ var define_INSTALL_SPECS_default = { "@dawcore/faust": "@dawcore/faust@^0.0.2-next.1", "@dawcore/midi": "@dawcore/midi@^0.0.6-next.4", "@dawcore/transport": "@dawcore/transport@^0.0.16-next.4", "@dawcore/wam": "@dawcore/wam@^0.0.5-next.0", "@waveform-playlist/core": "@waveform-playlist/core@^13.0.0-next.4", "@waveform-playlist/engine": "@waveform-playlist/engine@^14.0.0-next.3", "@waveform-playlist/worklets": "@waveform-playlist/worklets@^13.0.1-next.0", "@waveform-playlist/playout": "@waveform-playlist/playout@^13.0.0-next.4" };
86
86
 
87
87
  // src/elements/daw-annotation.ts
88
88
  var import_lit = require("lit");
@@ -306,6 +306,7 @@ var DawAnnotationTrackElement = class extends import_lit2.LitElement {
306
306
  this._onKeyDownCapture = (e) => {
307
307
  if (!this.keyboardControls) return;
308
308
  if (e.repeat) return;
309
+ if (e.key === "Escape" && e.defaultPrevented) return;
309
310
  if ((0, import_core.keyBelongsToFocusedControl)(e)) return;
310
311
  const match = this._shortcutEntries().find((entry) => (0, import_core.matchesKeyBinding)(e, entry.binding));
311
312
  if (!match) return;
@@ -2280,7 +2281,7 @@ DawStopButtonElement = __decorateClass([
2280
2281
  // src/elements/daw-editor.ts
2281
2282
  var import_lit19 = require("lit");
2282
2283
  var import_decorators16 = require("lit/decorators.js");
2283
- var import_core17 = require("@waveform-playlist/core");
2284
+ var import_core19 = require("@waveform-playlist/core");
2284
2285
 
2285
2286
  // src/workers/peaksWorker.ts
2286
2287
  var import_waveform_data = __toESM(require("waveform-data"));
@@ -3024,6 +3025,9 @@ DawRulerElement = __decorateClass([
3024
3025
  (0, import_decorators13.customElement)("daw-ruler")
3025
3026
  ], DawRulerElement);
3026
3027
 
3028
+ // src/elements/daw-editor.ts
3029
+ var import_engine = require("@waveform-playlist/engine");
3030
+
3027
3031
  // src/utils/track-mix.ts
3028
3032
  var DEFAULT_TRACK_MIX = Object.freeze({
3029
3033
  volume: 1,
@@ -3046,9 +3050,6 @@ function pickMix(mix, names) {
3046
3050
  ...named.has("soloed") && { soloed: mix.soloed }
3047
3051
  };
3048
3052
  }
3049
- function withMix(track, mix) {
3050
- return { ...track, ...mixOfElement(mix) };
3051
- }
3052
3053
  function clampNumber(value, min, max) {
3053
3054
  return Math.max(min, Math.min(max, Number(value)));
3054
3055
  }
@@ -3633,6 +3634,18 @@ var clipStyles = import_lit17.css`
3633
3634
  position: absolute;
3634
3635
  overflow: hidden;
3635
3636
  }
3637
+ /* A clip whose audio is still loading (#848). */
3638
+ .clip-container.placeholder {
3639
+ opacity: var(--daw-placeholder-clip-opacity, 0.5);
3640
+ background: color-mix(in srgb, var(--daw-wave-color, #c49a6c) 35%, transparent);
3641
+ }
3642
+ /* A clip whose audio failed to load: it stays, like a broken <img>. */
3643
+ .clip-container.placeholder.failed {
3644
+ opacity: 1;
3645
+ background: color-mix(in srgb, var(--daw-clip-failed-color, #e06c75) 15%, transparent);
3646
+ outline: 2px dashed var(--daw-clip-failed-color, #e06c75);
3647
+ outline-offset: -2px;
3648
+ }
3636
3649
  .clip-header {
3637
3650
  position: relative;
3638
3651
  z-index: 1;
@@ -3937,7 +3950,6 @@ var RecordingController = class {
3937
3950
  const bits = options.bits ?? 16;
3938
3951
  try {
3939
3952
  const rawCtx = this._host.audioContext;
3940
- this._host.resolveAudioContextSampleRate(rawCtx.sampleRate);
3941
3953
  if (rawCtx.state === "suspended") {
3942
3954
  await rawCtx.resume();
3943
3955
  }
@@ -4673,6 +4685,8 @@ var PointerHandler = class {
4673
4685
  // still holds; zeroing only the host would desync the two).
4674
4686
  this._preDragSelectionStart = 0;
4675
4687
  this._preDragSelectionEnd = 0;
4688
+ /** Cancels the armed clip drag; set while one is armed (#848). */
4689
+ this._cancelArmedClipDrag = null;
4676
4690
  this.onPointerDown = (e) => {
4677
4691
  const clipHandler = this._host._clipHandler;
4678
4692
  if (clipHandler) {
@@ -4687,12 +4701,13 @@ var PointerHandler = class {
4687
4701
  console.warn("[dawcore] setPointerCapture failed: " + String(err));
4688
4702
  }
4689
4703
  const onMove = (me) => clipHandler.onPointerMove(me);
4690
- const detach = (pe) => {
4704
+ const detach = (pointerId) => {
4705
+ this._cancelArmedClipDrag = null;
4691
4706
  this._timeline?.removeEventListener("pointermove", onMove);
4692
4707
  this._timeline?.removeEventListener("pointerup", onUp);
4693
4708
  this._timeline?.removeEventListener("pointercancel", onCancel);
4694
4709
  try {
4695
- this._timeline?.releasePointerCapture(pe.pointerId);
4710
+ this._timeline?.releasePointerCapture(pointerId);
4696
4711
  } catch (err) {
4697
4712
  console.warn(
4698
4713
  "[dawcore] releasePointerCapture failed (may already be released): " + String(err)
@@ -4702,13 +4717,19 @@ var PointerHandler = class {
4702
4717
  };
4703
4718
  const onUp = (ue) => {
4704
4719
  clipHandler.onPointerUp(ue);
4705
- detach(ue);
4720
+ detach(ue.pointerId);
4706
4721
  };
4707
4722
  const downPointerId = e.pointerId;
4708
4723
  const onCancel = (ce) => {
4709
4724
  if (ce.pointerId !== downPointerId) return;
4710
4725
  clipHandler.onPointerCancel(ce);
4711
- detach(ce);
4726
+ detach(ce.pointerId);
4727
+ };
4728
+ this._cancelArmedClipDrag = () => {
4729
+ clipHandler.onPointerCancel(
4730
+ new PointerEvent("pointercancel", { pointerId: downPointerId })
4731
+ );
4732
+ detach(downPointerId);
4712
4733
  };
4713
4734
  this._timeline.addEventListener("pointermove", onMove);
4714
4735
  this._timeline.addEventListener("pointerup", onUp);
@@ -4821,6 +4842,17 @@ var PointerHandler = class {
4821
4842
  }
4822
4843
  return time * h.effectiveSampleRate / h.samplesPerPixel;
4823
4844
  }
4845
+ /**
4846
+ * Cancel an armed clip move or trim as a `pointercancel` would: the clip
4847
+ * handler reverts it and the timeline's listeners and pointer capture are
4848
+ * released. Returns whether a clip drag was armed.
4849
+ */
4850
+ cancelClipDrag() {
4851
+ const cancel = this._cancelArmedClipDrag;
4852
+ if (!cancel) return false;
4853
+ cancel();
4854
+ return true;
4855
+ }
4824
4856
  /** Detach the drag listeners and release capture — shared by the up and
4825
4857
  * cancel terminals so a new listener added to onPointerDown can't be
4826
4858
  * missed on one of them. */
@@ -4975,6 +5007,11 @@ var ClipPointerHandler = class {
4975
5007
  get isActive() {
4976
5008
  return this._mode !== null;
4977
5009
  }
5010
+ /** True once the pointer of the current press has moved past the drag
5011
+ * threshold: a press that has not moved is not a drag (#848). */
5012
+ get isDragging() {
5013
+ return this._isDragging;
5014
+ }
4978
5015
  /**
4979
5016
  * Attempts to handle a pointerdown event on the given target element.
4980
5017
  * Returns true if the target is a recognized clip interaction element.
@@ -5009,21 +5046,32 @@ var ClipPointerHandler = class {
5009
5046
  this._startPx = e.clientX;
5010
5047
  this._isDragging = false;
5011
5048
  this._cumulativeDeltaSamples = 0;
5049
+ }
5050
+ /**
5051
+ * The press has become a drag (the pointer passed the threshold): take the
5052
+ * clip's bounds and open the transaction now, not at the press. An undo
5053
+ * made during the press (it is not a drag, so undo works) then has no
5054
+ * transaction to abort, and the drag that follows starts from the clip as
5055
+ * the undo left it, one undo step (#848, review of #915). Returns false
5056
+ * when the clip is gone (the undo removed it): the press is dropped.
5057
+ */
5058
+ _startDrag() {
5012
5059
  const engine = this._host.engine;
5060
+ const trackId = this._trackId;
5061
+ const clipId = this._clipId;
5013
5062
  if (engine) {
5014
5063
  const bounds = engine.getClipBounds(trackId, clipId);
5015
- if (bounds) {
5016
- this._originalStartSample = bounds.startSample;
5017
- }
5018
- }
5019
- if (engine) {
5064
+ if (!bounds) return false;
5065
+ this._originalStartSample = bounds.startSample;
5066
+ this._originalOffsetSamples = bounds.offsetSamples;
5067
+ this._originalDurationSamples = bounds.durationSamples;
5020
5068
  engine.beginTransaction();
5021
5069
  } else {
5022
5070
  console.warn(
5023
- "[dawcore] beginDrag: engine unavailable, drag mutations will not be grouped for undo"
5071
+ "[dawcore] drag start: engine unavailable, drag mutations will not be grouped for undo"
5024
5072
  );
5025
5073
  }
5026
- if (mode === "trim-left" || mode === "trim-right") {
5074
+ if (this._mode === "trim-left" || this._mode === "trim-right") {
5027
5075
  const container = this._host.shadowRoot?.querySelector(
5028
5076
  `.clip-container[data-clip-id="${clipId}"]`
5029
5077
  );
@@ -5034,21 +5082,18 @@ var ClipPointerHandler = class {
5034
5082
  } else {
5035
5083
  console.warn("[dawcore] clip container not found for trim visual feedback: " + clipId);
5036
5084
  }
5037
- const engine2 = this._host.engine;
5038
- if (engine2) {
5039
- const bounds = engine2.getClipBounds(trackId, clipId);
5040
- if (bounds) {
5041
- this._originalOffsetSamples = bounds.offsetSamples;
5042
- this._originalDurationSamples = bounds.durationSamples;
5043
- }
5044
- }
5045
5085
  }
5086
+ return true;
5046
5087
  }
5047
5088
  /** Processes pointermove events during an active drag. */
5048
5089
  onPointerMove(e) {
5049
5090
  if (this._mode === null) return;
5050
5091
  const totalDeltaPx = e.clientX - this._startPx;
5051
5092
  if (!this._isDragging && Math.abs(totalDeltaPx) > DRAG_THRESHOLD) {
5093
+ if (!this._startDrag()) {
5094
+ this._reset();
5095
+ return;
5096
+ }
5052
5097
  this._isDragging = true;
5053
5098
  if (this._boundaryEl) {
5054
5099
  this._boundaryEl.classList.add("dragging");
@@ -5170,10 +5215,12 @@ var ClipPointerHandler = class {
5170
5215
  }
5171
5216
  }
5172
5217
  } finally {
5173
- if (this._isDragging && this._cumulativeDeltaSamples !== 0) {
5174
- this._host.engine?.commitTransaction();
5175
- } else {
5176
- this._host.engine?.abortTransaction();
5218
+ if (this._isDragging) {
5219
+ if (this._cumulativeDeltaSamples !== 0) {
5220
+ this._host.engine?.commitTransaction();
5221
+ } else {
5222
+ this._host.engine?.abortTransaction();
5223
+ }
5177
5224
  }
5178
5225
  this._reset();
5179
5226
  }
@@ -5191,7 +5238,7 @@ var ClipPointerHandler = class {
5191
5238
  try {
5192
5239
  this._restoreTrimVisual();
5193
5240
  } finally {
5194
- this._host.engine?.abortTransaction();
5241
+ if (this._isDragging) this._host.engine?.abortTransaction();
5195
5242
  this._reset();
5196
5243
  }
5197
5244
  }
@@ -5363,16 +5410,35 @@ var AnnotationDragHandler = class {
5363
5410
  this._onPointerCancel = (e) => {
5364
5411
  const drag = this._drag;
5365
5412
  if (!drag || e.pointerId !== drag.pointerId) return;
5366
- const elements = drag.track.annotationElements;
5367
- if (drag.mode === "ticks") {
5368
- applyTickBoundaryResults(elements, drag.snapshot, (t) => this._host._ticksToSeconds(t));
5369
- } else {
5370
- applyBoundaryResults(elements, drag.snapshot);
5371
- }
5372
- this._teardown();
5413
+ this._restoreAndTeardown(drag);
5373
5414
  };
5374
5415
  this._host = host;
5375
5416
  }
5417
+ /** True from pointerdown on an annotation until the drag ends or is cancelled. */
5418
+ get isActive() {
5419
+ return this._drag !== null;
5420
+ }
5421
+ /** True once the pointer has moved at least `DRAG_THRESHOLD` px (an edge
5422
+ * drag, or a box press that moved): a press that has not moved (a click on
5423
+ * the box) is not a drag (#848). */
5424
+ get isDragging() {
5425
+ return this._drag?.moved ?? false;
5426
+ }
5427
+ /** Cancel the drag in progress (Escape, editor disconnect): the boundaries
5428
+ * go back to where they were when it began (#848). */
5429
+ cancel() {
5430
+ if (this._drag) this._restoreAndTeardown(this._drag);
5431
+ }
5432
+ /** Restore the drag-start snapshot — a cancelled drag must not commit. */
5433
+ _restoreAndTeardown(drag) {
5434
+ const elements = drag.track.annotationElements;
5435
+ if (drag.mode === "ticks") {
5436
+ applyTickBoundaryResults(elements, drag.snapshot, (t) => this._host._ticksToSeconds(t));
5437
+ } else {
5438
+ applyBoundaryResults(elements, drag.snapshot);
5439
+ }
5440
+ this._teardown();
5441
+ }
5376
5442
  _teardown() {
5377
5443
  const drag = this._drag;
5378
5444
  if (!drag) return;
@@ -5520,6 +5586,10 @@ var TrackReorderHandler = class _TrackReorderHandler {
5520
5586
  static _reducedMotion() {
5521
5587
  return typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
5522
5588
  }
5589
+ /** True from the grab until the drag ends or is cancelled. */
5590
+ get isActive() {
5591
+ return this._trackId !== null;
5592
+ }
5523
5593
  /** Abort any in-progress drag and reset state. Called by the editor on
5524
5594
  * disconnect — without this, a drag interrupted by editor removal (with no
5525
5595
  * pointercancel delivered) would leave the handler wedged and silently
@@ -5633,23 +5703,25 @@ async function loadFiles(host, files) {
5633
5703
  }
5634
5704
  };
5635
5705
  for (const file of fileArray) {
5706
+ if (!host.isConnected) {
5707
+ dispatchLoadError(file, new Error("<daw-editor> was disconnected"));
5708
+ continue;
5709
+ }
5636
5710
  if (file.type && !file.type.startsWith("audio/")) {
5637
5711
  const error = new Error("Non-audio MIME type: " + file.type);
5638
5712
  console.warn("[dawcore] Skipping non-audio file: " + file.name + " (" + file.type + ")");
5639
5713
  dispatchLoadError(file, error);
5640
5714
  continue;
5641
5715
  }
5642
- const blobUrl = URL.createObjectURL(file);
5643
- const name = file.name.replace(/\.\w+$/, "");
5716
+ let trackId = null;
5644
5717
  try {
5645
- const trackEl = await host.addTrack({ name, clips: [{ src: blobUrl, name }] });
5646
- loaded.push(trackEl.trackId);
5718
+ trackId = await host._addDroppedFile(file);
5719
+ await host._whenTrackLoaded(trackId);
5720
+ loaded.push(trackId);
5647
5721
  } catch (err) {
5648
5722
  console.warn("[dawcore] Failed to load file: " + file.name + " \u2014 " + String(err));
5723
+ if (trackId !== null) host._discardTrack(trackId);
5649
5724
  dispatchLoadError(file, err);
5650
- } finally {
5651
- URL.revokeObjectURL(blobUrl);
5652
- host._audioCache.delete(blobUrl);
5653
5725
  }
5654
5726
  }
5655
5727
  return { loaded, failed };
@@ -5737,7 +5809,7 @@ async function loadMidiImpl(host, source, options = {}) {
5737
5809
  throw first instanceof Error ? first : new Error(stringifyReason(first));
5738
5810
  }
5739
5811
  return {
5740
- trackIds: succeeded.map((el) => el.trackId),
5812
+ trackIds: succeeded,
5741
5813
  bpm: parsed.bpm,
5742
5814
  timeSignature: parsed.timeSignature,
5743
5815
  duration: parsed.duration,
@@ -5785,8 +5857,7 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
5785
5857
  host._clipBuffers = new Map(host._clipBuffers).set(clip.id, trimmedBuf);
5786
5858
  host._clipOffsets.set(clip.id, { offsetSamples: 0, durationSamples: durSamples });
5787
5859
  host._peakPipeline.generatePeaks(trimmedBuf, host.renderSamplesPerPixel, host.mono).then((pd) => {
5788
- const t = host._engineTracks.get(trackId);
5789
- if (!t) {
5860
+ if (!host._arrangement.getTracks().some((t) => t.id === trackId)) {
5790
5861
  const next = new Map(host._clipBuffers);
5791
5862
  next.delete(clip.id);
5792
5863
  host._clipBuffers = next;
@@ -5795,13 +5866,15 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
5795
5866
  }
5796
5867
  host._peaksData = new Map(host._peaksData).set(clip.id, pd);
5797
5868
  host._raiseZoomFloor(host._peakPipeline.getCachedScale(trimmedBuf));
5798
- host._engineTracks = new Map(host._engineTracks).set(trackId, {
5799
- ...t,
5800
- // Punch-in replace (#579): the recorded clip owns [startSample,
5801
- // startSample + durSamples) — carve overlapped content out of the
5802
- // existing clips before inserting (parity with the React provider).
5803
- clips: [...(0, import_core12.carveClipRange)(t.clips, startSample, startSample + durSamples), clip]
5804
- });
5869
+ host._arrangement.updateTrack(trackId, (current) => ({
5870
+ ...current,
5871
+ clips: [
5872
+ ...current.clips.flatMap(
5873
+ (c) => (0, import_core12.isLoadingClip)(c) ? [c] : (0, import_core12.carveClipRange)([c], startSample, startSample + durSamples)
5874
+ ),
5875
+ clip
5876
+ ]
5877
+ }));
5805
5878
  const desc = host._tracks.get(trackId);
5806
5879
  if (desc) {
5807
5880
  const sr = host.effectiveSampleRate;
@@ -5829,13 +5902,6 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
5829
5902
  clips: [...desc.clips, clipDesc]
5830
5903
  });
5831
5904
  }
5832
- host._recomputeDuration();
5833
- const updatedTrack = host._engineTracks.get(trackId);
5834
- if (host._engine?.updateTrack && updatedTrack) {
5835
- host._engine.updateTrack(trackId, updatedTrack);
5836
- } else {
5837
- host._engine?.setTracks([...host._engineTracks.values()]);
5838
- }
5839
5905
  if (host.isConnected) {
5840
5906
  host.dispatchEvent(
5841
5907
  new CustomEvent("daw-recording-clip-add", {
@@ -5979,6 +6045,7 @@ function syncPeaksForChangedClips(host, tracks) {
5979
6045
  clip.durationSamples
5980
6046
  ).then((peakData) => {
5981
6047
  host._peaksData = new Map(host._peaksData).set(clip.id, peakData);
6048
+ host._clipPeaksReady?.(clip.id, audioBuffer);
5982
6049
  }).catch((err) => {
5983
6050
  console.warn(
5984
6051
  "[dawcore] Failed to generate peaks for clip " + clip.id + ": " + String(err)
@@ -6029,6 +6096,205 @@ function findAudioBufferForClip(host, clip, track) {
6029
6096
  return null;
6030
6097
  }
6031
6098
 
6099
+ // src/interactions/track-entry.ts
6100
+ var import_core13 = require("@waveform-playlist/core");
6101
+ function validMidiNotes(notes) {
6102
+ return notes.filter((n) => {
6103
+ 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;
6104
+ if (!ok) {
6105
+ console.warn("[dawcore] dropping malformed MIDI note: " + JSON.stringify(n));
6106
+ }
6107
+ return ok;
6108
+ });
6109
+ }
6110
+ function clipSourceOf(clipDesc) {
6111
+ return !isDomClip(clipDesc) && clipDesc.file || clipDesc.src;
6112
+ }
6113
+ function isMidiDescriptor(clipDesc) {
6114
+ if (clipSourceOf(clipDesc)) {
6115
+ if (clipDesc.midiNotes != null) {
6116
+ console.warn(
6117
+ '[dawcore] clip "' + (clipDesc.name || (isDomClip(clipDesc) ? clipDesc.clipId : "?")) + '" has both src and midiNotes \u2014 treating as audio (notes will be ignored)'
6118
+ );
6119
+ }
6120
+ return false;
6121
+ }
6122
+ return true;
6123
+ }
6124
+ function clipKindError(trackName, kind, clipIsMidi, clipLabel) {
6125
+ if (clipIsMidi === (kind === "midi")) return null;
6126
+ return new Error(
6127
+ 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.'
6128
+ );
6129
+ }
6130
+ function buildMidiClip(clipDesc, sampleRate) {
6131
+ const notes = validMidiNotes(clipDesc.midiNotes ?? []);
6132
+ const noteSpanSeconds = notes.length ? notes.reduce((max, n) => Math.max(max, n.time + n.duration), 0) : 0;
6133
+ const sourceDurationSamples = Math.ceil(
6134
+ Math.max(noteSpanSeconds, clipDesc.duration, 1) * sampleRate
6135
+ );
6136
+ const requestedDurationSamples = clipDesc.duration > 0 ? Math.round(clipDesc.duration * sampleRate) : sourceDurationSamples;
6137
+ const clip = (0, import_core13.createClip)({
6138
+ startSample: Math.round(clipDesc.start * sampleRate),
6139
+ durationSamples: requestedDurationSamples,
6140
+ offsetSamples: Math.round(clipDesc.offset * sampleRate),
6141
+ sampleRate,
6142
+ sourceDurationSamples,
6143
+ gain: clipDesc.gain,
6144
+ name: clipDesc.name,
6145
+ midiNotes: notes,
6146
+ midiChannel: clipDesc.midiChannel ?? void 0,
6147
+ midiProgram: clipDesc.midiProgram ?? void 0
6148
+ });
6149
+ if (clipDesc.clipId) clip.id = clipDesc.clipId;
6150
+ return clip;
6151
+ }
6152
+ function buildLoadingClip(clipDesc) {
6153
+ return {
6154
+ id: clipDesc.clipId,
6155
+ src: clipSourceOf(clipDesc),
6156
+ start: clipDesc.start,
6157
+ offset: clipDesc.offset,
6158
+ gain: clipDesc.gain,
6159
+ ...clipDesc.duration > 0 && { duration: clipDesc.duration },
6160
+ ...clipDesc.name && { name: clipDesc.name }
6161
+ };
6162
+ }
6163
+ function withClipId(clipDesc) {
6164
+ if (clipDesc.clipId) return clipDesc;
6165
+ return { ...clipDesc, clipId: crypto.randomUUID() };
6166
+ }
6167
+ function buildArrangementTrack(trackId, descriptor, mix, sampleRate) {
6168
+ const clips = [];
6169
+ const refused = [];
6170
+ let changed = false;
6171
+ const descClips = descriptor.clips.map((clipDesc) => {
6172
+ const identified = withClipId(clipDesc);
6173
+ if (identified !== clipDesc) changed = true;
6174
+ const isMidi = isMidiDescriptor(identified);
6175
+ const source = clipSourceOf(identified);
6176
+ const sourceName = typeof source === "string" ? source : source instanceof File ? source.name : "";
6177
+ const label = identified.name || sourceName || identified.clipId;
6178
+ const kindError = clipKindError(descriptor.name, descriptor.kind, isMidi, label);
6179
+ if (kindError) refused.push({ clipId: identified.clipId, error: kindError });
6180
+ else clips.push(isMidi ? buildMidiClip(identified, sampleRate) : buildLoadingClip(identified));
6181
+ return identified;
6182
+ });
6183
+ const base = (0, import_core13.createTrack)({ name: descriptor.name, kind: descriptor.kind, clips: [], ...mix });
6184
+ const track = { ...base, id: trackId, clips };
6185
+ return { track, descriptor: changed ? { ...descriptor, clips: descClips } : descriptor, refused };
6186
+ }
6187
+ function entryIndex(trackEls, trackId, arrangementIds) {
6188
+ const at = trackEls.findIndex((el) => el.trackId === trackId);
6189
+ for (let i = at - 1; i >= 0; i--) {
6190
+ const position = arrangementIds.indexOf(trackEls[i].trackId);
6191
+ if (position !== -1) return position + 1;
6192
+ }
6193
+ return 0;
6194
+ }
6195
+
6196
+ // src/interactions/load-announcer.ts
6197
+ var import_core14 = require("@waveform-playlist/core");
6198
+ var LoadAnnouncer = class {
6199
+ constructor(_dispatch) {
6200
+ this._dispatch = _dispatch;
6201
+ this._tracks = /* @__PURE__ */ new Map();
6202
+ /** The failure each clip was last announced with. */
6203
+ this._clipErrors = /* @__PURE__ */ new Map();
6204
+ /** Clips seen while loading, and not yet announced as loaded. */
6205
+ this._loadingClips = /* @__PURE__ */ new Set();
6206
+ }
6207
+ /** A track is about to enter, with `refused` clips left out for their kind. */
6208
+ expect(trackId, refused) {
6209
+ this._tracks.set(trackId, { state: null, refused });
6210
+ }
6211
+ /**
6212
+ * A clip is about to enter while loading: it is announced ready when it
6213
+ * loads, also when its source was loaded already and it is never seen
6214
+ * loading.
6215
+ */
6216
+ expectClip(clipId) {
6217
+ this._loadingClips.add(clipId);
6218
+ }
6219
+ /** A loading clip was removed: its load will not be announced. */
6220
+ forgetClip(clipId) {
6221
+ this._loadingClips.delete(clipId);
6222
+ this._clipErrors.delete(clipId);
6223
+ }
6224
+ /** The error a failed track was announced with. */
6225
+ errorOf(trackId) {
6226
+ return this._tracks.get(trackId)?.error ?? new Error('track "' + trackId + '" failed to load');
6227
+ }
6228
+ /** A track was removed by the page or an editor method: nothing more is said of it. */
6229
+ forget(trackId, clipIds) {
6230
+ this._tracks.delete(trackId);
6231
+ for (const id of clipIds) {
6232
+ this._clipErrors.delete(id);
6233
+ this._loadingClips.delete(id);
6234
+ }
6235
+ }
6236
+ /** The state a track was last announced in (`null` before its first announcement). */
6237
+ stateOf(trackId) {
6238
+ return this._tracks.get(trackId)?.state ?? null;
6239
+ }
6240
+ update(tracks, sources) {
6241
+ for (const track of tracks) this._updateTrack(track, sources);
6242
+ }
6243
+ _updateTrack(track, sources) {
6244
+ const record = this._tracks.get(track.id) ?? { state: null, refused: 0 };
6245
+ this._tracks.set(track.id, record);
6246
+ let pending = 0;
6247
+ let failed = 0;
6248
+ let loaded = 0;
6249
+ let firstError = null;
6250
+ for (const clip of track.clips) {
6251
+ if (!(0, import_core14.isLoadingClip)(clip)) {
6252
+ loaded++;
6253
+ if (this._loadingClips.delete(clip.id)) {
6254
+ this._clipErrors.delete(clip.id);
6255
+ this._send("daw-clip-ready", { trackId: track.id, clipId: clip.id });
6256
+ }
6257
+ continue;
6258
+ }
6259
+ this._loadingClips.add(clip.id);
6260
+ const source = sources.get(clip.src);
6261
+ if (source?.status !== "failed") {
6262
+ pending++;
6263
+ this._clipErrors.delete(clip.id);
6264
+ continue;
6265
+ }
6266
+ failed++;
6267
+ const error = source.error ?? new Error('the audio of clip "' + clip.id + '" failed to load');
6268
+ firstError ?? (firstError = error);
6269
+ if (this._clipErrors.get(clip.id) !== error) {
6270
+ this._clipErrors.set(clip.id, error);
6271
+ this._send("daw-clip-error", {
6272
+ trackId: track.id,
6273
+ clipId: clip.id,
6274
+ error
6275
+ });
6276
+ }
6277
+ }
6278
+ const next = pending > 0 ? "pending" : loaded > 0 || failed + record.refused === 0 ? "ready" : "failed";
6279
+ if (next === record.state) return;
6280
+ record.state = next;
6281
+ record.error = void 0;
6282
+ if (next === "ready") {
6283
+ this._send("daw-track-ready", { trackId: track.id });
6284
+ } else if (next === "failed") {
6285
+ const requested = failed + record.refused;
6286
+ const error = requested === 1 && firstError ? firstError : new Error(
6287
+ "all " + requested + " clip(s) failed to load \u2014 see prior daw-clip-error events"
6288
+ );
6289
+ record.error = error;
6290
+ this._send("daw-track-error", { trackId: track.id, error });
6291
+ }
6292
+ }
6293
+ _send(type, detail) {
6294
+ this._dispatch(new CustomEvent(type, { bubbles: true, composed: true, detail }));
6295
+ }
6296
+ };
6297
+
6032
6298
  // src/effects/effects-chain-controller.ts
6033
6299
  var idCounter = 0;
6034
6300
  var EffectsChainController = class {
@@ -6242,10 +6508,10 @@ function loadFaustModule(feature) {
6242
6508
  }
6243
6509
 
6244
6510
  // src/effects/effects-manager.ts
6245
- var import_core14 = require("@waveform-playlist/core");
6511
+ var import_core16 = require("@waveform-playlist/core");
6246
6512
 
6247
6513
  // src/effects/effect-registry.ts
6248
- var import_core13 = require("@waveform-playlist/core");
6514
+ var import_core15 = require("@waveform-playlist/core");
6249
6515
  var MAX_DELAY_SECONDS = 10;
6250
6516
  function singleNode(node, applyParams) {
6251
6517
  return { input: node, output: node, applyParams };
@@ -6321,8 +6587,8 @@ function biquadDefinition(spec) {
6321
6587
  };
6322
6588
  }
6323
6589
  function registerBuiltIn(type, definition) {
6324
- if (!(0, import_core13.getEffectDefinitions)().has(type)) {
6325
- (0, import_core13.registerEffect)(type, { ...definition, builtIn: true });
6590
+ if (!(0, import_core15.getEffectDefinitions)().has(type)) {
6591
+ (0, import_core15.registerEffect)(type, { ...definition, builtIn: true });
6326
6592
  }
6327
6593
  }
6328
6594
  function registerBuiltIns() {
@@ -6477,7 +6743,7 @@ var EffectsManager = class {
6477
6743
  /** Run a registered effect's async `prepare` hook on the adapter's
6478
6744
  * context, so the synchronous addEffect() can create it. */
6479
6745
  async prepareEffect(type) {
6480
- await (0, import_core14.prepareEffect)(type, this._requireWiring().audioContext);
6746
+ await (0, import_core16.prepareEffect)(type, this._requireWiring().audioContext);
6481
6747
  }
6482
6748
  // --- Track chains ---
6483
6749
  addTrackEffect(trackId, target, type, params) {
@@ -6682,7 +6948,7 @@ var EffectsManager = class {
6682
6948
  this._runOp(chain, target, "setParams", effectId, { [paramId]: value });
6683
6949
  };
6684
6950
  if (entry.kind === "native") {
6685
- const definition = (0, import_core14.getEffectDefinitions)().get(entry.type);
6951
+ const definition = (0, import_core16.getEffectDefinitions)().get(entry.type);
6686
6952
  if (!definition) {
6687
6953
  throw new Error(
6688
6954
  PREFIX2 + 'openEffectGui: no registry definition for effect type "' + entry.type + '"'
@@ -6741,7 +7007,7 @@ var EffectsManager = class {
6741
7007
  }
6742
7008
  _addToChain(chain, target, type, params) {
6743
7009
  const audioContext = this._requireWiring().audioContext;
6744
- const created = (0, import_core14.createEffectInstance)(type, audioContext, params);
7010
+ const created = (0, import_core16.createEffectInstance)(type, audioContext, params);
6745
7011
  const effectId = chain.add({
6746
7012
  kind: "native",
6747
7013
  type,
@@ -6913,8 +7179,8 @@ var EffectsManager = class {
6913
7179
  if (entry.kind === "native") {
6914
7180
  try {
6915
7181
  const liveContext = this._requireWiring().audioContext;
6916
- if ((0, import_core14.needsPrepare)(entry.type, liveContext)) {
6917
- await (0, import_core14.ensureEffectPrepared)(entry.type, liveContext);
7182
+ if ((0, import_core16.needsPrepare)(entry.type, liveContext)) {
7183
+ await (0, import_core16.ensureEffectPrepared)(entry.type, liveContext);
6918
7184
  if (superseded() || chain.disposed) return;
6919
7185
  }
6920
7186
  const id = this._addToChain(chain, target, entry.type, entry.params);
@@ -7089,8 +7355,8 @@ function toWamParameterMap(params) {
7089
7355
  }
7090
7356
 
7091
7357
  // src/interactions/export-audio.ts
7092
- var import_core15 = require("@waveform-playlist/core");
7093
- var import_core16 = require("@waveform-playlist/core");
7358
+ var import_core17 = require("@waveform-playlist/core");
7359
+ var import_core18 = require("@waveform-playlist/core");
7094
7360
  var PREFIX3 = "[waveform-playlist] ";
7095
7361
  async function exportAudioImpl(host, options = {}) {
7096
7362
  const sampleRate = options.sampleRate ?? host.effectiveSampleRate;
@@ -7125,7 +7391,7 @@ async function exportAudioImpl(host, options = {}) {
7125
7391
  cleanups.push(chain.dispose);
7126
7392
  const volume = ctx.createGain();
7127
7393
  volume.gain.value = track.volume;
7128
- const panStage = (0, import_core15.createPanStage)(ctx, track.pan, (0, import_core15.trackChannelCount)(track));
7394
+ const panStage = (0, import_core17.createPanStage)(ctx, track.pan, (0, import_core17.trackChannelCount)(track));
7129
7395
  cleanups.push(panStage.dispose);
7130
7396
  chain.output.connect(volume);
7131
7397
  volume.connect(panStage.input);
@@ -7207,12 +7473,12 @@ async function buildOfflineChain(ctx, entries) {
7207
7473
  continue;
7208
7474
  }
7209
7475
  if (entry.kind === "native") {
7210
- const definition = (0, import_core16.getEffectDefinitions)().get(entry.type);
7476
+ const definition = (0, import_core18.getEffectDefinitions)().get(entry.type);
7211
7477
  if (entry.bypassed && definition && !definition.wetParam) {
7212
7478
  continue;
7213
7479
  }
7214
- await (0, import_core16.ensureEffectPrepared)(entry.type, ctx);
7215
- const created = (0, import_core16.createEffectInstance)(entry.type, ctx, entry.params);
7480
+ await (0, import_core18.ensureEffectPrepared)(entry.type, ctx);
7481
+ const created = (0, import_core18.createEffectInstance)(entry.type, ctx, entry.params);
7216
7482
  if (entry.bypassed && created.wetParam) {
7217
7483
  created.instance.applyParams({ [created.wetParam]: 0 });
7218
7484
  }
@@ -7479,16 +7745,9 @@ var PlaybackAnimationController = class {
7479
7745
  var import_meta = {};
7480
7746
  var RULER_HEIGHT = 30;
7481
7747
  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();";
7482
- var TrackLoadCancelledError = class extends Error {
7483
- constructor(message, reason) {
7484
- super(message);
7485
- this.reason = reason;
7486
- this.name = "TrackLoadCancelledError";
7487
- }
7488
- };
7489
7748
  var DawEditorElement = class extends import_lit19.LitElement {
7490
7749
  constructor() {
7491
- super(...arguments);
7750
+ super();
7492
7751
  this._samplesPerPixel = 1024;
7493
7752
  this._timeFormat = "hh:mm:ss.sss";
7494
7753
  this.waveHeight = 128;
@@ -7513,10 +7772,33 @@ var DawEditorElement = class extends import_lit19.LitElement {
7513
7772
  this.timeSignature = [4, 4];
7514
7773
  this._ppqn = 960;
7515
7774
  this.snapTo = "off";
7516
- /** Resolved sample rate — falls back to sampleRate property until first audio decode. */
7517
- this._resolvedSampleRate = null;
7775
+ /**
7776
+ * The one owner of the tracks, the clips, the mix, the undo history and
7777
+ * loading (#848). Made with the editor, kept across a disconnect; the
7778
+ * engine plays it once there is an adapter.
7779
+ */
7780
+ this._arrangement = (0, import_engine.createArrangement)();
7781
+ /** Sends the load events, read from the arrangement (#848). */
7782
+ this._announcer = new LoadAnnouncer((event) => this.dispatchEvent(event));
7783
+ /**
7784
+ * Ids of tracks registered (a `<daw-track>` connected, a file dropped) and
7785
+ * not yet in the arrangement: they enter at the next flush, once there is
7786
+ * an engine (#848).
7787
+ */
7788
+ this._entryQueue = [];
7789
+ this._entryFlushScheduled = false;
7790
+ /**
7791
+ * Clips an `addClip()` is waiting for, with their track and the way to
7792
+ * reject the call: a removal of the clip or of its track before the clip
7793
+ * loads settles it here, without a public event (#917).
7794
+ */
7795
+ this._awaitedClips = /* @__PURE__ */ new Map();
7796
+ /** `<daw-track>` elements `addTrack()` made: every other one is the page's (the history rule). */
7797
+ this._editorMadeTracks = /* @__PURE__ */ new WeakSet();
7798
+ this._previewPeaks = /* @__PURE__ */ new Map();
7799
+ /** The `.dat` data of those clips, handed to the peak pipeline when the audio arrives. */
7800
+ this._previewWaveforms = /* @__PURE__ */ new Map();
7518
7801
  this._tracks = /* @__PURE__ */ new Map();
7519
- this._seedMix = /* @__PURE__ */ new Map();
7520
7802
  this._engineTracks = /* @__PURE__ */ new Map();
7521
7803
  this._peaksData = /* @__PURE__ */ new Map();
7522
7804
  this._isPlaying = false;
@@ -7535,16 +7817,11 @@ var DawEditorElement = class extends import_lit19.LitElement {
7535
7817
  // hook, same pattern as the whole-track _duration check.
7536
7818
  this._activePlayEndTime = null;
7537
7819
  this._externalAdapter = null;
7538
- /** True after a disconnect disposed the consumer's adapter via the engine
7539
- * — rebuild attempts fail loudly until a fresh adapter is set. */
7540
- this._adapterConsumedByDispose = false;
7541
7820
  // --- Effects (master chain; per-track chains delegated from <daw-track>) ---
7542
7821
  this._effectsManager = null;
7543
7822
  this._engine = null;
7544
7823
  this._warnedMissingTicksToSeconds = false;
7545
7824
  this._warnedMissingSecondsToTicks = false;
7546
- this._enginePromise = null;
7547
- this._audioCache = /* @__PURE__ */ new Map();
7548
7825
  this._peaksCache = /* @__PURE__ */ new Map();
7549
7826
  this._clipBuffers = /* @__PURE__ */ new Map();
7550
7827
  this._clipOffsets = /* @__PURE__ */ new Map();
@@ -7552,11 +7829,6 @@ var DawEditorElement = class extends import_lit19.LitElement {
7552
7829
  /** Coarsest scale from pre-computed peaks — zoom cannot go finer than this. 0 = no limit. */
7553
7830
  this._minSamplesPerPixel = 0;
7554
7831
  this._trackElements = /* @__PURE__ */ new Map();
7555
- /** Track ids with a _loadTrack in flight. Distinct from `_engineTracks`
7556
- * membership: the peaks-first path inserts a render-only PREVIEW track
7557
- * into _engineTracks mid-load, so `has()` alone cannot answer "is this
7558
- * track still loading?". */
7559
- this._loadingTracks = /* @__PURE__ */ new Set();
7560
7832
  this._childObserver = null;
7561
7833
  this._audioResume = new AudioResumeController(this);
7562
7834
  this._recordingController = new RecordingController(this);
@@ -7639,9 +7911,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
7639
7911
  }
7640
7912
  const descriptor = this._readTrackDescriptor(trackEl);
7641
7913
  this._tracks = new Map(this._tracks).set(trackId, descriptor);
7642
- this._setSeedMix(trackId, mixOfElement(trackEl));
7643
7914
  this._trackElements.set(trackId, trackEl);
7644
- this._loadTrack(trackId, descriptor);
7915
+ this._queueEntry(trackId);
7645
7916
  };
7646
7917
  this._onTrackUpdate = (e) => {
7647
7918
  const trackId = e.detail?.trackId;
@@ -7664,11 +7935,14 @@ var DawEditorElement = class extends import_lit19.LitElement {
7664
7935
  trackEl.kind = keptKind;
7665
7936
  });
7666
7937
  }
7938
+ if (oldDescriptor && oldDescriptor.src === descriptor.src && !descriptor.clips.some(isDomClip) && !oldDescriptor.clips.some(isDomClip)) {
7939
+ descriptor = { ...descriptor, clips: oldDescriptor.clips };
7940
+ }
7667
7941
  this._tracks = new Map(this._tracks).set(trackId, descriptor);
7668
7942
  const changed = Array.isArray(e.detail.changed) ? e.detail.changed : [];
7669
7943
  this._writeMixFields(trackId, pickMix(mixOfElement(trackEl), changed));
7670
- if (oldDescriptor?.src !== descriptor.src) {
7671
- this._loadTrack(trackId, descriptor);
7944
+ if (oldDescriptor && oldDescriptor.src !== descriptor.src) {
7945
+ this._replaceShorthandClips(trackId, descriptor);
7672
7946
  }
7673
7947
  if (descriptor.renderMode === "spectrogram" && oldDescriptor?.renderMode !== "spectrogram") {
7674
7948
  const engineTrack = this._engineTracks.get(trackId);
@@ -7733,18 +8007,20 @@ var DawEditorElement = class extends import_lit19.LitElement {
7733
8007
  const trackEl = clipEl.closest("daw-track");
7734
8008
  if (!trackEl) return;
7735
8009
  const trackId = trackEl.trackId;
7736
- if (!this._engineTracks.has(trackId) || this._loadingTracks.has(trackId)) {
8010
+ if (!this._isEntered(trackId)) {
8011
+ if (!this._entryQueue.includes(trackId)) {
8012
+ this._rejectAwaitedClips(
8013
+ (id) => id === clipEl.clipId,
8014
+ 'addClip: track "' + trackId + '" is not in the editor (an Undo took it out)'
8015
+ );
8016
+ return;
8017
+ }
7737
8018
  const desc = this._tracks.get(trackId);
7738
8019
  if (desc && !desc.clips.some((c) => isDomClip(c) && c.clipId === clipEl.clipId)) {
7739
- 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.';
7740
- console.warn("[dawcore] " + message);
7741
- this.dispatchEvent(
7742
- new CustomEvent("daw-clip-error", {
7743
- bubbles: true,
7744
- composed: true,
7745
- detail: { trackId, clipId: clipEl.clipId, error: new Error(message) }
7746
- })
7747
- );
8020
+ this._tracks = new Map(this._tracks).set(trackId, {
8021
+ ...desc,
8022
+ clips: [...desc.clips, this._readClipDescriptor(clipEl)]
8023
+ });
7748
8024
  }
7749
8025
  return;
7750
8026
  }
@@ -7752,24 +8028,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
7752
8028
  if (loadedDesc && loadedDesc.clips.some((c) => isDomClip(c) && c.clipId === clipEl.clipId)) {
7753
8029
  return;
7754
8030
  }
7755
- const clipDesc = {
7756
- kind: "dom",
7757
- clipId: clipEl.clipId,
7758
- src: clipEl.src,
7759
- peaksSrc: clipEl.peaksSrc,
7760
- start: clipEl.start,
7761
- duration: clipEl.duration,
7762
- offset: clipEl.offset,
7763
- gain: clipEl.gain,
7764
- name: clipEl.name,
7765
- fadeIn: clipEl.fadeIn,
7766
- fadeOut: clipEl.fadeOut,
7767
- fadeType: clipEl.fadeType,
7768
- midiNotes: clipEl.midiNotes,
7769
- midiChannel: clipEl.midiChannel,
7770
- midiProgram: clipEl.midiProgram
7771
- };
7772
- this._loadAndAppendClip(trackId, clipDesc);
8031
+ this._loadAndAppendClip(trackId, this._readClipDescriptor(clipEl));
7773
8032
  };
7774
8033
  this._onClipUpdate = (e) => {
7775
8034
  const clipEl = e.target;
@@ -7781,8 +8040,26 @@ var DawEditorElement = class extends import_lit19.LitElement {
7781
8040
  );
7782
8041
  return;
7783
8042
  }
8043
+ const desc = this._tracks.get(detail.trackId);
8044
+ if (desc && !this._isEntered(detail.trackId)) {
8045
+ this._tracks = new Map(this._tracks).set(detail.trackId, {
8046
+ ...desc,
8047
+ clips: desc.clips.map(
8048
+ (c) => isDomClip(c) && c.clipId === clipEl.clipId ? this._readClipDescriptor(clipEl) : c
8049
+ )
8050
+ });
8051
+ return;
8052
+ }
7784
8053
  this._applyClipUpdate(detail.trackId, detail.clipId, clipEl);
7785
8054
  };
8055
+ this._waitingForDragEnd = false;
8056
+ /** Who waits for a track to enter (addTrack, a dropped file). */
8057
+ this._entryWaiters = /* @__PURE__ */ new Map();
8058
+ /** Ends the waits of `_whenTrackLoaded` (as loaded) when the editor is disconnected. */
8059
+ this._loadWaitEnds = /* @__PURE__ */ new Set();
8060
+ /** Last versions the statechange handler worked from; reset for each engine. */
8061
+ this._lastTracksVersion = -1;
8062
+ this._lastMixerVersion = -1;
7786
8063
  // --- File Drop ---
7787
8064
  this._onDragOver = (e) => {
7788
8065
  if (!this.fileDrop) return;
@@ -7823,6 +8100,16 @@ var DawEditorElement = class extends import_lit19.LitElement {
7823
8100
  if (!this.trackReordering) return;
7824
8101
  this._trackReorderDrag.onGrab(e.detail.trackId, e.detail.pointerEvent, e.detail.gripElement);
7825
8102
  };
8103
+ /**
8104
+ * Escape during a drag cancels it and does nothing else: the default is
8105
+ * prevented, so `<daw-keyboard-shortcuts>` (core's `handleKeyboardEvent`)
8106
+ * does not also stop playback. No `stopPropagation`: an app's own listener
8107
+ * can read `defaultPrevented`.
8108
+ */
8109
+ this._onDragEscape = (e) => {
8110
+ if (e.key !== "Escape") return;
8111
+ if (this._cancelDrags()) e.preventDefault();
8112
+ };
7826
8113
  // --- Recording ---
7827
8114
  this.recordingStream = null;
7828
8115
  /** Set in togglePauseRecording when Transport is paused alongside the
@@ -7841,6 +8128,10 @@ var DawEditorElement = class extends import_lit19.LitElement {
7841
8128
  * statechange emissions during the transaction would otherwise bounce
7842
8129
  * half-applied orders back into the DOM. */
7843
8130
  this._inOrderSync = false;
8131
+ this._arrangement.sources.subscribe(() => {
8132
+ this._announceLoading();
8133
+ this.requestUpdate();
8134
+ });
7844
8135
  }
7845
8136
  get samplesPerPixel() {
7846
8137
  return this._samplesPerPixel;
@@ -8019,16 +8310,33 @@ var DawEditorElement = class extends import_lit19.LitElement {
8019
8310
  get _hasTickCallbacks() {
8020
8311
  return !!(this.secondsToTicks && this.ticksToSeconds);
8021
8312
  }
8022
- /** Sample rate — reads from adapter's AudioContext when available, otherwise falls back to 48000. */
8313
+ /**
8314
+ * Sample rate: the adapter's AudioContext rate. Without an adapter (after a
8315
+ * disconnect let it go), the rate of the loaded clips the arrangement holds,
8316
+ * else 48000. Decoded audio is at the context's rate, so the two agree.
8317
+ */
8023
8318
  get sampleRate() {
8024
- return this._resolvedSampleRate ?? this._externalAdapter?.audioContext.sampleRate ?? 48e3;
8319
+ return this._externalAdapter?.audioContext.sampleRate ?? this._loadedClipSampleRate() ?? 48e3;
8320
+ }
8321
+ _loadedClipSampleRate() {
8322
+ for (const track of this._arrangement.getTracks()) {
8323
+ for (const clip of track.clips) {
8324
+ if ("sampleRate" in clip && typeof clip.sampleRate === "number") return clip.sampleRate;
8325
+ }
8326
+ }
8327
+ return null;
8328
+ }
8329
+ /** Reject the `addClip()` calls waiting for clips that match `which`. */
8330
+ _rejectAwaitedClips(which, message) {
8331
+ for (const [clipId, awaited] of [...this._awaitedClips]) {
8332
+ if (which(clipId, awaited.trackId)) awaited.reject(new Error(message));
8333
+ }
8025
8334
  }
8026
8335
  set adapter(value) {
8027
8336
  if (value && value.audioContext.state === "closed") {
8028
8337
  console.warn("[dawcore] Adapter AudioContext is already closed. Ignoring.");
8029
8338
  return;
8030
8339
  }
8031
- this._adapterConsumedByDispose = false;
8032
8340
  if (this._engine) {
8033
8341
  console.warn(
8034
8342
  "[dawcore] adapter set after engine is built. The engine will continue using the previous adapter."
@@ -8042,6 +8350,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
8042
8350
  this._effectsManager = null;
8043
8351
  }
8044
8352
  this._externalAdapter = value;
8353
+ if (value && this.isConnected && !this._engine) this._buildEngineReporting();
8045
8354
  }
8046
8355
  get adapter() {
8047
8356
  return this._externalAdapter;
@@ -8256,10 +8565,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
8256
8565
  return clip?.midiNotes != null;
8257
8566
  }
8258
8567
  get effectiveSampleRate() {
8259
- return this._resolvedSampleRate ?? this.sampleRate;
8260
- }
8261
- resolveAudioContextSampleRate(rate) {
8262
- if (!this._resolvedSampleRate) this._resolvedSampleRate = rate;
8568
+ return this.sampleRate;
8263
8569
  }
8264
8570
  /**
8265
8571
  * In beats mode, derive samplesPerPixel from ticksPerPixel so that
@@ -8330,72 +8636,55 @@ var DawEditorElement = class extends import_lit19.LitElement {
8330
8636
  _setSelectedTrackId(trackId) {
8331
8637
  this._selectedTrackId = trackId;
8332
8638
  }
8639
+ /**
8640
+ * Every track: those in the arrangement, in its order, then those still
8641
+ * waiting to enter (#848). A `<daw-track>` whose track an Undo took out of
8642
+ * the arrangement is not listed (its descriptor stays for a Redo).
8643
+ */
8333
8644
  get tracks() {
8334
- return [...this._tracks.entries()].map(([trackId, descriptor]) => ({
8335
- trackId,
8336
- ...descriptor,
8337
- ...this._mixOf(trackId)
8338
- }));
8645
+ const ids = [...this._arrangement.getTracks().map((t) => t.id), ...this._entryQueue];
8646
+ return ids.flatMap((trackId) => {
8647
+ const descriptor = this._tracks.get(trackId);
8648
+ return descriptor ? [{ trackId, ...descriptor, ...this._mixOf(trackId) }] : [];
8649
+ });
8339
8650
  }
8340
8651
  /**
8341
- * A track's mix, from its one owner: the arrangement (through
8342
- * `_engineTracks`, which follows `mixerVersion`) for a track the engine
8343
- * holds, the seed for one still on its way in (#843).
8652
+ * A track's mix, from its one owner, the arrangement (#843), as the engine
8653
+ * plays it: its projection carries the take's mute, which `getMixer()`
8654
+ * leaves out (the stored mute comes back when the take ends). A track still
8655
+ * waiting to enter shows what its element declares.
8344
8656
  */
8345
8657
  _mixOf(trackId) {
8346
- const seed = this._seedMix.get(trackId);
8347
- if (seed) return seed;
8348
- const track = this._engineTracks.get(trackId);
8349
- return track ? mixOfTrack(track) : DEFAULT_TRACK_MIX;
8350
- }
8351
- /** Replace a track's seed (a new Map: `_seedMix` is reactive state). */
8352
- _setSeedMix(trackId, mix) {
8353
- this._seedMix = new Map(this._seedMix).set(trackId, mix);
8354
- }
8355
- _deleteSeedMix(trackIds) {
8356
- let next = null;
8357
- for (const id of trackIds) {
8358
- if (!this._seedMix.has(id)) continue;
8359
- next ?? (next = new Map(this._seedMix));
8360
- next.delete(id);
8361
- }
8362
- if (next) this._seedMix = next;
8658
+ const played = this._engineTracks.get(trackId);
8659
+ if (played) return mixOfTrack(played);
8660
+ const mix = this._arrangement.getMixer().get(trackId);
8661
+ if (mix) return mix;
8662
+ const el = this._trackElements.get(trackId);
8663
+ return el ? mixOfElement(el) : DEFAULT_TRACK_MIX;
8363
8664
  }
8364
8665
  /**
8365
- * Change one mixer field of a track: the seed while the track is loading
8366
- * (not an undo step, nothing sent), else the engine's setter with
8367
- * `options` (an undo step; changes with one `gesture` id are one step).
8666
+ * Change one mixer field of a track: the arrangement's setter with
8667
+ * `options` (an undo step; changes with one `gesture` id are one step). A
8668
+ * track that has not entered yet changes nothing.
8368
8669
  */
8369
8670
  _writeMix(trackId, field, value, options) {
8370
- const seed = this._seedMix.get(trackId);
8371
- if (seed) {
8372
- if (seed[field] !== value) this._setSeedMix(trackId, { ...seed, [field]: value });
8373
- return;
8374
- }
8375
- if (!this._engine) return;
8376
- if (field === "volume") this._engine.setTrackVolume(trackId, value, options);
8377
- else if (field === "pan") this._engine.setTrackPan(trackId, value, options);
8378
- else if (field === "muted") this._engine.setTrackMute(trackId, value, options);
8379
- else this._engine.setTrackSolo(trackId, value, options);
8671
+ const arrangement = this._arrangement;
8672
+ if (field === "volume") arrangement.setTrackVolume(trackId, value, options);
8673
+ else if (field === "pan") arrangement.setTrackPan(trackId, value, options);
8674
+ else if (field === "muted") arrangement.setTrackMute(trackId, value, options);
8675
+ else arrangement.setTrackSolo(trackId, value, options);
8380
8676
  }
8381
8677
  /**
8382
8678
  * Change the given mixer fields of a track as ONE undo step (#843): all
8383
8679
  * of them carry one fresh gesture id. A field left out is not sent.
8384
8680
  */
8385
8681
  _writeMixFields(trackId, mix) {
8386
- const options = { gesture: (0, import_core17.createMixerGesture)().id };
8682
+ const options = { gesture: (0, import_core19.createMixerGesture)().id };
8387
8683
  if (mix.volume !== void 0) this._writeMix(trackId, "volume", mix.volume, options);
8388
8684
  if (mix.pan !== void 0) this._writeMix(trackId, "pan", mix.pan, options);
8389
8685
  if (mix.muted !== void 0) this._writeMix(trackId, "muted", mix.muted, options);
8390
8686
  if (mix.soloed !== void 0) this._writeMix(trackId, "soloed", mix.soloed, options);
8391
8687
  }
8392
- /** The ordered tracks for `engine.setTracks`, a loading track with its seed. */
8393
- _tracksForEngine() {
8394
- return this._getOrderedTracks().map(([trackId, track]) => {
8395
- const seed = this._seedMix.get(trackId);
8396
- return seed ? withMix(track, seed) : track;
8397
- });
8398
- }
8399
8688
  get selectedTrackId() {
8400
8689
  return this._selectedTrackId;
8401
8690
  }
@@ -8421,6 +8710,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
8421
8710
  // --- Lifecycle ---
8422
8711
  connectedCallback() {
8423
8712
  super.connectedCallback();
8713
+ window.addEventListener("keydown", this._onDragEscape, { capture: true });
8424
8714
  this.addEventListener("daw-track-connected", this._onTrackConnected);
8425
8715
  this.addEventListener("daw-track-update", this._onTrackUpdate);
8426
8716
  this.addEventListener("daw-track-control", this._onTrackControl);
@@ -8478,9 +8768,14 @@ var DawEditorElement = class extends import_lit19.LitElement {
8478
8768
  if (orderMayHaveChanged) this._syncEngineOrderToDom();
8479
8769
  });
8480
8770
  this._childObserver.observe(this, { childList: true, subtree: true });
8771
+ for (const [trackId, el] of [...this._trackElements]) {
8772
+ if (!this.contains(el)) this._onTrackRemoved(trackId);
8773
+ }
8774
+ if (this._externalAdapter && !this._engine) this._buildEngineReporting();
8481
8775
  }
8482
8776
  disconnectedCallback() {
8483
8777
  super.disconnectedCallback();
8778
+ window.removeEventListener("keydown", this._onDragEscape, { capture: true });
8484
8779
  this._effectsManager?.disposeAll();
8485
8780
  this._effectsManager = null;
8486
8781
  this.removeEventListener("daw-track-connected", this._onTrackConnected);
@@ -8496,16 +8791,23 @@ var DawEditorElement = class extends import_lit19.LitElement {
8496
8791
  this.removeEventListener("daw-annotation-select", this._onAnnotationSelect);
8497
8792
  this.removeEventListener("daw-track-reorder", this._onTrackReorder);
8498
8793
  this.removeEventListener("daw-track-reorder-grab", this._onTrackReorderGrab);
8499
- this._trackReorderDrag.cancel();
8794
+ this._cancelDrags(true);
8795
+ for (const end of [...this._loadWaitEnds]) end();
8796
+ for (const trackId of this._entryQueue) {
8797
+ if (this._trackElements.has(trackId) || !this._entryWaiters.has(trackId)) continue;
8798
+ const nextTracks = new Map(this._tracks);
8799
+ nextTracks.delete(trackId);
8800
+ this._tracks = nextTracks;
8801
+ this._entryQueue = this._entryQueue.filter((id) => id !== trackId);
8802
+ this._settleEntry(
8803
+ trackId,
8804
+ new Error("<daw-editor> was disconnected before the file entered")
8805
+ );
8806
+ }
8500
8807
  this._childObserver?.disconnect();
8501
8808
  this._childObserver = null;
8502
- this._trackElements.clear();
8503
- this._audioCache.clear();
8504
8809
  this._peaksCache.clear();
8505
- this._clipBuffers.clear();
8506
- this._clipOffsets.clear();
8507
8810
  this._peakPipeline.terminate();
8508
- this._minSamplesPerPixel = 0;
8509
8811
  this._spectrogramController?.dispose();
8510
8812
  this._spectrogramController = null;
8511
8813
  this._lastSpectrogramViewport = null;
@@ -8516,14 +8818,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
8516
8818
  console.warn("[dawcore] Error disposing engine: " + String(err));
8517
8819
  }
8518
8820
  if (hadEngine) {
8519
- this._adapterConsumedByDispose = true;
8821
+ this._externalAdapter = null;
8520
8822
  }
8521
- this._tracks = /* @__PURE__ */ new Map();
8522
- this._seedMix = /* @__PURE__ */ new Map();
8523
- this._engineTracks = /* @__PURE__ */ new Map();
8524
- this._peaksData = /* @__PURE__ */ new Map();
8525
- this._loadingTracks.clear();
8526
- this._recomputeDuration();
8527
8823
  }
8528
8824
  willUpdate(changedProperties) {
8529
8825
  if (changedProperties.has("eagerResume")) {
@@ -8577,6 +8873,21 @@ var DawEditorElement = class extends import_lit19.LitElement {
8577
8873
  }
8578
8874
  _onTrackRemoved(trackId) {
8579
8875
  const existed = this._tracks.has(trackId);
8876
+ this._rejectAwaitedClips(
8877
+ (_, awaitedTrackId) => awaitedTrackId === trackId,
8878
+ "the track of the clip was removed before the clip loaded"
8879
+ );
8880
+ this._entryQueue = this._entryQueue.filter((id) => id !== trackId);
8881
+ this._settleEntry(trackId, new Error('track "' + trackId + '" was removed before it entered'));
8882
+ const arrangementTrack = this._arrangement.getTracks().find((t) => t.id === trackId);
8883
+ const clipIds = arrangementTrack?.clips.map((c) => c.id) ?? [];
8884
+ this._announcer.forget(trackId, clipIds);
8885
+ if (clipIds.some((id) => this._previewPeaks.has(id))) {
8886
+ const nextPreview = new Map(this._previewPeaks);
8887
+ for (const id of clipIds) nextPreview.delete(id);
8888
+ this._previewPeaks = nextPreview;
8889
+ }
8890
+ for (const id of clipIds) this._previewWaveforms.delete(id);
8580
8891
  this._trackElements.delete(trackId);
8581
8892
  this._effectsManager?.disposeTrackChain(trackId);
8582
8893
  const removedTrack = this._engineTracks.get(trackId);
@@ -8593,14 +8904,11 @@ var DawEditorElement = class extends import_lit19.LitElement {
8593
8904
  const nextTracks = new Map(this._tracks);
8594
8905
  nextTracks.delete(trackId);
8595
8906
  this._tracks = nextTracks;
8596
- this._deleteSeedMix([trackId]);
8597
8907
  const nextEngine = new Map(this._engineTracks);
8598
8908
  nextEngine.delete(trackId);
8599
8909
  this._engineTracks = nextEngine;
8600
8910
  this._recomputeDuration();
8601
- if (this._engine) {
8602
- this._engine.removeTrack(trackId);
8603
- }
8911
+ this._arrangement.removeTrack(trackId);
8604
8912
  this._recomputeZoomFloor();
8605
8913
  this._disposeSpectrogramControllerIfEmpty();
8606
8914
  if (existed && nextEngine.size === 0) {
@@ -8655,13 +8963,13 @@ var DawEditorElement = class extends import_lit19.LitElement {
8655
8963
  next.set(track.id, {
8656
8964
  name: track.name ?? "",
8657
8965
  src: "",
8658
- kind: (0, import_core17.trackKind)(track),
8659
- renderMode: trackDescriptorRenderMode((0, import_core17.trackKind)(track), "waveform"),
8966
+ kind: (0, import_core19.trackKind)(track),
8967
+ renderMode: trackDescriptorRenderMode((0, import_core19.trackKind)(track), "waveform"),
8660
8968
  clips: []
8661
8969
  });
8662
8970
  }
8663
8971
  for (const trackId of this._tracks.keys()) {
8664
- if (engineIds.has(trackId) || this._loadingTracks.has(trackId) || this._trackElements.has(trackId)) {
8972
+ if (engineIds.has(trackId) || this._entryQueue.includes(trackId) || this._trackElements.has(trackId)) {
8665
8973
  continue;
8666
8974
  }
8667
8975
  next ?? (next = new Map(this._tracks));
@@ -8713,12 +9021,22 @@ var DawEditorElement = class extends import_lit19.LitElement {
8713
9021
  }
8714
9022
  _onClipRemovedFromDom(clipEl) {
8715
9023
  const clipId = clipEl.clipId;
8716
- for (const [trackId, t] of this._engineTracks.entries()) {
9024
+ for (const t of this._arrangement.getTracks()) {
8717
9025
  if (t.clips.some((c) => c.id === clipId)) {
8718
- this._removeClipFromTrack(trackId, clipId);
9026
+ this._removeClipFromTrack(t.id, clipId);
8719
9027
  return;
8720
9028
  }
8721
9029
  }
9030
+ for (const [trackId, desc] of this._tracks) {
9031
+ if (this._isEntered(trackId) || !desc.clips.some((c) => c.clipId === clipId)) continue;
9032
+ this._tracks = new Map(this._tracks).set(trackId, {
9033
+ ...desc,
9034
+ clips: desc.clips.filter((c) => c.clipId !== clipId)
9035
+ });
9036
+ this._rejectAwaitedClips((id) => id === clipId, "the clip was removed before it loaded");
9037
+ return;
9038
+ }
9039
+ this._rejectAwaitedClips((id) => id === clipId, "the clip was removed before it loaded");
8722
9040
  if (this._clipBuffers.has(clipId) || this._clipOffsets.has(clipId) || this._peaksData.has(clipId)) {
8723
9041
  console.warn(
8724
9042
  '[dawcore] _onClipRemovedFromDom: orphaned cache entries for clip "' + clipId + '" \u2014 purging (DOM/engine id mismatch?)'
@@ -8726,62 +9044,52 @@ var DawEditorElement = class extends import_lit19.LitElement {
8726
9044
  this._purgeClipCaches(clipId);
8727
9045
  }
8728
9046
  }
8729
- async _loadAndAppendClip(trackId, clipDesc) {
8730
- if (!clipDesc.src) return;
8731
- const clipId = clipDesc.clipId;
8732
- let insertedClipId = null;
9047
+ /**
9048
+ * A `<daw-clip>` appended to a track that has entered: the clip goes in as
9049
+ * a loading clip (a loaded one for MIDI), one undo step. Its audio loads
9050
+ * like any other; `daw-clip-ready` or `daw-clip-error` follows (#848).
9051
+ */
9052
+ _loadAndAppendClip(trackId, clipDesc) {
9053
+ const trackDesc = this._tracks.get(trackId);
9054
+ if (!trackDesc) return;
9055
+ const clipIsMidi = isMidiDescriptor(clipDesc);
9056
+ const kindError = clipKindError(
9057
+ trackDesc.name,
9058
+ trackDesc.kind,
9059
+ clipIsMidi,
9060
+ clipDesc.name || clipDesc.src || clipDesc.clipId
9061
+ );
9062
+ const clip = clipIsMidi ? buildMidiClip(clipDesc, this.effectiveSampleRate) : buildLoadingClip(clipDesc);
9063
+ if (!clipIsMidi) this._announcer.expectClip(clipDesc.clipId);
8733
9064
  try {
8734
- const trackDesc = this._tracks.get(trackId);
8735
- const kindError = trackDesc ? this._clipKindError(trackDesc.name, trackDesc.kind, false, clipDesc.name || clipDesc.src) : null;
8736
9065
  if (kindError) throw kindError;
8737
- const waveformDataPromise = clipDesc.peaksSrc ? this._resolvePeaks(clipDesc.peaksSrc) : Promise.resolve(null);
8738
- const audioPromise = this._fetchAndDecode(clipDesc.src);
8739
- const [waveformData, audioBuffer] = await Promise.all([waveformDataPromise, audioPromise]);
8740
- this._resolvedSampleRate = audioBuffer.sampleRate;
8741
- const clip = await this._finalizeAudioClip(clipDesc, audioBuffer, waveformData);
8742
- insertedClipId = clip.id;
8743
- const t = this._engineTracks.get(trackId);
8744
- if (!t) {
8745
- this._purgeClipCaches(clip.id);
8746
- return;
8747
- }
8748
- const updatedTrack = { ...t, clips: [...t.clips, clip] };
8749
- this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);
8750
- const desc = this._tracks.get(trackId);
8751
- if (desc) {
8752
- this._tracks = new Map(this._tracks).set(trackId, {
8753
- ...desc,
8754
- clips: [...desc.clips, clipDesc]
8755
- });
8756
- }
8757
- this._commitTrackChange(trackId, updatedTrack);
8758
- this._maybeRegisterSpectrogramClipAudio(trackId, clip);
8759
- this.dispatchEvent(
8760
- new CustomEvent("daw-clip-ready", {
8761
- bubbles: true,
8762
- composed: true,
8763
- detail: { trackId, clipId: clip.id }
8764
- })
8765
- );
9066
+ this._arrangement.updateTrack(trackId, (current) => ({
9067
+ ...current,
9068
+ clips: [...current.clips, clip]
9069
+ }));
8766
9070
  } catch (err) {
8767
9071
  console.warn("[dawcore] _loadAndAppendClip failed: " + String(err));
8768
- if (insertedClipId) this._purgeClipCaches(insertedClipId);
8769
9072
  this.dispatchEvent(
8770
9073
  new CustomEvent("daw-clip-error", {
8771
9074
  bubbles: true,
8772
9075
  composed: true,
8773
- detail: { trackId, clipId: insertedClipId ?? clipId, error: err }
9076
+ detail: { trackId, clipId: clipDesc.clipId, error: err }
8774
9077
  })
8775
9078
  );
9079
+ return;
8776
9080
  }
9081
+ this._tracks = new Map(this._tracks).set(trackId, {
9082
+ ...trackDesc,
9083
+ clips: [...trackDesc.clips, clipDesc]
9084
+ });
9085
+ if (!clipIsMidi && clipDesc.peaksSrc) this._requestPreview(clipDesc.clipId, clipDesc.peaksSrc);
8777
9086
  }
8778
9087
  /**
8779
9088
  * Resolve pre-computed peaks for a clip: fetch the .dat/.json, validate the
8780
9089
  * sample rate matches the AudioContext, return the WaveformData or null.
8781
9090
  * Warns on fetch failure and on sample-rate mismatch — never silent.
8782
9091
  *
8783
- * Shared between `_loadTrack` (peaks-first preview path) and
8784
- * `_loadAndAppendClip` (incremental late-append).
9092
+ * Used by `_requestPreview` for a clip that is still loading.
8785
9093
  */
8786
9094
  async _resolvePeaks(peaksSrc) {
8787
9095
  try {
@@ -8799,127 +9107,6 @@ var DawEditorElement = class extends import_lit19.LitElement {
8799
9107
  return null;
8800
9108
  }
8801
9109
  }
8802
- /**
8803
- * Construct an AudioClip from a decoded buffer (and optional WaveformData),
8804
- * align its id with the source `<daw-clip>.clipId` when present, populate
8805
- * `_clipBuffers` / `_clipOffsets`, generate peaks via the worker pipeline,
8806
- * and populate `_peaksData`. Returns the finished AudioClip.
8807
- *
8808
- * Shared between `_loadTrack`'s standard path and `_loadAndAppendClip`.
8809
- * Not used by `_loadTrack`'s peaks-first preview path because that path
8810
- * uses sync `extractPeaks` and inserts a preview track BEFORE audio decode.
8811
- */
8812
- async _finalizeAudioClip(clipDesc, audioBuffer, waveformData) {
8813
- let clip;
8814
- if (waveformData) {
8815
- const wdRate = waveformData.sample_rate;
8816
- clip = (0, import_core17.createClip)({
8817
- audioBuffer,
8818
- waveformData,
8819
- startSample: Math.round(clipDesc.start * wdRate),
8820
- durationSamples: Math.round((clipDesc.duration || waveformData.duration) * wdRate),
8821
- offsetSamples: Math.round(clipDesc.offset * wdRate),
8822
- gain: clipDesc.gain,
8823
- name: clipDesc.name,
8824
- sampleRate: wdRate,
8825
- sourceDurationSamples: Math.ceil(waveformData.duration * wdRate)
8826
- });
8827
- this._peakPipeline.cacheWaveformData(audioBuffer, waveformData);
8828
- } else {
8829
- clip = (0, import_core17.createClipFromSeconds)({
8830
- audioBuffer,
8831
- startTime: clipDesc.start,
8832
- duration: clipDesc.duration || audioBuffer.duration,
8833
- offset: clipDesc.offset,
8834
- gain: clipDesc.gain,
8835
- name: clipDesc.name,
8836
- sampleRate: audioBuffer.sampleRate,
8837
- sourceDuration: audioBuffer.duration
8838
- });
8839
- }
8840
- if (isDomClip(clipDesc)) clip.id = clipDesc.clipId;
8841
- this._clipBuffers = new Map(this._clipBuffers).set(clip.id, audioBuffer);
8842
- this._clipOffsets.set(clip.id, {
8843
- offsetSamples: clip.offsetSamples,
8844
- durationSamples: clip.durationSamples
8845
- });
8846
- let peakData;
8847
- try {
8848
- peakData = await this._peakPipeline.generatePeaks(
8849
- audioBuffer,
8850
- this._renderSpp,
8851
- this.mono,
8852
- clip.offsetSamples,
8853
- clip.durationSamples
8854
- );
8855
- } catch (err) {
8856
- this._purgeClipCaches(clip.id);
8857
- throw err;
8858
- }
8859
- this._peaksData = new Map(this._peaksData).set(clip.id, peakData);
8860
- const cachedScale = waveformData?.scale ?? this._peakPipeline.getCachedScale(audioBuffer);
8861
- this._raiseZoomFloor(cachedScale);
8862
- return clip;
8863
- }
8864
- /**
8865
- * Filter MIDI notes to only those with finite, in-range fields. Logs a
8866
- * warning for each dropped note. Used by _buildMidiClip and the
8867
- * _applyClipUpdate MIDI branch to prevent NaN propagation through the
8868
- * timeline.
8869
- */
8870
- _validMidiNotes(notes) {
8871
- return notes.filter((n) => {
8872
- 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;
8873
- if (!ok) {
8874
- console.warn("[dawcore] dropping malformed MIDI note: " + JSON.stringify(n));
8875
- }
8876
- return ok;
8877
- });
8878
- }
8879
- /**
8880
- * A clip descriptor is treated as MIDI when it has no audio src.
8881
- * Includes placeholder MIDI clips (no notes, no duration yet — registered
8882
- * with a 1s default span; notes upgrade via _applyClipUpdate). Warns when
8883
- * a clip ambiguously has both src and midiNotes — the audio path runs
8884
- * and notes would be silently ignored.
8885
- */
8886
- _isMidiDescriptor(clipDesc) {
8887
- if (clipDesc.src) {
8888
- if (clipDesc.midiNotes != null) {
8889
- console.warn(
8890
- '[dawcore] clip "' + (clipDesc.name || (isDomClip(clipDesc) ? clipDesc.clipId : "?")) + '" has both src and midiNotes \u2014 treating as audio (notes will be ignored)'
8891
- );
8892
- }
8893
- return false;
8894
- }
8895
- return true;
8896
- }
8897
- /**
8898
- * Build an engine clip from a MIDI clip descriptor. Always returns a clip
8899
- * — empty notes / no declared duration get a 1-second placeholder span so
8900
- * the clip is reachable via `engine.updateTrack` once notes arrive.
8901
- */
8902
- _buildMidiClip(clipDesc) {
8903
- const sr = this.effectiveSampleRate;
8904
- const notes = this._validMidiNotes(clipDesc.midiNotes ?? []);
8905
- const noteSpanSeconds = notes.length ? notes.reduce((max, n) => Math.max(max, n.time + n.duration), 0) : 0;
8906
- const sourceDurationSamples = Math.ceil(Math.max(noteSpanSeconds, clipDesc.duration, 1) * sr);
8907
- const requestedDurationSamples = clipDesc.duration > 0 ? Math.round(clipDesc.duration * sr) : sourceDurationSamples;
8908
- const clip = (0, import_core17.createClip)({
8909
- startSample: Math.round(clipDesc.start * sr),
8910
- durationSamples: requestedDurationSamples,
8911
- offsetSamples: Math.round(clipDesc.offset * sr),
8912
- sampleRate: sr,
8913
- sourceDurationSamples,
8914
- gain: clipDesc.gain,
8915
- name: clipDesc.name,
8916
- midiNotes: notes,
8917
- midiChannel: clipDesc.midiChannel ?? void 0,
8918
- midiProgram: clipDesc.midiProgram ?? void 0
8919
- });
8920
- if (isDomClip(clipDesc)) clip.id = clipDesc.clipId;
8921
- return clip;
8922
- }
8923
9110
  /** Remove a single clip from all per-clip caches. Used by error rollbacks. */
8924
9111
  _purgeClipCaches(clipId) {
8925
9112
  const nextBuffers = new Map(this._clipBuffers);
@@ -8932,16 +9119,14 @@ var DawEditorElement = class extends import_lit19.LitElement {
8932
9119
  this._spectrogramController?.unregisterClipAudio(clipId);
8933
9120
  }
8934
9121
  /**
8935
- * Recompute duration and forward an updated track to the engine. Single
8936
- * source of truth for the incremental-vs-full-rebuild policy used by every
8937
- * clip-level mutation (addClip, updateClip, removeClip, _applyClipUpdate).
8938
- * Use the engine's incremental updateTrack when available; otherwise fall
8939
- * back to full setTracks (legacy adapters).
9122
+ * Replace one loaded clip of a track in the arrangement: an undo step. The
9123
+ * function form, so the track's loading clips stay as they are (#848).
8940
9124
  */
8941
- _commitTrackChange(trackId, updatedTrack) {
8942
- this._recomputeDuration();
8943
- if (this._engine?.updateTrack) this._engine.updateTrack(trackId, updatedTrack);
8944
- else if (this._engine) this._engine.setTracks(this._tracksForEngine());
9125
+ _replaceClip(trackId, clipId, clip) {
9126
+ this._arrangement.updateTrack(trackId, (current) => ({
9127
+ ...current,
9128
+ clips: current.clips.map((c) => c.id === clipId ? clip : c)
9129
+ }));
8945
9130
  }
8946
9131
  _applyClipUpdate(trackId, clipId, clipEl) {
8947
9132
  const t = this._engineTracks.get(trackId);
@@ -8951,8 +9136,9 @@ var DawEditorElement = class extends import_lit19.LitElement {
8951
9136
  }
8952
9137
  const idx = t.clips.findIndex((c) => c.id === clipId);
8953
9138
  if (idx === -1) {
9139
+ const loading = this._arrangement.getTracks().find((track) => track.id === trackId)?.clips.some((c) => c.id === clipId);
8954
9140
  console.warn(
8955
- '[dawcore] _applyClipUpdate: clip "' + clipId + '" not found in track "' + trackId + '" (DOM/engine clip-id misalignment?)'
9141
+ '[dawcore] _applyClipUpdate: clip "' + clipId + '" ' + (loading ? "is still loading; the change is dropped" : 'not found in track "' + trackId + '" (DOM/engine clip-id misalignment?)')
8956
9142
  );
8957
9143
  return;
8958
9144
  }
@@ -8960,8 +9146,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
8960
9146
  const sr = oldClip.sampleRate ?? this.effectiveSampleRate;
8961
9147
  const isMidiNow = clipEl.midiNotes != null && !clipEl.src;
8962
9148
  const wasMidi = oldClip.midiNotes != null;
8963
- if (isMidiNow && (0, import_core17.trackKind)(t) !== "midi") {
8964
- const kindError = this._clipKindError(t.name, "audio", true, clipEl.name || clipId);
9149
+ if (isMidiNow && (0, import_core19.trackKind)(t) !== "midi") {
9150
+ const kindError = clipKindError(t.name ?? "", "audio", true, clipEl.name || clipId);
8965
9151
  console.warn("[dawcore] _applyClipUpdate: " + kindError?.message);
8966
9152
  this.dispatchEvent(
8967
9153
  new CustomEvent("daw-clip-error", {
@@ -8973,7 +9159,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
8973
9159
  return;
8974
9160
  }
8975
9161
  if (isMidiNow || wasMidi) {
8976
- const notes = this._validMidiNotes(clipEl.midiNotes ?? []);
9162
+ const notes = validMidiNotes(clipEl.midiNotes ?? []);
8977
9163
  const noteSpanSeconds = notes.length ? notes.reduce((max, n) => Math.max(max, n.time + n.duration), 0) : 0;
8978
9164
  const sourceDurationSamples = Math.ceil(Math.max(noteSpanSeconds, clipEl.duration, 1) * sr);
8979
9165
  const requestedDurationSamples = clipEl.duration > 0 ? Math.round(clipEl.duration * sr) : sourceDurationSamples;
@@ -8990,12 +9176,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
8990
9176
  midiChannel: clipEl.midiChannel ?? void 0,
8991
9177
  midiProgram: clipEl.midiProgram ?? void 0
8992
9178
  };
8993
- const updatedClips2 = [...t.clips];
8994
- updatedClips2[idx] = updatedClip2;
8995
- const updatedTrack2 = { ...t, clips: updatedClips2 };
8996
- this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack2);
8997
9179
  this._purgeClipCaches(clipId);
8998
- this._commitTrackChange(trackId, updatedTrack2);
9180
+ this._replaceClip(trackId, clipId, updatedClip2);
8999
9181
  return;
9000
9182
  }
9001
9183
  const newStartSample = Math.round(clipEl.start * sr);
@@ -9009,10 +9191,6 @@ var DawEditorElement = class extends import_lit19.LitElement {
9009
9191
  gain: clipEl.gain,
9010
9192
  name: clipEl.name || oldClip.name
9011
9193
  };
9012
- const updatedClips = [...t.clips];
9013
- updatedClips[idx] = updatedClip;
9014
- const updatedTrack = { ...t, clips: updatedClips };
9015
- this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);
9016
9194
  const boundsChanged = oldClip.offsetSamples !== newOffsetSamples || oldClip.durationSamples !== newDurationSamples;
9017
9195
  if (boundsChanged) {
9018
9196
  this._clipOffsets.set(clipId, {
@@ -9024,40 +9202,41 @@ var DawEditorElement = class extends import_lit19.LitElement {
9024
9202
  this._peaksData = new Map(this._peaksData).set(clipId, peaks);
9025
9203
  }
9026
9204
  }
9027
- this._commitTrackChange(trackId, updatedTrack);
9205
+ this._replaceClip(trackId, clipId, updatedClip);
9028
9206
  }
9207
+ /** Remove a clip (loaded or still loading) from a track of the arrangement: an undo step. */
9029
9208
  _removeClipFromTrack(trackId, clipId) {
9030
- const t = this._engineTracks.get(trackId);
9031
- if (!t) {
9032
- console.warn('[dawcore] _removeClipFromTrack: no engine track for id "' + trackId + '"');
9209
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9210
+ if (!track) {
9211
+ console.warn('[dawcore] _removeClipFromTrack: no track for id "' + trackId + '"');
9033
9212
  return;
9034
9213
  }
9035
- const updatedClips = t.clips.filter((c) => c.id !== clipId);
9036
- if (updatedClips.length === t.clips.length) {
9214
+ if (!track.clips.some((c) => c.id === clipId)) {
9037
9215
  console.warn(
9038
9216
  '[dawcore] _removeClipFromTrack: clip "' + clipId + '" not found in track "' + trackId + '"'
9039
9217
  );
9040
9218
  return;
9041
9219
  }
9042
- const updatedTrack = { ...t, clips: updatedClips };
9043
- this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);
9044
- const nextBuffers = new Map(this._clipBuffers);
9045
- nextBuffers.delete(clipId);
9046
- this._clipBuffers = nextBuffers;
9047
- this._clipOffsets.delete(clipId);
9048
- const nextPeaks = new Map(this._peaksData);
9049
- nextPeaks.delete(clipId);
9050
- this._peaksData = nextPeaks;
9220
+ this._purgeClipCaches(clipId);
9221
+ this._previewWaveforms.delete(clipId);
9222
+ if (this._previewPeaks.has(clipId)) {
9223
+ const nextPreview = new Map(this._previewPeaks);
9224
+ nextPreview.delete(clipId);
9225
+ this._previewPeaks = nextPreview;
9226
+ }
9051
9227
  const desc = this._tracks.get(trackId);
9052
9228
  if (desc) {
9053
9229
  this._tracks = new Map(this._tracks).set(trackId, {
9054
9230
  ...desc,
9055
- // Descriptors without an id (file drops, the <daw-track src>
9056
- // shorthand) are kept — their identity is the descriptor itself.
9057
9231
  clips: desc.clips.filter((c) => c.clipId !== clipId)
9058
9232
  });
9059
9233
  }
9060
- this._commitTrackChange(trackId, updatedTrack);
9234
+ const wasLoading = track.clips.some((c) => c.id === clipId && (0, import_core19.isLoadingClip)(c));
9235
+ this._arrangement.updateTrack(trackId, (current) => ({
9236
+ ...current,
9237
+ clips: current.clips.filter((c) => c.id !== clipId)
9238
+ }));
9239
+ if (wasLoading) this._announcer.forgetClip(clipId);
9061
9240
  }
9062
9241
  _readTrackDescriptor(trackEl) {
9063
9242
  const clipEls = trackEl.querySelectorAll("daw-clip");
@@ -9080,25 +9259,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9080
9259
  midiProgram: null
9081
9260
  });
9082
9261
  } else {
9083
- for (const clipEl of clipEls) {
9084
- clips.push({
9085
- kind: "dom",
9086
- clipId: clipEl.clipId,
9087
- src: clipEl.src,
9088
- peaksSrc: clipEl.peaksSrc,
9089
- start: clipEl.start,
9090
- duration: clipEl.duration,
9091
- offset: clipEl.offset,
9092
- gain: clipEl.gain,
9093
- name: clipEl.name,
9094
- fadeIn: clipEl.fadeIn,
9095
- fadeOut: clipEl.fadeOut,
9096
- fadeType: clipEl.fadeType,
9097
- midiNotes: clipEl.midiNotes,
9098
- midiChannel: clipEl.midiChannel,
9099
- midiProgram: clipEl.midiProgram
9100
- });
9101
- }
9262
+ for (const clipEl of clipEls) clips.push(this._readClipDescriptor(clipEl));
9102
9263
  }
9103
9264
  return {
9104
9265
  name: trackEl.name || "Untitled",
@@ -9108,228 +9269,312 @@ var DawEditorElement = class extends import_lit19.LitElement {
9108
9269
  clips
9109
9270
  };
9110
9271
  }
9272
+ _readClipDescriptor(clipEl) {
9273
+ return {
9274
+ kind: "dom",
9275
+ clipId: clipEl.clipId,
9276
+ src: clipEl.src,
9277
+ peaksSrc: clipEl.peaksSrc,
9278
+ start: clipEl.start,
9279
+ duration: clipEl.duration,
9280
+ offset: clipEl.offset,
9281
+ gain: clipEl.gain,
9282
+ name: clipEl.name,
9283
+ fadeIn: clipEl.fadeIn,
9284
+ fadeOut: clipEl.fadeOut,
9285
+ fadeType: clipEl.fadeType,
9286
+ midiNotes: clipEl.midiNotes,
9287
+ midiChannel: clipEl.midiChannel,
9288
+ midiProgram: clipEl.midiProgram
9289
+ };
9290
+ }
9291
+ // --- Entering the arrangement (#848) ---
9292
+ _isEntered(trackId) {
9293
+ return this._arrangement.getTracks().some((t) => t.id === trackId);
9294
+ }
9295
+ /** Queue a registered track for the next flush. */
9296
+ _queueEntry(trackId) {
9297
+ if (!this._entryQueue.includes(trackId)) this._entryQueue = [...this._entryQueue, trackId];
9298
+ if (this._entryFlushScheduled) return;
9299
+ this._entryFlushScheduled = true;
9300
+ queueMicrotask(() => {
9301
+ this._entryFlushScheduled = false;
9302
+ this._flushTrackEntries();
9303
+ });
9304
+ }
9111
9305
  /**
9112
- * The error for a clip whose kind is not its track's (#756), or null. A clip
9113
- * with no `src` is a MIDI clip (see _isMidiDescriptor).
9306
+ * Enter the queued tracks into the arrangement, in DOM order. Without an
9307
+ * engine they wait (the sample rate of a MIDI clip comes from the
9308
+ * adapter); the engine's build flushes again. The page's tracks entering
9309
+ * while the arrangement has no history are not undo steps: the history is
9310
+ * cleared after them, so Undo right after load removes nothing (and the
9311
+ * next page track finds it empty again).
9114
9312
  */
9115
- _clipKindError(trackName, kind, clipIsMidi, clipLabel) {
9116
- if (clipIsMidi === (kind === "midi")) return null;
9117
- return new Error(
9118
- 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.'
9313
+ _flushTrackEntries() {
9314
+ if (this._entryQueue.length === 0) return;
9315
+ if (!this._engine) return;
9316
+ if (this._dragInProgress) {
9317
+ this._flushAfterDrag();
9318
+ return;
9319
+ }
9320
+ const queued = this._entryQueue;
9321
+ this._entryQueue = [];
9322
+ const domOrder = [...this.querySelectorAll("daw-track")].map(
9323
+ (el) => el.trackId
9119
9324
  );
9325
+ const position = (id) => {
9326
+ const at = domOrder.indexOf(id);
9327
+ return at === -1 ? domOrder.length : at;
9328
+ };
9329
+ const ordered = [...queued].sort((a, b) => position(a) - position(b));
9330
+ const isPageTrack = (id) => {
9331
+ const el = this._trackElements.get(id);
9332
+ return el !== void 0 && !this._editorMadeTracks.has(el);
9333
+ };
9334
+ const arrangement = this._arrangement;
9335
+ const historyWasEmpty = !arrangement.canUndo && !arrangement.canRedo && !this._dragInProgress;
9336
+ let pageEntered = false;
9337
+ for (const id of ordered.filter(isPageTrack)) {
9338
+ if (this._enterTrack(id)) pageEntered = true;
9339
+ }
9340
+ if (historyWasEmpty && pageEntered) arrangement.clearHistory();
9341
+ for (const id of ordered.filter((id2) => !isPageTrack(id2))) this._enterTrack(id);
9342
+ }
9343
+ /** Flush the queue once the drag in progress has ended (its pointer or key is released). */
9344
+ _flushAfterDrag() {
9345
+ if (this._waitingForDragEnd) return;
9346
+ this._waitingForDragEnd = true;
9347
+ const events = ["pointerup", "pointercancel", "keyup"];
9348
+ const retry = () => {
9349
+ for (const type of events) window.removeEventListener(type, retry);
9350
+ this._waitingForDragEnd = false;
9351
+ setTimeout(() => this._flushTrackEntries(), 0);
9352
+ };
9353
+ for (const type of events) window.addEventListener(type, retry);
9120
9354
  }
9121
- // --- Audio Loading ---
9122
- async _loadTrack(trackId, descriptor) {
9123
- this._loadingTracks.add(trackId);
9124
- const sppAtLoadStart = this._samplesPerPixel;
9125
- try {
9126
- const clips = [];
9127
- let refusedMidiClips = 0;
9128
- for (const clipDesc of descriptor.clips) {
9129
- const clipIsMidi = this._isMidiDescriptor(clipDesc);
9130
- const kindError = this._clipKindError(
9131
- descriptor.name,
9132
- descriptor.kind,
9133
- clipIsMidi,
9134
- clipDesc.name || clipDesc.src || (isDomClip(clipDesc) ? clipDesc.clipId : "")
9135
- );
9136
- if (kindError) {
9137
- console.warn("[dawcore] _loadTrack: " + kindError.message);
9138
- if (this.isConnected) {
9139
- this.dispatchEvent(
9140
- new CustomEvent("daw-clip-error", {
9141
- bubbles: true,
9142
- composed: true,
9143
- detail: {
9144
- trackId,
9145
- clipId: isDomClip(clipDesc) ? clipDesc.clipId : "",
9146
- error: kindError
9147
- }
9148
- })
9149
- );
9150
- }
9151
- if (clipIsMidi) refusedMidiClips++;
9152
- continue;
9153
- }
9154
- if (clipIsMidi) {
9155
- clips.push(this._buildMidiClip(clipDesc));
9156
- continue;
9157
- }
9158
- try {
9159
- const waveformDataPromise = clipDesc.peaksSrc ? this._resolvePeaks(clipDesc.peaksSrc) : Promise.resolve(null);
9160
- const audioPromise = this._fetchAndDecode(clipDesc.src);
9161
- const waveformData = await waveformDataPromise;
9162
- if (waveformData) {
9163
- const wdRate = waveformData.sample_rate;
9164
- const clip2 = (0, import_core17.createClip)({
9165
- waveformData,
9166
- startSample: Math.round(clipDesc.start * wdRate),
9167
- durationSamples: Math.round((clipDesc.duration || waveformData.duration) * wdRate),
9168
- offsetSamples: Math.round(clipDesc.offset * wdRate),
9169
- gain: clipDesc.gain,
9170
- name: clipDesc.name,
9171
- sampleRate: wdRate,
9172
- sourceDurationSamples: Math.ceil(waveformData.duration * wdRate)
9173
- });
9174
- if (isDomClip(clipDesc)) clip2.id = clipDesc.clipId;
9175
- const effectiveScale = Math.max(this._renderSpp, waveformData.scale);
9176
- const peakData = extractPeaks(
9177
- waveformData,
9178
- effectiveScale,
9179
- this.mono,
9180
- clip2.offsetSamples,
9181
- clip2.durationSamples
9182
- );
9183
- this._clipOffsets.set(clip2.id, {
9184
- offsetSamples: clip2.offsetSamples,
9185
- durationSamples: clip2.durationSamples
9186
- });
9187
- this._peaksData = new Map(this._peaksData).set(clip2.id, peakData);
9188
- this._raiseZoomFloor(waveformData.scale);
9189
- if (this._tracks.has(trackId)) {
9190
- const previewTrack = (0, import_core17.createTrack)({
9191
- name: descriptor.name,
9192
- kind: descriptor.kind,
9193
- clips: [clip2],
9194
- ...this._mixOf(trackId)
9195
- });
9196
- previewTrack.id = trackId;
9197
- this._engineTracks = new Map(this._engineTracks).set(trackId, previewTrack);
9198
- this._recomputeDuration();
9199
- }
9200
- let audioBuffer2;
9201
- try {
9202
- audioBuffer2 = await audioPromise;
9203
- } catch (audioErr) {
9204
- const nextPeaks = new Map(this._peaksData);
9205
- nextPeaks.delete(clip2.id);
9206
- this._peaksData = nextPeaks;
9207
- this._clipOffsets.delete(clip2.id);
9208
- const nextEngine = new Map(this._engineTracks);
9209
- nextEngine.delete(trackId);
9210
- this._engineTracks = nextEngine;
9211
- this._recomputeZoomFloor();
9212
- this._recomputeDuration();
9213
- throw audioErr;
9214
- }
9215
- this._resolvedSampleRate = audioBuffer2.sampleRate;
9216
- const updatedClip = { ...clip2, audioBuffer: audioBuffer2 };
9217
- this._clipBuffers = new Map(this._clipBuffers).set(clip2.id, audioBuffer2);
9218
- this._peakPipeline.cacheWaveformData(audioBuffer2, waveformData);
9219
- clips.push(updatedClip);
9220
- continue;
9221
- }
9222
- const audioBuffer = await audioPromise;
9223
- this._resolvedSampleRate = audioBuffer.sampleRate;
9224
- const clip = await this._finalizeAudioClip(clipDesc, audioBuffer, null);
9225
- clips.push(clip);
9226
- } catch (clipErr) {
9227
- console.warn(
9228
- '[dawcore] _loadTrack: clip "' + clipDesc.src + '" failed: ' + String(clipErr)
9229
- );
9230
- if (this.isConnected) {
9231
- this.dispatchEvent(
9232
- new CustomEvent("daw-clip-error", {
9233
- bubbles: true,
9234
- composed: true,
9235
- detail: {
9236
- trackId,
9237
- clipId: isDomClip(clipDesc) ? clipDesc.clipId : "",
9238
- error: clipErr
9239
- }
9240
- })
9241
- );
9242
- }
9243
- }
9244
- }
9245
- const trackWasRemoved = !this._tracks.has(trackId);
9246
- if (trackWasRemoved || !this.isConnected) {
9247
- for (const clip of clips) {
9248
- this._purgeClipCaches(clip.id);
9249
- }
9250
- if (this._engineTracks.has(trackId)) {
9251
- const nextEngine = new Map(this._engineTracks);
9252
- nextEngine.delete(trackId);
9253
- this._engineTracks = nextEngine;
9254
- this._recomputeDuration();
9255
- }
9256
- this._recomputeZoomFloor();
9257
- if (this._samplesPerPixel !== sppAtLoadStart && sppAtLoadStart >= this._minSamplesPerPixel) {
9258
- this.samplesPerPixel = sppAtLoadStart;
9259
- }
9260
- throw new TrackLoadCancelledError(
9261
- trackWasRemoved ? 'track "' + trackId + '" was removed while loading' : 'editor was disconnected while track "' + trackId + '" was loading',
9262
- trackWasRemoved ? "removed" : "disconnected"
9263
- );
9264
- }
9265
- const track = (0, import_core17.createTrack)({
9266
- name: descriptor.name,
9267
- kind: descriptor.kind,
9268
- clips,
9269
- ...this._mixOf(trackId)
9270
- });
9271
- const requestedClips = descriptor.clips.filter((c) => c.src).length + refusedMidiClips;
9272
- if (requestedClips > 0 && clips.length === 0) {
9273
- throw new Error(
9274
- "all " + requestedClips + " clip(s) failed to load \u2014 see prior daw-clip-error events"
9275
- );
9276
- }
9277
- track.id = trackId;
9278
- this._engineTracks = new Map(this._engineTracks).set(trackId, track);
9279
- this._recomputeDuration();
9280
- for (const c of clips) {
9281
- this._maybeRegisterSpectrogramClipAudio(trackId, c);
9282
- }
9283
- const engine = await this._ensureEngine();
9284
- engine.setTracks(this._tracksForEngine());
9355
+ /** Enter one registered track. False when it is gone, already in, or refused. */
9356
+ _enterTrack(trackId) {
9357
+ const descriptor = this._tracks.get(trackId);
9358
+ if (!descriptor || this._isEntered(trackId)) return false;
9359
+ const el = this._trackElements.get(trackId);
9360
+ const built = buildArrangementTrack(
9361
+ trackId,
9362
+ descriptor,
9363
+ el ? mixOfElement(el) : DEFAULT_TRACK_MIX,
9364
+ this.effectiveSampleRate
9365
+ );
9366
+ if (built.descriptor !== descriptor) {
9367
+ this._tracks = new Map(this._tracks).set(trackId, built.descriptor);
9368
+ }
9369
+ for (const { clipId, error } of built.refused) {
9370
+ console.warn("[dawcore] " + error.message);
9285
9371
  this.dispatchEvent(
9286
- new CustomEvent("daw-track-ready", {
9372
+ new CustomEvent("daw-clip-error", {
9287
9373
  bubbles: true,
9288
9374
  composed: true,
9289
- detail: { trackId }
9375
+ detail: { trackId, clipId, error }
9290
9376
  })
9291
9377
  );
9378
+ }
9379
+ const index = el ? entryIndex(
9380
+ [...this.querySelectorAll("daw-track")],
9381
+ trackId,
9382
+ this._arrangement.getTracks().map((t) => t.id)
9383
+ ) : void 0;
9384
+ this._announcer.expect(trackId, built.refused.length);
9385
+ for (const clip of built.track.clips) {
9386
+ if ((0, import_core19.isLoadingClip)(clip)) this._announcer.expectClip(clip.id);
9387
+ }
9388
+ try {
9389
+ this._arrangement.addTrack(built.track, index === void 0 ? void 0 : { index });
9292
9390
  } catch (err) {
9293
- const cancelled = err instanceof TrackLoadCancelledError;
9294
- console.warn(
9295
- cancelled ? "[dawcore] Track load cancelled: " + err.message : '[dawcore] Failed to load track "' + trackId + '": ' + String(err)
9296
- );
9391
+ console.warn('[dawcore] Failed to add track "' + trackId + '": ' + String(err));
9392
+ this._settleEntry(trackId, err instanceof Error ? err : new Error(String(err)));
9297
9393
  this.dispatchEvent(
9298
9394
  new CustomEvent("daw-track-error", {
9299
9395
  bubbles: true,
9300
9396
  composed: true,
9301
- detail: {
9302
- trackId,
9303
- error: err,
9304
- ...cancelled ? { reason: err.reason } : {}
9305
- }
9397
+ detail: { trackId, error: err }
9306
9398
  })
9307
9399
  );
9308
- } finally {
9309
- this._loadingTracks.delete(trackId);
9310
- }
9311
- }
9312
- async _fetchAndDecode(src) {
9313
- if (this._audioCache.has(src)) {
9314
- return this._audioCache.get(src);
9400
+ return false;
9315
9401
  }
9316
- const promise = (async () => {
9317
- const response = await fetch(src);
9318
- if (!response.ok) {
9319
- throw new Error(
9320
- 'Failed to fetch audio "' + src + '": ' + response.status + " " + response.statusText
9321
- );
9402
+ this._settleEntry(trackId, null);
9403
+ for (const clipDesc of built.descriptor.clips) {
9404
+ if (clipDesc.peaksSrc && clipDesc.clipId && clipSourceOf(clipDesc)) {
9405
+ this._requestPreview(clipDesc.clipId, clipDesc.peaksSrc);
9322
9406
  }
9323
- const arrayBuffer = await response.arrayBuffer();
9324
- return this.audioContext.decodeAudioData(arrayBuffer);
9325
- })();
9326
- this._audioCache.set(src, promise);
9327
- try {
9328
- return await promise;
9329
- } catch (err) {
9330
- this._audioCache.delete(src);
9331
- throw err;
9332
9407
  }
9408
+ return true;
9409
+ }
9410
+ /**
9411
+ * The `<daw-track src>` shorthand changed its src: the entered track gets a
9412
+ * new loading clip for it, one undo step. A track whose clips are
9413
+ * `<daw-clip>` children keeps them. A track still queued reads the new
9414
+ * descriptor when it enters.
9415
+ */
9416
+ _replaceShorthandClips(trackId, descriptor) {
9417
+ if (!this._isEntered(trackId) || descriptor.clips.some(isDomClip)) return;
9418
+ const built = buildArrangementTrack(
9419
+ trackId,
9420
+ descriptor,
9421
+ DEFAULT_TRACK_MIX,
9422
+ this.effectiveSampleRate
9423
+ );
9424
+ this._tracks = new Map(this._tracks).set(trackId, built.descriptor);
9425
+ this._arrangement.updateTrack(trackId, (current) => ({ ...current, clips: built.track.clips }));
9426
+ }
9427
+ /** Run the load announcements over the arrangement's current state. */
9428
+ _announceLoading() {
9429
+ this._announcer.update(
9430
+ this._arrangement.getTracks(),
9431
+ this._arrangement.sources.getSnapshot().sources
9432
+ );
9433
+ }
9434
+ /**
9435
+ * Fetch a loading clip's `.dat` peaks and draw them until its audio
9436
+ * arrives (an editor-only cache, not the arrangement: writing the clip
9437
+ * after it entered would be an undo step).
9438
+ */
9439
+ async _requestPreview(clipId, peaksSrc) {
9440
+ const waveformData = await this._resolvePeaks(peaksSrc);
9441
+ if (!waveformData) return;
9442
+ const clip = this._arrangement.getTracks().flatMap((t) => t.clips).find((c) => c.id === clipId);
9443
+ if (!clip || !(0, import_core19.isLoadingClip)(clip)) return;
9444
+ const rate = waveformData.sample_rate;
9445
+ const offset = clip.offset ?? 0;
9446
+ const seconds = clip.duration ?? Math.max(0, waveformData.duration - offset);
9447
+ const peakData = extractPeaks(
9448
+ waveformData,
9449
+ Math.max(this._renderSpp, waveformData.scale),
9450
+ this.mono,
9451
+ Math.round(offset * rate),
9452
+ Math.round(seconds * rate)
9453
+ );
9454
+ this._previewPeaks = new Map(this._previewPeaks).set(clipId, peakData);
9455
+ this._previewWaveforms.set(clipId, waveformData);
9456
+ this._raiseZoomFloor(waveformData.scale);
9457
+ this._recomputeDuration();
9458
+ }
9459
+ /** The peak sync made a clip's peaks: its zoom floor holds, its preview goes. */
9460
+ _clipPeaksReady(clipId, audioBuffer) {
9461
+ this._raiseZoomFloor(this._peakPipeline.getCachedScale(audioBuffer));
9462
+ if (!this._previewPeaks.has(clipId)) return;
9463
+ const next = new Map(this._previewPeaks);
9464
+ next.delete(clipId);
9465
+ this._previewPeaks = next;
9466
+ }
9467
+ _waitForEntry(trackId) {
9468
+ return new Promise((resolve, reject) => {
9469
+ this._entryWaiters.set(trackId, { resolve, reject });
9470
+ });
9471
+ }
9472
+ /** Settle the wait for a track's entry: entered (`null`), or refused or gone. */
9473
+ _settleEntry(trackId, error) {
9474
+ const waiter = this._entryWaiters.get(trackId);
9475
+ if (!waiter) return;
9476
+ this._entryWaiters.delete(trackId);
9477
+ if (error) waiter.reject(error);
9478
+ else waiter.resolve(trackId);
9479
+ }
9480
+ /**
9481
+ * A dropped file as a track with no element (a File cannot be an attribute):
9482
+ * one loading clip whose source is the file. Resolves with the track id once
9483
+ * it has entered, an undo step like any track an editor method adds.
9484
+ */
9485
+ _addDroppedFile(file) {
9486
+ const trackId = crypto.randomUUID();
9487
+ const name = file.name.replace(/\.\w+$/, "");
9488
+ this._tracks = new Map(this._tracks).set(trackId, {
9489
+ name,
9490
+ src: "",
9491
+ kind: "audio",
9492
+ renderMode: trackDescriptorRenderMode("audio", "waveform"),
9493
+ clips: [
9494
+ {
9495
+ kind: "drop",
9496
+ file,
9497
+ src: "",
9498
+ peaksSrc: "",
9499
+ start: 0,
9500
+ duration: 0,
9501
+ offset: 0,
9502
+ gain: 1,
9503
+ name,
9504
+ fadeIn: 0,
9505
+ fadeOut: 0,
9506
+ fadeType: "linear",
9507
+ midiNotes: null,
9508
+ midiChannel: null,
9509
+ midiProgram: null
9510
+ }
9511
+ ]
9512
+ });
9513
+ const entered = this._waitForEntry(trackId);
9514
+ this._queueEntry(trackId);
9515
+ return entered;
9516
+ }
9517
+ /**
9518
+ * Take a track out for good: no undo step, and no undo or redo brings it
9519
+ * back (a dropped file that could not be loaded was never a declaration).
9520
+ */
9521
+ _discardTrack(trackId) {
9522
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9523
+ this._announcer.forget(trackId, track?.clips.map((c) => c.id) ?? []);
9524
+ this._arrangement.removeTrack(trackId, { undoable: false });
9525
+ this._onTrackRemoved(trackId);
9526
+ }
9527
+ /**
9528
+ * Resolves once the track has loaded (`daw-track-ready`), or when the
9529
+ * editor is disconnected meanwhile (the track is kept and loads after a
9530
+ * reparent); rejects when its audio failed (`daw-track-error`).
9531
+ */
9532
+ _whenTrackLoaded(trackId) {
9533
+ const state9 = this._announcer.stateOf(trackId);
9534
+ if (state9 === "ready") return Promise.resolve();
9535
+ if (state9 === "failed") return Promise.reject(this._announcer.errorOf(trackId));
9536
+ return new Promise((resolve, reject) => {
9537
+ const cleanup = () => {
9538
+ this.removeEventListener("daw-track-ready", onReady);
9539
+ this.removeEventListener("daw-track-error", onError);
9540
+ this._loadWaitEnds.delete(end);
9541
+ };
9542
+ const onReady = (e) => {
9543
+ if (e.detail.trackId !== trackId) return;
9544
+ cleanup();
9545
+ resolve();
9546
+ };
9547
+ const onError = (e) => {
9548
+ const detail = e.detail;
9549
+ if (detail.trackId !== trackId) return;
9550
+ cleanup();
9551
+ reject(detail.error instanceof Error ? detail.error : new Error(String(detail.error)));
9552
+ };
9553
+ const end = () => {
9554
+ cleanup();
9555
+ resolve();
9556
+ };
9557
+ this.addEventListener("daw-track-ready", onReady);
9558
+ this.addEventListener("daw-track-error", onError);
9559
+ this._loadWaitEnds.add(end);
9560
+ });
9561
+ }
9562
+ /**
9563
+ * Load again every failed source the track's clips name (#848). A track
9564
+ * whose audio failed stays in the editor, like a broken `<img>`;
9565
+ * `daw-track-ready` follows when it loads.
9566
+ */
9567
+ retryTrack(trackId) {
9568
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9569
+ if (!track) {
9570
+ console.warn('[dawcore] retryTrack: no track found for id "' + trackId + '"');
9571
+ return;
9572
+ }
9573
+ const sources = this._arrangement.sources.getSnapshot().sources;
9574
+ const failed = new Set(
9575
+ track.clips.filter(import_core19.isLoadingClip).map((clip) => clip.src).filter((src) => sources.get(src)?.status === "failed")
9576
+ );
9577
+ for (const src of failed) this._arrangement.retry(src);
9333
9578
  }
9334
9579
  _fetchPeaks(src) {
9335
9580
  const cached = this._peaksCache.get(src);
@@ -9341,7 +9586,13 @@ var DawEditorElement = class extends import_lit19.LitElement {
9341
9586
  this._peaksCache.set(src, promise);
9342
9587
  return promise;
9343
9588
  }
9589
+ /**
9590
+ * The timeline's duration, the one writer of `_duration`: the loaded clips,
9591
+ * and the clips still loading whose length is known (a duration, or `.dat`
9592
+ * peaks), so the timeline is as wide as what is drawn (#848).
9593
+ */
9344
9594
  _recomputeDuration() {
9595
+ const sr = this.effectiveSampleRate;
9345
9596
  let maxSample = 0;
9346
9597
  for (const track of this._engineTracks.values()) {
9347
9598
  for (const clip of track.clips) {
@@ -9349,28 +9600,60 @@ var DawEditorElement = class extends import_lit19.LitElement {
9349
9600
  if (endSample > maxSample) maxSample = endSample;
9350
9601
  }
9351
9602
  }
9352
- this._duration = maxSample / this.effectiveSampleRate;
9603
+ for (const track of this._arrangement.getTracks()) {
9604
+ for (const clip of track.clips) {
9605
+ if (!(0, import_core19.isLoadingClip)(clip)) continue;
9606
+ const seconds = this._placeholderSeconds(clip);
9607
+ if (seconds === null) continue;
9608
+ maxSample = Math.max(maxSample, Math.round(((clip.start ?? 0) + seconds) * sr));
9609
+ }
9610
+ }
9611
+ this._duration = maxSample / sr;
9612
+ }
9613
+ /** How long a loading clip is drawn: its duration, else what its `.dat` peaks cover; null when unknown. */
9614
+ _placeholderSeconds(clip) {
9615
+ if (clip.duration != null && clip.duration > 0) return clip.duration;
9616
+ const waveformData = this._previewWaveforms.get(clip.id);
9617
+ if (!waveformData) return null;
9618
+ const seconds = waveformData.duration - (clip.offset ?? 0);
9619
+ return seconds > 0 ? seconds : null;
9353
9620
  }
9354
9621
  // --- Engine ---
9622
+ /**
9623
+ * The engine, built now when the editor is connected with an adapter.
9624
+ * Rejects without an adapter, and on a detached editor (an engine built
9625
+ * there would hold the adapter's graph with nothing to dispose it).
9626
+ */
9355
9627
  _ensureEngine() {
9356
9628
  if (this._engine) return Promise.resolve(this._engine);
9357
- if (this._enginePromise) return this._enginePromise;
9358
- this._enginePromise = this._buildEngine().catch((err) => {
9359
- this._enginePromise = null;
9360
- throw err;
9361
- });
9362
- return this._enginePromise;
9629
+ try {
9630
+ if (!this.isConnected && this._externalAdapter) {
9631
+ throw new Error("[dawcore] <daw-editor> is not connected: no engine is built for it.");
9632
+ }
9633
+ return Promise.resolve(this._buildEngine());
9634
+ } catch (err) {
9635
+ return Promise.reject(err);
9636
+ }
9637
+ }
9638
+ /** Build the engine from the adapter setter or a connect: a failure is reported, not thrown. */
9639
+ _buildEngineReporting() {
9640
+ try {
9641
+ this._buildEngine();
9642
+ } catch (err) {
9643
+ console.warn("[dawcore] Failed to build the engine: " + String(err));
9644
+ this.dispatchEvent(
9645
+ new CustomEvent("daw-error", {
9646
+ bubbles: true,
9647
+ composed: true,
9648
+ detail: { operation: "engine", error: err }
9649
+ })
9650
+ );
9651
+ }
9363
9652
  }
9364
- async _buildEngine() {
9653
+ _buildEngine() {
9365
9654
  if (!this._externalAdapter) {
9366
9655
  throw new Error(noAdapterError());
9367
9656
  }
9368
- if (this._adapterConsumedByDispose) {
9369
- throw new Error(
9370
- "[dawcore] editor.adapter was disposed by a previous disconnect \u2014 set a fresh PlayoutAdapter after reparenting <daw-editor>."
9371
- );
9372
- }
9373
- const { PlaylistEngine } = await import("@waveform-playlist/engine");
9374
9657
  const adapter = this._externalAdapter;
9375
9658
  if (!this._hasTickCallbacks) {
9376
9659
  if (adapter.setTempo) {
@@ -9383,65 +9666,94 @@ var DawEditorElement = class extends import_lit19.LitElement {
9383
9666
  }
9384
9667
  adapter.setPpqn?.(this._ppqn);
9385
9668
  this.ppqn = adapter.ppqn;
9386
- const engine = new PlaylistEngine({
9669
+ const engine = new import_engine.PlaylistEngine({
9387
9670
  adapter,
9388
- sampleRate: this.effectiveSampleRate,
9671
+ arrangement: this._arrangement,
9672
+ sampleRate: adapter.audioContext.sampleRate,
9389
9673
  samplesPerPixel: this.samplesPerPixel,
9390
9674
  bpm: this._bpm,
9391
9675
  zoomLevels: [256, 512, 1024, 2048, 4096, 8192, this.samplesPerPixel].filter((v, i, a) => a.indexOf(v) === i).sort((a, b) => a - b)
9392
9676
  });
9393
- let lastTracksVersion = -1;
9394
- let lastMixerVersion = -1;
9395
- engine.on("statechange", (engineState) => {
9396
- this._isPlaying = engineState.isPlaying;
9397
- this._duration = engineState.duration;
9398
- this._selectedTrackId = engineState.selectedTrackId;
9399
- const structuralChange = engineState.tracksVersion !== lastTracksVersion;
9400
- const mixerChange = engineState.mixerVersion !== lastMixerVersion;
9401
- if (structuralChange || mixerChange) {
9402
- lastTracksVersion = engineState.tracksVersion;
9403
- lastMixerVersion = engineState.mixerVersion;
9404
- const nextTracks = /* @__PURE__ */ new Map();
9405
- for (const track of engineState.tracks) {
9406
- nextTracks.set(track.id, track);
9407
- }
9408
- this._engineTracks = nextTracks;
9409
- this._deleteSeedMix(nextTracks.keys());
9410
- this._reconcileDescriptorsWithEngineTracks(engineState.tracks);
9411
- }
9412
- if (structuralChange) {
9413
- if (!this._inOrderSync) {
9414
- this._syncDomToEngineOrder(engineState.tracks);
9415
- }
9416
- this._effectsManager?.rewireTrackChains();
9417
- const audioTracks = engineState.tracks.filter((t) => (0, import_core17.trackKind)(t) !== "midi");
9418
- syncPeaksForChangedClips(this, audioTracks);
9419
- }
9420
- if (engineState.bpm !== this._lastAnnotationBpm) {
9421
- this._lastAnnotationBpm = engineState.bpm;
9422
- this._annotations.deriveSecondsCaches();
9423
- }
9424
- });
9677
+ this._lastTracksVersion = -1;
9678
+ this._lastMixerVersion = -1;
9679
+ engine.on("statechange", (engineState) => this._onEngineState(engineState));
9425
9680
  engine.on("pause", () => {
9426
9681
  this._currentTime = engine.getCurrentTime();
9427
9682
  });
9428
- engine.on("stop", () => {
9429
- this._currentTime = engine.getCurrentTime();
9430
- this._stopPlayhead();
9431
- this._activePlayEndTime = null;
9432
- if (!this._inConsumerStop && !this._inSeekTransition && this.isConnected) {
9433
- this.dispatchEvent(new CustomEvent("daw-stop", { bubbles: true, composed: true }));
9434
- }
9435
- });
9683
+ engine.on("stop", () => this._onEngineStop(engine));
9436
9684
  this._engine = engine;
9685
+ this._onEngineState(engine.getState());
9686
+ for (const track of this._engineTracks.values()) {
9687
+ for (const clip of track.clips) this._maybeRegisterSpectrogramClipAudio(track.id, clip);
9688
+ }
9689
+ this._flushTrackEntries();
9437
9690
  return engine;
9438
9691
  }
9692
+ /**
9693
+ * Clips whose audio has just arrived: a `.dat` preview's data goes to the
9694
+ * peak pipeline (no worker run), a spectrogram track gets the audio. The
9695
+ * peak sync then makes their peaks.
9696
+ */
9697
+ _adoptLoadedClips(tracks) {
9698
+ for (const track of tracks) {
9699
+ for (const clip of track.clips) {
9700
+ const waveformData = this._previewWaveforms.get(clip.id);
9701
+ if (waveformData && clip.audioBuffer) {
9702
+ if (waveformData.sample_rate === clip.audioBuffer.sampleRate) {
9703
+ this._peakPipeline.cacheWaveformData(clip.audioBuffer, waveformData);
9704
+ }
9705
+ this._previewWaveforms.delete(clip.id);
9706
+ }
9707
+ if (!this._clipBuffers.has(clip.id))
9708
+ this._maybeRegisterSpectrogramClipAudio(track.id, clip);
9709
+ }
9710
+ }
9711
+ }
9712
+ /** The engine's state changed: follow it (the one writer of `_engineTracks`). */
9713
+ _onEngineState(engineState) {
9714
+ this._isPlaying = engineState.isPlaying;
9715
+ this._selectedTrackId = engineState.selectedTrackId;
9716
+ const structuralChange = engineState.tracksVersion !== this._lastTracksVersion;
9717
+ const mixerChange = engineState.mixerVersion !== this._lastMixerVersion;
9718
+ if (structuralChange || mixerChange) {
9719
+ this._lastTracksVersion = engineState.tracksVersion;
9720
+ this._lastMixerVersion = engineState.mixerVersion;
9721
+ const nextTracks = /* @__PURE__ */ new Map();
9722
+ for (const track of engineState.tracks) {
9723
+ nextTracks.set(track.id, track);
9724
+ }
9725
+ this._engineTracks = nextTracks;
9726
+ this._reconcileDescriptorsWithEngineTracks(engineState.tracks);
9727
+ }
9728
+ if (structuralChange) {
9729
+ this._recomputeDuration();
9730
+ if (!this._inOrderSync) {
9731
+ this._syncDomToEngineOrder(engineState.tracks);
9732
+ }
9733
+ this._effectsManager?.rewireTrackChains();
9734
+ const audioTracks = engineState.tracks.filter((t) => (0, import_core19.trackKind)(t) !== "midi");
9735
+ this._adoptLoadedClips(audioTracks);
9736
+ syncPeaksForChangedClips(this, audioTracks);
9737
+ this._announceLoading();
9738
+ }
9739
+ if (engineState.bpm !== this._lastAnnotationBpm) {
9740
+ this._lastAnnotationBpm = engineState.bpm;
9741
+ this._annotations.deriveSecondsCaches();
9742
+ }
9743
+ }
9744
+ _onEngineStop(engine) {
9745
+ this._currentTime = engine.getCurrentTime();
9746
+ this._stopPlayhead();
9747
+ this._activePlayEndTime = null;
9748
+ if (!this._inConsumerStop && !this._inSeekTransition && this.isConnected) {
9749
+ this.dispatchEvent(new CustomEvent("daw-stop", { bubbles: true, composed: true }));
9750
+ }
9751
+ }
9439
9752
  _disposeEngine() {
9440
9753
  if (this._engine) {
9441
9754
  this._engine.dispose();
9442
9755
  this._engine = null;
9443
9756
  }
9444
- this._enginePromise = null;
9445
9757
  }
9446
9758
  async loadFiles(files) {
9447
9759
  return loadFiles(this, files);
@@ -9472,43 +9784,17 @@ var DawEditorElement = class extends import_lit19.LitElement {
9472
9784
  return this._ensureEngine();
9473
9785
  }
9474
9786
  /**
9475
- * Wait for either `readyEvent` or `errorEvent` to fire on this editor for
9476
- * the entity matching `matchesId`. Listeners are wired synchronously, then
9477
- * `setup` is called (typical: appendChild). Resolves with `resolveValue`
9478
- * on ready; rejects with a normalized Error on error. Used by addTrack and
9479
- * addClip to share their Promise-with-listener-cleanup machinery.
9480
- */
9481
- _awaitId(readyEvent, errorEvent, matchesId, resolveValue, setup) {
9482
- return new Promise((resolve, reject) => {
9483
- const onReady = (e) => {
9484
- if (!matchesId(e.detail)) return;
9485
- cleanup();
9486
- resolve(resolveValue);
9487
- };
9488
- const onError = (e) => {
9489
- const detail = e.detail;
9490
- if (!matchesId(e.detail)) return;
9491
- cleanup();
9492
- const err = detail.error;
9493
- reject(err instanceof Error ? err : new Error(String(err)));
9494
- };
9495
- const cleanup = () => {
9496
- this.removeEventListener(readyEvent, onReady);
9497
- this.removeEventListener(errorEvent, onError);
9498
- };
9499
- this.addEventListener(readyEvent, onReady);
9500
- this.addEventListener(errorEvent, onError);
9501
- setup();
9502
- });
9503
- }
9504
- /**
9505
- * Append a `<daw-track>` element built from `config` and resolve once the
9506
- * track finishes loading (or reject on `daw-track-error`). Goes through
9507
- * the same `_loadTrack` pipeline as declarative tracks, so descriptors,
9508
- * peaks, and clip buffers are populated correctly.
9787
+ * Append a `<daw-track>` element built from `config` and resolve with its
9788
+ * track id once the track has entered the arrangement (#848), before its
9789
+ * audio has loaded. To follow loading, add the `daw-track-ready` /
9790
+ * `daw-track-error` listener BEFORE calling: for a track with nothing to
9791
+ * fetch, or whose audio is already loaded, it fires before this resolves.
9792
+ * Without `editor.adapter` it waits for one. Rejects when the track is
9793
+ * refused by the arrangement or removed before it enters.
9509
9794
  */
9510
9795
  addTrack(config = {}) {
9511
9796
  const trackEl = document.createElement("daw-track");
9797
+ this._editorMadeTracks.add(trackEl);
9512
9798
  if (config.name !== void 0) trackEl.setAttribute("name", config.name);
9513
9799
  if (config.volume !== void 0) trackEl.volume = config.volume;
9514
9800
  if (config.pan !== void 0) trackEl.pan = config.pan;
@@ -9528,13 +9814,9 @@ var DawEditorElement = class extends import_lit19.LitElement {
9528
9814
  for (const clipConfig of clipConfigs) {
9529
9815
  trackEl.appendChild(this._buildClipElement(clipConfig));
9530
9816
  }
9531
- return this._awaitId(
9532
- "daw-track-ready",
9533
- "daw-track-error",
9534
- (d) => d.trackId === trackEl.trackId,
9535
- trackEl,
9536
- () => this.appendChild(trackEl)
9537
- );
9817
+ const entered = this._waitForEntry(trackEl.trackId);
9818
+ this.appendChild(trackEl);
9819
+ return entered;
9538
9820
  }
9539
9821
  /**
9540
9822
  * Remove a track by id. Equivalent to `trackElement.remove()` —
@@ -9545,7 +9827,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
9545
9827
  const trackEl = this._trackElements.get(trackId);
9546
9828
  if (trackEl) {
9547
9829
  trackEl.remove();
9548
- } else if (this._engineTracks.has(trackId)) {
9830
+ if (!this.isConnected) this._onTrackRemoved(trackId);
9831
+ } else if (this._tracks.has(trackId) || this._isEntered(trackId)) {
9549
9832
  this._onTrackRemoved(trackId);
9550
9833
  } else {
9551
9834
  console.warn('[dawcore] removeTrack: no track found for id "' + trackId + '"');
@@ -9572,8 +9855,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
9572
9855
  const anchor = els[clamped];
9573
9856
  if (clamped > from) anchor.after(el);
9574
9857
  else anchor.before(el);
9575
- } else if (this._engineTracks.has(trackId)) {
9576
- this._engine.reorderTrack(trackId, toIndex);
9858
+ } else if (this._isEntered(trackId)) {
9859
+ this._arrangement.reorderTrack(trackId, toIndex);
9577
9860
  this.requestUpdate();
9578
9861
  } else {
9579
9862
  console.warn('[dawcore] reorderTrack: no track found for id "' + trackId + '"');
@@ -9581,8 +9864,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
9581
9864
  }
9582
9865
  /**
9583
9866
  * Update reflected attributes on a track. The mixer fields go to their
9584
- * owner as one undo step (#843): the engine, or while the track is loading
9585
- * the values it will enter with (not a step). For DOM-element tracks the
9867
+ * owner, the arrangement, as one undo step (#843; also while the track
9868
+ * loads, #848). For DOM-element tracks the
9586
9869
  * changes are also written to the `<daw-track>` element; for tracks
9587
9870
  * without a DOM element (file drops) the descriptor is updated in place.
9588
9871
  */
@@ -9631,8 +9914,10 @@ var DawEditorElement = class extends import_lit19.LitElement {
9631
9914
  }
9632
9915
  /**
9633
9916
  * Append a clip to an existing track. Builds a `<daw-clip>` from `config`
9634
- * and appends it to the track's DOM element when one exists; resolves with
9635
- * the new clip's id once the audio decode + peak generation finish.
9917
+ * and appends it to the track's DOM element; resolves with the new clip's
9918
+ * id once its audio has loaded (`daw-clip-ready`, before its peaks are
9919
+ * drawn); rejects when it fails to load, is refused, or leaves the
9920
+ * arrangement before it loads (a removal, an Undo).
9636
9921
  */
9637
9922
  addClip(trackId, config) {
9638
9923
  if (!config.src) {
@@ -9650,14 +9935,54 @@ var DawEditorElement = class extends import_lit19.LitElement {
9650
9935
  )
9651
9936
  );
9652
9937
  }
9938
+ if (!this._isEntered(trackId) && !this._entryQueue.includes(trackId)) {
9939
+ return Promise.reject(
9940
+ new Error(
9941
+ 'addClip: track "' + trackId + '" is not in the editor (an Undo took it out, or the arrangement refused it)'
9942
+ )
9943
+ );
9944
+ }
9653
9945
  const clipEl = this._buildClipElement(config);
9654
- return this._awaitId(
9655
- "daw-clip-ready",
9656
- "daw-clip-error",
9657
- (d) => d.clipId === clipEl.clipId,
9658
- clipEl.clipId,
9659
- () => trackEl.appendChild(clipEl)
9660
- );
9946
+ const clipId = clipEl.clipId;
9947
+ return new Promise((resolve, reject) => {
9948
+ let seen = false;
9949
+ const onReady = (e) => {
9950
+ if (e.detail.clipId !== clipId) return;
9951
+ cleanup();
9952
+ resolve(clipId);
9953
+ };
9954
+ const onError = (e) => {
9955
+ const detail = e.detail;
9956
+ if (detail.clipId !== clipId) return;
9957
+ cleanup();
9958
+ reject(detail.error instanceof Error ? detail.error : new Error(String(detail.error)));
9959
+ };
9960
+ const stopWatching = this._arrangement.subscribe(() => {
9961
+ const present = this._arrangement.getTracks().some((t) => t.clips.some((c) => c.id === clipId));
9962
+ if (present) {
9963
+ seen = true;
9964
+ } else if (seen) {
9965
+ cleanup();
9966
+ reject(new Error('clip "' + clipId + '" was removed before its audio loaded'));
9967
+ }
9968
+ });
9969
+ const cleanup = () => {
9970
+ this.removeEventListener("daw-clip-ready", onReady);
9971
+ this.removeEventListener("daw-clip-error", onError);
9972
+ stopWatching();
9973
+ this._awaitedClips.delete(clipId);
9974
+ };
9975
+ this.addEventListener("daw-clip-ready", onReady);
9976
+ this.addEventListener("daw-clip-error", onError);
9977
+ this._awaitedClips.set(clipId, {
9978
+ trackId,
9979
+ reject: (error) => {
9980
+ cleanup();
9981
+ reject(error);
9982
+ }
9983
+ });
9984
+ trackEl.appendChild(clipEl);
9985
+ });
9661
9986
  }
9662
9987
  /**
9663
9988
  * Remove a clip by id. Removes the matching `<daw-clip>` DOM element when
@@ -9675,7 +10000,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9675
10000
  return;
9676
10001
  }
9677
10002
  }
9678
- if (this._engineTracks.has(trackId)) {
10003
+ if (this._isEntered(trackId)) {
9679
10004
  this._removeClipFromTrack(trackId, clipId);
9680
10005
  return;
9681
10006
  }
@@ -9736,10 +10061,6 @@ var DawEditorElement = class extends import_lit19.LitElement {
9736
10061
  ...partial.gain !== void 0 && { gain: partial.gain },
9737
10062
  ...partial.name !== void 0 && { name: partial.name }
9738
10063
  };
9739
- const updatedClips = [...t.clips];
9740
- updatedClips[idx] = updatedClip;
9741
- const updatedTrack = { ...t, clips: updatedClips };
9742
- this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);
9743
10064
  const desc = this._tracks.get(trackId);
9744
10065
  if (desc?.clips.some((c) => c.clipId === clipId)) {
9745
10066
  this._tracks = new Map(this._tracks).set(trackId, {
@@ -9756,7 +10077,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9756
10077
  )
9757
10078
  });
9758
10079
  }
9759
- this._commitTrackChange(trackId, updatedTrack);
10080
+ this._replaceClip(trackId, clipId, updatedClip);
9760
10081
  }
9761
10082
  _buildClipElement(config) {
9762
10083
  const clipEl = document.createElement("daw-clip");
@@ -9887,16 +10208,49 @@ var DawEditorElement = class extends import_lit19.LitElement {
9887
10208
  })
9888
10209
  );
9889
10210
  }
9890
- /** Undo the last structural edit. */
10211
+ /**
10212
+ * A clip or track drag is in progress: undo and redo do nothing until it
10213
+ * ends (#848). A clip counts once its pointer has moved past the drag
10214
+ * threshold; annotation drags do not count (annotations are not in the
10215
+ * undo history).
10216
+ */
10217
+ get _dragInProgress() {
10218
+ return this._clipPointer.isDragging || this._trackReorderDrag.isActive;
10219
+ }
10220
+ /**
10221
+ * Cancel every drag in progress, as a `pointercancel` would. Returns whether
10222
+ * one was. A clip or annotation press that has not moved is not a drag and
10223
+ * is left alone, unless `includePresses` (the editor's disconnect, which
10224
+ * ends every pointer interaction).
10225
+ */
10226
+ _cancelDrags(includePresses = false) {
10227
+ let cancelled = false;
10228
+ if (includePresses || this._clipPointer.isDragging) {
10229
+ cancelled = this._pointer.cancelClipDrag() || cancelled;
10230
+ }
10231
+ if (this._trackReorderDrag.isActive) {
10232
+ this._trackReorderDrag.cancel();
10233
+ cancelled = true;
10234
+ }
10235
+ const annotation = this._annotationDrag;
10236
+ if (includePresses ? annotation.isActive : annotation.isDragging) {
10237
+ annotation.cancel();
10238
+ cancelled = true;
10239
+ }
10240
+ return cancelled;
10241
+ }
10242
+ /** Undo the last edit. Does nothing while a drag is in progress. */
9891
10243
  undo() {
10244
+ if (this._dragInProgress) return;
9892
10245
  if (!this._engine) {
9893
10246
  console.warn("[dawcore] undo: engine not ready, call ignored");
9894
10247
  return;
9895
10248
  }
9896
10249
  this._engine.undo();
9897
10250
  }
9898
- /** Redo the last undone edit. */
10251
+ /** Redo the last undone edit. Does nothing while a drag is in progress. */
9899
10252
  redo() {
10253
+ if (this._dragInProgress) return;
9900
10254
  if (!this._engine) {
9901
10255
  console.warn("[dawcore] redo: engine not ready, call ignored");
9902
10256
  return;
@@ -10132,11 +10486,12 @@ var DawEditorElement = class extends import_lit19.LitElement {
10132
10486
  (el) => el.trackId
10133
10487
  );
10134
10488
  const engineIds = engine.getState().tracks.map((t) => t.id);
10135
- const target = [...engineIds].sort((a, b) => {
10136
- const ai = domOrder.indexOf(a);
10137
- const bi = domOrder.indexOf(b);
10138
- if (ai === -1 || bi === -1) return 0;
10139
- return ai - bi;
10489
+ const inDom = new Set(domOrder);
10490
+ const slots = engineIds.flatMap((id, i) => inDom.has(id) ? [i] : []);
10491
+ const domSorted = domOrder.filter((id) => engineIds.includes(id));
10492
+ const target = [...engineIds];
10493
+ slots.forEach((slot, k) => {
10494
+ target[slot] = domSorted[k];
10140
10495
  });
10141
10496
  if (target.every((id, i) => id === engineIds[i])) return;
10142
10497
  this._inOrderSync = true;
@@ -10179,18 +10534,67 @@ var DawEditorElement = class extends import_lit19.LitElement {
10179
10534
  slots.splice(i, 0, desired[i]);
10180
10535
  }
10181
10536
  }
10537
+ /**
10538
+ * The rows, in the arrangement's order (#848): each track's loaded clips
10539
+ * (the engine's projection, with the current mix) and the clips still loading.
10540
+ */
10182
10541
  _getOrderedTracks() {
10183
- const domOrder = [...this.querySelectorAll("daw-track")].map(
10184
- (el) => el.trackId
10185
- );
10186
- return [...this._engineTracks.entries()].sort((a, b) => {
10187
- const ai = domOrder.indexOf(a[0]);
10188
- const bi = domOrder.indexOf(b[0]);
10189
- if (ai === -1 && bi === -1) return 0;
10190
- if (ai === -1) return 1;
10191
- if (bi === -1) return -1;
10192
- return ai - bi;
10193
- });
10542
+ const rows = [];
10543
+ for (const track of this._arrangement.getTracks()) {
10544
+ const loaded = this._engineTracks.get(track.id);
10545
+ if (!loaded) continue;
10546
+ rows.push([track.id, loaded, track.clips.filter(import_core19.isLoadingClip)]);
10547
+ }
10548
+ return rows;
10549
+ }
10550
+ /**
10551
+ * A clip still loading: a placeholder box where its length is known, with
10552
+ * its `.dat` peaks when they came, drawn failed when its source failed. Its
10553
+ * header carries no clip id, so it cannot be dragged.
10554
+ */
10555
+ _renderPlaceholder(clip, row) {
10556
+ const seconds = this._placeholderSeconds(clip);
10557
+ if (seconds === null) return "";
10558
+ const sr = this.effectiveSampleRate;
10559
+ const spp = this._renderSpp;
10560
+ const startSec = clip.start ?? 0;
10561
+ let left;
10562
+ let width;
10563
+ if (this.scaleMode === "beats") {
10564
+ left = Math.round(this._secondsToTicks(startSec) / this.ticksPerPixel);
10565
+ width = Math.round(this._secondsToTicks(startSec + seconds) / this.ticksPerPixel) - left;
10566
+ } else {
10567
+ const startSample = Math.round(startSec * sr);
10568
+ left = Math.floor(startSample / spp);
10569
+ width = (0, import_core19.clipPixelWidth)(startSample, Math.round(seconds * sr), spp);
10570
+ }
10571
+ const failed = this._arrangement.sources.getSnapshot().sources.get(clip.src)?.status === "failed";
10572
+ const peakData = this._previewPeaks.get(clip.id);
10573
+ const hdrH = this.clipHeaders ? this.clipHeaderHeight : 0;
10574
+ const chH = this.waveHeight;
10575
+ return import_lit19.html`<div
10576
+ class="clip-container placeholder ${failed ? "failed" : ""}"
10577
+ style="left:${left}px;top:0;width:${width}px;height:${row.trackHeight}px;"
10578
+ data-clip-id=${clip.id}
10579
+ >
10580
+ ${hdrH > 0 ? import_lit19.html`<div class="clip-header">
10581
+ <span>${clip.name || row.descriptor?.name || ""}</span>
10582
+ </div>` : ""}
10583
+ ${(peakData?.data ?? []).map(
10584
+ (chPeaks, chIdx) => import_lit19.html`<daw-waveform
10585
+ style="position:absolute;left:0;top:${hdrH + chIdx * chH}px;"
10586
+ .peaks=${chPeaks}
10587
+ .length=${peakData?.length ?? width}
10588
+ .waveHeight=${chH}
10589
+ .barWidth=${this.barWidth}
10590
+ .barGap=${this.barGap}
10591
+ .roundedBars=${this.roundedBars}
10592
+ .visibleStart=${this._viewport.visibleStart}
10593
+ .visibleEnd=${this._viewport.visibleEnd}
10594
+ .originX=${left}
10595
+ ></daw-waveform>`
10596
+ )}
10597
+ </div>`;
10194
10598
  }
10195
10599
  // --- Render ---
10196
10600
  render() {
@@ -10207,14 +10611,15 @@ var DawEditorElement = class extends import_lit19.LitElement {
10207
10611
  selStartPx = this._selectionStartTime * sr / spp;
10208
10612
  selEndPx = this._selectionEndTime * sr / spp;
10209
10613
  }
10210
- const orderedTracks = this._getOrderedTracks().map(([trackId, track]) => {
10614
+ const orderedTracks = this._getOrderedTracks().map(([trackId, track, loading]) => {
10211
10615
  const descriptor = this._tracks.get(trackId);
10212
- const firstPeaks = track.clips.map((c) => this._peaksData.get(c.id)).find((p) => p && p.data.length > 0);
10616
+ const firstPeaks = [...track.clips, ...loading].map((c) => this._peaksData.get(c.id) ?? this._previewPeaks.get(c.id)).find((p) => p && p.data.length > 0);
10213
10617
  const recSession = this._recordingController.getSession(trackId);
10214
10618
  const numChannels = firstPeaks ? firstPeaks.data.length : recSession ? recSession.channelCount : 1;
10215
10619
  return {
10216
10620
  trackId,
10217
10621
  track,
10622
+ loading,
10218
10623
  descriptor,
10219
10624
  numChannels,
10220
10625
  trackHeight: this.waveHeight * numChannels + (this.clipHeaders ? this.clipHeaderHeight : 0)
@@ -10312,7 +10717,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
10312
10717
  data-track-id=${t.trackId}
10313
10718
  >
10314
10719
  ${t.track.clips.map((clip) => {
10315
- const peakData = this._peaksData.get(clip.id);
10720
+ const peakData = this._peaksData.get(clip.id) ?? this._previewPeaks.get(clip.id);
10316
10721
  let clipLeft;
10317
10722
  let width;
10318
10723
  if (this.scaleMode === "beats") {
@@ -10324,7 +10729,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
10324
10729
  width = Math.round(endTick / this.ticksPerPixel) - clipLeft;
10325
10730
  } else {
10326
10731
  clipLeft = Math.floor(clip.startSample / spp);
10327
- width = (0, import_core17.clipPixelWidth)(clip.startSample, clip.durationSamples, spp);
10732
+ width = (0, import_core19.clipPixelWidth)(clip.startSample, clip.durationSamples, spp);
10328
10733
  }
10329
10734
  let clipSegments;
10330
10735
  let segmentChannels;
@@ -10441,6 +10846,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
10441
10846
  ></div>` : ""}
10442
10847
  </div>`;
10443
10848
  })}
10849
+ ${t.loading.map((clip) => this._renderPlaceholder(clip, t))}
10444
10850
  ${this._renderRecordingPreview(t.trackId, channelHeight)}
10445
10851
  </div>
10446
10852
  `;
@@ -10681,10 +11087,10 @@ __decorateClass([
10681
11087
  ], DawEditorElement.prototype, "ticksToSeconds", 2);
10682
11088
  __decorateClass([
10683
11089
  (0, import_decorators16.state)()
10684
- ], DawEditorElement.prototype, "_tracks", 2);
11090
+ ], DawEditorElement.prototype, "_previewPeaks", 2);
10685
11091
  __decorateClass([
10686
11092
  (0, import_decorators16.state)()
10687
- ], DawEditorElement.prototype, "_seedMix", 2);
11093
+ ], DawEditorElement.prototype, "_tracks", 2);
10688
11094
  __decorateClass([
10689
11095
  (0, import_decorators16.state)()
10690
11096
  ], DawEditorElement.prototype, "_engineTracks", 2);
@@ -10852,7 +11258,7 @@ DawRecordButtonElement = __decorateClass([
10852
11258
  // src/elements/daw-keyboard-shortcuts.ts
10853
11259
  var import_lit22 = require("lit");
10854
11260
  var import_decorators19 = require("lit/decorators.js");
10855
- var import_core18 = require("@waveform-playlist/core");
11261
+ var import_core20 = require("@waveform-playlist/core");
10856
11262
  var DawKeyboardShortcutsElement = class extends import_lit22.LitElement {
10857
11263
  constructor() {
10858
11264
  super(...arguments);
@@ -10877,7 +11283,7 @@ var DawKeyboardShortcutsElement = class extends import_lit22.LitElement {
10877
11283
  const shortcuts = this.shortcuts;
10878
11284
  if (shortcuts.length === 0) return;
10879
11285
  try {
10880
- (0, import_core18.handleKeyboardEvent)(e, shortcuts, true);
11286
+ (0, import_core20.handleKeyboardEvent)(e, shortcuts, true);
10881
11287
  } catch (err) {
10882
11288
  console.warn("[dawcore] Keyboard shortcut failed (key=" + e.key + "): " + String(err));
10883
11289
  const target = this._editor ?? this;
@@ -11067,7 +11473,7 @@ DawKeyboardShortcutsElement = __decorateClass([
11067
11473
  // src/elements/daw-spectrogram.ts
11068
11474
  var import_lit23 = require("lit");
11069
11475
  var import_decorators20 = require("lit/decorators.js");
11070
- var import_core19 = require("@waveform-playlist/core");
11476
+ var import_core21 = require("@waveform-playlist/core");
11071
11477
  var DawSpectrogramElement = class extends import_lit23.LitElement {
11072
11478
  constructor() {
11073
11479
  super(...arguments);
@@ -11132,11 +11538,11 @@ var DawSpectrogramElement = class extends import_lit23.LitElement {
11132
11538
  this._unregisterAllCanvases();
11133
11539
  this._canvases = [];
11134
11540
  if (this.length <= 0) return;
11135
- const chunkCount = Math.ceil(this.length / import_core19.MAX_CANVAS_WIDTH);
11541
+ const chunkCount = Math.ceil(this.length / import_core21.MAX_CANVAS_WIDTH);
11136
11542
  for (let i = 0; i < chunkCount; i++) {
11137
- const widthPx = Math.min(import_core19.MAX_CANVAS_WIDTH, this.length - i * import_core19.MAX_CANVAS_WIDTH);
11543
+ const widthPx = Math.min(import_core21.MAX_CANVAS_WIDTH, this.length - i * import_core21.MAX_CANVAS_WIDTH);
11138
11544
  const canvas = document.createElement("canvas");
11139
- canvas.style.left = i * import_core19.MAX_CANVAS_WIDTH + "px";
11545
+ canvas.style.left = i * import_core21.MAX_CANVAS_WIDTH + "px";
11140
11546
  canvas.style.width = widthPx + "px";
11141
11547
  const dpr = window.devicePixelRatio || 1;
11142
11548
  canvas.width = widthPx * dpr;
@@ -11162,7 +11568,7 @@ var DawSpectrogramElement = class extends import_lit23.LitElement {
11162
11568
  }
11163
11569
  for (let i = 0; i < this._canvases.length; i++) {
11164
11570
  const canvas = this._canvases[i];
11165
- const canvasId = (0, import_core19.buildSpectrogramCanvasId)({
11571
+ const canvasId = (0, import_core21.buildSpectrogramCanvasId)({
11166
11572
  clipId: this.clipId,
11167
11573
  channelIndex: this.channelIndex,
11168
11574
  chunkIndex: i
@@ -11183,7 +11589,7 @@ var DawSpectrogramElement = class extends import_lit23.LitElement {
11183
11589
  trackId: this.trackId,
11184
11590
  channelIndex: this.channelIndex,
11185
11591
  chunkIndex: i,
11186
- globalPixelOffset: this.originX + i * import_core19.MAX_CANVAS_WIDTH,
11592
+ globalPixelOffset: this.originX + i * import_core21.MAX_CANVAS_WIDTH,
11187
11593
  widthPx: parseFloat(canvas.style.width),
11188
11594
  heightPx: this.waveHeight
11189
11595
  });