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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -10,7 +10,7 @@ var __decorateClass = (decorators, target, key, kind) => {
10
10
  };
11
11
 
12
12
  // <define:__INSTALL_SPECS__>
13
- var define_INSTALL_SPECS_default = { "@dawcore/faust": "@dawcore/faust@^0.0.2-next.1", "@dawcore/midi": "@dawcore/midi@^0.0.6-next.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.2", "@waveform-playlist/worklets": "@waveform-playlist/worklets@^13.0.1-next.0", "@waveform-playlist/playout": "@waveform-playlist/playout@^13.0.0-next.4" };
13
+ var define_INSTALL_SPECS_default = { "@dawcore/faust": "@dawcore/faust@^0.0.2-next.1", "@dawcore/midi": "@dawcore/midi@^0.0.6-next.4", "@dawcore/transport": "@dawcore/transport@^0.0.16-next.4", "@dawcore/wam": "@dawcore/wam@^0.0.5-next.0", "@waveform-playlist/core": "@waveform-playlist/core@^13.0.0-next.4", "@waveform-playlist/engine": "@waveform-playlist/engine@^14.0.0-next.3", "@waveform-playlist/worklets": "@waveform-playlist/worklets@^13.0.1-next.0", "@waveform-playlist/playout": "@waveform-playlist/playout@^13.0.0-next.4" };
14
14
 
15
15
  // src/elements/daw-annotation.ts
16
16
  import { LitElement } from "lit";
@@ -2217,11 +2217,9 @@ DawStopButtonElement = __decorateClass([
2217
2217
  import { LitElement as LitElement14, html as html12, css as css11 } from "lit";
2218
2218
  import { customElement as customElement16, property as property12, state as state4 } from "lit/decorators.js";
2219
2219
  import {
2220
- createClip as createClip2,
2221
- createClipFromSeconds,
2222
2220
  createMixerGesture as createMixerGesture2,
2223
- createTrack,
2224
2221
  clipPixelWidth,
2222
+ isLoadingClip as isLoadingClip3,
2225
2223
  trackKind
2226
2224
  } from "@waveform-playlist/core";
2227
2225
 
@@ -2967,6 +2965,9 @@ DawRulerElement = __decorateClass([
2967
2965
  customElement13("daw-ruler")
2968
2966
  ], DawRulerElement);
2969
2967
 
2968
+ // src/elements/daw-editor.ts
2969
+ import { createArrangement, PlaylistEngine } from "@waveform-playlist/engine";
2970
+
2970
2971
  // src/utils/track-mix.ts
2971
2972
  var DEFAULT_TRACK_MIX = Object.freeze({
2972
2973
  volume: 1,
@@ -2989,9 +2990,6 @@ function pickMix(mix, names) {
2989
2990
  ...named.has("soloed") && { soloed: mix.soloed }
2990
2991
  };
2991
2992
  }
2992
- function withMix(track, mix) {
2993
- return { ...track, ...mixOfElement(mix) };
2994
- }
2995
2993
  function clampNumber(value, min, max) {
2996
2994
  return Math.max(min, Math.min(max, Number(value)));
2997
2995
  }
@@ -3576,6 +3574,18 @@ var clipStyles = css10`
3576
3574
  position: absolute;
3577
3575
  overflow: hidden;
3578
3576
  }
3577
+ /* A clip whose audio is still loading (#848). */
3578
+ .clip-container.placeholder {
3579
+ opacity: var(--daw-placeholder-clip-opacity, 0.5);
3580
+ background: color-mix(in srgb, var(--daw-wave-color, #c49a6c) 35%, transparent);
3581
+ }
3582
+ /* A clip whose audio failed to load: it stays, like a broken <img>. */
3583
+ .clip-container.placeholder.failed {
3584
+ opacity: 1;
3585
+ background: color-mix(in srgb, var(--daw-clip-failed-color, #e06c75) 15%, transparent);
3586
+ outline: 2px dashed var(--daw-clip-failed-color, #e06c75);
3587
+ outline-offset: -2px;
3588
+ }
3579
3589
  .clip-header {
3580
3590
  position: relative;
3581
3591
  z-index: 1;
@@ -3885,7 +3895,6 @@ var RecordingController = class {
3885
3895
  const bits = options.bits ?? 16;
3886
3896
  try {
3887
3897
  const rawCtx = this._host.audioContext;
3888
- this._host.resolveAudioContextSampleRate(rawCtx.sampleRate);
3889
3898
  if (rawCtx.state === "suspended") {
3890
3899
  await rawCtx.resume();
3891
3900
  }
@@ -5647,23 +5656,25 @@ async function loadFiles(host, files) {
5647
5656
  }
5648
5657
  };
5649
5658
  for (const file of fileArray) {
5659
+ if (!host.isConnected) {
5660
+ dispatchLoadError(file, new Error("<daw-editor> was disconnected"));
5661
+ continue;
5662
+ }
5650
5663
  if (file.type && !file.type.startsWith("audio/")) {
5651
5664
  const error = new Error("Non-audio MIME type: " + file.type);
5652
5665
  console.warn("[dawcore] Skipping non-audio file: " + file.name + " (" + file.type + ")");
5653
5666
  dispatchLoadError(file, error);
5654
5667
  continue;
5655
5668
  }
5656
- const blobUrl = URL.createObjectURL(file);
5657
- const name = file.name.replace(/\.\w+$/, "");
5669
+ let trackId = null;
5658
5670
  try {
5659
- const trackEl = await host.addTrack({ name, clips: [{ src: blobUrl, name }] });
5660
- loaded.push(trackEl.trackId);
5671
+ trackId = await host._addDroppedFile(file);
5672
+ await host._whenTrackLoaded(trackId);
5673
+ loaded.push(trackId);
5661
5674
  } catch (err) {
5662
5675
  console.warn("[dawcore] Failed to load file: " + file.name + " \u2014 " + String(err));
5676
+ if (trackId !== null) host._discardTrack(trackId);
5663
5677
  dispatchLoadError(file, err);
5664
- } finally {
5665
- URL.revokeObjectURL(blobUrl);
5666
- host._audioCache.delete(blobUrl);
5667
5678
  }
5668
5679
  }
5669
5680
  return { loaded, failed };
@@ -5751,7 +5762,7 @@ async function loadMidiImpl(host, source, options = {}) {
5751
5762
  throw first instanceof Error ? first : new Error(stringifyReason(first));
5752
5763
  }
5753
5764
  return {
5754
- trackIds: succeeded.map((el) => el.trackId),
5765
+ trackIds: succeeded,
5755
5766
  bpm: parsed.bpm,
5756
5767
  timeSignature: parsed.timeSignature,
5757
5768
  duration: parsed.duration,
@@ -5772,7 +5783,7 @@ function stringifyReason(reason) {
5772
5783
  }
5773
5784
 
5774
5785
  // src/interactions/recording-clip.ts
5775
- import { carveClipRange, createClip } from "@waveform-playlist/core";
5786
+ import { carveClipRange, createClip, isLoadingClip } from "@waveform-playlist/core";
5776
5787
  function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamples = 0, clipName) {
5777
5788
  let trimmedBuf = buf;
5778
5789
  if (offsetSamples > 0 && offsetSamples < buf.length) {
@@ -5799,8 +5810,7 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
5799
5810
  host._clipBuffers = new Map(host._clipBuffers).set(clip.id, trimmedBuf);
5800
5811
  host._clipOffsets.set(clip.id, { offsetSamples: 0, durationSamples: durSamples });
5801
5812
  host._peakPipeline.generatePeaks(trimmedBuf, host.renderSamplesPerPixel, host.mono).then((pd) => {
5802
- const t = host._engineTracks.get(trackId);
5803
- if (!t) {
5813
+ if (!host._arrangement.getTracks().some((t) => t.id === trackId)) {
5804
5814
  const next = new Map(host._clipBuffers);
5805
5815
  next.delete(clip.id);
5806
5816
  host._clipBuffers = next;
@@ -5809,13 +5819,15 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
5809
5819
  }
5810
5820
  host._peaksData = new Map(host._peaksData).set(clip.id, pd);
5811
5821
  host._raiseZoomFloor(host._peakPipeline.getCachedScale(trimmedBuf));
5812
- host._engineTracks = new Map(host._engineTracks).set(trackId, {
5813
- ...t,
5814
- // Punch-in replace (#579): the recorded clip owns [startSample,
5815
- // startSample + durSamples) — carve overlapped content out of the
5816
- // existing clips before inserting (parity with the React provider).
5817
- clips: [...carveClipRange(t.clips, startSample, startSample + durSamples), clip]
5818
- });
5822
+ host._arrangement.updateTrack(trackId, (current) => ({
5823
+ ...current,
5824
+ clips: [
5825
+ ...current.clips.flatMap(
5826
+ (c) => isLoadingClip(c) ? [c] : carveClipRange([c], startSample, startSample + durSamples)
5827
+ ),
5828
+ clip
5829
+ ]
5830
+ }));
5819
5831
  const desc = host._tracks.get(trackId);
5820
5832
  if (desc) {
5821
5833
  const sr = host.effectiveSampleRate;
@@ -5843,13 +5855,6 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
5843
5855
  clips: [...desc.clips, clipDesc]
5844
5856
  });
5845
5857
  }
5846
- host._recomputeDuration();
5847
- const updatedTrack = host._engineTracks.get(trackId);
5848
- if (host._engine?.updateTrack && updatedTrack) {
5849
- host._engine.updateTrack(trackId, updatedTrack);
5850
- } else {
5851
- host._engine?.setTracks([...host._engineTracks.values()]);
5852
- }
5853
5858
  if (host.isConnected) {
5854
5859
  host.dispatchEvent(
5855
5860
  new CustomEvent("daw-recording-clip-add", {
@@ -5993,6 +5998,7 @@ function syncPeaksForChangedClips(host, tracks) {
5993
5998
  clip.durationSamples
5994
5999
  ).then((peakData) => {
5995
6000
  host._peaksData = new Map(host._peaksData).set(clip.id, peakData);
6001
+ host._clipPeaksReady?.(clip.id, audioBuffer);
5996
6002
  }).catch((err) => {
5997
6003
  console.warn(
5998
6004
  "[dawcore] Failed to generate peaks for clip " + clip.id + ": " + String(err)
@@ -6043,6 +6049,205 @@ function findAudioBufferForClip(host, clip, track) {
6043
6049
  return null;
6044
6050
  }
6045
6051
 
6052
+ // src/interactions/track-entry.ts
6053
+ import { createClip as createClip2, createTrack } from "@waveform-playlist/core";
6054
+ function validMidiNotes(notes) {
6055
+ return notes.filter((n) => {
6056
+ const ok = Number.isFinite(n.time) && n.time >= 0 && Number.isFinite(n.duration) && n.duration > 0 && Number.isInteger(n.midi) && n.midi >= 0 && n.midi <= 127 && Number.isFinite(n.velocity) && n.velocity >= 0 && n.velocity <= 1;
6057
+ if (!ok) {
6058
+ console.warn("[dawcore] dropping malformed MIDI note: " + JSON.stringify(n));
6059
+ }
6060
+ return ok;
6061
+ });
6062
+ }
6063
+ function clipSourceOf(clipDesc) {
6064
+ return !isDomClip(clipDesc) && clipDesc.file || clipDesc.src;
6065
+ }
6066
+ function isMidiDescriptor(clipDesc) {
6067
+ if (clipSourceOf(clipDesc)) {
6068
+ if (clipDesc.midiNotes != null) {
6069
+ console.warn(
6070
+ '[dawcore] clip "' + (clipDesc.name || (isDomClip(clipDesc) ? clipDesc.clipId : "?")) + '" has both src and midiNotes \u2014 treating as audio (notes will be ignored)'
6071
+ );
6072
+ }
6073
+ return false;
6074
+ }
6075
+ return true;
6076
+ }
6077
+ function clipKindError(trackName, kind, clipIsMidi, clipLabel) {
6078
+ if (clipIsMidi === (kind === "midi")) return null;
6079
+ return new Error(
6080
+ clipIsMidi ? 'clip "' + clipLabel + '" is a MIDI clip (no src) on audio track "' + trackName + `". A track holds one kind of clip: set kind="midi" on the <daw-track> (or kind: 'midi' in addTrack) for a track of MIDI clips.` : 'clip "' + clipLabel + '" is an audio clip on MIDI track "' + trackName + '". A track holds one kind of clip: put the clip on an audio track.'
6081
+ );
6082
+ }
6083
+ function buildMidiClip(clipDesc, sampleRate) {
6084
+ const notes = validMidiNotes(clipDesc.midiNotes ?? []);
6085
+ const noteSpanSeconds = notes.length ? notes.reduce((max, n) => Math.max(max, n.time + n.duration), 0) : 0;
6086
+ const sourceDurationSamples = Math.ceil(
6087
+ Math.max(noteSpanSeconds, clipDesc.duration, 1) * sampleRate
6088
+ );
6089
+ const requestedDurationSamples = clipDesc.duration > 0 ? Math.round(clipDesc.duration * sampleRate) : sourceDurationSamples;
6090
+ const clip = createClip2({
6091
+ startSample: Math.round(clipDesc.start * sampleRate),
6092
+ durationSamples: requestedDurationSamples,
6093
+ offsetSamples: Math.round(clipDesc.offset * sampleRate),
6094
+ sampleRate,
6095
+ sourceDurationSamples,
6096
+ gain: clipDesc.gain,
6097
+ name: clipDesc.name,
6098
+ midiNotes: notes,
6099
+ midiChannel: clipDesc.midiChannel ?? void 0,
6100
+ midiProgram: clipDesc.midiProgram ?? void 0
6101
+ });
6102
+ if (clipDesc.clipId) clip.id = clipDesc.clipId;
6103
+ return clip;
6104
+ }
6105
+ function buildLoadingClip(clipDesc) {
6106
+ return {
6107
+ id: clipDesc.clipId,
6108
+ src: clipSourceOf(clipDesc),
6109
+ start: clipDesc.start,
6110
+ offset: clipDesc.offset,
6111
+ gain: clipDesc.gain,
6112
+ ...clipDesc.duration > 0 && { duration: clipDesc.duration },
6113
+ ...clipDesc.name && { name: clipDesc.name }
6114
+ };
6115
+ }
6116
+ function withClipId(clipDesc) {
6117
+ if (clipDesc.clipId) return clipDesc;
6118
+ return { ...clipDesc, clipId: crypto.randomUUID() };
6119
+ }
6120
+ function buildArrangementTrack(trackId, descriptor, mix, sampleRate) {
6121
+ const clips = [];
6122
+ const refused = [];
6123
+ let changed = false;
6124
+ const descClips = descriptor.clips.map((clipDesc) => {
6125
+ const identified = withClipId(clipDesc);
6126
+ if (identified !== clipDesc) changed = true;
6127
+ const isMidi = isMidiDescriptor(identified);
6128
+ const source = clipSourceOf(identified);
6129
+ const sourceName = typeof source === "string" ? source : source instanceof File ? source.name : "";
6130
+ const label = identified.name || sourceName || identified.clipId;
6131
+ const kindError = clipKindError(descriptor.name, descriptor.kind, isMidi, label);
6132
+ if (kindError) refused.push({ clipId: identified.clipId, error: kindError });
6133
+ else clips.push(isMidi ? buildMidiClip(identified, sampleRate) : buildLoadingClip(identified));
6134
+ return identified;
6135
+ });
6136
+ const base = createTrack({ name: descriptor.name, kind: descriptor.kind, clips: [], ...mix });
6137
+ const track = { ...base, id: trackId, clips };
6138
+ return { track, descriptor: changed ? { ...descriptor, clips: descClips } : descriptor, refused };
6139
+ }
6140
+ function entryIndex(trackEls, trackId, arrangementIds) {
6141
+ const at = trackEls.findIndex((el) => el.trackId === trackId);
6142
+ for (let i = at - 1; i >= 0; i--) {
6143
+ const position = arrangementIds.indexOf(trackEls[i].trackId);
6144
+ if (position !== -1) return position + 1;
6145
+ }
6146
+ return 0;
6147
+ }
6148
+
6149
+ // src/interactions/load-announcer.ts
6150
+ import { isLoadingClip as isLoadingClip2 } from "@waveform-playlist/core";
6151
+ var LoadAnnouncer = class {
6152
+ constructor(_dispatch) {
6153
+ this._dispatch = _dispatch;
6154
+ this._tracks = /* @__PURE__ */ new Map();
6155
+ /** The failure each clip was last announced with. */
6156
+ this._clipErrors = /* @__PURE__ */ new Map();
6157
+ /** Clips seen while loading, and not yet announced as loaded. */
6158
+ this._loadingClips = /* @__PURE__ */ new Set();
6159
+ }
6160
+ /** A track is about to enter, with `refused` clips left out for their kind. */
6161
+ expect(trackId, refused) {
6162
+ this._tracks.set(trackId, { state: null, refused });
6163
+ }
6164
+ /**
6165
+ * A clip is about to enter while loading: it is announced ready when it
6166
+ * loads, also when its source was loaded already and it is never seen
6167
+ * loading.
6168
+ */
6169
+ expectClip(clipId) {
6170
+ this._loadingClips.add(clipId);
6171
+ }
6172
+ /** A loading clip was removed: its load will not be announced. */
6173
+ forgetClip(clipId) {
6174
+ this._loadingClips.delete(clipId);
6175
+ this._clipErrors.delete(clipId);
6176
+ }
6177
+ /** The error a failed track was announced with. */
6178
+ errorOf(trackId) {
6179
+ return this._tracks.get(trackId)?.error ?? new Error('track "' + trackId + '" failed to load');
6180
+ }
6181
+ /** A track was removed by the page or an editor method: nothing more is said of it. */
6182
+ forget(trackId, clipIds) {
6183
+ this._tracks.delete(trackId);
6184
+ for (const id of clipIds) {
6185
+ this._clipErrors.delete(id);
6186
+ this._loadingClips.delete(id);
6187
+ }
6188
+ }
6189
+ /** The state a track was last announced in (`null` before its first announcement). */
6190
+ stateOf(trackId) {
6191
+ return this._tracks.get(trackId)?.state ?? null;
6192
+ }
6193
+ update(tracks, sources) {
6194
+ for (const track of tracks) this._updateTrack(track, sources);
6195
+ }
6196
+ _updateTrack(track, sources) {
6197
+ const record = this._tracks.get(track.id) ?? { state: null, refused: 0 };
6198
+ this._tracks.set(track.id, record);
6199
+ let pending = 0;
6200
+ let failed = 0;
6201
+ let loaded = 0;
6202
+ let firstError = null;
6203
+ for (const clip of track.clips) {
6204
+ if (!isLoadingClip2(clip)) {
6205
+ loaded++;
6206
+ if (this._loadingClips.delete(clip.id)) {
6207
+ this._clipErrors.delete(clip.id);
6208
+ this._send("daw-clip-ready", { trackId: track.id, clipId: clip.id });
6209
+ }
6210
+ continue;
6211
+ }
6212
+ this._loadingClips.add(clip.id);
6213
+ const source = sources.get(clip.src);
6214
+ if (source?.status !== "failed") {
6215
+ pending++;
6216
+ this._clipErrors.delete(clip.id);
6217
+ continue;
6218
+ }
6219
+ failed++;
6220
+ const error = source.error ?? new Error('the audio of clip "' + clip.id + '" failed to load');
6221
+ firstError ?? (firstError = error);
6222
+ if (this._clipErrors.get(clip.id) !== error) {
6223
+ this._clipErrors.set(clip.id, error);
6224
+ this._send("daw-clip-error", {
6225
+ trackId: track.id,
6226
+ clipId: clip.id,
6227
+ error
6228
+ });
6229
+ }
6230
+ }
6231
+ const next = pending > 0 ? "pending" : loaded > 0 || failed + record.refused === 0 ? "ready" : "failed";
6232
+ if (next === record.state) return;
6233
+ record.state = next;
6234
+ record.error = void 0;
6235
+ if (next === "ready") {
6236
+ this._send("daw-track-ready", { trackId: track.id });
6237
+ } else if (next === "failed") {
6238
+ const requested = failed + record.refused;
6239
+ const error = requested === 1 && firstError ? firstError : new Error(
6240
+ "all " + requested + " clip(s) failed to load \u2014 see prior daw-clip-error events"
6241
+ );
6242
+ record.error = error;
6243
+ this._send("daw-track-error", { trackId: track.id, error });
6244
+ }
6245
+ }
6246
+ _send(type, detail) {
6247
+ this._dispatch(new CustomEvent(type, { bubbles: true, composed: true, detail }));
6248
+ }
6249
+ };
6250
+
6046
6251
  // src/effects/effects-chain-controller.ts
6047
6252
  var idCounter = 0;
6048
6253
  var EffectsChainController = class {
@@ -7506,16 +7711,9 @@ var PlaybackAnimationController = class {
7506
7711
  // src/elements/daw-editor.ts
7507
7712
  var RULER_HEIGHT = 30;
7508
7713
  var noAdapterError = () => "No PlayoutAdapter set on <daw-editor>. Set editor.adapter before use.\n\n // Option 1: Native Web Audio (no Tone.js)\n " + installCommand("@dawcore/transport") + "\n import { NativePlayoutAdapter } from '@dawcore/transport';\n editor.adapter = new NativePlayoutAdapter(new AudioContext());\n\n // Option 2: Tone.js (effects, MIDI synths)\n " + installCommand("@waveform-playlist/playout") + "\n import { createToneAdapter } from '@waveform-playlist/playout';\n editor.adapter = createToneAdapter();";
7509
- var TrackLoadCancelledError = class extends Error {
7510
- constructor(message, reason) {
7511
- super(message);
7512
- this.reason = reason;
7513
- this.name = "TrackLoadCancelledError";
7514
- }
7515
- };
7516
7714
  var DawEditorElement = class extends LitElement14 {
7517
7715
  constructor() {
7518
- super(...arguments);
7716
+ super();
7519
7717
  this._samplesPerPixel = 1024;
7520
7718
  this._timeFormat = "hh:mm:ss.sss";
7521
7719
  this.waveHeight = 128;
@@ -7540,10 +7738,33 @@ var DawEditorElement = class extends LitElement14 {
7540
7738
  this.timeSignature = [4, 4];
7541
7739
  this._ppqn = 960;
7542
7740
  this.snapTo = "off";
7543
- /** Resolved sample rate — falls back to sampleRate property until first audio decode. */
7544
- this._resolvedSampleRate = null;
7741
+ /**
7742
+ * The one owner of the tracks, the clips, the mix, the undo history and
7743
+ * loading (#848). Made with the editor, kept across a disconnect; the
7744
+ * engine plays it once there is an adapter.
7745
+ */
7746
+ this._arrangement = createArrangement();
7747
+ /** Sends the load events, read from the arrangement (#848). */
7748
+ this._announcer = new LoadAnnouncer((event) => this.dispatchEvent(event));
7749
+ /**
7750
+ * Ids of tracks registered (a `<daw-track>` connected, a file dropped) and
7751
+ * not yet in the arrangement: they enter at the next flush, once there is
7752
+ * an engine (#848).
7753
+ */
7754
+ this._entryQueue = [];
7755
+ this._entryFlushScheduled = false;
7756
+ /**
7757
+ * Clips an `addClip()` is waiting for, with their track and the way to
7758
+ * reject the call: a removal of the clip or of its track before the clip
7759
+ * loads settles it here, without a public event (#917).
7760
+ */
7761
+ this._awaitedClips = /* @__PURE__ */ new Map();
7762
+ /** `<daw-track>` elements `addTrack()` made: every other one is the page's (the history rule). */
7763
+ this._editorMadeTracks = /* @__PURE__ */ new WeakSet();
7764
+ this._previewPeaks = /* @__PURE__ */ new Map();
7765
+ /** The `.dat` data of those clips, handed to the peak pipeline when the audio arrives. */
7766
+ this._previewWaveforms = /* @__PURE__ */ new Map();
7545
7767
  this._tracks = /* @__PURE__ */ new Map();
7546
- this._seedMix = /* @__PURE__ */ new Map();
7547
7768
  this._engineTracks = /* @__PURE__ */ new Map();
7548
7769
  this._peaksData = /* @__PURE__ */ new Map();
7549
7770
  this._isPlaying = false;
@@ -7562,16 +7783,11 @@ var DawEditorElement = class extends LitElement14 {
7562
7783
  // hook, same pattern as the whole-track _duration check.
7563
7784
  this._activePlayEndTime = null;
7564
7785
  this._externalAdapter = null;
7565
- /** True after a disconnect disposed the consumer's adapter via the engine
7566
- * — rebuild attempts fail loudly until a fresh adapter is set. */
7567
- this._adapterConsumedByDispose = false;
7568
7786
  // --- Effects (master chain; per-track chains delegated from <daw-track>) ---
7569
7787
  this._effectsManager = null;
7570
7788
  this._engine = null;
7571
7789
  this._warnedMissingTicksToSeconds = false;
7572
7790
  this._warnedMissingSecondsToTicks = false;
7573
- this._enginePromise = null;
7574
- this._audioCache = /* @__PURE__ */ new Map();
7575
7791
  this._peaksCache = /* @__PURE__ */ new Map();
7576
7792
  this._clipBuffers = /* @__PURE__ */ new Map();
7577
7793
  this._clipOffsets = /* @__PURE__ */ new Map();
@@ -7579,11 +7795,6 @@ var DawEditorElement = class extends LitElement14 {
7579
7795
  /** Coarsest scale from pre-computed peaks — zoom cannot go finer than this. 0 = no limit. */
7580
7796
  this._minSamplesPerPixel = 0;
7581
7797
  this._trackElements = /* @__PURE__ */ new Map();
7582
- /** Track ids with a _loadTrack in flight. Distinct from `_engineTracks`
7583
- * membership: the peaks-first path inserts a render-only PREVIEW track
7584
- * into _engineTracks mid-load, so `has()` alone cannot answer "is this
7585
- * track still loading?". */
7586
- this._loadingTracks = /* @__PURE__ */ new Set();
7587
7798
  this._childObserver = null;
7588
7799
  this._audioResume = new AudioResumeController(this);
7589
7800
  this._recordingController = new RecordingController(this);
@@ -7666,9 +7877,8 @@ var DawEditorElement = class extends LitElement14 {
7666
7877
  }
7667
7878
  const descriptor = this._readTrackDescriptor(trackEl);
7668
7879
  this._tracks = new Map(this._tracks).set(trackId, descriptor);
7669
- this._setSeedMix(trackId, mixOfElement(trackEl));
7670
7880
  this._trackElements.set(trackId, trackEl);
7671
- this._loadTrack(trackId, descriptor);
7881
+ this._queueEntry(trackId);
7672
7882
  };
7673
7883
  this._onTrackUpdate = (e) => {
7674
7884
  const trackId = e.detail?.trackId;
@@ -7691,11 +7901,14 @@ var DawEditorElement = class extends LitElement14 {
7691
7901
  trackEl.kind = keptKind;
7692
7902
  });
7693
7903
  }
7904
+ if (oldDescriptor && oldDescriptor.src === descriptor.src && !descriptor.clips.some(isDomClip) && !oldDescriptor.clips.some(isDomClip)) {
7905
+ descriptor = { ...descriptor, clips: oldDescriptor.clips };
7906
+ }
7694
7907
  this._tracks = new Map(this._tracks).set(trackId, descriptor);
7695
7908
  const changed = Array.isArray(e.detail.changed) ? e.detail.changed : [];
7696
7909
  this._writeMixFields(trackId, pickMix(mixOfElement(trackEl), changed));
7697
- if (oldDescriptor?.src !== descriptor.src) {
7698
- this._loadTrack(trackId, descriptor);
7910
+ if (oldDescriptor && oldDescriptor.src !== descriptor.src) {
7911
+ this._replaceShorthandClips(trackId, descriptor);
7699
7912
  }
7700
7913
  if (descriptor.renderMode === "spectrogram" && oldDescriptor?.renderMode !== "spectrogram") {
7701
7914
  const engineTrack = this._engineTracks.get(trackId);
@@ -7760,18 +7973,20 @@ var DawEditorElement = class extends LitElement14 {
7760
7973
  const trackEl = clipEl.closest("daw-track");
7761
7974
  if (!trackEl) return;
7762
7975
  const trackId = trackEl.trackId;
7763
- if (!this._engineTracks.has(trackId) || this._loadingTracks.has(trackId)) {
7976
+ if (!this._isEntered(trackId)) {
7977
+ if (!this._entryQueue.includes(trackId)) {
7978
+ this._rejectAwaitedClips(
7979
+ (id) => id === clipEl.clipId,
7980
+ 'addClip: track "' + trackId + '" is not in the editor (an Undo took it out)'
7981
+ );
7982
+ return;
7983
+ }
7764
7984
  const desc = this._tracks.get(trackId);
7765
7985
  if (desc && !desc.clips.some((c) => isDomClip(c) && c.clipId === clipEl.clipId)) {
7766
- 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.';
7767
- console.warn("[dawcore] " + message);
7768
- this.dispatchEvent(
7769
- new CustomEvent("daw-clip-error", {
7770
- bubbles: true,
7771
- composed: true,
7772
- detail: { trackId, clipId: clipEl.clipId, error: new Error(message) }
7773
- })
7774
- );
7986
+ this._tracks = new Map(this._tracks).set(trackId, {
7987
+ ...desc,
7988
+ clips: [...desc.clips, this._readClipDescriptor(clipEl)]
7989
+ });
7775
7990
  }
7776
7991
  return;
7777
7992
  }
@@ -7779,24 +7994,7 @@ var DawEditorElement = class extends LitElement14 {
7779
7994
  if (loadedDesc && loadedDesc.clips.some((c) => isDomClip(c) && c.clipId === clipEl.clipId)) {
7780
7995
  return;
7781
7996
  }
7782
- const clipDesc = {
7783
- kind: "dom",
7784
- clipId: clipEl.clipId,
7785
- src: clipEl.src,
7786
- peaksSrc: clipEl.peaksSrc,
7787
- start: clipEl.start,
7788
- duration: clipEl.duration,
7789
- offset: clipEl.offset,
7790
- gain: clipEl.gain,
7791
- name: clipEl.name,
7792
- fadeIn: clipEl.fadeIn,
7793
- fadeOut: clipEl.fadeOut,
7794
- fadeType: clipEl.fadeType,
7795
- midiNotes: clipEl.midiNotes,
7796
- midiChannel: clipEl.midiChannel,
7797
- midiProgram: clipEl.midiProgram
7798
- };
7799
- this._loadAndAppendClip(trackId, clipDesc);
7997
+ this._loadAndAppendClip(trackId, this._readClipDescriptor(clipEl));
7800
7998
  };
7801
7999
  this._onClipUpdate = (e) => {
7802
8000
  const clipEl = e.target;
@@ -7808,8 +8006,26 @@ var DawEditorElement = class extends LitElement14 {
7808
8006
  );
7809
8007
  return;
7810
8008
  }
8009
+ const desc = this._tracks.get(detail.trackId);
8010
+ if (desc && !this._isEntered(detail.trackId)) {
8011
+ this._tracks = new Map(this._tracks).set(detail.trackId, {
8012
+ ...desc,
8013
+ clips: desc.clips.map(
8014
+ (c) => isDomClip(c) && c.clipId === clipEl.clipId ? this._readClipDescriptor(clipEl) : c
8015
+ )
8016
+ });
8017
+ return;
8018
+ }
7811
8019
  this._applyClipUpdate(detail.trackId, detail.clipId, clipEl);
7812
8020
  };
8021
+ this._waitingForDragEnd = false;
8022
+ /** Who waits for a track to enter (addTrack, a dropped file). */
8023
+ this._entryWaiters = /* @__PURE__ */ new Map();
8024
+ /** Ends the waits of `_whenTrackLoaded` (as loaded) when the editor is disconnected. */
8025
+ this._loadWaitEnds = /* @__PURE__ */ new Set();
8026
+ /** Last versions the statechange handler worked from; reset for each engine. */
8027
+ this._lastTracksVersion = -1;
8028
+ this._lastMixerVersion = -1;
7813
8029
  // --- File Drop ---
7814
8030
  this._onDragOver = (e) => {
7815
8031
  if (!this.fileDrop) return;
@@ -7878,6 +8094,10 @@ var DawEditorElement = class extends LitElement14 {
7878
8094
  * statechange emissions during the transaction would otherwise bounce
7879
8095
  * half-applied orders back into the DOM. */
7880
8096
  this._inOrderSync = false;
8097
+ this._arrangement.sources.subscribe(() => {
8098
+ this._announceLoading();
8099
+ this.requestUpdate();
8100
+ });
7881
8101
  }
7882
8102
  get samplesPerPixel() {
7883
8103
  return this._samplesPerPixel;
@@ -8056,16 +8276,33 @@ var DawEditorElement = class extends LitElement14 {
8056
8276
  get _hasTickCallbacks() {
8057
8277
  return !!(this.secondsToTicks && this.ticksToSeconds);
8058
8278
  }
8059
- /** Sample rate — reads from adapter's AudioContext when available, otherwise falls back to 48000. */
8279
+ /**
8280
+ * Sample rate: the adapter's AudioContext rate. Without an adapter (after a
8281
+ * disconnect let it go), the rate of the loaded clips the arrangement holds,
8282
+ * else 48000. Decoded audio is at the context's rate, so the two agree.
8283
+ */
8060
8284
  get sampleRate() {
8061
- return this._resolvedSampleRate ?? this._externalAdapter?.audioContext.sampleRate ?? 48e3;
8285
+ return this._externalAdapter?.audioContext.sampleRate ?? this._loadedClipSampleRate() ?? 48e3;
8286
+ }
8287
+ _loadedClipSampleRate() {
8288
+ for (const track of this._arrangement.getTracks()) {
8289
+ for (const clip of track.clips) {
8290
+ if ("sampleRate" in clip && typeof clip.sampleRate === "number") return clip.sampleRate;
8291
+ }
8292
+ }
8293
+ return null;
8294
+ }
8295
+ /** Reject the `addClip()` calls waiting for clips that match `which`. */
8296
+ _rejectAwaitedClips(which, message) {
8297
+ for (const [clipId, awaited] of [...this._awaitedClips]) {
8298
+ if (which(clipId, awaited.trackId)) awaited.reject(new Error(message));
8299
+ }
8062
8300
  }
8063
8301
  set adapter(value) {
8064
8302
  if (value && value.audioContext.state === "closed") {
8065
8303
  console.warn("[dawcore] Adapter AudioContext is already closed. Ignoring.");
8066
8304
  return;
8067
8305
  }
8068
- this._adapterConsumedByDispose = false;
8069
8306
  if (this._engine) {
8070
8307
  console.warn(
8071
8308
  "[dawcore] adapter set after engine is built. The engine will continue using the previous adapter."
@@ -8079,6 +8316,7 @@ var DawEditorElement = class extends LitElement14 {
8079
8316
  this._effectsManager = null;
8080
8317
  }
8081
8318
  this._externalAdapter = value;
8319
+ if (value && this.isConnected && !this._engine) this._buildEngineReporting();
8082
8320
  }
8083
8321
  get adapter() {
8084
8322
  return this._externalAdapter;
@@ -8293,10 +8531,7 @@ var DawEditorElement = class extends LitElement14 {
8293
8531
  return clip?.midiNotes != null;
8294
8532
  }
8295
8533
  get effectiveSampleRate() {
8296
- return this._resolvedSampleRate ?? this.sampleRate;
8297
- }
8298
- resolveAudioContextSampleRate(rate) {
8299
- if (!this._resolvedSampleRate) this._resolvedSampleRate = rate;
8534
+ return this.sampleRate;
8300
8535
  }
8301
8536
  /**
8302
8537
  * In beats mode, derive samplesPerPixel from ticksPerPixel so that
@@ -8367,53 +8602,43 @@ var DawEditorElement = class extends LitElement14 {
8367
8602
  _setSelectedTrackId(trackId) {
8368
8603
  this._selectedTrackId = trackId;
8369
8604
  }
8605
+ /**
8606
+ * Every track: those in the arrangement, in its order, then those still
8607
+ * waiting to enter (#848). A `<daw-track>` whose track an Undo took out of
8608
+ * the arrangement is not listed (its descriptor stays for a Redo).
8609
+ */
8370
8610
  get tracks() {
8371
- return [...this._tracks.entries()].map(([trackId, descriptor]) => ({
8372
- trackId,
8373
- ...descriptor,
8374
- ...this._mixOf(trackId)
8375
- }));
8611
+ const ids = [...this._arrangement.getTracks().map((t) => t.id), ...this._entryQueue];
8612
+ return ids.flatMap((trackId) => {
8613
+ const descriptor = this._tracks.get(trackId);
8614
+ return descriptor ? [{ trackId, ...descriptor, ...this._mixOf(trackId) }] : [];
8615
+ });
8376
8616
  }
8377
8617
  /**
8378
- * A track's mix, from its one owner: the arrangement (through
8379
- * `_engineTracks`, which follows `mixerVersion`) for a track the engine
8380
- * holds, the seed for one still on its way in (#843).
8618
+ * A track's mix, from its one owner, the arrangement (#843), as the engine
8619
+ * plays it: its projection carries the take's mute, which `getMixer()`
8620
+ * leaves out (the stored mute comes back when the take ends). A track still
8621
+ * waiting to enter shows what its element declares.
8381
8622
  */
8382
8623
  _mixOf(trackId) {
8383
- const seed = this._seedMix.get(trackId);
8384
- if (seed) return seed;
8385
- const track = this._engineTracks.get(trackId);
8386
- return track ? mixOfTrack(track) : DEFAULT_TRACK_MIX;
8387
- }
8388
- /** Replace a track's seed (a new Map: `_seedMix` is reactive state). */
8389
- _setSeedMix(trackId, mix) {
8390
- this._seedMix = new Map(this._seedMix).set(trackId, mix);
8391
- }
8392
- _deleteSeedMix(trackIds) {
8393
- let next = null;
8394
- for (const id of trackIds) {
8395
- if (!this._seedMix.has(id)) continue;
8396
- next ?? (next = new Map(this._seedMix));
8397
- next.delete(id);
8398
- }
8399
- if (next) this._seedMix = next;
8624
+ const played = this._engineTracks.get(trackId);
8625
+ if (played) return mixOfTrack(played);
8626
+ const mix = this._arrangement.getMixer().get(trackId);
8627
+ if (mix) return mix;
8628
+ const el = this._trackElements.get(trackId);
8629
+ return el ? mixOfElement(el) : DEFAULT_TRACK_MIX;
8400
8630
  }
8401
8631
  /**
8402
- * Change one mixer field of a track: the seed while the track is loading
8403
- * (not an undo step, nothing sent), else the engine's setter with
8404
- * `options` (an undo step; changes with one `gesture` id are one step).
8632
+ * Change one mixer field of a track: the arrangement's setter with
8633
+ * `options` (an undo step; changes with one `gesture` id are one step). A
8634
+ * track that has not entered yet changes nothing.
8405
8635
  */
8406
8636
  _writeMix(trackId, field, value, options) {
8407
- const seed = this._seedMix.get(trackId);
8408
- if (seed) {
8409
- if (seed[field] !== value) this._setSeedMix(trackId, { ...seed, [field]: value });
8410
- return;
8411
- }
8412
- if (!this._engine) return;
8413
- if (field === "volume") this._engine.setTrackVolume(trackId, value, options);
8414
- else if (field === "pan") this._engine.setTrackPan(trackId, value, options);
8415
- else if (field === "muted") this._engine.setTrackMute(trackId, value, options);
8416
- else this._engine.setTrackSolo(trackId, value, options);
8637
+ const arrangement = this._arrangement;
8638
+ if (field === "volume") arrangement.setTrackVolume(trackId, value, options);
8639
+ else if (field === "pan") arrangement.setTrackPan(trackId, value, options);
8640
+ else if (field === "muted") arrangement.setTrackMute(trackId, value, options);
8641
+ else arrangement.setTrackSolo(trackId, value, options);
8417
8642
  }
8418
8643
  /**
8419
8644
  * Change the given mixer fields of a track as ONE undo step (#843): all
@@ -8426,13 +8651,6 @@ var DawEditorElement = class extends LitElement14 {
8426
8651
  if (mix.muted !== void 0) this._writeMix(trackId, "muted", mix.muted, options);
8427
8652
  if (mix.soloed !== void 0) this._writeMix(trackId, "soloed", mix.soloed, options);
8428
8653
  }
8429
- /** The ordered tracks for `engine.setTracks`, a loading track with its seed. */
8430
- _tracksForEngine() {
8431
- return this._getOrderedTracks().map(([trackId, track]) => {
8432
- const seed = this._seedMix.get(trackId);
8433
- return seed ? withMix(track, seed) : track;
8434
- });
8435
- }
8436
8654
  get selectedTrackId() {
8437
8655
  return this._selectedTrackId;
8438
8656
  }
@@ -8516,6 +8734,10 @@ var DawEditorElement = class extends LitElement14 {
8516
8734
  if (orderMayHaveChanged) this._syncEngineOrderToDom();
8517
8735
  });
8518
8736
  this._childObserver.observe(this, { childList: true, subtree: true });
8737
+ for (const [trackId, el] of [...this._trackElements]) {
8738
+ if (!this.contains(el)) this._onTrackRemoved(trackId);
8739
+ }
8740
+ if (this._externalAdapter && !this._engine) this._buildEngineReporting();
8519
8741
  }
8520
8742
  disconnectedCallback() {
8521
8743
  super.disconnectedCallback();
@@ -8536,15 +8758,22 @@ var DawEditorElement = class extends LitElement14 {
8536
8758
  this.removeEventListener("daw-track-reorder", this._onTrackReorder);
8537
8759
  this.removeEventListener("daw-track-reorder-grab", this._onTrackReorderGrab);
8538
8760
  this._cancelDrags(true);
8761
+ for (const end of [...this._loadWaitEnds]) end();
8762
+ for (const trackId of this._entryQueue) {
8763
+ if (this._trackElements.has(trackId) || !this._entryWaiters.has(trackId)) continue;
8764
+ const nextTracks = new Map(this._tracks);
8765
+ nextTracks.delete(trackId);
8766
+ this._tracks = nextTracks;
8767
+ this._entryQueue = this._entryQueue.filter((id) => id !== trackId);
8768
+ this._settleEntry(
8769
+ trackId,
8770
+ new Error("<daw-editor> was disconnected before the file entered")
8771
+ );
8772
+ }
8539
8773
  this._childObserver?.disconnect();
8540
8774
  this._childObserver = null;
8541
- this._trackElements.clear();
8542
- this._audioCache.clear();
8543
8775
  this._peaksCache.clear();
8544
- this._clipBuffers.clear();
8545
- this._clipOffsets.clear();
8546
8776
  this._peakPipeline.terminate();
8547
- this._minSamplesPerPixel = 0;
8548
8777
  this._spectrogramController?.dispose();
8549
8778
  this._spectrogramController = null;
8550
8779
  this._lastSpectrogramViewport = null;
@@ -8555,14 +8784,8 @@ var DawEditorElement = class extends LitElement14 {
8555
8784
  console.warn("[dawcore] Error disposing engine: " + String(err));
8556
8785
  }
8557
8786
  if (hadEngine) {
8558
- this._adapterConsumedByDispose = true;
8787
+ this._externalAdapter = null;
8559
8788
  }
8560
- this._tracks = /* @__PURE__ */ new Map();
8561
- this._seedMix = /* @__PURE__ */ new Map();
8562
- this._engineTracks = /* @__PURE__ */ new Map();
8563
- this._peaksData = /* @__PURE__ */ new Map();
8564
- this._loadingTracks.clear();
8565
- this._recomputeDuration();
8566
8789
  }
8567
8790
  willUpdate(changedProperties) {
8568
8791
  if (changedProperties.has("eagerResume")) {
@@ -8616,6 +8839,21 @@ var DawEditorElement = class extends LitElement14 {
8616
8839
  }
8617
8840
  _onTrackRemoved(trackId) {
8618
8841
  const existed = this._tracks.has(trackId);
8842
+ this._rejectAwaitedClips(
8843
+ (_, awaitedTrackId) => awaitedTrackId === trackId,
8844
+ "the track of the clip was removed before the clip loaded"
8845
+ );
8846
+ this._entryQueue = this._entryQueue.filter((id) => id !== trackId);
8847
+ this._settleEntry(trackId, new Error('track "' + trackId + '" was removed before it entered'));
8848
+ const arrangementTrack = this._arrangement.getTracks().find((t) => t.id === trackId);
8849
+ const clipIds = arrangementTrack?.clips.map((c) => c.id) ?? [];
8850
+ this._announcer.forget(trackId, clipIds);
8851
+ if (clipIds.some((id) => this._previewPeaks.has(id))) {
8852
+ const nextPreview = new Map(this._previewPeaks);
8853
+ for (const id of clipIds) nextPreview.delete(id);
8854
+ this._previewPeaks = nextPreview;
8855
+ }
8856
+ for (const id of clipIds) this._previewWaveforms.delete(id);
8619
8857
  this._trackElements.delete(trackId);
8620
8858
  this._effectsManager?.disposeTrackChain(trackId);
8621
8859
  const removedTrack = this._engineTracks.get(trackId);
@@ -8632,14 +8870,11 @@ var DawEditorElement = class extends LitElement14 {
8632
8870
  const nextTracks = new Map(this._tracks);
8633
8871
  nextTracks.delete(trackId);
8634
8872
  this._tracks = nextTracks;
8635
- this._deleteSeedMix([trackId]);
8636
8873
  const nextEngine = new Map(this._engineTracks);
8637
8874
  nextEngine.delete(trackId);
8638
8875
  this._engineTracks = nextEngine;
8639
8876
  this._recomputeDuration();
8640
- if (this._engine) {
8641
- this._engine.removeTrack(trackId);
8642
- }
8877
+ this._arrangement.removeTrack(trackId);
8643
8878
  this._recomputeZoomFloor();
8644
8879
  this._disposeSpectrogramControllerIfEmpty();
8645
8880
  if (existed && nextEngine.size === 0) {
@@ -8700,7 +8935,7 @@ var DawEditorElement = class extends LitElement14 {
8700
8935
  });
8701
8936
  }
8702
8937
  for (const trackId of this._tracks.keys()) {
8703
- if (engineIds.has(trackId) || this._loadingTracks.has(trackId) || this._trackElements.has(trackId)) {
8938
+ if (engineIds.has(trackId) || this._entryQueue.includes(trackId) || this._trackElements.has(trackId)) {
8704
8939
  continue;
8705
8940
  }
8706
8941
  next ?? (next = new Map(this._tracks));
@@ -8752,12 +8987,22 @@ var DawEditorElement = class extends LitElement14 {
8752
8987
  }
8753
8988
  _onClipRemovedFromDom(clipEl) {
8754
8989
  const clipId = clipEl.clipId;
8755
- for (const [trackId, t] of this._engineTracks.entries()) {
8990
+ for (const t of this._arrangement.getTracks()) {
8756
8991
  if (t.clips.some((c) => c.id === clipId)) {
8757
- this._removeClipFromTrack(trackId, clipId);
8992
+ this._removeClipFromTrack(t.id, clipId);
8758
8993
  return;
8759
8994
  }
8760
8995
  }
8996
+ for (const [trackId, desc] of this._tracks) {
8997
+ if (this._isEntered(trackId) || !desc.clips.some((c) => c.clipId === clipId)) continue;
8998
+ this._tracks = new Map(this._tracks).set(trackId, {
8999
+ ...desc,
9000
+ clips: desc.clips.filter((c) => c.clipId !== clipId)
9001
+ });
9002
+ this._rejectAwaitedClips((id) => id === clipId, "the clip was removed before it loaded");
9003
+ return;
9004
+ }
9005
+ this._rejectAwaitedClips((id) => id === clipId, "the clip was removed before it loaded");
8761
9006
  if (this._clipBuffers.has(clipId) || this._clipOffsets.has(clipId) || this._peaksData.has(clipId)) {
8762
9007
  console.warn(
8763
9008
  '[dawcore] _onClipRemovedFromDom: orphaned cache entries for clip "' + clipId + '" \u2014 purging (DOM/engine id mismatch?)'
@@ -8765,62 +9010,52 @@ var DawEditorElement = class extends LitElement14 {
8765
9010
  this._purgeClipCaches(clipId);
8766
9011
  }
8767
9012
  }
8768
- async _loadAndAppendClip(trackId, clipDesc) {
8769
- if (!clipDesc.src) return;
8770
- const clipId = clipDesc.clipId;
8771
- let insertedClipId = null;
9013
+ /**
9014
+ * A `<daw-clip>` appended to a track that has entered: the clip goes in as
9015
+ * a loading clip (a loaded one for MIDI), one undo step. Its audio loads
9016
+ * like any other; `daw-clip-ready` or `daw-clip-error` follows (#848).
9017
+ */
9018
+ _loadAndAppendClip(trackId, clipDesc) {
9019
+ const trackDesc = this._tracks.get(trackId);
9020
+ if (!trackDesc) return;
9021
+ const clipIsMidi = isMidiDescriptor(clipDesc);
9022
+ const kindError = clipKindError(
9023
+ trackDesc.name,
9024
+ trackDesc.kind,
9025
+ clipIsMidi,
9026
+ clipDesc.name || clipDesc.src || clipDesc.clipId
9027
+ );
9028
+ const clip = clipIsMidi ? buildMidiClip(clipDesc, this.effectiveSampleRate) : buildLoadingClip(clipDesc);
9029
+ if (!clipIsMidi) this._announcer.expectClip(clipDesc.clipId);
8772
9030
  try {
8773
- const trackDesc = this._tracks.get(trackId);
8774
- const kindError = trackDesc ? this._clipKindError(trackDesc.name, trackDesc.kind, false, clipDesc.name || clipDesc.src) : null;
8775
9031
  if (kindError) throw kindError;
8776
- const waveformDataPromise = clipDesc.peaksSrc ? this._resolvePeaks(clipDesc.peaksSrc) : Promise.resolve(null);
8777
- const audioPromise = this._fetchAndDecode(clipDesc.src);
8778
- const [waveformData, audioBuffer] = await Promise.all([waveformDataPromise, audioPromise]);
8779
- this._resolvedSampleRate = audioBuffer.sampleRate;
8780
- const clip = await this._finalizeAudioClip(clipDesc, audioBuffer, waveformData);
8781
- insertedClipId = clip.id;
8782
- const t = this._engineTracks.get(trackId);
8783
- if (!t) {
8784
- this._purgeClipCaches(clip.id);
8785
- return;
8786
- }
8787
- const updatedTrack = { ...t, clips: [...t.clips, clip] };
8788
- this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);
8789
- const desc = this._tracks.get(trackId);
8790
- if (desc) {
8791
- this._tracks = new Map(this._tracks).set(trackId, {
8792
- ...desc,
8793
- clips: [...desc.clips, clipDesc]
8794
- });
8795
- }
8796
- this._commitTrackChange(trackId, updatedTrack);
8797
- this._maybeRegisterSpectrogramClipAudio(trackId, clip);
8798
- this.dispatchEvent(
8799
- new CustomEvent("daw-clip-ready", {
8800
- bubbles: true,
8801
- composed: true,
8802
- detail: { trackId, clipId: clip.id }
8803
- })
8804
- );
9032
+ this._arrangement.updateTrack(trackId, (current) => ({
9033
+ ...current,
9034
+ clips: [...current.clips, clip]
9035
+ }));
8805
9036
  } catch (err) {
8806
9037
  console.warn("[dawcore] _loadAndAppendClip failed: " + String(err));
8807
- if (insertedClipId) this._purgeClipCaches(insertedClipId);
8808
9038
  this.dispatchEvent(
8809
9039
  new CustomEvent("daw-clip-error", {
8810
9040
  bubbles: true,
8811
9041
  composed: true,
8812
- detail: { trackId, clipId: insertedClipId ?? clipId, error: err }
9042
+ detail: { trackId, clipId: clipDesc.clipId, error: err }
8813
9043
  })
8814
9044
  );
9045
+ return;
8815
9046
  }
9047
+ this._tracks = new Map(this._tracks).set(trackId, {
9048
+ ...trackDesc,
9049
+ clips: [...trackDesc.clips, clipDesc]
9050
+ });
9051
+ if (!clipIsMidi && clipDesc.peaksSrc) this._requestPreview(clipDesc.clipId, clipDesc.peaksSrc);
8816
9052
  }
8817
9053
  /**
8818
9054
  * Resolve pre-computed peaks for a clip: fetch the .dat/.json, validate the
8819
9055
  * sample rate matches the AudioContext, return the WaveformData or null.
8820
9056
  * Warns on fetch failure and on sample-rate mismatch — never silent.
8821
9057
  *
8822
- * Shared between `_loadTrack` (peaks-first preview path) and
8823
- * `_loadAndAppendClip` (incremental late-append).
9058
+ * Used by `_requestPreview` for a clip that is still loading.
8824
9059
  */
8825
9060
  async _resolvePeaks(peaksSrc) {
8826
9061
  try {
@@ -8838,127 +9073,6 @@ var DawEditorElement = class extends LitElement14 {
8838
9073
  return null;
8839
9074
  }
8840
9075
  }
8841
- /**
8842
- * Construct an AudioClip from a decoded buffer (and optional WaveformData),
8843
- * align its id with the source `<daw-clip>.clipId` when present, populate
8844
- * `_clipBuffers` / `_clipOffsets`, generate peaks via the worker pipeline,
8845
- * and populate `_peaksData`. Returns the finished AudioClip.
8846
- *
8847
- * Shared between `_loadTrack`'s standard path and `_loadAndAppendClip`.
8848
- * Not used by `_loadTrack`'s peaks-first preview path because that path
8849
- * uses sync `extractPeaks` and inserts a preview track BEFORE audio decode.
8850
- */
8851
- async _finalizeAudioClip(clipDesc, audioBuffer, waveformData) {
8852
- let clip;
8853
- if (waveformData) {
8854
- const wdRate = waveformData.sample_rate;
8855
- clip = createClip2({
8856
- audioBuffer,
8857
- waveformData,
8858
- startSample: Math.round(clipDesc.start * wdRate),
8859
- durationSamples: Math.round((clipDesc.duration || waveformData.duration) * wdRate),
8860
- offsetSamples: Math.round(clipDesc.offset * wdRate),
8861
- gain: clipDesc.gain,
8862
- name: clipDesc.name,
8863
- sampleRate: wdRate,
8864
- sourceDurationSamples: Math.ceil(waveformData.duration * wdRate)
8865
- });
8866
- this._peakPipeline.cacheWaveformData(audioBuffer, waveformData);
8867
- } else {
8868
- clip = createClipFromSeconds({
8869
- audioBuffer,
8870
- startTime: clipDesc.start,
8871
- duration: clipDesc.duration || audioBuffer.duration,
8872
- offset: clipDesc.offset,
8873
- gain: clipDesc.gain,
8874
- name: clipDesc.name,
8875
- sampleRate: audioBuffer.sampleRate,
8876
- sourceDuration: audioBuffer.duration
8877
- });
8878
- }
8879
- if (isDomClip(clipDesc)) clip.id = clipDesc.clipId;
8880
- this._clipBuffers = new Map(this._clipBuffers).set(clip.id, audioBuffer);
8881
- this._clipOffsets.set(clip.id, {
8882
- offsetSamples: clip.offsetSamples,
8883
- durationSamples: clip.durationSamples
8884
- });
8885
- let peakData;
8886
- try {
8887
- peakData = await this._peakPipeline.generatePeaks(
8888
- audioBuffer,
8889
- this._renderSpp,
8890
- this.mono,
8891
- clip.offsetSamples,
8892
- clip.durationSamples
8893
- );
8894
- } catch (err) {
8895
- this._purgeClipCaches(clip.id);
8896
- throw err;
8897
- }
8898
- this._peaksData = new Map(this._peaksData).set(clip.id, peakData);
8899
- const cachedScale = waveformData?.scale ?? this._peakPipeline.getCachedScale(audioBuffer);
8900
- this._raiseZoomFloor(cachedScale);
8901
- return clip;
8902
- }
8903
- /**
8904
- * Filter MIDI notes to only those with finite, in-range fields. Logs a
8905
- * warning for each dropped note. Used by _buildMidiClip and the
8906
- * _applyClipUpdate MIDI branch to prevent NaN propagation through the
8907
- * timeline.
8908
- */
8909
- _validMidiNotes(notes) {
8910
- return notes.filter((n) => {
8911
- 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;
8912
- if (!ok) {
8913
- console.warn("[dawcore] dropping malformed MIDI note: " + JSON.stringify(n));
8914
- }
8915
- return ok;
8916
- });
8917
- }
8918
- /**
8919
- * A clip descriptor is treated as MIDI when it has no audio src.
8920
- * Includes placeholder MIDI clips (no notes, no duration yet — registered
8921
- * with a 1s default span; notes upgrade via _applyClipUpdate). Warns when
8922
- * a clip ambiguously has both src and midiNotes — the audio path runs
8923
- * and notes would be silently ignored.
8924
- */
8925
- _isMidiDescriptor(clipDesc) {
8926
- if (clipDesc.src) {
8927
- if (clipDesc.midiNotes != null) {
8928
- console.warn(
8929
- '[dawcore] clip "' + (clipDesc.name || (isDomClip(clipDesc) ? clipDesc.clipId : "?")) + '" has both src and midiNotes \u2014 treating as audio (notes will be ignored)'
8930
- );
8931
- }
8932
- return false;
8933
- }
8934
- return true;
8935
- }
8936
- /**
8937
- * Build an engine clip from a MIDI clip descriptor. Always returns a clip
8938
- * — empty notes / no declared duration get a 1-second placeholder span so
8939
- * the clip is reachable via `engine.updateTrack` once notes arrive.
8940
- */
8941
- _buildMidiClip(clipDesc) {
8942
- const sr = this.effectiveSampleRate;
8943
- const notes = this._validMidiNotes(clipDesc.midiNotes ?? []);
8944
- const noteSpanSeconds = notes.length ? notes.reduce((max, n) => Math.max(max, n.time + n.duration), 0) : 0;
8945
- const sourceDurationSamples = Math.ceil(Math.max(noteSpanSeconds, clipDesc.duration, 1) * sr);
8946
- const requestedDurationSamples = clipDesc.duration > 0 ? Math.round(clipDesc.duration * sr) : sourceDurationSamples;
8947
- const clip = createClip2({
8948
- startSample: Math.round(clipDesc.start * sr),
8949
- durationSamples: requestedDurationSamples,
8950
- offsetSamples: Math.round(clipDesc.offset * sr),
8951
- sampleRate: sr,
8952
- sourceDurationSamples,
8953
- gain: clipDesc.gain,
8954
- name: clipDesc.name,
8955
- midiNotes: notes,
8956
- midiChannel: clipDesc.midiChannel ?? void 0,
8957
- midiProgram: clipDesc.midiProgram ?? void 0
8958
- });
8959
- if (isDomClip(clipDesc)) clip.id = clipDesc.clipId;
8960
- return clip;
8961
- }
8962
9076
  /** Remove a single clip from all per-clip caches. Used by error rollbacks. */
8963
9077
  _purgeClipCaches(clipId) {
8964
9078
  const nextBuffers = new Map(this._clipBuffers);
@@ -8971,16 +9085,14 @@ var DawEditorElement = class extends LitElement14 {
8971
9085
  this._spectrogramController?.unregisterClipAudio(clipId);
8972
9086
  }
8973
9087
  /**
8974
- * Recompute duration and forward an updated track to the engine. Single
8975
- * source of truth for the incremental-vs-full-rebuild policy used by every
8976
- * clip-level mutation (addClip, updateClip, removeClip, _applyClipUpdate).
8977
- * Use the engine's incremental updateTrack when available; otherwise fall
8978
- * back to full setTracks (legacy adapters).
9088
+ * Replace one loaded clip of a track in the arrangement: an undo step. The
9089
+ * function form, so the track's loading clips stay as they are (#848).
8979
9090
  */
8980
- _commitTrackChange(trackId, updatedTrack) {
8981
- this._recomputeDuration();
8982
- if (this._engine?.updateTrack) this._engine.updateTrack(trackId, updatedTrack);
8983
- else if (this._engine) this._engine.setTracks(this._tracksForEngine());
9091
+ _replaceClip(trackId, clipId, clip) {
9092
+ this._arrangement.updateTrack(trackId, (current) => ({
9093
+ ...current,
9094
+ clips: current.clips.map((c) => c.id === clipId ? clip : c)
9095
+ }));
8984
9096
  }
8985
9097
  _applyClipUpdate(trackId, clipId, clipEl) {
8986
9098
  const t = this._engineTracks.get(trackId);
@@ -8990,8 +9102,9 @@ var DawEditorElement = class extends LitElement14 {
8990
9102
  }
8991
9103
  const idx = t.clips.findIndex((c) => c.id === clipId);
8992
9104
  if (idx === -1) {
9105
+ const loading = this._arrangement.getTracks().find((track) => track.id === trackId)?.clips.some((c) => c.id === clipId);
8993
9106
  console.warn(
8994
- '[dawcore] _applyClipUpdate: clip "' + clipId + '" not found in track "' + trackId + '" (DOM/engine clip-id misalignment?)'
9107
+ '[dawcore] _applyClipUpdate: clip "' + clipId + '" ' + (loading ? "is still loading; the change is dropped" : 'not found in track "' + trackId + '" (DOM/engine clip-id misalignment?)')
8995
9108
  );
8996
9109
  return;
8997
9110
  }
@@ -9000,7 +9113,7 @@ var DawEditorElement = class extends LitElement14 {
9000
9113
  const isMidiNow = clipEl.midiNotes != null && !clipEl.src;
9001
9114
  const wasMidi = oldClip.midiNotes != null;
9002
9115
  if (isMidiNow && trackKind(t) !== "midi") {
9003
- const kindError = this._clipKindError(t.name, "audio", true, clipEl.name || clipId);
9116
+ const kindError = clipKindError(t.name ?? "", "audio", true, clipEl.name || clipId);
9004
9117
  console.warn("[dawcore] _applyClipUpdate: " + kindError?.message);
9005
9118
  this.dispatchEvent(
9006
9119
  new CustomEvent("daw-clip-error", {
@@ -9012,7 +9125,7 @@ var DawEditorElement = class extends LitElement14 {
9012
9125
  return;
9013
9126
  }
9014
9127
  if (isMidiNow || wasMidi) {
9015
- const notes = this._validMidiNotes(clipEl.midiNotes ?? []);
9128
+ const notes = validMidiNotes(clipEl.midiNotes ?? []);
9016
9129
  const noteSpanSeconds = notes.length ? notes.reduce((max, n) => Math.max(max, n.time + n.duration), 0) : 0;
9017
9130
  const sourceDurationSamples = Math.ceil(Math.max(noteSpanSeconds, clipEl.duration, 1) * sr);
9018
9131
  const requestedDurationSamples = clipEl.duration > 0 ? Math.round(clipEl.duration * sr) : sourceDurationSamples;
@@ -9029,12 +9142,8 @@ var DawEditorElement = class extends LitElement14 {
9029
9142
  midiChannel: clipEl.midiChannel ?? void 0,
9030
9143
  midiProgram: clipEl.midiProgram ?? void 0
9031
9144
  };
9032
- const updatedClips2 = [...t.clips];
9033
- updatedClips2[idx] = updatedClip2;
9034
- const updatedTrack2 = { ...t, clips: updatedClips2 };
9035
- this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack2);
9036
9145
  this._purgeClipCaches(clipId);
9037
- this._commitTrackChange(trackId, updatedTrack2);
9146
+ this._replaceClip(trackId, clipId, updatedClip2);
9038
9147
  return;
9039
9148
  }
9040
9149
  const newStartSample = Math.round(clipEl.start * sr);
@@ -9048,10 +9157,6 @@ var DawEditorElement = class extends LitElement14 {
9048
9157
  gain: clipEl.gain,
9049
9158
  name: clipEl.name || oldClip.name
9050
9159
  };
9051
- const updatedClips = [...t.clips];
9052
- updatedClips[idx] = updatedClip;
9053
- const updatedTrack = { ...t, clips: updatedClips };
9054
- this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);
9055
9160
  const boundsChanged = oldClip.offsetSamples !== newOffsetSamples || oldClip.durationSamples !== newDurationSamples;
9056
9161
  if (boundsChanged) {
9057
9162
  this._clipOffsets.set(clipId, {
@@ -9063,40 +9168,41 @@ var DawEditorElement = class extends LitElement14 {
9063
9168
  this._peaksData = new Map(this._peaksData).set(clipId, peaks);
9064
9169
  }
9065
9170
  }
9066
- this._commitTrackChange(trackId, updatedTrack);
9171
+ this._replaceClip(trackId, clipId, updatedClip);
9067
9172
  }
9173
+ /** Remove a clip (loaded or still loading) from a track of the arrangement: an undo step. */
9068
9174
  _removeClipFromTrack(trackId, clipId) {
9069
- const t = this._engineTracks.get(trackId);
9070
- if (!t) {
9071
- console.warn('[dawcore] _removeClipFromTrack: no engine track for id "' + trackId + '"');
9175
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9176
+ if (!track) {
9177
+ console.warn('[dawcore] _removeClipFromTrack: no track for id "' + trackId + '"');
9072
9178
  return;
9073
9179
  }
9074
- const updatedClips = t.clips.filter((c) => c.id !== clipId);
9075
- if (updatedClips.length === t.clips.length) {
9180
+ if (!track.clips.some((c) => c.id === clipId)) {
9076
9181
  console.warn(
9077
9182
  '[dawcore] _removeClipFromTrack: clip "' + clipId + '" not found in track "' + trackId + '"'
9078
9183
  );
9079
9184
  return;
9080
9185
  }
9081
- const updatedTrack = { ...t, clips: updatedClips };
9082
- this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);
9083
- const nextBuffers = new Map(this._clipBuffers);
9084
- nextBuffers.delete(clipId);
9085
- this._clipBuffers = nextBuffers;
9086
- this._clipOffsets.delete(clipId);
9087
- const nextPeaks = new Map(this._peaksData);
9088
- nextPeaks.delete(clipId);
9089
- this._peaksData = nextPeaks;
9186
+ this._purgeClipCaches(clipId);
9187
+ this._previewWaveforms.delete(clipId);
9188
+ if (this._previewPeaks.has(clipId)) {
9189
+ const nextPreview = new Map(this._previewPeaks);
9190
+ nextPreview.delete(clipId);
9191
+ this._previewPeaks = nextPreview;
9192
+ }
9090
9193
  const desc = this._tracks.get(trackId);
9091
9194
  if (desc) {
9092
9195
  this._tracks = new Map(this._tracks).set(trackId, {
9093
9196
  ...desc,
9094
- // Descriptors without an id (file drops, the <daw-track src>
9095
- // shorthand) are kept — their identity is the descriptor itself.
9096
9197
  clips: desc.clips.filter((c) => c.clipId !== clipId)
9097
9198
  });
9098
9199
  }
9099
- this._commitTrackChange(trackId, updatedTrack);
9200
+ const wasLoading = track.clips.some((c) => c.id === clipId && isLoadingClip3(c));
9201
+ this._arrangement.updateTrack(trackId, (current) => ({
9202
+ ...current,
9203
+ clips: current.clips.filter((c) => c.id !== clipId)
9204
+ }));
9205
+ if (wasLoading) this._announcer.forgetClip(clipId);
9100
9206
  }
9101
9207
  _readTrackDescriptor(trackEl) {
9102
9208
  const clipEls = trackEl.querySelectorAll("daw-clip");
@@ -9119,25 +9225,7 @@ var DawEditorElement = class extends LitElement14 {
9119
9225
  midiProgram: null
9120
9226
  });
9121
9227
  } else {
9122
- for (const clipEl of clipEls) {
9123
- clips.push({
9124
- kind: "dom",
9125
- clipId: clipEl.clipId,
9126
- src: clipEl.src,
9127
- peaksSrc: clipEl.peaksSrc,
9128
- start: clipEl.start,
9129
- duration: clipEl.duration,
9130
- offset: clipEl.offset,
9131
- gain: clipEl.gain,
9132
- name: clipEl.name,
9133
- fadeIn: clipEl.fadeIn,
9134
- fadeOut: clipEl.fadeOut,
9135
- fadeType: clipEl.fadeType,
9136
- midiNotes: clipEl.midiNotes,
9137
- midiChannel: clipEl.midiChannel,
9138
- midiProgram: clipEl.midiProgram
9139
- });
9140
- }
9228
+ for (const clipEl of clipEls) clips.push(this._readClipDescriptor(clipEl));
9141
9229
  }
9142
9230
  return {
9143
9231
  name: trackEl.name || "Untitled",
@@ -9147,228 +9235,312 @@ var DawEditorElement = class extends LitElement14 {
9147
9235
  clips
9148
9236
  };
9149
9237
  }
9238
+ _readClipDescriptor(clipEl) {
9239
+ return {
9240
+ kind: "dom",
9241
+ clipId: clipEl.clipId,
9242
+ src: clipEl.src,
9243
+ peaksSrc: clipEl.peaksSrc,
9244
+ start: clipEl.start,
9245
+ duration: clipEl.duration,
9246
+ offset: clipEl.offset,
9247
+ gain: clipEl.gain,
9248
+ name: clipEl.name,
9249
+ fadeIn: clipEl.fadeIn,
9250
+ fadeOut: clipEl.fadeOut,
9251
+ fadeType: clipEl.fadeType,
9252
+ midiNotes: clipEl.midiNotes,
9253
+ midiChannel: clipEl.midiChannel,
9254
+ midiProgram: clipEl.midiProgram
9255
+ };
9256
+ }
9257
+ // --- Entering the arrangement (#848) ---
9258
+ _isEntered(trackId) {
9259
+ return this._arrangement.getTracks().some((t) => t.id === trackId);
9260
+ }
9261
+ /** Queue a registered track for the next flush. */
9262
+ _queueEntry(trackId) {
9263
+ if (!this._entryQueue.includes(trackId)) this._entryQueue = [...this._entryQueue, trackId];
9264
+ if (this._entryFlushScheduled) return;
9265
+ this._entryFlushScheduled = true;
9266
+ queueMicrotask(() => {
9267
+ this._entryFlushScheduled = false;
9268
+ this._flushTrackEntries();
9269
+ });
9270
+ }
9150
9271
  /**
9151
- * The error for a clip whose kind is not its track's (#756), or null. A clip
9152
- * with no `src` is a MIDI clip (see _isMidiDescriptor).
9272
+ * Enter the queued tracks into the arrangement, in DOM order. Without an
9273
+ * engine they wait (the sample rate of a MIDI clip comes from the
9274
+ * adapter); the engine's build flushes again. The page's tracks entering
9275
+ * while the arrangement has no history are not undo steps: the history is
9276
+ * cleared after them, so Undo right after load removes nothing (and the
9277
+ * next page track finds it empty again).
9153
9278
  */
9154
- _clipKindError(trackName, kind, clipIsMidi, clipLabel) {
9155
- if (clipIsMidi === (kind === "midi")) return null;
9156
- return new Error(
9157
- clipIsMidi ? 'clip "' + clipLabel + '" is a MIDI clip (no src) on audio track "' + trackName + `". A track holds one kind of clip: set kind="midi" on the <daw-track> (or kind: 'midi' in addTrack) for a track of MIDI clips.` : 'clip "' + clipLabel + '" is an audio clip on MIDI track "' + trackName + '". A track holds one kind of clip: put the clip on an audio track.'
9279
+ _flushTrackEntries() {
9280
+ if (this._entryQueue.length === 0) return;
9281
+ if (!this._engine) return;
9282
+ if (this._dragInProgress) {
9283
+ this._flushAfterDrag();
9284
+ return;
9285
+ }
9286
+ const queued = this._entryQueue;
9287
+ this._entryQueue = [];
9288
+ const domOrder = [...this.querySelectorAll("daw-track")].map(
9289
+ (el) => el.trackId
9158
9290
  );
9291
+ const position = (id) => {
9292
+ const at = domOrder.indexOf(id);
9293
+ return at === -1 ? domOrder.length : at;
9294
+ };
9295
+ const ordered = [...queued].sort((a, b) => position(a) - position(b));
9296
+ const isPageTrack = (id) => {
9297
+ const el = this._trackElements.get(id);
9298
+ return el !== void 0 && !this._editorMadeTracks.has(el);
9299
+ };
9300
+ const arrangement = this._arrangement;
9301
+ const historyWasEmpty = !arrangement.canUndo && !arrangement.canRedo && !this._dragInProgress;
9302
+ let pageEntered = false;
9303
+ for (const id of ordered.filter(isPageTrack)) {
9304
+ if (this._enterTrack(id)) pageEntered = true;
9305
+ }
9306
+ if (historyWasEmpty && pageEntered) arrangement.clearHistory();
9307
+ for (const id of ordered.filter((id2) => !isPageTrack(id2))) this._enterTrack(id);
9308
+ }
9309
+ /** Flush the queue once the drag in progress has ended (its pointer or key is released). */
9310
+ _flushAfterDrag() {
9311
+ if (this._waitingForDragEnd) return;
9312
+ this._waitingForDragEnd = true;
9313
+ const events = ["pointerup", "pointercancel", "keyup"];
9314
+ const retry = () => {
9315
+ for (const type of events) window.removeEventListener(type, retry);
9316
+ this._waitingForDragEnd = false;
9317
+ setTimeout(() => this._flushTrackEntries(), 0);
9318
+ };
9319
+ for (const type of events) window.addEventListener(type, retry);
9159
9320
  }
9160
- // --- Audio Loading ---
9161
- async _loadTrack(trackId, descriptor) {
9162
- this._loadingTracks.add(trackId);
9163
- const sppAtLoadStart = this._samplesPerPixel;
9164
- try {
9165
- const clips = [];
9166
- let refusedMidiClips = 0;
9167
- for (const clipDesc of descriptor.clips) {
9168
- const clipIsMidi = this._isMidiDescriptor(clipDesc);
9169
- const kindError = this._clipKindError(
9170
- descriptor.name,
9171
- descriptor.kind,
9172
- clipIsMidi,
9173
- clipDesc.name || clipDesc.src || (isDomClip(clipDesc) ? clipDesc.clipId : "")
9174
- );
9175
- if (kindError) {
9176
- console.warn("[dawcore] _loadTrack: " + kindError.message);
9177
- if (this.isConnected) {
9178
- this.dispatchEvent(
9179
- new CustomEvent("daw-clip-error", {
9180
- bubbles: true,
9181
- composed: true,
9182
- detail: {
9183
- trackId,
9184
- clipId: isDomClip(clipDesc) ? clipDesc.clipId : "",
9185
- error: kindError
9186
- }
9187
- })
9188
- );
9189
- }
9190
- if (clipIsMidi) refusedMidiClips++;
9191
- continue;
9192
- }
9193
- if (clipIsMidi) {
9194
- clips.push(this._buildMidiClip(clipDesc));
9195
- continue;
9196
- }
9197
- try {
9198
- const waveformDataPromise = clipDesc.peaksSrc ? this._resolvePeaks(clipDesc.peaksSrc) : Promise.resolve(null);
9199
- const audioPromise = this._fetchAndDecode(clipDesc.src);
9200
- const waveformData = await waveformDataPromise;
9201
- if (waveformData) {
9202
- const wdRate = waveformData.sample_rate;
9203
- const clip2 = createClip2({
9204
- waveformData,
9205
- startSample: Math.round(clipDesc.start * wdRate),
9206
- durationSamples: Math.round((clipDesc.duration || waveformData.duration) * wdRate),
9207
- offsetSamples: Math.round(clipDesc.offset * wdRate),
9208
- gain: clipDesc.gain,
9209
- name: clipDesc.name,
9210
- sampleRate: wdRate,
9211
- sourceDurationSamples: Math.ceil(waveformData.duration * wdRate)
9212
- });
9213
- if (isDomClip(clipDesc)) clip2.id = clipDesc.clipId;
9214
- const effectiveScale = Math.max(this._renderSpp, waveformData.scale);
9215
- const peakData = extractPeaks(
9216
- waveformData,
9217
- effectiveScale,
9218
- this.mono,
9219
- clip2.offsetSamples,
9220
- clip2.durationSamples
9221
- );
9222
- this._clipOffsets.set(clip2.id, {
9223
- offsetSamples: clip2.offsetSamples,
9224
- durationSamples: clip2.durationSamples
9225
- });
9226
- this._peaksData = new Map(this._peaksData).set(clip2.id, peakData);
9227
- this._raiseZoomFloor(waveformData.scale);
9228
- if (this._tracks.has(trackId)) {
9229
- const previewTrack = createTrack({
9230
- name: descriptor.name,
9231
- kind: descriptor.kind,
9232
- clips: [clip2],
9233
- ...this._mixOf(trackId)
9234
- });
9235
- previewTrack.id = trackId;
9236
- this._engineTracks = new Map(this._engineTracks).set(trackId, previewTrack);
9237
- this._recomputeDuration();
9238
- }
9239
- let audioBuffer2;
9240
- try {
9241
- audioBuffer2 = await audioPromise;
9242
- } catch (audioErr) {
9243
- const nextPeaks = new Map(this._peaksData);
9244
- nextPeaks.delete(clip2.id);
9245
- this._peaksData = nextPeaks;
9246
- this._clipOffsets.delete(clip2.id);
9247
- const nextEngine = new Map(this._engineTracks);
9248
- nextEngine.delete(trackId);
9249
- this._engineTracks = nextEngine;
9250
- this._recomputeZoomFloor();
9251
- this._recomputeDuration();
9252
- throw audioErr;
9253
- }
9254
- this._resolvedSampleRate = audioBuffer2.sampleRate;
9255
- const updatedClip = { ...clip2, audioBuffer: audioBuffer2 };
9256
- this._clipBuffers = new Map(this._clipBuffers).set(clip2.id, audioBuffer2);
9257
- this._peakPipeline.cacheWaveformData(audioBuffer2, waveformData);
9258
- clips.push(updatedClip);
9259
- continue;
9260
- }
9261
- const audioBuffer = await audioPromise;
9262
- this._resolvedSampleRate = audioBuffer.sampleRate;
9263
- const clip = await this._finalizeAudioClip(clipDesc, audioBuffer, null);
9264
- clips.push(clip);
9265
- } catch (clipErr) {
9266
- console.warn(
9267
- '[dawcore] _loadTrack: clip "' + clipDesc.src + '" failed: ' + String(clipErr)
9268
- );
9269
- if (this.isConnected) {
9270
- this.dispatchEvent(
9271
- new CustomEvent("daw-clip-error", {
9272
- bubbles: true,
9273
- composed: true,
9274
- detail: {
9275
- trackId,
9276
- clipId: isDomClip(clipDesc) ? clipDesc.clipId : "",
9277
- error: clipErr
9278
- }
9279
- })
9280
- );
9281
- }
9282
- }
9283
- }
9284
- const trackWasRemoved = !this._tracks.has(trackId);
9285
- if (trackWasRemoved || !this.isConnected) {
9286
- for (const clip of clips) {
9287
- this._purgeClipCaches(clip.id);
9288
- }
9289
- if (this._engineTracks.has(trackId)) {
9290
- const nextEngine = new Map(this._engineTracks);
9291
- nextEngine.delete(trackId);
9292
- this._engineTracks = nextEngine;
9293
- this._recomputeDuration();
9294
- }
9295
- this._recomputeZoomFloor();
9296
- if (this._samplesPerPixel !== sppAtLoadStart && sppAtLoadStart >= this._minSamplesPerPixel) {
9297
- this.samplesPerPixel = sppAtLoadStart;
9298
- }
9299
- throw new TrackLoadCancelledError(
9300
- trackWasRemoved ? 'track "' + trackId + '" was removed while loading' : 'editor was disconnected while track "' + trackId + '" was loading',
9301
- trackWasRemoved ? "removed" : "disconnected"
9302
- );
9303
- }
9304
- const track = createTrack({
9305
- name: descriptor.name,
9306
- kind: descriptor.kind,
9307
- clips,
9308
- ...this._mixOf(trackId)
9309
- });
9310
- const requestedClips = descriptor.clips.filter((c) => c.src).length + refusedMidiClips;
9311
- if (requestedClips > 0 && clips.length === 0) {
9312
- throw new Error(
9313
- "all " + requestedClips + " clip(s) failed to load \u2014 see prior daw-clip-error events"
9314
- );
9315
- }
9316
- track.id = trackId;
9317
- this._engineTracks = new Map(this._engineTracks).set(trackId, track);
9318
- this._recomputeDuration();
9319
- for (const c of clips) {
9320
- this._maybeRegisterSpectrogramClipAudio(trackId, c);
9321
- }
9322
- const engine = await this._ensureEngine();
9323
- engine.setTracks(this._tracksForEngine());
9321
+ /** Enter one registered track. False when it is gone, already in, or refused. */
9322
+ _enterTrack(trackId) {
9323
+ const descriptor = this._tracks.get(trackId);
9324
+ if (!descriptor || this._isEntered(trackId)) return false;
9325
+ const el = this._trackElements.get(trackId);
9326
+ const built = buildArrangementTrack(
9327
+ trackId,
9328
+ descriptor,
9329
+ el ? mixOfElement(el) : DEFAULT_TRACK_MIX,
9330
+ this.effectiveSampleRate
9331
+ );
9332
+ if (built.descriptor !== descriptor) {
9333
+ this._tracks = new Map(this._tracks).set(trackId, built.descriptor);
9334
+ }
9335
+ for (const { clipId, error } of built.refused) {
9336
+ console.warn("[dawcore] " + error.message);
9324
9337
  this.dispatchEvent(
9325
- new CustomEvent("daw-track-ready", {
9338
+ new CustomEvent("daw-clip-error", {
9326
9339
  bubbles: true,
9327
9340
  composed: true,
9328
- detail: { trackId }
9341
+ detail: { trackId, clipId, error }
9329
9342
  })
9330
9343
  );
9344
+ }
9345
+ const index = el ? entryIndex(
9346
+ [...this.querySelectorAll("daw-track")],
9347
+ trackId,
9348
+ this._arrangement.getTracks().map((t) => t.id)
9349
+ ) : void 0;
9350
+ this._announcer.expect(trackId, built.refused.length);
9351
+ for (const clip of built.track.clips) {
9352
+ if (isLoadingClip3(clip)) this._announcer.expectClip(clip.id);
9353
+ }
9354
+ try {
9355
+ this._arrangement.addTrack(built.track, index === void 0 ? void 0 : { index });
9331
9356
  } catch (err) {
9332
- const cancelled = err instanceof TrackLoadCancelledError;
9333
- console.warn(
9334
- cancelled ? "[dawcore] Track load cancelled: " + err.message : '[dawcore] Failed to load track "' + trackId + '": ' + String(err)
9335
- );
9357
+ console.warn('[dawcore] Failed to add track "' + trackId + '": ' + String(err));
9358
+ this._settleEntry(trackId, err instanceof Error ? err : new Error(String(err)));
9336
9359
  this.dispatchEvent(
9337
9360
  new CustomEvent("daw-track-error", {
9338
9361
  bubbles: true,
9339
9362
  composed: true,
9340
- detail: {
9341
- trackId,
9342
- error: err,
9343
- ...cancelled ? { reason: err.reason } : {}
9344
- }
9363
+ detail: { trackId, error: err }
9345
9364
  })
9346
9365
  );
9347
- } finally {
9348
- this._loadingTracks.delete(trackId);
9349
- }
9350
- }
9351
- async _fetchAndDecode(src) {
9352
- if (this._audioCache.has(src)) {
9353
- return this._audioCache.get(src);
9366
+ return false;
9354
9367
  }
9355
- const promise = (async () => {
9356
- const response = await fetch(src);
9357
- if (!response.ok) {
9358
- throw new Error(
9359
- 'Failed to fetch audio "' + src + '": ' + response.status + " " + response.statusText
9360
- );
9368
+ this._settleEntry(trackId, null);
9369
+ for (const clipDesc of built.descriptor.clips) {
9370
+ if (clipDesc.peaksSrc && clipDesc.clipId && clipSourceOf(clipDesc)) {
9371
+ this._requestPreview(clipDesc.clipId, clipDesc.peaksSrc);
9361
9372
  }
9362
- const arrayBuffer = await response.arrayBuffer();
9363
- return this.audioContext.decodeAudioData(arrayBuffer);
9364
- })();
9365
- this._audioCache.set(src, promise);
9366
- try {
9367
- return await promise;
9368
- } catch (err) {
9369
- this._audioCache.delete(src);
9370
- throw err;
9371
9373
  }
9374
+ return true;
9375
+ }
9376
+ /**
9377
+ * The `<daw-track src>` shorthand changed its src: the entered track gets a
9378
+ * new loading clip for it, one undo step. A track whose clips are
9379
+ * `<daw-clip>` children keeps them. A track still queued reads the new
9380
+ * descriptor when it enters.
9381
+ */
9382
+ _replaceShorthandClips(trackId, descriptor) {
9383
+ if (!this._isEntered(trackId) || descriptor.clips.some(isDomClip)) return;
9384
+ const built = buildArrangementTrack(
9385
+ trackId,
9386
+ descriptor,
9387
+ DEFAULT_TRACK_MIX,
9388
+ this.effectiveSampleRate
9389
+ );
9390
+ this._tracks = new Map(this._tracks).set(trackId, built.descriptor);
9391
+ this._arrangement.updateTrack(trackId, (current) => ({ ...current, clips: built.track.clips }));
9392
+ }
9393
+ /** Run the load announcements over the arrangement's current state. */
9394
+ _announceLoading() {
9395
+ this._announcer.update(
9396
+ this._arrangement.getTracks(),
9397
+ this._arrangement.sources.getSnapshot().sources
9398
+ );
9399
+ }
9400
+ /**
9401
+ * Fetch a loading clip's `.dat` peaks and draw them until its audio
9402
+ * arrives (an editor-only cache, not the arrangement: writing the clip
9403
+ * after it entered would be an undo step).
9404
+ */
9405
+ async _requestPreview(clipId, peaksSrc) {
9406
+ const waveformData = await this._resolvePeaks(peaksSrc);
9407
+ if (!waveformData) return;
9408
+ const clip = this._arrangement.getTracks().flatMap((t) => t.clips).find((c) => c.id === clipId);
9409
+ if (!clip || !isLoadingClip3(clip)) return;
9410
+ const rate = waveformData.sample_rate;
9411
+ const offset = clip.offset ?? 0;
9412
+ const seconds = clip.duration ?? Math.max(0, waveformData.duration - offset);
9413
+ const peakData = extractPeaks(
9414
+ waveformData,
9415
+ Math.max(this._renderSpp, waveformData.scale),
9416
+ this.mono,
9417
+ Math.round(offset * rate),
9418
+ Math.round(seconds * rate)
9419
+ );
9420
+ this._previewPeaks = new Map(this._previewPeaks).set(clipId, peakData);
9421
+ this._previewWaveforms.set(clipId, waveformData);
9422
+ this._raiseZoomFloor(waveformData.scale);
9423
+ this._recomputeDuration();
9424
+ }
9425
+ /** The peak sync made a clip's peaks: its zoom floor holds, its preview goes. */
9426
+ _clipPeaksReady(clipId, audioBuffer) {
9427
+ this._raiseZoomFloor(this._peakPipeline.getCachedScale(audioBuffer));
9428
+ if (!this._previewPeaks.has(clipId)) return;
9429
+ const next = new Map(this._previewPeaks);
9430
+ next.delete(clipId);
9431
+ this._previewPeaks = next;
9432
+ }
9433
+ _waitForEntry(trackId) {
9434
+ return new Promise((resolve, reject) => {
9435
+ this._entryWaiters.set(trackId, { resolve, reject });
9436
+ });
9437
+ }
9438
+ /** Settle the wait for a track's entry: entered (`null`), or refused or gone. */
9439
+ _settleEntry(trackId, error) {
9440
+ const waiter = this._entryWaiters.get(trackId);
9441
+ if (!waiter) return;
9442
+ this._entryWaiters.delete(trackId);
9443
+ if (error) waiter.reject(error);
9444
+ else waiter.resolve(trackId);
9445
+ }
9446
+ /**
9447
+ * A dropped file as a track with no element (a File cannot be an attribute):
9448
+ * one loading clip whose source is the file. Resolves with the track id once
9449
+ * it has entered, an undo step like any track an editor method adds.
9450
+ */
9451
+ _addDroppedFile(file) {
9452
+ const trackId = crypto.randomUUID();
9453
+ const name = file.name.replace(/\.\w+$/, "");
9454
+ this._tracks = new Map(this._tracks).set(trackId, {
9455
+ name,
9456
+ src: "",
9457
+ kind: "audio",
9458
+ renderMode: trackDescriptorRenderMode("audio", "waveform"),
9459
+ clips: [
9460
+ {
9461
+ kind: "drop",
9462
+ file,
9463
+ src: "",
9464
+ peaksSrc: "",
9465
+ start: 0,
9466
+ duration: 0,
9467
+ offset: 0,
9468
+ gain: 1,
9469
+ name,
9470
+ fadeIn: 0,
9471
+ fadeOut: 0,
9472
+ fadeType: "linear",
9473
+ midiNotes: null,
9474
+ midiChannel: null,
9475
+ midiProgram: null
9476
+ }
9477
+ ]
9478
+ });
9479
+ const entered = this._waitForEntry(trackId);
9480
+ this._queueEntry(trackId);
9481
+ return entered;
9482
+ }
9483
+ /**
9484
+ * Take a track out for good: no undo step, and no undo or redo brings it
9485
+ * back (a dropped file that could not be loaded was never a declaration).
9486
+ */
9487
+ _discardTrack(trackId) {
9488
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9489
+ this._announcer.forget(trackId, track?.clips.map((c) => c.id) ?? []);
9490
+ this._arrangement.removeTrack(trackId, { undoable: false });
9491
+ this._onTrackRemoved(trackId);
9492
+ }
9493
+ /**
9494
+ * Resolves once the track has loaded (`daw-track-ready`), or when the
9495
+ * editor is disconnected meanwhile (the track is kept and loads after a
9496
+ * reparent); rejects when its audio failed (`daw-track-error`).
9497
+ */
9498
+ _whenTrackLoaded(trackId) {
9499
+ const state9 = this._announcer.stateOf(trackId);
9500
+ if (state9 === "ready") return Promise.resolve();
9501
+ if (state9 === "failed") return Promise.reject(this._announcer.errorOf(trackId));
9502
+ return new Promise((resolve, reject) => {
9503
+ const cleanup = () => {
9504
+ this.removeEventListener("daw-track-ready", onReady);
9505
+ this.removeEventListener("daw-track-error", onError);
9506
+ this._loadWaitEnds.delete(end);
9507
+ };
9508
+ const onReady = (e) => {
9509
+ if (e.detail.trackId !== trackId) return;
9510
+ cleanup();
9511
+ resolve();
9512
+ };
9513
+ const onError = (e) => {
9514
+ const detail = e.detail;
9515
+ if (detail.trackId !== trackId) return;
9516
+ cleanup();
9517
+ reject(detail.error instanceof Error ? detail.error : new Error(String(detail.error)));
9518
+ };
9519
+ const end = () => {
9520
+ cleanup();
9521
+ resolve();
9522
+ };
9523
+ this.addEventListener("daw-track-ready", onReady);
9524
+ this.addEventListener("daw-track-error", onError);
9525
+ this._loadWaitEnds.add(end);
9526
+ });
9527
+ }
9528
+ /**
9529
+ * Load again every failed source the track's clips name (#848). A track
9530
+ * whose audio failed stays in the editor, like a broken `<img>`;
9531
+ * `daw-track-ready` follows when it loads.
9532
+ */
9533
+ retryTrack(trackId) {
9534
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9535
+ if (!track) {
9536
+ console.warn('[dawcore] retryTrack: no track found for id "' + trackId + '"');
9537
+ return;
9538
+ }
9539
+ const sources = this._arrangement.sources.getSnapshot().sources;
9540
+ const failed = new Set(
9541
+ track.clips.filter(isLoadingClip3).map((clip) => clip.src).filter((src) => sources.get(src)?.status === "failed")
9542
+ );
9543
+ for (const src of failed) this._arrangement.retry(src);
9372
9544
  }
9373
9545
  _fetchPeaks(src) {
9374
9546
  const cached = this._peaksCache.get(src);
@@ -9380,7 +9552,13 @@ var DawEditorElement = class extends LitElement14 {
9380
9552
  this._peaksCache.set(src, promise);
9381
9553
  return promise;
9382
9554
  }
9555
+ /**
9556
+ * The timeline's duration, the one writer of `_duration`: the loaded clips,
9557
+ * and the clips still loading whose length is known (a duration, or `.dat`
9558
+ * peaks), so the timeline is as wide as what is drawn (#848).
9559
+ */
9383
9560
  _recomputeDuration() {
9561
+ const sr = this.effectiveSampleRate;
9384
9562
  let maxSample = 0;
9385
9563
  for (const track of this._engineTracks.values()) {
9386
9564
  for (const clip of track.clips) {
@@ -9388,28 +9566,60 @@ var DawEditorElement = class extends LitElement14 {
9388
9566
  if (endSample > maxSample) maxSample = endSample;
9389
9567
  }
9390
9568
  }
9391
- this._duration = maxSample / this.effectiveSampleRate;
9569
+ for (const track of this._arrangement.getTracks()) {
9570
+ for (const clip of track.clips) {
9571
+ if (!isLoadingClip3(clip)) continue;
9572
+ const seconds = this._placeholderSeconds(clip);
9573
+ if (seconds === null) continue;
9574
+ maxSample = Math.max(maxSample, Math.round(((clip.start ?? 0) + seconds) * sr));
9575
+ }
9576
+ }
9577
+ this._duration = maxSample / sr;
9578
+ }
9579
+ /** How long a loading clip is drawn: its duration, else what its `.dat` peaks cover; null when unknown. */
9580
+ _placeholderSeconds(clip) {
9581
+ if (clip.duration != null && clip.duration > 0) return clip.duration;
9582
+ const waveformData = this._previewWaveforms.get(clip.id);
9583
+ if (!waveformData) return null;
9584
+ const seconds = waveformData.duration - (clip.offset ?? 0);
9585
+ return seconds > 0 ? seconds : null;
9392
9586
  }
9393
9587
  // --- Engine ---
9588
+ /**
9589
+ * The engine, built now when the editor is connected with an adapter.
9590
+ * Rejects without an adapter, and on a detached editor (an engine built
9591
+ * there would hold the adapter's graph with nothing to dispose it).
9592
+ */
9394
9593
  _ensureEngine() {
9395
9594
  if (this._engine) return Promise.resolve(this._engine);
9396
- if (this._enginePromise) return this._enginePromise;
9397
- this._enginePromise = this._buildEngine().catch((err) => {
9398
- this._enginePromise = null;
9399
- throw err;
9400
- });
9401
- return this._enginePromise;
9595
+ try {
9596
+ if (!this.isConnected && this._externalAdapter) {
9597
+ throw new Error("[dawcore] <daw-editor> is not connected: no engine is built for it.");
9598
+ }
9599
+ return Promise.resolve(this._buildEngine());
9600
+ } catch (err) {
9601
+ return Promise.reject(err);
9602
+ }
9402
9603
  }
9403
- async _buildEngine() {
9604
+ /** Build the engine from the adapter setter or a connect: a failure is reported, not thrown. */
9605
+ _buildEngineReporting() {
9606
+ try {
9607
+ this._buildEngine();
9608
+ } catch (err) {
9609
+ console.warn("[dawcore] Failed to build the engine: " + String(err));
9610
+ this.dispatchEvent(
9611
+ new CustomEvent("daw-error", {
9612
+ bubbles: true,
9613
+ composed: true,
9614
+ detail: { operation: "engine", error: err }
9615
+ })
9616
+ );
9617
+ }
9618
+ }
9619
+ _buildEngine() {
9404
9620
  if (!this._externalAdapter) {
9405
9621
  throw new Error(noAdapterError());
9406
9622
  }
9407
- if (this._adapterConsumedByDispose) {
9408
- throw new Error(
9409
- "[dawcore] editor.adapter was disposed by a previous disconnect \u2014 set a fresh PlayoutAdapter after reparenting <daw-editor>."
9410
- );
9411
- }
9412
- const { PlaylistEngine } = await import("@waveform-playlist/engine");
9413
9623
  const adapter = this._externalAdapter;
9414
9624
  if (!this._hasTickCallbacks) {
9415
9625
  if (adapter.setTempo) {
@@ -9424,63 +9634,92 @@ var DawEditorElement = class extends LitElement14 {
9424
9634
  this.ppqn = adapter.ppqn;
9425
9635
  const engine = new PlaylistEngine({
9426
9636
  adapter,
9427
- sampleRate: this.effectiveSampleRate,
9637
+ arrangement: this._arrangement,
9638
+ sampleRate: adapter.audioContext.sampleRate,
9428
9639
  samplesPerPixel: this.samplesPerPixel,
9429
9640
  bpm: this._bpm,
9430
9641
  zoomLevels: [256, 512, 1024, 2048, 4096, 8192, this.samplesPerPixel].filter((v, i, a) => a.indexOf(v) === i).sort((a, b) => a - b)
9431
9642
  });
9432
- let lastTracksVersion = -1;
9433
- let lastMixerVersion = -1;
9434
- engine.on("statechange", (engineState) => {
9435
- this._isPlaying = engineState.isPlaying;
9436
- this._duration = engineState.duration;
9437
- this._selectedTrackId = engineState.selectedTrackId;
9438
- const structuralChange = engineState.tracksVersion !== lastTracksVersion;
9439
- const mixerChange = engineState.mixerVersion !== lastMixerVersion;
9440
- if (structuralChange || mixerChange) {
9441
- lastTracksVersion = engineState.tracksVersion;
9442
- lastMixerVersion = engineState.mixerVersion;
9443
- const nextTracks = /* @__PURE__ */ new Map();
9444
- for (const track of engineState.tracks) {
9445
- nextTracks.set(track.id, track);
9446
- }
9447
- this._engineTracks = nextTracks;
9448
- this._deleteSeedMix(nextTracks.keys());
9449
- this._reconcileDescriptorsWithEngineTracks(engineState.tracks);
9450
- }
9451
- if (structuralChange) {
9452
- if (!this._inOrderSync) {
9453
- this._syncDomToEngineOrder(engineState.tracks);
9454
- }
9455
- this._effectsManager?.rewireTrackChains();
9456
- const audioTracks = engineState.tracks.filter((t) => trackKind(t) !== "midi");
9457
- syncPeaksForChangedClips(this, audioTracks);
9458
- }
9459
- if (engineState.bpm !== this._lastAnnotationBpm) {
9460
- this._lastAnnotationBpm = engineState.bpm;
9461
- this._annotations.deriveSecondsCaches();
9462
- }
9463
- });
9643
+ this._lastTracksVersion = -1;
9644
+ this._lastMixerVersion = -1;
9645
+ engine.on("statechange", (engineState) => this._onEngineState(engineState));
9464
9646
  engine.on("pause", () => {
9465
9647
  this._currentTime = engine.getCurrentTime();
9466
9648
  });
9467
- engine.on("stop", () => {
9468
- this._currentTime = engine.getCurrentTime();
9469
- this._stopPlayhead();
9470
- this._activePlayEndTime = null;
9471
- if (!this._inConsumerStop && !this._inSeekTransition && this.isConnected) {
9472
- this.dispatchEvent(new CustomEvent("daw-stop", { bubbles: true, composed: true }));
9473
- }
9474
- });
9649
+ engine.on("stop", () => this._onEngineStop(engine));
9475
9650
  this._engine = engine;
9651
+ this._onEngineState(engine.getState());
9652
+ for (const track of this._engineTracks.values()) {
9653
+ for (const clip of track.clips) this._maybeRegisterSpectrogramClipAudio(track.id, clip);
9654
+ }
9655
+ this._flushTrackEntries();
9476
9656
  return engine;
9477
9657
  }
9658
+ /**
9659
+ * Clips whose audio has just arrived: a `.dat` preview's data goes to the
9660
+ * peak pipeline (no worker run), a spectrogram track gets the audio. The
9661
+ * peak sync then makes their peaks.
9662
+ */
9663
+ _adoptLoadedClips(tracks) {
9664
+ for (const track of tracks) {
9665
+ for (const clip of track.clips) {
9666
+ const waveformData = this._previewWaveforms.get(clip.id);
9667
+ if (waveformData && clip.audioBuffer) {
9668
+ if (waveformData.sample_rate === clip.audioBuffer.sampleRate) {
9669
+ this._peakPipeline.cacheWaveformData(clip.audioBuffer, waveformData);
9670
+ }
9671
+ this._previewWaveforms.delete(clip.id);
9672
+ }
9673
+ if (!this._clipBuffers.has(clip.id))
9674
+ this._maybeRegisterSpectrogramClipAudio(track.id, clip);
9675
+ }
9676
+ }
9677
+ }
9678
+ /** The engine's state changed: follow it (the one writer of `_engineTracks`). */
9679
+ _onEngineState(engineState) {
9680
+ this._isPlaying = engineState.isPlaying;
9681
+ this._selectedTrackId = engineState.selectedTrackId;
9682
+ const structuralChange = engineState.tracksVersion !== this._lastTracksVersion;
9683
+ const mixerChange = engineState.mixerVersion !== this._lastMixerVersion;
9684
+ if (structuralChange || mixerChange) {
9685
+ this._lastTracksVersion = engineState.tracksVersion;
9686
+ this._lastMixerVersion = engineState.mixerVersion;
9687
+ const nextTracks = /* @__PURE__ */ new Map();
9688
+ for (const track of engineState.tracks) {
9689
+ nextTracks.set(track.id, track);
9690
+ }
9691
+ this._engineTracks = nextTracks;
9692
+ this._reconcileDescriptorsWithEngineTracks(engineState.tracks);
9693
+ }
9694
+ if (structuralChange) {
9695
+ this._recomputeDuration();
9696
+ if (!this._inOrderSync) {
9697
+ this._syncDomToEngineOrder(engineState.tracks);
9698
+ }
9699
+ this._effectsManager?.rewireTrackChains();
9700
+ const audioTracks = engineState.tracks.filter((t) => trackKind(t) !== "midi");
9701
+ this._adoptLoadedClips(audioTracks);
9702
+ syncPeaksForChangedClips(this, audioTracks);
9703
+ this._announceLoading();
9704
+ }
9705
+ if (engineState.bpm !== this._lastAnnotationBpm) {
9706
+ this._lastAnnotationBpm = engineState.bpm;
9707
+ this._annotations.deriveSecondsCaches();
9708
+ }
9709
+ }
9710
+ _onEngineStop(engine) {
9711
+ this._currentTime = engine.getCurrentTime();
9712
+ this._stopPlayhead();
9713
+ this._activePlayEndTime = null;
9714
+ if (!this._inConsumerStop && !this._inSeekTransition && this.isConnected) {
9715
+ this.dispatchEvent(new CustomEvent("daw-stop", { bubbles: true, composed: true }));
9716
+ }
9717
+ }
9478
9718
  _disposeEngine() {
9479
9719
  if (this._engine) {
9480
9720
  this._engine.dispose();
9481
9721
  this._engine = null;
9482
9722
  }
9483
- this._enginePromise = null;
9484
9723
  }
9485
9724
  async loadFiles(files) {
9486
9725
  return loadFiles(this, files);
@@ -9511,43 +9750,17 @@ var DawEditorElement = class extends LitElement14 {
9511
9750
  return this._ensureEngine();
9512
9751
  }
9513
9752
  /**
9514
- * Wait for either `readyEvent` or `errorEvent` to fire on this editor for
9515
- * the entity matching `matchesId`. Listeners are wired synchronously, then
9516
- * `setup` is called (typical: appendChild). Resolves with `resolveValue`
9517
- * on ready; rejects with a normalized Error on error. Used by addTrack and
9518
- * addClip to share their Promise-with-listener-cleanup machinery.
9519
- */
9520
- _awaitId(readyEvent, errorEvent, matchesId, resolveValue, setup) {
9521
- return new Promise((resolve, reject) => {
9522
- const onReady = (e) => {
9523
- if (!matchesId(e.detail)) return;
9524
- cleanup();
9525
- resolve(resolveValue);
9526
- };
9527
- const onError = (e) => {
9528
- const detail = e.detail;
9529
- if (!matchesId(e.detail)) return;
9530
- cleanup();
9531
- const err = detail.error;
9532
- reject(err instanceof Error ? err : new Error(String(err)));
9533
- };
9534
- const cleanup = () => {
9535
- this.removeEventListener(readyEvent, onReady);
9536
- this.removeEventListener(errorEvent, onError);
9537
- };
9538
- this.addEventListener(readyEvent, onReady);
9539
- this.addEventListener(errorEvent, onError);
9540
- setup();
9541
- });
9542
- }
9543
- /**
9544
- * Append a `<daw-track>` element built from `config` and resolve once the
9545
- * track finishes loading (or reject on `daw-track-error`). Goes through
9546
- * the same `_loadTrack` pipeline as declarative tracks, so descriptors,
9547
- * peaks, and clip buffers are populated correctly.
9753
+ * Append a `<daw-track>` element built from `config` and resolve with its
9754
+ * track id once the track has entered the arrangement (#848), before its
9755
+ * audio has loaded. To follow loading, add the `daw-track-ready` /
9756
+ * `daw-track-error` listener BEFORE calling: for a track with nothing to
9757
+ * fetch, or whose audio is already loaded, it fires before this resolves.
9758
+ * Without `editor.adapter` it waits for one. Rejects when the track is
9759
+ * refused by the arrangement or removed before it enters.
9548
9760
  */
9549
9761
  addTrack(config = {}) {
9550
9762
  const trackEl = document.createElement("daw-track");
9763
+ this._editorMadeTracks.add(trackEl);
9551
9764
  if (config.name !== void 0) trackEl.setAttribute("name", config.name);
9552
9765
  if (config.volume !== void 0) trackEl.volume = config.volume;
9553
9766
  if (config.pan !== void 0) trackEl.pan = config.pan;
@@ -9567,13 +9780,9 @@ var DawEditorElement = class extends LitElement14 {
9567
9780
  for (const clipConfig of clipConfigs) {
9568
9781
  trackEl.appendChild(this._buildClipElement(clipConfig));
9569
9782
  }
9570
- return this._awaitId(
9571
- "daw-track-ready",
9572
- "daw-track-error",
9573
- (d) => d.trackId === trackEl.trackId,
9574
- trackEl,
9575
- () => this.appendChild(trackEl)
9576
- );
9783
+ const entered = this._waitForEntry(trackEl.trackId);
9784
+ this.appendChild(trackEl);
9785
+ return entered;
9577
9786
  }
9578
9787
  /**
9579
9788
  * Remove a track by id. Equivalent to `trackElement.remove()` —
@@ -9584,7 +9793,8 @@ var DawEditorElement = class extends LitElement14 {
9584
9793
  const trackEl = this._trackElements.get(trackId);
9585
9794
  if (trackEl) {
9586
9795
  trackEl.remove();
9587
- } else if (this._engineTracks.has(trackId)) {
9796
+ if (!this.isConnected) this._onTrackRemoved(trackId);
9797
+ } else if (this._tracks.has(trackId) || this._isEntered(trackId)) {
9588
9798
  this._onTrackRemoved(trackId);
9589
9799
  } else {
9590
9800
  console.warn('[dawcore] removeTrack: no track found for id "' + trackId + '"');
@@ -9611,8 +9821,8 @@ var DawEditorElement = class extends LitElement14 {
9611
9821
  const anchor = els[clamped];
9612
9822
  if (clamped > from) anchor.after(el);
9613
9823
  else anchor.before(el);
9614
- } else if (this._engineTracks.has(trackId)) {
9615
- this._engine.reorderTrack(trackId, toIndex);
9824
+ } else if (this._isEntered(trackId)) {
9825
+ this._arrangement.reorderTrack(trackId, toIndex);
9616
9826
  this.requestUpdate();
9617
9827
  } else {
9618
9828
  console.warn('[dawcore] reorderTrack: no track found for id "' + trackId + '"');
@@ -9620,8 +9830,8 @@ var DawEditorElement = class extends LitElement14 {
9620
9830
  }
9621
9831
  /**
9622
9832
  * Update reflected attributes on a track. The mixer fields go to their
9623
- * owner as one undo step (#843): the engine, or while the track is loading
9624
- * the values it will enter with (not a step). For DOM-element tracks the
9833
+ * owner, the arrangement, as one undo step (#843; also while the track
9834
+ * loads, #848). For DOM-element tracks the
9625
9835
  * changes are also written to the `<daw-track>` element; for tracks
9626
9836
  * without a DOM element (file drops) the descriptor is updated in place.
9627
9837
  */
@@ -9670,8 +9880,10 @@ var DawEditorElement = class extends LitElement14 {
9670
9880
  }
9671
9881
  /**
9672
9882
  * Append a clip to an existing track. Builds a `<daw-clip>` from `config`
9673
- * and appends it to the track's DOM element when one exists; resolves with
9674
- * the new clip's id once the audio decode + peak generation finish.
9883
+ * and appends it to the track's DOM element; resolves with the new clip's
9884
+ * id once its audio has loaded (`daw-clip-ready`, before its peaks are
9885
+ * drawn); rejects when it fails to load, is refused, or leaves the
9886
+ * arrangement before it loads (a removal, an Undo).
9675
9887
  */
9676
9888
  addClip(trackId, config) {
9677
9889
  if (!config.src) {
@@ -9689,14 +9901,54 @@ var DawEditorElement = class extends LitElement14 {
9689
9901
  )
9690
9902
  );
9691
9903
  }
9904
+ if (!this._isEntered(trackId) && !this._entryQueue.includes(trackId)) {
9905
+ return Promise.reject(
9906
+ new Error(
9907
+ 'addClip: track "' + trackId + '" is not in the editor (an Undo took it out, or the arrangement refused it)'
9908
+ )
9909
+ );
9910
+ }
9692
9911
  const clipEl = this._buildClipElement(config);
9693
- return this._awaitId(
9694
- "daw-clip-ready",
9695
- "daw-clip-error",
9696
- (d) => d.clipId === clipEl.clipId,
9697
- clipEl.clipId,
9698
- () => trackEl.appendChild(clipEl)
9699
- );
9912
+ const clipId = clipEl.clipId;
9913
+ return new Promise((resolve, reject) => {
9914
+ let seen = false;
9915
+ const onReady = (e) => {
9916
+ if (e.detail.clipId !== clipId) return;
9917
+ cleanup();
9918
+ resolve(clipId);
9919
+ };
9920
+ const onError = (e) => {
9921
+ const detail = e.detail;
9922
+ if (detail.clipId !== clipId) return;
9923
+ cleanup();
9924
+ reject(detail.error instanceof Error ? detail.error : new Error(String(detail.error)));
9925
+ };
9926
+ const stopWatching = this._arrangement.subscribe(() => {
9927
+ const present = this._arrangement.getTracks().some((t) => t.clips.some((c) => c.id === clipId));
9928
+ if (present) {
9929
+ seen = true;
9930
+ } else if (seen) {
9931
+ cleanup();
9932
+ reject(new Error('clip "' + clipId + '" was removed before its audio loaded'));
9933
+ }
9934
+ });
9935
+ const cleanup = () => {
9936
+ this.removeEventListener("daw-clip-ready", onReady);
9937
+ this.removeEventListener("daw-clip-error", onError);
9938
+ stopWatching();
9939
+ this._awaitedClips.delete(clipId);
9940
+ };
9941
+ this.addEventListener("daw-clip-ready", onReady);
9942
+ this.addEventListener("daw-clip-error", onError);
9943
+ this._awaitedClips.set(clipId, {
9944
+ trackId,
9945
+ reject: (error) => {
9946
+ cleanup();
9947
+ reject(error);
9948
+ }
9949
+ });
9950
+ trackEl.appendChild(clipEl);
9951
+ });
9700
9952
  }
9701
9953
  /**
9702
9954
  * Remove a clip by id. Removes the matching `<daw-clip>` DOM element when
@@ -9714,7 +9966,7 @@ var DawEditorElement = class extends LitElement14 {
9714
9966
  return;
9715
9967
  }
9716
9968
  }
9717
- if (this._engineTracks.has(trackId)) {
9969
+ if (this._isEntered(trackId)) {
9718
9970
  this._removeClipFromTrack(trackId, clipId);
9719
9971
  return;
9720
9972
  }
@@ -9775,10 +10027,6 @@ var DawEditorElement = class extends LitElement14 {
9775
10027
  ...partial.gain !== void 0 && { gain: partial.gain },
9776
10028
  ...partial.name !== void 0 && { name: partial.name }
9777
10029
  };
9778
- const updatedClips = [...t.clips];
9779
- updatedClips[idx] = updatedClip;
9780
- const updatedTrack = { ...t, clips: updatedClips };
9781
- this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);
9782
10030
  const desc = this._tracks.get(trackId);
9783
10031
  if (desc?.clips.some((c) => c.clipId === clipId)) {
9784
10032
  this._tracks = new Map(this._tracks).set(trackId, {
@@ -9795,7 +10043,7 @@ var DawEditorElement = class extends LitElement14 {
9795
10043
  )
9796
10044
  });
9797
10045
  }
9798
- this._commitTrackChange(trackId, updatedTrack);
10046
+ this._replaceClip(trackId, clipId, updatedClip);
9799
10047
  }
9800
10048
  _buildClipElement(config) {
9801
10049
  const clipEl = document.createElement("daw-clip");
@@ -10204,11 +10452,12 @@ var DawEditorElement = class extends LitElement14 {
10204
10452
  (el) => el.trackId
10205
10453
  );
10206
10454
  const engineIds = engine.getState().tracks.map((t) => t.id);
10207
- const target = [...engineIds].sort((a, b) => {
10208
- const ai = domOrder.indexOf(a);
10209
- const bi = domOrder.indexOf(b);
10210
- if (ai === -1 || bi === -1) return 0;
10211
- return ai - bi;
10455
+ const inDom = new Set(domOrder);
10456
+ const slots = engineIds.flatMap((id, i) => inDom.has(id) ? [i] : []);
10457
+ const domSorted = domOrder.filter((id) => engineIds.includes(id));
10458
+ const target = [...engineIds];
10459
+ slots.forEach((slot, k) => {
10460
+ target[slot] = domSorted[k];
10212
10461
  });
10213
10462
  if (target.every((id, i) => id === engineIds[i])) return;
10214
10463
  this._inOrderSync = true;
@@ -10251,18 +10500,67 @@ var DawEditorElement = class extends LitElement14 {
10251
10500
  slots.splice(i, 0, desired[i]);
10252
10501
  }
10253
10502
  }
10503
+ /**
10504
+ * The rows, in the arrangement's order (#848): each track's loaded clips
10505
+ * (the engine's projection, with the current mix) and the clips still loading.
10506
+ */
10254
10507
  _getOrderedTracks() {
10255
- const domOrder = [...this.querySelectorAll("daw-track")].map(
10256
- (el) => el.trackId
10257
- );
10258
- return [...this._engineTracks.entries()].sort((a, b) => {
10259
- const ai = domOrder.indexOf(a[0]);
10260
- const bi = domOrder.indexOf(b[0]);
10261
- if (ai === -1 && bi === -1) return 0;
10262
- if (ai === -1) return 1;
10263
- if (bi === -1) return -1;
10264
- return ai - bi;
10265
- });
10508
+ const rows = [];
10509
+ for (const track of this._arrangement.getTracks()) {
10510
+ const loaded = this._engineTracks.get(track.id);
10511
+ if (!loaded) continue;
10512
+ rows.push([track.id, loaded, track.clips.filter(isLoadingClip3)]);
10513
+ }
10514
+ return rows;
10515
+ }
10516
+ /**
10517
+ * A clip still loading: a placeholder box where its length is known, with
10518
+ * its `.dat` peaks when they came, drawn failed when its source failed. Its
10519
+ * header carries no clip id, so it cannot be dragged.
10520
+ */
10521
+ _renderPlaceholder(clip, row) {
10522
+ const seconds = this._placeholderSeconds(clip);
10523
+ if (seconds === null) return "";
10524
+ const sr = this.effectiveSampleRate;
10525
+ const spp = this._renderSpp;
10526
+ const startSec = clip.start ?? 0;
10527
+ let left;
10528
+ let width;
10529
+ if (this.scaleMode === "beats") {
10530
+ left = Math.round(this._secondsToTicks(startSec) / this.ticksPerPixel);
10531
+ width = Math.round(this._secondsToTicks(startSec + seconds) / this.ticksPerPixel) - left;
10532
+ } else {
10533
+ const startSample = Math.round(startSec * sr);
10534
+ left = Math.floor(startSample / spp);
10535
+ width = clipPixelWidth(startSample, Math.round(seconds * sr), spp);
10536
+ }
10537
+ const failed = this._arrangement.sources.getSnapshot().sources.get(clip.src)?.status === "failed";
10538
+ const peakData = this._previewPeaks.get(clip.id);
10539
+ const hdrH = this.clipHeaders ? this.clipHeaderHeight : 0;
10540
+ const chH = this.waveHeight;
10541
+ return html12`<div
10542
+ class="clip-container placeholder ${failed ? "failed" : ""}"
10543
+ style="left:${left}px;top:0;width:${width}px;height:${row.trackHeight}px;"
10544
+ data-clip-id=${clip.id}
10545
+ >
10546
+ ${hdrH > 0 ? html12`<div class="clip-header">
10547
+ <span>${clip.name || row.descriptor?.name || ""}</span>
10548
+ </div>` : ""}
10549
+ ${(peakData?.data ?? []).map(
10550
+ (chPeaks, chIdx) => html12`<daw-waveform
10551
+ style="position:absolute;left:0;top:${hdrH + chIdx * chH}px;"
10552
+ .peaks=${chPeaks}
10553
+ .length=${peakData?.length ?? width}
10554
+ .waveHeight=${chH}
10555
+ .barWidth=${this.barWidth}
10556
+ .barGap=${this.barGap}
10557
+ .roundedBars=${this.roundedBars}
10558
+ .visibleStart=${this._viewport.visibleStart}
10559
+ .visibleEnd=${this._viewport.visibleEnd}
10560
+ .originX=${left}
10561
+ ></daw-waveform>`
10562
+ )}
10563
+ </div>`;
10266
10564
  }
10267
10565
  // --- Render ---
10268
10566
  render() {
@@ -10279,14 +10577,15 @@ var DawEditorElement = class extends LitElement14 {
10279
10577
  selStartPx = this._selectionStartTime * sr / spp;
10280
10578
  selEndPx = this._selectionEndTime * sr / spp;
10281
10579
  }
10282
- const orderedTracks = this._getOrderedTracks().map(([trackId, track]) => {
10580
+ const orderedTracks = this._getOrderedTracks().map(([trackId, track, loading]) => {
10283
10581
  const descriptor = this._tracks.get(trackId);
10284
- const firstPeaks = track.clips.map((c) => this._peaksData.get(c.id)).find((p) => p && p.data.length > 0);
10582
+ const firstPeaks = [...track.clips, ...loading].map((c) => this._peaksData.get(c.id) ?? this._previewPeaks.get(c.id)).find((p) => p && p.data.length > 0);
10285
10583
  const recSession = this._recordingController.getSession(trackId);
10286
10584
  const numChannels = firstPeaks ? firstPeaks.data.length : recSession ? recSession.channelCount : 1;
10287
10585
  return {
10288
10586
  trackId,
10289
10587
  track,
10588
+ loading,
10290
10589
  descriptor,
10291
10590
  numChannels,
10292
10591
  trackHeight: this.waveHeight * numChannels + (this.clipHeaders ? this.clipHeaderHeight : 0)
@@ -10384,7 +10683,7 @@ var DawEditorElement = class extends LitElement14 {
10384
10683
  data-track-id=${t.trackId}
10385
10684
  >
10386
10685
  ${t.track.clips.map((clip) => {
10387
- const peakData = this._peaksData.get(clip.id);
10686
+ const peakData = this._peaksData.get(clip.id) ?? this._previewPeaks.get(clip.id);
10388
10687
  let clipLeft;
10389
10688
  let width;
10390
10689
  if (this.scaleMode === "beats") {
@@ -10513,6 +10812,7 @@ var DawEditorElement = class extends LitElement14 {
10513
10812
  ></div>` : ""}
10514
10813
  </div>`;
10515
10814
  })}
10815
+ ${t.loading.map((clip) => this._renderPlaceholder(clip, t))}
10516
10816
  ${this._renderRecordingPreview(t.trackId, channelHeight)}
10517
10817
  </div>
10518
10818
  `;
@@ -10753,10 +11053,10 @@ __decorateClass([
10753
11053
  ], DawEditorElement.prototype, "ticksToSeconds", 2);
10754
11054
  __decorateClass([
10755
11055
  state4()
10756
- ], DawEditorElement.prototype, "_tracks", 2);
11056
+ ], DawEditorElement.prototype, "_previewPeaks", 2);
10757
11057
  __decorateClass([
10758
11058
  state4()
10759
- ], DawEditorElement.prototype, "_seedMix", 2);
11059
+ ], DawEditorElement.prototype, "_tracks", 2);
10760
11060
  __decorateClass([
10761
11061
  state4()
10762
11062
  ], DawEditorElement.prototype, "_engineTracks", 2);