@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.js CHANGED
@@ -82,7 +82,7 @@ __export(index_exports, {
82
82
  module.exports = __toCommonJS(index_exports);
83
83
 
84
84
  // <define:__INSTALL_SPECS__>
85
- var define_INSTALL_SPECS_default = { "@dawcore/faust": "@dawcore/faust@^0.0.2-next.1", "@dawcore/midi": "@dawcore/midi@^0.0.6-next.4", "@dawcore/transport": "@dawcore/transport@^0.0.16-next.4", "@dawcore/wam": "@dawcore/wam@^0.0.5-next.0", "@waveform-playlist/core": "@waveform-playlist/core@^13.0.0-next.4", "@waveform-playlist/engine": "@waveform-playlist/engine@^14.0.0-next.2", "@waveform-playlist/worklets": "@waveform-playlist/worklets@^13.0.1-next.0", "@waveform-playlist/playout": "@waveform-playlist/playout@^13.0.0-next.4" };
85
+ var define_INSTALL_SPECS_default = { "@dawcore/faust": "@dawcore/faust@^0.0.2-next.1", "@dawcore/midi": "@dawcore/midi@^0.0.6-next.4", "@dawcore/transport": "@dawcore/transport@^0.0.16-next.4", "@dawcore/wam": "@dawcore/wam@^0.0.5-next.0", "@waveform-playlist/core": "@waveform-playlist/core@^13.0.0-next.4", "@waveform-playlist/engine": "@waveform-playlist/engine@^14.0.0-next.3", "@waveform-playlist/worklets": "@waveform-playlist/worklets@^13.0.1-next.0", "@waveform-playlist/playout": "@waveform-playlist/playout@^13.0.0-next.4" };
86
86
 
87
87
  // src/elements/daw-annotation.ts
88
88
  var import_lit = require("lit");
@@ -2281,7 +2281,7 @@ DawStopButtonElement = __decorateClass([
2281
2281
  // src/elements/daw-editor.ts
2282
2282
  var import_lit19 = require("lit");
2283
2283
  var import_decorators16 = require("lit/decorators.js");
2284
- var import_core17 = require("@waveform-playlist/core");
2284
+ var import_core19 = require("@waveform-playlist/core");
2285
2285
 
2286
2286
  // src/workers/peaksWorker.ts
2287
2287
  var import_waveform_data = __toESM(require("waveform-data"));
@@ -3025,6 +3025,9 @@ DawRulerElement = __decorateClass([
3025
3025
  (0, import_decorators13.customElement)("daw-ruler")
3026
3026
  ], DawRulerElement);
3027
3027
 
3028
+ // src/elements/daw-editor.ts
3029
+ var import_engine = require("@waveform-playlist/engine");
3030
+
3028
3031
  // src/utils/track-mix.ts
3029
3032
  var DEFAULT_TRACK_MIX = Object.freeze({
3030
3033
  volume: 1,
@@ -3047,9 +3050,6 @@ function pickMix(mix, names) {
3047
3050
  ...named.has("soloed") && { soloed: mix.soloed }
3048
3051
  };
3049
3052
  }
3050
- function withMix(track, mix) {
3051
- return { ...track, ...mixOfElement(mix) };
3052
- }
3053
3053
  function clampNumber(value, min, max) {
3054
3054
  return Math.max(min, Math.min(max, Number(value)));
3055
3055
  }
@@ -3634,6 +3634,18 @@ var clipStyles = import_lit17.css`
3634
3634
  position: absolute;
3635
3635
  overflow: hidden;
3636
3636
  }
3637
+ /* A clip whose audio is still loading (#848). */
3638
+ .clip-container.placeholder {
3639
+ opacity: var(--daw-placeholder-clip-opacity, 0.5);
3640
+ background: color-mix(in srgb, var(--daw-wave-color, #c49a6c) 35%, transparent);
3641
+ }
3642
+ /* A clip whose audio failed to load: it stays, like a broken <img>. */
3643
+ .clip-container.placeholder.failed {
3644
+ opacity: 1;
3645
+ background: color-mix(in srgb, var(--daw-clip-failed-color, #e06c75) 15%, transparent);
3646
+ outline: 2px dashed var(--daw-clip-failed-color, #e06c75);
3647
+ outline-offset: -2px;
3648
+ }
3637
3649
  .clip-header {
3638
3650
  position: relative;
3639
3651
  z-index: 1;
@@ -3938,7 +3950,6 @@ var RecordingController = class {
3938
3950
  const bits = options.bits ?? 16;
3939
3951
  try {
3940
3952
  const rawCtx = this._host.audioContext;
3941
- this._host.resolveAudioContextSampleRate(rawCtx.sampleRate);
3942
3953
  if (rawCtx.state === "suspended") {
3943
3954
  await rawCtx.resume();
3944
3955
  }
@@ -5692,23 +5703,25 @@ async function loadFiles(host, files) {
5692
5703
  }
5693
5704
  };
5694
5705
  for (const file of fileArray) {
5706
+ if (!host.isConnected) {
5707
+ dispatchLoadError(file, new Error("<daw-editor> was disconnected"));
5708
+ continue;
5709
+ }
5695
5710
  if (file.type && !file.type.startsWith("audio/")) {
5696
5711
  const error = new Error("Non-audio MIME type: " + file.type);
5697
5712
  console.warn("[dawcore] Skipping non-audio file: " + file.name + " (" + file.type + ")");
5698
5713
  dispatchLoadError(file, error);
5699
5714
  continue;
5700
5715
  }
5701
- const blobUrl = URL.createObjectURL(file);
5702
- const name = file.name.replace(/\.\w+$/, "");
5716
+ let trackId = null;
5703
5717
  try {
5704
- const trackEl = await host.addTrack({ name, clips: [{ src: blobUrl, name }] });
5705
- loaded.push(trackEl.trackId);
5718
+ trackId = await host._addDroppedFile(file);
5719
+ await host._whenTrackLoaded(trackId);
5720
+ loaded.push(trackId);
5706
5721
  } catch (err) {
5707
5722
  console.warn("[dawcore] Failed to load file: " + file.name + " \u2014 " + String(err));
5723
+ if (trackId !== null) host._discardTrack(trackId);
5708
5724
  dispatchLoadError(file, err);
5709
- } finally {
5710
- URL.revokeObjectURL(blobUrl);
5711
- host._audioCache.delete(blobUrl);
5712
5725
  }
5713
5726
  }
5714
5727
  return { loaded, failed };
@@ -5796,7 +5809,7 @@ async function loadMidiImpl(host, source, options = {}) {
5796
5809
  throw first instanceof Error ? first : new Error(stringifyReason(first));
5797
5810
  }
5798
5811
  return {
5799
- trackIds: succeeded.map((el) => el.trackId),
5812
+ trackIds: succeeded,
5800
5813
  bpm: parsed.bpm,
5801
5814
  timeSignature: parsed.timeSignature,
5802
5815
  duration: parsed.duration,
@@ -5844,8 +5857,7 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
5844
5857
  host._clipBuffers = new Map(host._clipBuffers).set(clip.id, trimmedBuf);
5845
5858
  host._clipOffsets.set(clip.id, { offsetSamples: 0, durationSamples: durSamples });
5846
5859
  host._peakPipeline.generatePeaks(trimmedBuf, host.renderSamplesPerPixel, host.mono).then((pd) => {
5847
- const t = host._engineTracks.get(trackId);
5848
- if (!t) {
5860
+ if (!host._arrangement.getTracks().some((t) => t.id === trackId)) {
5849
5861
  const next = new Map(host._clipBuffers);
5850
5862
  next.delete(clip.id);
5851
5863
  host._clipBuffers = next;
@@ -5854,13 +5866,15 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
5854
5866
  }
5855
5867
  host._peaksData = new Map(host._peaksData).set(clip.id, pd);
5856
5868
  host._raiseZoomFloor(host._peakPipeline.getCachedScale(trimmedBuf));
5857
- host._engineTracks = new Map(host._engineTracks).set(trackId, {
5858
- ...t,
5859
- // Punch-in replace (#579): the recorded clip owns [startSample,
5860
- // startSample + durSamples) — carve overlapped content out of the
5861
- // existing clips before inserting (parity with the React provider).
5862
- clips: [...(0, import_core12.carveClipRange)(t.clips, startSample, startSample + durSamples), clip]
5863
- });
5869
+ host._arrangement.updateTrack(trackId, (current) => ({
5870
+ ...current,
5871
+ clips: [
5872
+ ...current.clips.flatMap(
5873
+ (c) => (0, import_core12.isLoadingClip)(c) ? [c] : (0, import_core12.carveClipRange)([c], startSample, startSample + durSamples)
5874
+ ),
5875
+ clip
5876
+ ]
5877
+ }));
5864
5878
  const desc = host._tracks.get(trackId);
5865
5879
  if (desc) {
5866
5880
  const sr = host.effectiveSampleRate;
@@ -5888,13 +5902,6 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
5888
5902
  clips: [...desc.clips, clipDesc]
5889
5903
  });
5890
5904
  }
5891
- host._recomputeDuration();
5892
- const updatedTrack = host._engineTracks.get(trackId);
5893
- if (host._engine?.updateTrack && updatedTrack) {
5894
- host._engine.updateTrack(trackId, updatedTrack);
5895
- } else {
5896
- host._engine?.setTracks([...host._engineTracks.values()]);
5897
- }
5898
5905
  if (host.isConnected) {
5899
5906
  host.dispatchEvent(
5900
5907
  new CustomEvent("daw-recording-clip-add", {
@@ -6038,6 +6045,7 @@ function syncPeaksForChangedClips(host, tracks) {
6038
6045
  clip.durationSamples
6039
6046
  ).then((peakData) => {
6040
6047
  host._peaksData = new Map(host._peaksData).set(clip.id, peakData);
6048
+ host._clipPeaksReady?.(clip.id, audioBuffer);
6041
6049
  }).catch((err) => {
6042
6050
  console.warn(
6043
6051
  "[dawcore] Failed to generate peaks for clip " + clip.id + ": " + String(err)
@@ -6088,6 +6096,205 @@ function findAudioBufferForClip(host, clip, track) {
6088
6096
  return null;
6089
6097
  }
6090
6098
 
6099
+ // src/interactions/track-entry.ts
6100
+ var import_core13 = require("@waveform-playlist/core");
6101
+ function validMidiNotes(notes) {
6102
+ return notes.filter((n) => {
6103
+ const ok = Number.isFinite(n.time) && n.time >= 0 && Number.isFinite(n.duration) && n.duration > 0 && Number.isInteger(n.midi) && n.midi >= 0 && n.midi <= 127 && Number.isFinite(n.velocity) && n.velocity >= 0 && n.velocity <= 1;
6104
+ if (!ok) {
6105
+ console.warn("[dawcore] dropping malformed MIDI note: " + JSON.stringify(n));
6106
+ }
6107
+ return ok;
6108
+ });
6109
+ }
6110
+ function clipSourceOf(clipDesc) {
6111
+ return !isDomClip(clipDesc) && clipDesc.file || clipDesc.src;
6112
+ }
6113
+ function isMidiDescriptor(clipDesc) {
6114
+ if (clipSourceOf(clipDesc)) {
6115
+ if (clipDesc.midiNotes != null) {
6116
+ console.warn(
6117
+ '[dawcore] clip "' + (clipDesc.name || (isDomClip(clipDesc) ? clipDesc.clipId : "?")) + '" has both src and midiNotes \u2014 treating as audio (notes will be ignored)'
6118
+ );
6119
+ }
6120
+ return false;
6121
+ }
6122
+ return true;
6123
+ }
6124
+ function clipKindError(trackName, kind, clipIsMidi, clipLabel) {
6125
+ if (clipIsMidi === (kind === "midi")) return null;
6126
+ return new Error(
6127
+ clipIsMidi ? 'clip "' + clipLabel + '" is a MIDI clip (no src) on audio track "' + trackName + `". A track holds one kind of clip: set kind="midi" on the <daw-track> (or kind: 'midi' in addTrack) for a track of MIDI clips.` : 'clip "' + clipLabel + '" is an audio clip on MIDI track "' + trackName + '". A track holds one kind of clip: put the clip on an audio track.'
6128
+ );
6129
+ }
6130
+ function buildMidiClip(clipDesc, sampleRate) {
6131
+ const notes = validMidiNotes(clipDesc.midiNotes ?? []);
6132
+ const noteSpanSeconds = notes.length ? notes.reduce((max, n) => Math.max(max, n.time + n.duration), 0) : 0;
6133
+ const sourceDurationSamples = Math.ceil(
6134
+ Math.max(noteSpanSeconds, clipDesc.duration, 1) * sampleRate
6135
+ );
6136
+ const requestedDurationSamples = clipDesc.duration > 0 ? Math.round(clipDesc.duration * sampleRate) : sourceDurationSamples;
6137
+ const clip = (0, import_core13.createClip)({
6138
+ startSample: Math.round(clipDesc.start * sampleRate),
6139
+ durationSamples: requestedDurationSamples,
6140
+ offsetSamples: Math.round(clipDesc.offset * sampleRate),
6141
+ sampleRate,
6142
+ sourceDurationSamples,
6143
+ gain: clipDesc.gain,
6144
+ name: clipDesc.name,
6145
+ midiNotes: notes,
6146
+ midiChannel: clipDesc.midiChannel ?? void 0,
6147
+ midiProgram: clipDesc.midiProgram ?? void 0
6148
+ });
6149
+ if (clipDesc.clipId) clip.id = clipDesc.clipId;
6150
+ return clip;
6151
+ }
6152
+ function buildLoadingClip(clipDesc) {
6153
+ return {
6154
+ id: clipDesc.clipId,
6155
+ src: clipSourceOf(clipDesc),
6156
+ start: clipDesc.start,
6157
+ offset: clipDesc.offset,
6158
+ gain: clipDesc.gain,
6159
+ ...clipDesc.duration > 0 && { duration: clipDesc.duration },
6160
+ ...clipDesc.name && { name: clipDesc.name }
6161
+ };
6162
+ }
6163
+ function withClipId(clipDesc) {
6164
+ if (clipDesc.clipId) return clipDesc;
6165
+ return { ...clipDesc, clipId: crypto.randomUUID() };
6166
+ }
6167
+ function buildArrangementTrack(trackId, descriptor, mix, sampleRate) {
6168
+ const clips = [];
6169
+ const refused = [];
6170
+ let changed = false;
6171
+ const descClips = descriptor.clips.map((clipDesc) => {
6172
+ const identified = withClipId(clipDesc);
6173
+ if (identified !== clipDesc) changed = true;
6174
+ const isMidi = isMidiDescriptor(identified);
6175
+ const source = clipSourceOf(identified);
6176
+ const sourceName = typeof source === "string" ? source : source instanceof File ? source.name : "";
6177
+ const label = identified.name || sourceName || identified.clipId;
6178
+ const kindError = clipKindError(descriptor.name, descriptor.kind, isMidi, label);
6179
+ if (kindError) refused.push({ clipId: identified.clipId, error: kindError });
6180
+ else clips.push(isMidi ? buildMidiClip(identified, sampleRate) : buildLoadingClip(identified));
6181
+ return identified;
6182
+ });
6183
+ const base = (0, import_core13.createTrack)({ name: descriptor.name, kind: descriptor.kind, clips: [], ...mix });
6184
+ const track = { ...base, id: trackId, clips };
6185
+ return { track, descriptor: changed ? { ...descriptor, clips: descClips } : descriptor, refused };
6186
+ }
6187
+ function entryIndex(trackEls, trackId, arrangementIds) {
6188
+ const at = trackEls.findIndex((el) => el.trackId === trackId);
6189
+ for (let i = at - 1; i >= 0; i--) {
6190
+ const position = arrangementIds.indexOf(trackEls[i].trackId);
6191
+ if (position !== -1) return position + 1;
6192
+ }
6193
+ return 0;
6194
+ }
6195
+
6196
+ // src/interactions/load-announcer.ts
6197
+ var import_core14 = require("@waveform-playlist/core");
6198
+ var LoadAnnouncer = class {
6199
+ constructor(_dispatch) {
6200
+ this._dispatch = _dispatch;
6201
+ this._tracks = /* @__PURE__ */ new Map();
6202
+ /** The failure each clip was last announced with. */
6203
+ this._clipErrors = /* @__PURE__ */ new Map();
6204
+ /** Clips seen while loading, and not yet announced as loaded. */
6205
+ this._loadingClips = /* @__PURE__ */ new Set();
6206
+ }
6207
+ /** A track is about to enter, with `refused` clips left out for their kind. */
6208
+ expect(trackId, refused) {
6209
+ this._tracks.set(trackId, { state: null, refused });
6210
+ }
6211
+ /**
6212
+ * A clip is about to enter while loading: it is announced ready when it
6213
+ * loads, also when its source was loaded already and it is never seen
6214
+ * loading.
6215
+ */
6216
+ expectClip(clipId) {
6217
+ this._loadingClips.add(clipId);
6218
+ }
6219
+ /** A loading clip was removed: its load will not be announced. */
6220
+ forgetClip(clipId) {
6221
+ this._loadingClips.delete(clipId);
6222
+ this._clipErrors.delete(clipId);
6223
+ }
6224
+ /** The error a failed track was announced with. */
6225
+ errorOf(trackId) {
6226
+ return this._tracks.get(trackId)?.error ?? new Error('track "' + trackId + '" failed to load');
6227
+ }
6228
+ /** A track was removed by the page or an editor method: nothing more is said of it. */
6229
+ forget(trackId, clipIds) {
6230
+ this._tracks.delete(trackId);
6231
+ for (const id of clipIds) {
6232
+ this._clipErrors.delete(id);
6233
+ this._loadingClips.delete(id);
6234
+ }
6235
+ }
6236
+ /** The state a track was last announced in (`null` before its first announcement). */
6237
+ stateOf(trackId) {
6238
+ return this._tracks.get(trackId)?.state ?? null;
6239
+ }
6240
+ update(tracks, sources) {
6241
+ for (const track of tracks) this._updateTrack(track, sources);
6242
+ }
6243
+ _updateTrack(track, sources) {
6244
+ const record = this._tracks.get(track.id) ?? { state: null, refused: 0 };
6245
+ this._tracks.set(track.id, record);
6246
+ let pending = 0;
6247
+ let failed = 0;
6248
+ let loaded = 0;
6249
+ let firstError = null;
6250
+ for (const clip of track.clips) {
6251
+ if (!(0, import_core14.isLoadingClip)(clip)) {
6252
+ loaded++;
6253
+ if (this._loadingClips.delete(clip.id)) {
6254
+ this._clipErrors.delete(clip.id);
6255
+ this._send("daw-clip-ready", { trackId: track.id, clipId: clip.id });
6256
+ }
6257
+ continue;
6258
+ }
6259
+ this._loadingClips.add(clip.id);
6260
+ const source = sources.get(clip.src);
6261
+ if (source?.status !== "failed") {
6262
+ pending++;
6263
+ this._clipErrors.delete(clip.id);
6264
+ continue;
6265
+ }
6266
+ failed++;
6267
+ const error = source.error ?? new Error('the audio of clip "' + clip.id + '" failed to load');
6268
+ firstError ?? (firstError = error);
6269
+ if (this._clipErrors.get(clip.id) !== error) {
6270
+ this._clipErrors.set(clip.id, error);
6271
+ this._send("daw-clip-error", {
6272
+ trackId: track.id,
6273
+ clipId: clip.id,
6274
+ error
6275
+ });
6276
+ }
6277
+ }
6278
+ const next = pending > 0 ? "pending" : loaded > 0 || failed + record.refused === 0 ? "ready" : "failed";
6279
+ if (next === record.state) return;
6280
+ record.state = next;
6281
+ record.error = void 0;
6282
+ if (next === "ready") {
6283
+ this._send("daw-track-ready", { trackId: track.id });
6284
+ } else if (next === "failed") {
6285
+ const requested = failed + record.refused;
6286
+ const error = requested === 1 && firstError ? firstError : new Error(
6287
+ "all " + requested + " clip(s) failed to load \u2014 see prior daw-clip-error events"
6288
+ );
6289
+ record.error = error;
6290
+ this._send("daw-track-error", { trackId: track.id, error });
6291
+ }
6292
+ }
6293
+ _send(type, detail) {
6294
+ this._dispatch(new CustomEvent(type, { bubbles: true, composed: true, detail }));
6295
+ }
6296
+ };
6297
+
6091
6298
  // src/effects/effects-chain-controller.ts
6092
6299
  var idCounter = 0;
6093
6300
  var EffectsChainController = class {
@@ -6301,10 +6508,10 @@ function loadFaustModule(feature) {
6301
6508
  }
6302
6509
 
6303
6510
  // src/effects/effects-manager.ts
6304
- var import_core14 = require("@waveform-playlist/core");
6511
+ var import_core16 = require("@waveform-playlist/core");
6305
6512
 
6306
6513
  // src/effects/effect-registry.ts
6307
- var import_core13 = require("@waveform-playlist/core");
6514
+ var import_core15 = require("@waveform-playlist/core");
6308
6515
  var MAX_DELAY_SECONDS = 10;
6309
6516
  function singleNode(node, applyParams) {
6310
6517
  return { input: node, output: node, applyParams };
@@ -6380,8 +6587,8 @@ function biquadDefinition(spec) {
6380
6587
  };
6381
6588
  }
6382
6589
  function registerBuiltIn(type, definition) {
6383
- if (!(0, import_core13.getEffectDefinitions)().has(type)) {
6384
- (0, import_core13.registerEffect)(type, { ...definition, builtIn: true });
6590
+ if (!(0, import_core15.getEffectDefinitions)().has(type)) {
6591
+ (0, import_core15.registerEffect)(type, { ...definition, builtIn: true });
6385
6592
  }
6386
6593
  }
6387
6594
  function registerBuiltIns() {
@@ -6536,7 +6743,7 @@ var EffectsManager = class {
6536
6743
  /** Run a registered effect's async `prepare` hook on the adapter's
6537
6744
  * context, so the synchronous addEffect() can create it. */
6538
6745
  async prepareEffect(type) {
6539
- await (0, import_core14.prepareEffect)(type, this._requireWiring().audioContext);
6746
+ await (0, import_core16.prepareEffect)(type, this._requireWiring().audioContext);
6540
6747
  }
6541
6748
  // --- Track chains ---
6542
6749
  addTrackEffect(trackId, target, type, params) {
@@ -6741,7 +6948,7 @@ var EffectsManager = class {
6741
6948
  this._runOp(chain, target, "setParams", effectId, { [paramId]: value });
6742
6949
  };
6743
6950
  if (entry.kind === "native") {
6744
- const definition = (0, import_core14.getEffectDefinitions)().get(entry.type);
6951
+ const definition = (0, import_core16.getEffectDefinitions)().get(entry.type);
6745
6952
  if (!definition) {
6746
6953
  throw new Error(
6747
6954
  PREFIX2 + 'openEffectGui: no registry definition for effect type "' + entry.type + '"'
@@ -6800,7 +7007,7 @@ var EffectsManager = class {
6800
7007
  }
6801
7008
  _addToChain(chain, target, type, params) {
6802
7009
  const audioContext = this._requireWiring().audioContext;
6803
- const created = (0, import_core14.createEffectInstance)(type, audioContext, params);
7010
+ const created = (0, import_core16.createEffectInstance)(type, audioContext, params);
6804
7011
  const effectId = chain.add({
6805
7012
  kind: "native",
6806
7013
  type,
@@ -6972,8 +7179,8 @@ var EffectsManager = class {
6972
7179
  if (entry.kind === "native") {
6973
7180
  try {
6974
7181
  const liveContext = this._requireWiring().audioContext;
6975
- if ((0, import_core14.needsPrepare)(entry.type, liveContext)) {
6976
- await (0, import_core14.ensureEffectPrepared)(entry.type, liveContext);
7182
+ if ((0, import_core16.needsPrepare)(entry.type, liveContext)) {
7183
+ await (0, import_core16.ensureEffectPrepared)(entry.type, liveContext);
6977
7184
  if (superseded() || chain.disposed) return;
6978
7185
  }
6979
7186
  const id = this._addToChain(chain, target, entry.type, entry.params);
@@ -7148,8 +7355,8 @@ function toWamParameterMap(params) {
7148
7355
  }
7149
7356
 
7150
7357
  // src/interactions/export-audio.ts
7151
- var import_core15 = require("@waveform-playlist/core");
7152
- var import_core16 = require("@waveform-playlist/core");
7358
+ var import_core17 = require("@waveform-playlist/core");
7359
+ var import_core18 = require("@waveform-playlist/core");
7153
7360
  var PREFIX3 = "[waveform-playlist] ";
7154
7361
  async function exportAudioImpl(host, options = {}) {
7155
7362
  const sampleRate = options.sampleRate ?? host.effectiveSampleRate;
@@ -7184,7 +7391,7 @@ async function exportAudioImpl(host, options = {}) {
7184
7391
  cleanups.push(chain.dispose);
7185
7392
  const volume = ctx.createGain();
7186
7393
  volume.gain.value = track.volume;
7187
- const panStage = (0, import_core15.createPanStage)(ctx, track.pan, (0, import_core15.trackChannelCount)(track));
7394
+ const panStage = (0, import_core17.createPanStage)(ctx, track.pan, (0, import_core17.trackChannelCount)(track));
7188
7395
  cleanups.push(panStage.dispose);
7189
7396
  chain.output.connect(volume);
7190
7397
  volume.connect(panStage.input);
@@ -7266,12 +7473,12 @@ async function buildOfflineChain(ctx, entries) {
7266
7473
  continue;
7267
7474
  }
7268
7475
  if (entry.kind === "native") {
7269
- const definition = (0, import_core16.getEffectDefinitions)().get(entry.type);
7476
+ const definition = (0, import_core18.getEffectDefinitions)().get(entry.type);
7270
7477
  if (entry.bypassed && definition && !definition.wetParam) {
7271
7478
  continue;
7272
7479
  }
7273
- await (0, import_core16.ensureEffectPrepared)(entry.type, ctx);
7274
- const created = (0, import_core16.createEffectInstance)(entry.type, ctx, entry.params);
7480
+ await (0, import_core18.ensureEffectPrepared)(entry.type, ctx);
7481
+ const created = (0, import_core18.createEffectInstance)(entry.type, ctx, entry.params);
7275
7482
  if (entry.bypassed && created.wetParam) {
7276
7483
  created.instance.applyParams({ [created.wetParam]: 0 });
7277
7484
  }
@@ -7538,16 +7745,9 @@ var PlaybackAnimationController = class {
7538
7745
  var import_meta = {};
7539
7746
  var RULER_HEIGHT = 30;
7540
7747
  var noAdapterError = () => "No PlayoutAdapter set on <daw-editor>. Set editor.adapter before use.\n\n // Option 1: Native Web Audio (no Tone.js)\n " + installCommand("@dawcore/transport") + "\n import { NativePlayoutAdapter } from '@dawcore/transport';\n editor.adapter = new NativePlayoutAdapter(new AudioContext());\n\n // Option 2: Tone.js (effects, MIDI synths)\n " + installCommand("@waveform-playlist/playout") + "\n import { createToneAdapter } from '@waveform-playlist/playout';\n editor.adapter = createToneAdapter();";
7541
- var TrackLoadCancelledError = class extends Error {
7542
- constructor(message, reason) {
7543
- super(message);
7544
- this.reason = reason;
7545
- this.name = "TrackLoadCancelledError";
7546
- }
7547
- };
7548
7748
  var DawEditorElement = class extends import_lit19.LitElement {
7549
7749
  constructor() {
7550
- super(...arguments);
7750
+ super();
7551
7751
  this._samplesPerPixel = 1024;
7552
7752
  this._timeFormat = "hh:mm:ss.sss";
7553
7753
  this.waveHeight = 128;
@@ -7572,10 +7772,33 @@ var DawEditorElement = class extends import_lit19.LitElement {
7572
7772
  this.timeSignature = [4, 4];
7573
7773
  this._ppqn = 960;
7574
7774
  this.snapTo = "off";
7575
- /** Resolved sample rate — falls back to sampleRate property until first audio decode. */
7576
- this._resolvedSampleRate = null;
7775
+ /**
7776
+ * The one owner of the tracks, the clips, the mix, the undo history and
7777
+ * loading (#848). Made with the editor, kept across a disconnect; the
7778
+ * engine plays it once there is an adapter.
7779
+ */
7780
+ this._arrangement = (0, import_engine.createArrangement)();
7781
+ /** Sends the load events, read from the arrangement (#848). */
7782
+ this._announcer = new LoadAnnouncer((event) => this.dispatchEvent(event));
7783
+ /**
7784
+ * Ids of tracks registered (a `<daw-track>` connected, a file dropped) and
7785
+ * not yet in the arrangement: they enter at the next flush, once there is
7786
+ * an engine (#848).
7787
+ */
7788
+ this._entryQueue = [];
7789
+ this._entryFlushScheduled = false;
7790
+ /**
7791
+ * Clips an `addClip()` is waiting for, with their track and the way to
7792
+ * reject the call: a removal of the clip or of its track before the clip
7793
+ * loads settles it here, without a public event (#917).
7794
+ */
7795
+ this._awaitedClips = /* @__PURE__ */ new Map();
7796
+ /** `<daw-track>` elements `addTrack()` made: every other one is the page's (the history rule). */
7797
+ this._editorMadeTracks = /* @__PURE__ */ new WeakSet();
7798
+ this._previewPeaks = /* @__PURE__ */ new Map();
7799
+ /** The `.dat` data of those clips, handed to the peak pipeline when the audio arrives. */
7800
+ this._previewWaveforms = /* @__PURE__ */ new Map();
7577
7801
  this._tracks = /* @__PURE__ */ new Map();
7578
- this._seedMix = /* @__PURE__ */ new Map();
7579
7802
  this._engineTracks = /* @__PURE__ */ new Map();
7580
7803
  this._peaksData = /* @__PURE__ */ new Map();
7581
7804
  this._isPlaying = false;
@@ -7594,16 +7817,11 @@ var DawEditorElement = class extends import_lit19.LitElement {
7594
7817
  // hook, same pattern as the whole-track _duration check.
7595
7818
  this._activePlayEndTime = null;
7596
7819
  this._externalAdapter = null;
7597
- /** True after a disconnect disposed the consumer's adapter via the engine
7598
- * — rebuild attempts fail loudly until a fresh adapter is set. */
7599
- this._adapterConsumedByDispose = false;
7600
7820
  // --- Effects (master chain; per-track chains delegated from <daw-track>) ---
7601
7821
  this._effectsManager = null;
7602
7822
  this._engine = null;
7603
7823
  this._warnedMissingTicksToSeconds = false;
7604
7824
  this._warnedMissingSecondsToTicks = false;
7605
- this._enginePromise = null;
7606
- this._audioCache = /* @__PURE__ */ new Map();
7607
7825
  this._peaksCache = /* @__PURE__ */ new Map();
7608
7826
  this._clipBuffers = /* @__PURE__ */ new Map();
7609
7827
  this._clipOffsets = /* @__PURE__ */ new Map();
@@ -7611,11 +7829,6 @@ var DawEditorElement = class extends import_lit19.LitElement {
7611
7829
  /** Coarsest scale from pre-computed peaks — zoom cannot go finer than this. 0 = no limit. */
7612
7830
  this._minSamplesPerPixel = 0;
7613
7831
  this._trackElements = /* @__PURE__ */ new Map();
7614
- /** Track ids with a _loadTrack in flight. Distinct from `_engineTracks`
7615
- * membership: the peaks-first path inserts a render-only PREVIEW track
7616
- * into _engineTracks mid-load, so `has()` alone cannot answer "is this
7617
- * track still loading?". */
7618
- this._loadingTracks = /* @__PURE__ */ new Set();
7619
7832
  this._childObserver = null;
7620
7833
  this._audioResume = new AudioResumeController(this);
7621
7834
  this._recordingController = new RecordingController(this);
@@ -7698,9 +7911,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
7698
7911
  }
7699
7912
  const descriptor = this._readTrackDescriptor(trackEl);
7700
7913
  this._tracks = new Map(this._tracks).set(trackId, descriptor);
7701
- this._setSeedMix(trackId, mixOfElement(trackEl));
7702
7914
  this._trackElements.set(trackId, trackEl);
7703
- this._loadTrack(trackId, descriptor);
7915
+ this._queueEntry(trackId);
7704
7916
  };
7705
7917
  this._onTrackUpdate = (e) => {
7706
7918
  const trackId = e.detail?.trackId;
@@ -7723,11 +7935,14 @@ var DawEditorElement = class extends import_lit19.LitElement {
7723
7935
  trackEl.kind = keptKind;
7724
7936
  });
7725
7937
  }
7938
+ if (oldDescriptor && oldDescriptor.src === descriptor.src && !descriptor.clips.some(isDomClip) && !oldDescriptor.clips.some(isDomClip)) {
7939
+ descriptor = { ...descriptor, clips: oldDescriptor.clips };
7940
+ }
7726
7941
  this._tracks = new Map(this._tracks).set(trackId, descriptor);
7727
7942
  const changed = Array.isArray(e.detail.changed) ? e.detail.changed : [];
7728
7943
  this._writeMixFields(trackId, pickMix(mixOfElement(trackEl), changed));
7729
- if (oldDescriptor?.src !== descriptor.src) {
7730
- this._loadTrack(trackId, descriptor);
7944
+ if (oldDescriptor && oldDescriptor.src !== descriptor.src) {
7945
+ this._replaceShorthandClips(trackId, descriptor);
7731
7946
  }
7732
7947
  if (descriptor.renderMode === "spectrogram" && oldDescriptor?.renderMode !== "spectrogram") {
7733
7948
  const engineTrack = this._engineTracks.get(trackId);
@@ -7792,18 +8007,20 @@ var DawEditorElement = class extends import_lit19.LitElement {
7792
8007
  const trackEl = clipEl.closest("daw-track");
7793
8008
  if (!trackEl) return;
7794
8009
  const trackId = trackEl.trackId;
7795
- if (!this._engineTracks.has(trackId) || this._loadingTracks.has(trackId)) {
8010
+ if (!this._isEntered(trackId)) {
8011
+ if (!this._entryQueue.includes(trackId)) {
8012
+ this._rejectAwaitedClips(
8013
+ (id) => id === clipEl.clipId,
8014
+ 'addClip: track "' + trackId + '" is not in the editor (an Undo took it out)'
8015
+ );
8016
+ return;
8017
+ }
7796
8018
  const desc = this._tracks.get(trackId);
7797
8019
  if (desc && !desc.clips.some((c) => isDomClip(c) && c.clipId === clipEl.clipId)) {
7798
- 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.';
7799
- console.warn("[dawcore] " + message);
7800
- this.dispatchEvent(
7801
- new CustomEvent("daw-clip-error", {
7802
- bubbles: true,
7803
- composed: true,
7804
- detail: { trackId, clipId: clipEl.clipId, error: new Error(message) }
7805
- })
7806
- );
8020
+ this._tracks = new Map(this._tracks).set(trackId, {
8021
+ ...desc,
8022
+ clips: [...desc.clips, this._readClipDescriptor(clipEl)]
8023
+ });
7807
8024
  }
7808
8025
  return;
7809
8026
  }
@@ -7811,24 +8028,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
7811
8028
  if (loadedDesc && loadedDesc.clips.some((c) => isDomClip(c) && c.clipId === clipEl.clipId)) {
7812
8029
  return;
7813
8030
  }
7814
- const clipDesc = {
7815
- kind: "dom",
7816
- clipId: clipEl.clipId,
7817
- src: clipEl.src,
7818
- peaksSrc: clipEl.peaksSrc,
7819
- start: clipEl.start,
7820
- duration: clipEl.duration,
7821
- offset: clipEl.offset,
7822
- gain: clipEl.gain,
7823
- name: clipEl.name,
7824
- fadeIn: clipEl.fadeIn,
7825
- fadeOut: clipEl.fadeOut,
7826
- fadeType: clipEl.fadeType,
7827
- midiNotes: clipEl.midiNotes,
7828
- midiChannel: clipEl.midiChannel,
7829
- midiProgram: clipEl.midiProgram
7830
- };
7831
- this._loadAndAppendClip(trackId, clipDesc);
8031
+ this._loadAndAppendClip(trackId, this._readClipDescriptor(clipEl));
7832
8032
  };
7833
8033
  this._onClipUpdate = (e) => {
7834
8034
  const clipEl = e.target;
@@ -7840,8 +8040,26 @@ var DawEditorElement = class extends import_lit19.LitElement {
7840
8040
  );
7841
8041
  return;
7842
8042
  }
8043
+ const desc = this._tracks.get(detail.trackId);
8044
+ if (desc && !this._isEntered(detail.trackId)) {
8045
+ this._tracks = new Map(this._tracks).set(detail.trackId, {
8046
+ ...desc,
8047
+ clips: desc.clips.map(
8048
+ (c) => isDomClip(c) && c.clipId === clipEl.clipId ? this._readClipDescriptor(clipEl) : c
8049
+ )
8050
+ });
8051
+ return;
8052
+ }
7843
8053
  this._applyClipUpdate(detail.trackId, detail.clipId, clipEl);
7844
8054
  };
8055
+ this._waitingForDragEnd = false;
8056
+ /** Who waits for a track to enter (addTrack, a dropped file). */
8057
+ this._entryWaiters = /* @__PURE__ */ new Map();
8058
+ /** Ends the waits of `_whenTrackLoaded` (as loaded) when the editor is disconnected. */
8059
+ this._loadWaitEnds = /* @__PURE__ */ new Set();
8060
+ /** Last versions the statechange handler worked from; reset for each engine. */
8061
+ this._lastTracksVersion = -1;
8062
+ this._lastMixerVersion = -1;
7845
8063
  // --- File Drop ---
7846
8064
  this._onDragOver = (e) => {
7847
8065
  if (!this.fileDrop) return;
@@ -7910,6 +8128,10 @@ var DawEditorElement = class extends import_lit19.LitElement {
7910
8128
  * statechange emissions during the transaction would otherwise bounce
7911
8129
  * half-applied orders back into the DOM. */
7912
8130
  this._inOrderSync = false;
8131
+ this._arrangement.sources.subscribe(() => {
8132
+ this._announceLoading();
8133
+ this.requestUpdate();
8134
+ });
7913
8135
  }
7914
8136
  get samplesPerPixel() {
7915
8137
  return this._samplesPerPixel;
@@ -8088,16 +8310,33 @@ var DawEditorElement = class extends import_lit19.LitElement {
8088
8310
  get _hasTickCallbacks() {
8089
8311
  return !!(this.secondsToTicks && this.ticksToSeconds);
8090
8312
  }
8091
- /** Sample rate — reads from adapter's AudioContext when available, otherwise falls back to 48000. */
8313
+ /**
8314
+ * Sample rate: the adapter's AudioContext rate. Without an adapter (after a
8315
+ * disconnect let it go), the rate of the loaded clips the arrangement holds,
8316
+ * else 48000. Decoded audio is at the context's rate, so the two agree.
8317
+ */
8092
8318
  get sampleRate() {
8093
- return this._resolvedSampleRate ?? this._externalAdapter?.audioContext.sampleRate ?? 48e3;
8319
+ return this._externalAdapter?.audioContext.sampleRate ?? this._loadedClipSampleRate() ?? 48e3;
8320
+ }
8321
+ _loadedClipSampleRate() {
8322
+ for (const track of this._arrangement.getTracks()) {
8323
+ for (const clip of track.clips) {
8324
+ if ("sampleRate" in clip && typeof clip.sampleRate === "number") return clip.sampleRate;
8325
+ }
8326
+ }
8327
+ return null;
8328
+ }
8329
+ /** Reject the `addClip()` calls waiting for clips that match `which`. */
8330
+ _rejectAwaitedClips(which, message) {
8331
+ for (const [clipId, awaited] of [...this._awaitedClips]) {
8332
+ if (which(clipId, awaited.trackId)) awaited.reject(new Error(message));
8333
+ }
8094
8334
  }
8095
8335
  set adapter(value) {
8096
8336
  if (value && value.audioContext.state === "closed") {
8097
8337
  console.warn("[dawcore] Adapter AudioContext is already closed. Ignoring.");
8098
8338
  return;
8099
8339
  }
8100
- this._adapterConsumedByDispose = false;
8101
8340
  if (this._engine) {
8102
8341
  console.warn(
8103
8342
  "[dawcore] adapter set after engine is built. The engine will continue using the previous adapter."
@@ -8111,6 +8350,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
8111
8350
  this._effectsManager = null;
8112
8351
  }
8113
8352
  this._externalAdapter = value;
8353
+ if (value && this.isConnected && !this._engine) this._buildEngineReporting();
8114
8354
  }
8115
8355
  get adapter() {
8116
8356
  return this._externalAdapter;
@@ -8325,10 +8565,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
8325
8565
  return clip?.midiNotes != null;
8326
8566
  }
8327
8567
  get effectiveSampleRate() {
8328
- return this._resolvedSampleRate ?? this.sampleRate;
8329
- }
8330
- resolveAudioContextSampleRate(rate) {
8331
- if (!this._resolvedSampleRate) this._resolvedSampleRate = rate;
8568
+ return this.sampleRate;
8332
8569
  }
8333
8570
  /**
8334
8571
  * In beats mode, derive samplesPerPixel from ticksPerPixel so that
@@ -8399,72 +8636,55 @@ var DawEditorElement = class extends import_lit19.LitElement {
8399
8636
  _setSelectedTrackId(trackId) {
8400
8637
  this._selectedTrackId = trackId;
8401
8638
  }
8639
+ /**
8640
+ * Every track: those in the arrangement, in its order, then those still
8641
+ * waiting to enter (#848). A `<daw-track>` whose track an Undo took out of
8642
+ * the arrangement is not listed (its descriptor stays for a Redo).
8643
+ */
8402
8644
  get tracks() {
8403
- return [...this._tracks.entries()].map(([trackId, descriptor]) => ({
8404
- trackId,
8405
- ...descriptor,
8406
- ...this._mixOf(trackId)
8407
- }));
8645
+ const ids = [...this._arrangement.getTracks().map((t) => t.id), ...this._entryQueue];
8646
+ return ids.flatMap((trackId) => {
8647
+ const descriptor = this._tracks.get(trackId);
8648
+ return descriptor ? [{ trackId, ...descriptor, ...this._mixOf(trackId) }] : [];
8649
+ });
8408
8650
  }
8409
8651
  /**
8410
- * A track's mix, from its one owner: the arrangement (through
8411
- * `_engineTracks`, which follows `mixerVersion`) for a track the engine
8412
- * holds, the seed for one still on its way in (#843).
8652
+ * A track's mix, from its one owner, the arrangement (#843), as the engine
8653
+ * plays it: its projection carries the take's mute, which `getMixer()`
8654
+ * leaves out (the stored mute comes back when the take ends). A track still
8655
+ * waiting to enter shows what its element declares.
8413
8656
  */
8414
8657
  _mixOf(trackId) {
8415
- const seed = this._seedMix.get(trackId);
8416
- if (seed) return seed;
8417
- const track = this._engineTracks.get(trackId);
8418
- return track ? mixOfTrack(track) : DEFAULT_TRACK_MIX;
8419
- }
8420
- /** Replace a track's seed (a new Map: `_seedMix` is reactive state). */
8421
- _setSeedMix(trackId, mix) {
8422
- this._seedMix = new Map(this._seedMix).set(trackId, mix);
8423
- }
8424
- _deleteSeedMix(trackIds) {
8425
- let next = null;
8426
- for (const id of trackIds) {
8427
- if (!this._seedMix.has(id)) continue;
8428
- next ?? (next = new Map(this._seedMix));
8429
- next.delete(id);
8430
- }
8431
- if (next) this._seedMix = next;
8658
+ const played = this._engineTracks.get(trackId);
8659
+ if (played) return mixOfTrack(played);
8660
+ const mix = this._arrangement.getMixer().get(trackId);
8661
+ if (mix) return mix;
8662
+ const el = this._trackElements.get(trackId);
8663
+ return el ? mixOfElement(el) : DEFAULT_TRACK_MIX;
8432
8664
  }
8433
8665
  /**
8434
- * Change one mixer field of a track: the seed while the track is loading
8435
- * (not an undo step, nothing sent), else the engine's setter with
8436
- * `options` (an undo step; changes with one `gesture` id are one step).
8666
+ * Change one mixer field of a track: the arrangement's setter with
8667
+ * `options` (an undo step; changes with one `gesture` id are one step). A
8668
+ * track that has not entered yet changes nothing.
8437
8669
  */
8438
8670
  _writeMix(trackId, field, value, options) {
8439
- const seed = this._seedMix.get(trackId);
8440
- if (seed) {
8441
- if (seed[field] !== value) this._setSeedMix(trackId, { ...seed, [field]: value });
8442
- return;
8443
- }
8444
- if (!this._engine) return;
8445
- if (field === "volume") this._engine.setTrackVolume(trackId, value, options);
8446
- else if (field === "pan") this._engine.setTrackPan(trackId, value, options);
8447
- else if (field === "muted") this._engine.setTrackMute(trackId, value, options);
8448
- else this._engine.setTrackSolo(trackId, value, options);
8671
+ const arrangement = this._arrangement;
8672
+ if (field === "volume") arrangement.setTrackVolume(trackId, value, options);
8673
+ else if (field === "pan") arrangement.setTrackPan(trackId, value, options);
8674
+ else if (field === "muted") arrangement.setTrackMute(trackId, value, options);
8675
+ else arrangement.setTrackSolo(trackId, value, options);
8449
8676
  }
8450
8677
  /**
8451
8678
  * Change the given mixer fields of a track as ONE undo step (#843): all
8452
8679
  * of them carry one fresh gesture id. A field left out is not sent.
8453
8680
  */
8454
8681
  _writeMixFields(trackId, mix) {
8455
- const options = { gesture: (0, import_core17.createMixerGesture)().id };
8682
+ const options = { gesture: (0, import_core19.createMixerGesture)().id };
8456
8683
  if (mix.volume !== void 0) this._writeMix(trackId, "volume", mix.volume, options);
8457
8684
  if (mix.pan !== void 0) this._writeMix(trackId, "pan", mix.pan, options);
8458
8685
  if (mix.muted !== void 0) this._writeMix(trackId, "muted", mix.muted, options);
8459
8686
  if (mix.soloed !== void 0) this._writeMix(trackId, "soloed", mix.soloed, options);
8460
8687
  }
8461
- /** The ordered tracks for `engine.setTracks`, a loading track with its seed. */
8462
- _tracksForEngine() {
8463
- return this._getOrderedTracks().map(([trackId, track]) => {
8464
- const seed = this._seedMix.get(trackId);
8465
- return seed ? withMix(track, seed) : track;
8466
- });
8467
- }
8468
8688
  get selectedTrackId() {
8469
8689
  return this._selectedTrackId;
8470
8690
  }
@@ -8548,6 +8768,10 @@ var DawEditorElement = class extends import_lit19.LitElement {
8548
8768
  if (orderMayHaveChanged) this._syncEngineOrderToDom();
8549
8769
  });
8550
8770
  this._childObserver.observe(this, { childList: true, subtree: true });
8771
+ for (const [trackId, el] of [...this._trackElements]) {
8772
+ if (!this.contains(el)) this._onTrackRemoved(trackId);
8773
+ }
8774
+ if (this._externalAdapter && !this._engine) this._buildEngineReporting();
8551
8775
  }
8552
8776
  disconnectedCallback() {
8553
8777
  super.disconnectedCallback();
@@ -8568,15 +8792,22 @@ var DawEditorElement = class extends import_lit19.LitElement {
8568
8792
  this.removeEventListener("daw-track-reorder", this._onTrackReorder);
8569
8793
  this.removeEventListener("daw-track-reorder-grab", this._onTrackReorderGrab);
8570
8794
  this._cancelDrags(true);
8795
+ for (const end of [...this._loadWaitEnds]) end();
8796
+ for (const trackId of this._entryQueue) {
8797
+ if (this._trackElements.has(trackId) || !this._entryWaiters.has(trackId)) continue;
8798
+ const nextTracks = new Map(this._tracks);
8799
+ nextTracks.delete(trackId);
8800
+ this._tracks = nextTracks;
8801
+ this._entryQueue = this._entryQueue.filter((id) => id !== trackId);
8802
+ this._settleEntry(
8803
+ trackId,
8804
+ new Error("<daw-editor> was disconnected before the file entered")
8805
+ );
8806
+ }
8571
8807
  this._childObserver?.disconnect();
8572
8808
  this._childObserver = null;
8573
- this._trackElements.clear();
8574
- this._audioCache.clear();
8575
8809
  this._peaksCache.clear();
8576
- this._clipBuffers.clear();
8577
- this._clipOffsets.clear();
8578
8810
  this._peakPipeline.terminate();
8579
- this._minSamplesPerPixel = 0;
8580
8811
  this._spectrogramController?.dispose();
8581
8812
  this._spectrogramController = null;
8582
8813
  this._lastSpectrogramViewport = null;
@@ -8587,14 +8818,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
8587
8818
  console.warn("[dawcore] Error disposing engine: " + String(err));
8588
8819
  }
8589
8820
  if (hadEngine) {
8590
- this._adapterConsumedByDispose = true;
8821
+ this._externalAdapter = null;
8591
8822
  }
8592
- this._tracks = /* @__PURE__ */ new Map();
8593
- this._seedMix = /* @__PURE__ */ new Map();
8594
- this._engineTracks = /* @__PURE__ */ new Map();
8595
- this._peaksData = /* @__PURE__ */ new Map();
8596
- this._loadingTracks.clear();
8597
- this._recomputeDuration();
8598
8823
  }
8599
8824
  willUpdate(changedProperties) {
8600
8825
  if (changedProperties.has("eagerResume")) {
@@ -8648,6 +8873,21 @@ var DawEditorElement = class extends import_lit19.LitElement {
8648
8873
  }
8649
8874
  _onTrackRemoved(trackId) {
8650
8875
  const existed = this._tracks.has(trackId);
8876
+ this._rejectAwaitedClips(
8877
+ (_, awaitedTrackId) => awaitedTrackId === trackId,
8878
+ "the track of the clip was removed before the clip loaded"
8879
+ );
8880
+ this._entryQueue = this._entryQueue.filter((id) => id !== trackId);
8881
+ this._settleEntry(trackId, new Error('track "' + trackId + '" was removed before it entered'));
8882
+ const arrangementTrack = this._arrangement.getTracks().find((t) => t.id === trackId);
8883
+ const clipIds = arrangementTrack?.clips.map((c) => c.id) ?? [];
8884
+ this._announcer.forget(trackId, clipIds);
8885
+ if (clipIds.some((id) => this._previewPeaks.has(id))) {
8886
+ const nextPreview = new Map(this._previewPeaks);
8887
+ for (const id of clipIds) nextPreview.delete(id);
8888
+ this._previewPeaks = nextPreview;
8889
+ }
8890
+ for (const id of clipIds) this._previewWaveforms.delete(id);
8651
8891
  this._trackElements.delete(trackId);
8652
8892
  this._effectsManager?.disposeTrackChain(trackId);
8653
8893
  const removedTrack = this._engineTracks.get(trackId);
@@ -8664,14 +8904,11 @@ var DawEditorElement = class extends import_lit19.LitElement {
8664
8904
  const nextTracks = new Map(this._tracks);
8665
8905
  nextTracks.delete(trackId);
8666
8906
  this._tracks = nextTracks;
8667
- this._deleteSeedMix([trackId]);
8668
8907
  const nextEngine = new Map(this._engineTracks);
8669
8908
  nextEngine.delete(trackId);
8670
8909
  this._engineTracks = nextEngine;
8671
8910
  this._recomputeDuration();
8672
- if (this._engine) {
8673
- this._engine.removeTrack(trackId);
8674
- }
8911
+ this._arrangement.removeTrack(trackId);
8675
8912
  this._recomputeZoomFloor();
8676
8913
  this._disposeSpectrogramControllerIfEmpty();
8677
8914
  if (existed && nextEngine.size === 0) {
@@ -8726,13 +8963,13 @@ var DawEditorElement = class extends import_lit19.LitElement {
8726
8963
  next.set(track.id, {
8727
8964
  name: track.name ?? "",
8728
8965
  src: "",
8729
- kind: (0, import_core17.trackKind)(track),
8730
- renderMode: trackDescriptorRenderMode((0, import_core17.trackKind)(track), "waveform"),
8966
+ kind: (0, import_core19.trackKind)(track),
8967
+ renderMode: trackDescriptorRenderMode((0, import_core19.trackKind)(track), "waveform"),
8731
8968
  clips: []
8732
8969
  });
8733
8970
  }
8734
8971
  for (const trackId of this._tracks.keys()) {
8735
- if (engineIds.has(trackId) || this._loadingTracks.has(trackId) || this._trackElements.has(trackId)) {
8972
+ if (engineIds.has(trackId) || this._entryQueue.includes(trackId) || this._trackElements.has(trackId)) {
8736
8973
  continue;
8737
8974
  }
8738
8975
  next ?? (next = new Map(this._tracks));
@@ -8784,12 +9021,22 @@ var DawEditorElement = class extends import_lit19.LitElement {
8784
9021
  }
8785
9022
  _onClipRemovedFromDom(clipEl) {
8786
9023
  const clipId = clipEl.clipId;
8787
- for (const [trackId, t] of this._engineTracks.entries()) {
9024
+ for (const t of this._arrangement.getTracks()) {
8788
9025
  if (t.clips.some((c) => c.id === clipId)) {
8789
- this._removeClipFromTrack(trackId, clipId);
9026
+ this._removeClipFromTrack(t.id, clipId);
8790
9027
  return;
8791
9028
  }
8792
9029
  }
9030
+ for (const [trackId, desc] of this._tracks) {
9031
+ if (this._isEntered(trackId) || !desc.clips.some((c) => c.clipId === clipId)) continue;
9032
+ this._tracks = new Map(this._tracks).set(trackId, {
9033
+ ...desc,
9034
+ clips: desc.clips.filter((c) => c.clipId !== clipId)
9035
+ });
9036
+ this._rejectAwaitedClips((id) => id === clipId, "the clip was removed before it loaded");
9037
+ return;
9038
+ }
9039
+ this._rejectAwaitedClips((id) => id === clipId, "the clip was removed before it loaded");
8793
9040
  if (this._clipBuffers.has(clipId) || this._clipOffsets.has(clipId) || this._peaksData.has(clipId)) {
8794
9041
  console.warn(
8795
9042
  '[dawcore] _onClipRemovedFromDom: orphaned cache entries for clip "' + clipId + '" \u2014 purging (DOM/engine id mismatch?)'
@@ -8797,62 +9044,52 @@ var DawEditorElement = class extends import_lit19.LitElement {
8797
9044
  this._purgeClipCaches(clipId);
8798
9045
  }
8799
9046
  }
8800
- async _loadAndAppendClip(trackId, clipDesc) {
8801
- if (!clipDesc.src) return;
8802
- const clipId = clipDesc.clipId;
8803
- let insertedClipId = null;
9047
+ /**
9048
+ * A `<daw-clip>` appended to a track that has entered: the clip goes in as
9049
+ * a loading clip (a loaded one for MIDI), one undo step. Its audio loads
9050
+ * like any other; `daw-clip-ready` or `daw-clip-error` follows (#848).
9051
+ */
9052
+ _loadAndAppendClip(trackId, clipDesc) {
9053
+ const trackDesc = this._tracks.get(trackId);
9054
+ if (!trackDesc) return;
9055
+ const clipIsMidi = isMidiDescriptor(clipDesc);
9056
+ const kindError = clipKindError(
9057
+ trackDesc.name,
9058
+ trackDesc.kind,
9059
+ clipIsMidi,
9060
+ clipDesc.name || clipDesc.src || clipDesc.clipId
9061
+ );
9062
+ const clip = clipIsMidi ? buildMidiClip(clipDesc, this.effectiveSampleRate) : buildLoadingClip(clipDesc);
9063
+ if (!clipIsMidi) this._announcer.expectClip(clipDesc.clipId);
8804
9064
  try {
8805
- const trackDesc = this._tracks.get(trackId);
8806
- const kindError = trackDesc ? this._clipKindError(trackDesc.name, trackDesc.kind, false, clipDesc.name || clipDesc.src) : null;
8807
9065
  if (kindError) throw kindError;
8808
- const waveformDataPromise = clipDesc.peaksSrc ? this._resolvePeaks(clipDesc.peaksSrc) : Promise.resolve(null);
8809
- const audioPromise = this._fetchAndDecode(clipDesc.src);
8810
- const [waveformData, audioBuffer] = await Promise.all([waveformDataPromise, audioPromise]);
8811
- this._resolvedSampleRate = audioBuffer.sampleRate;
8812
- const clip = await this._finalizeAudioClip(clipDesc, audioBuffer, waveformData);
8813
- insertedClipId = clip.id;
8814
- const t = this._engineTracks.get(trackId);
8815
- if (!t) {
8816
- this._purgeClipCaches(clip.id);
8817
- return;
8818
- }
8819
- const updatedTrack = { ...t, clips: [...t.clips, clip] };
8820
- this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);
8821
- const desc = this._tracks.get(trackId);
8822
- if (desc) {
8823
- this._tracks = new Map(this._tracks).set(trackId, {
8824
- ...desc,
8825
- clips: [...desc.clips, clipDesc]
8826
- });
8827
- }
8828
- this._commitTrackChange(trackId, updatedTrack);
8829
- this._maybeRegisterSpectrogramClipAudio(trackId, clip);
8830
- this.dispatchEvent(
8831
- new CustomEvent("daw-clip-ready", {
8832
- bubbles: true,
8833
- composed: true,
8834
- detail: { trackId, clipId: clip.id }
8835
- })
8836
- );
9066
+ this._arrangement.updateTrack(trackId, (current) => ({
9067
+ ...current,
9068
+ clips: [...current.clips, clip]
9069
+ }));
8837
9070
  } catch (err) {
8838
9071
  console.warn("[dawcore] _loadAndAppendClip failed: " + String(err));
8839
- if (insertedClipId) this._purgeClipCaches(insertedClipId);
8840
9072
  this.dispatchEvent(
8841
9073
  new CustomEvent("daw-clip-error", {
8842
9074
  bubbles: true,
8843
9075
  composed: true,
8844
- detail: { trackId, clipId: insertedClipId ?? clipId, error: err }
9076
+ detail: { trackId, clipId: clipDesc.clipId, error: err }
8845
9077
  })
8846
9078
  );
9079
+ return;
8847
9080
  }
9081
+ this._tracks = new Map(this._tracks).set(trackId, {
9082
+ ...trackDesc,
9083
+ clips: [...trackDesc.clips, clipDesc]
9084
+ });
9085
+ if (!clipIsMidi && clipDesc.peaksSrc) this._requestPreview(clipDesc.clipId, clipDesc.peaksSrc);
8848
9086
  }
8849
9087
  /**
8850
9088
  * Resolve pre-computed peaks for a clip: fetch the .dat/.json, validate the
8851
9089
  * sample rate matches the AudioContext, return the WaveformData or null.
8852
9090
  * Warns on fetch failure and on sample-rate mismatch — never silent.
8853
9091
  *
8854
- * Shared between `_loadTrack` (peaks-first preview path) and
8855
- * `_loadAndAppendClip` (incremental late-append).
9092
+ * Used by `_requestPreview` for a clip that is still loading.
8856
9093
  */
8857
9094
  async _resolvePeaks(peaksSrc) {
8858
9095
  try {
@@ -8870,127 +9107,6 @@ var DawEditorElement = class extends import_lit19.LitElement {
8870
9107
  return null;
8871
9108
  }
8872
9109
  }
8873
- /**
8874
- * Construct an AudioClip from a decoded buffer (and optional WaveformData),
8875
- * align its id with the source `<daw-clip>.clipId` when present, populate
8876
- * `_clipBuffers` / `_clipOffsets`, generate peaks via the worker pipeline,
8877
- * and populate `_peaksData`. Returns the finished AudioClip.
8878
- *
8879
- * Shared between `_loadTrack`'s standard path and `_loadAndAppendClip`.
8880
- * Not used by `_loadTrack`'s peaks-first preview path because that path
8881
- * uses sync `extractPeaks` and inserts a preview track BEFORE audio decode.
8882
- */
8883
- async _finalizeAudioClip(clipDesc, audioBuffer, waveformData) {
8884
- let clip;
8885
- if (waveformData) {
8886
- const wdRate = waveformData.sample_rate;
8887
- clip = (0, import_core17.createClip)({
8888
- audioBuffer,
8889
- waveformData,
8890
- startSample: Math.round(clipDesc.start * wdRate),
8891
- durationSamples: Math.round((clipDesc.duration || waveformData.duration) * wdRate),
8892
- offsetSamples: Math.round(clipDesc.offset * wdRate),
8893
- gain: clipDesc.gain,
8894
- name: clipDesc.name,
8895
- sampleRate: wdRate,
8896
- sourceDurationSamples: Math.ceil(waveformData.duration * wdRate)
8897
- });
8898
- this._peakPipeline.cacheWaveformData(audioBuffer, waveformData);
8899
- } else {
8900
- clip = (0, import_core17.createClipFromSeconds)({
8901
- audioBuffer,
8902
- startTime: clipDesc.start,
8903
- duration: clipDesc.duration || audioBuffer.duration,
8904
- offset: clipDesc.offset,
8905
- gain: clipDesc.gain,
8906
- name: clipDesc.name,
8907
- sampleRate: audioBuffer.sampleRate,
8908
- sourceDuration: audioBuffer.duration
8909
- });
8910
- }
8911
- if (isDomClip(clipDesc)) clip.id = clipDesc.clipId;
8912
- this._clipBuffers = new Map(this._clipBuffers).set(clip.id, audioBuffer);
8913
- this._clipOffsets.set(clip.id, {
8914
- offsetSamples: clip.offsetSamples,
8915
- durationSamples: clip.durationSamples
8916
- });
8917
- let peakData;
8918
- try {
8919
- peakData = await this._peakPipeline.generatePeaks(
8920
- audioBuffer,
8921
- this._renderSpp,
8922
- this.mono,
8923
- clip.offsetSamples,
8924
- clip.durationSamples
8925
- );
8926
- } catch (err) {
8927
- this._purgeClipCaches(clip.id);
8928
- throw err;
8929
- }
8930
- this._peaksData = new Map(this._peaksData).set(clip.id, peakData);
8931
- const cachedScale = waveformData?.scale ?? this._peakPipeline.getCachedScale(audioBuffer);
8932
- this._raiseZoomFloor(cachedScale);
8933
- return clip;
8934
- }
8935
- /**
8936
- * Filter MIDI notes to only those with finite, in-range fields. Logs a
8937
- * warning for each dropped note. Used by _buildMidiClip and the
8938
- * _applyClipUpdate MIDI branch to prevent NaN propagation through the
8939
- * timeline.
8940
- */
8941
- _validMidiNotes(notes) {
8942
- return notes.filter((n) => {
8943
- 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;
8944
- if (!ok) {
8945
- console.warn("[dawcore] dropping malformed MIDI note: " + JSON.stringify(n));
8946
- }
8947
- return ok;
8948
- });
8949
- }
8950
- /**
8951
- * A clip descriptor is treated as MIDI when it has no audio src.
8952
- * Includes placeholder MIDI clips (no notes, no duration yet — registered
8953
- * with a 1s default span; notes upgrade via _applyClipUpdate). Warns when
8954
- * a clip ambiguously has both src and midiNotes — the audio path runs
8955
- * and notes would be silently ignored.
8956
- */
8957
- _isMidiDescriptor(clipDesc) {
8958
- if (clipDesc.src) {
8959
- if (clipDesc.midiNotes != null) {
8960
- console.warn(
8961
- '[dawcore] clip "' + (clipDesc.name || (isDomClip(clipDesc) ? clipDesc.clipId : "?")) + '" has both src and midiNotes \u2014 treating as audio (notes will be ignored)'
8962
- );
8963
- }
8964
- return false;
8965
- }
8966
- return true;
8967
- }
8968
- /**
8969
- * Build an engine clip from a MIDI clip descriptor. Always returns a clip
8970
- * — empty notes / no declared duration get a 1-second placeholder span so
8971
- * the clip is reachable via `engine.updateTrack` once notes arrive.
8972
- */
8973
- _buildMidiClip(clipDesc) {
8974
- const sr = this.effectiveSampleRate;
8975
- const notes = this._validMidiNotes(clipDesc.midiNotes ?? []);
8976
- const noteSpanSeconds = notes.length ? notes.reduce((max, n) => Math.max(max, n.time + n.duration), 0) : 0;
8977
- const sourceDurationSamples = Math.ceil(Math.max(noteSpanSeconds, clipDesc.duration, 1) * sr);
8978
- const requestedDurationSamples = clipDesc.duration > 0 ? Math.round(clipDesc.duration * sr) : sourceDurationSamples;
8979
- const clip = (0, import_core17.createClip)({
8980
- startSample: Math.round(clipDesc.start * sr),
8981
- durationSamples: requestedDurationSamples,
8982
- offsetSamples: Math.round(clipDesc.offset * sr),
8983
- sampleRate: sr,
8984
- sourceDurationSamples,
8985
- gain: clipDesc.gain,
8986
- name: clipDesc.name,
8987
- midiNotes: notes,
8988
- midiChannel: clipDesc.midiChannel ?? void 0,
8989
- midiProgram: clipDesc.midiProgram ?? void 0
8990
- });
8991
- if (isDomClip(clipDesc)) clip.id = clipDesc.clipId;
8992
- return clip;
8993
- }
8994
9110
  /** Remove a single clip from all per-clip caches. Used by error rollbacks. */
8995
9111
  _purgeClipCaches(clipId) {
8996
9112
  const nextBuffers = new Map(this._clipBuffers);
@@ -9003,16 +9119,14 @@ var DawEditorElement = class extends import_lit19.LitElement {
9003
9119
  this._spectrogramController?.unregisterClipAudio(clipId);
9004
9120
  }
9005
9121
  /**
9006
- * Recompute duration and forward an updated track to the engine. Single
9007
- * source of truth for the incremental-vs-full-rebuild policy used by every
9008
- * clip-level mutation (addClip, updateClip, removeClip, _applyClipUpdate).
9009
- * Use the engine's incremental updateTrack when available; otherwise fall
9010
- * back to full setTracks (legacy adapters).
9122
+ * Replace one loaded clip of a track in the arrangement: an undo step. The
9123
+ * function form, so the track's loading clips stay as they are (#848).
9011
9124
  */
9012
- _commitTrackChange(trackId, updatedTrack) {
9013
- this._recomputeDuration();
9014
- if (this._engine?.updateTrack) this._engine.updateTrack(trackId, updatedTrack);
9015
- else if (this._engine) this._engine.setTracks(this._tracksForEngine());
9125
+ _replaceClip(trackId, clipId, clip) {
9126
+ this._arrangement.updateTrack(trackId, (current) => ({
9127
+ ...current,
9128
+ clips: current.clips.map((c) => c.id === clipId ? clip : c)
9129
+ }));
9016
9130
  }
9017
9131
  _applyClipUpdate(trackId, clipId, clipEl) {
9018
9132
  const t = this._engineTracks.get(trackId);
@@ -9022,8 +9136,9 @@ var DawEditorElement = class extends import_lit19.LitElement {
9022
9136
  }
9023
9137
  const idx = t.clips.findIndex((c) => c.id === clipId);
9024
9138
  if (idx === -1) {
9139
+ const loading = this._arrangement.getTracks().find((track) => track.id === trackId)?.clips.some((c) => c.id === clipId);
9025
9140
  console.warn(
9026
- '[dawcore] _applyClipUpdate: clip "' + clipId + '" not found in track "' + trackId + '" (DOM/engine clip-id misalignment?)'
9141
+ '[dawcore] _applyClipUpdate: clip "' + clipId + '" ' + (loading ? "is still loading; the change is dropped" : 'not found in track "' + trackId + '" (DOM/engine clip-id misalignment?)')
9027
9142
  );
9028
9143
  return;
9029
9144
  }
@@ -9031,8 +9146,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
9031
9146
  const sr = oldClip.sampleRate ?? this.effectiveSampleRate;
9032
9147
  const isMidiNow = clipEl.midiNotes != null && !clipEl.src;
9033
9148
  const wasMidi = oldClip.midiNotes != null;
9034
- if (isMidiNow && (0, import_core17.trackKind)(t) !== "midi") {
9035
- const kindError = this._clipKindError(t.name, "audio", true, clipEl.name || clipId);
9149
+ if (isMidiNow && (0, import_core19.trackKind)(t) !== "midi") {
9150
+ const kindError = clipKindError(t.name ?? "", "audio", true, clipEl.name || clipId);
9036
9151
  console.warn("[dawcore] _applyClipUpdate: " + kindError?.message);
9037
9152
  this.dispatchEvent(
9038
9153
  new CustomEvent("daw-clip-error", {
@@ -9044,7 +9159,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9044
9159
  return;
9045
9160
  }
9046
9161
  if (isMidiNow || wasMidi) {
9047
- const notes = this._validMidiNotes(clipEl.midiNotes ?? []);
9162
+ const notes = validMidiNotes(clipEl.midiNotes ?? []);
9048
9163
  const noteSpanSeconds = notes.length ? notes.reduce((max, n) => Math.max(max, n.time + n.duration), 0) : 0;
9049
9164
  const sourceDurationSamples = Math.ceil(Math.max(noteSpanSeconds, clipEl.duration, 1) * sr);
9050
9165
  const requestedDurationSamples = clipEl.duration > 0 ? Math.round(clipEl.duration * sr) : sourceDurationSamples;
@@ -9061,12 +9176,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
9061
9176
  midiChannel: clipEl.midiChannel ?? void 0,
9062
9177
  midiProgram: clipEl.midiProgram ?? void 0
9063
9178
  };
9064
- const updatedClips2 = [...t.clips];
9065
- updatedClips2[idx] = updatedClip2;
9066
- const updatedTrack2 = { ...t, clips: updatedClips2 };
9067
- this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack2);
9068
9179
  this._purgeClipCaches(clipId);
9069
- this._commitTrackChange(trackId, updatedTrack2);
9180
+ this._replaceClip(trackId, clipId, updatedClip2);
9070
9181
  return;
9071
9182
  }
9072
9183
  const newStartSample = Math.round(clipEl.start * sr);
@@ -9080,10 +9191,6 @@ var DawEditorElement = class extends import_lit19.LitElement {
9080
9191
  gain: clipEl.gain,
9081
9192
  name: clipEl.name || oldClip.name
9082
9193
  };
9083
- const updatedClips = [...t.clips];
9084
- updatedClips[idx] = updatedClip;
9085
- const updatedTrack = { ...t, clips: updatedClips };
9086
- this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);
9087
9194
  const boundsChanged = oldClip.offsetSamples !== newOffsetSamples || oldClip.durationSamples !== newDurationSamples;
9088
9195
  if (boundsChanged) {
9089
9196
  this._clipOffsets.set(clipId, {
@@ -9095,40 +9202,41 @@ var DawEditorElement = class extends import_lit19.LitElement {
9095
9202
  this._peaksData = new Map(this._peaksData).set(clipId, peaks);
9096
9203
  }
9097
9204
  }
9098
- this._commitTrackChange(trackId, updatedTrack);
9205
+ this._replaceClip(trackId, clipId, updatedClip);
9099
9206
  }
9207
+ /** Remove a clip (loaded or still loading) from a track of the arrangement: an undo step. */
9100
9208
  _removeClipFromTrack(trackId, clipId) {
9101
- const t = this._engineTracks.get(trackId);
9102
- if (!t) {
9103
- console.warn('[dawcore] _removeClipFromTrack: no engine track for id "' + trackId + '"');
9209
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9210
+ if (!track) {
9211
+ console.warn('[dawcore] _removeClipFromTrack: no track for id "' + trackId + '"');
9104
9212
  return;
9105
9213
  }
9106
- const updatedClips = t.clips.filter((c) => c.id !== clipId);
9107
- if (updatedClips.length === t.clips.length) {
9214
+ if (!track.clips.some((c) => c.id === clipId)) {
9108
9215
  console.warn(
9109
9216
  '[dawcore] _removeClipFromTrack: clip "' + clipId + '" not found in track "' + trackId + '"'
9110
9217
  );
9111
9218
  return;
9112
9219
  }
9113
- const updatedTrack = { ...t, clips: updatedClips };
9114
- this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);
9115
- const nextBuffers = new Map(this._clipBuffers);
9116
- nextBuffers.delete(clipId);
9117
- this._clipBuffers = nextBuffers;
9118
- this._clipOffsets.delete(clipId);
9119
- const nextPeaks = new Map(this._peaksData);
9120
- nextPeaks.delete(clipId);
9121
- this._peaksData = nextPeaks;
9220
+ this._purgeClipCaches(clipId);
9221
+ this._previewWaveforms.delete(clipId);
9222
+ if (this._previewPeaks.has(clipId)) {
9223
+ const nextPreview = new Map(this._previewPeaks);
9224
+ nextPreview.delete(clipId);
9225
+ this._previewPeaks = nextPreview;
9226
+ }
9122
9227
  const desc = this._tracks.get(trackId);
9123
9228
  if (desc) {
9124
9229
  this._tracks = new Map(this._tracks).set(trackId, {
9125
9230
  ...desc,
9126
- // Descriptors without an id (file drops, the <daw-track src>
9127
- // shorthand) are kept — their identity is the descriptor itself.
9128
9231
  clips: desc.clips.filter((c) => c.clipId !== clipId)
9129
9232
  });
9130
9233
  }
9131
- this._commitTrackChange(trackId, updatedTrack);
9234
+ const wasLoading = track.clips.some((c) => c.id === clipId && (0, import_core19.isLoadingClip)(c));
9235
+ this._arrangement.updateTrack(trackId, (current) => ({
9236
+ ...current,
9237
+ clips: current.clips.filter((c) => c.id !== clipId)
9238
+ }));
9239
+ if (wasLoading) this._announcer.forgetClip(clipId);
9132
9240
  }
9133
9241
  _readTrackDescriptor(trackEl) {
9134
9242
  const clipEls = trackEl.querySelectorAll("daw-clip");
@@ -9151,25 +9259,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9151
9259
  midiProgram: null
9152
9260
  });
9153
9261
  } else {
9154
- for (const clipEl of clipEls) {
9155
- clips.push({
9156
- kind: "dom",
9157
- clipId: clipEl.clipId,
9158
- src: clipEl.src,
9159
- peaksSrc: clipEl.peaksSrc,
9160
- start: clipEl.start,
9161
- duration: clipEl.duration,
9162
- offset: clipEl.offset,
9163
- gain: clipEl.gain,
9164
- name: clipEl.name,
9165
- fadeIn: clipEl.fadeIn,
9166
- fadeOut: clipEl.fadeOut,
9167
- fadeType: clipEl.fadeType,
9168
- midiNotes: clipEl.midiNotes,
9169
- midiChannel: clipEl.midiChannel,
9170
- midiProgram: clipEl.midiProgram
9171
- });
9172
- }
9262
+ for (const clipEl of clipEls) clips.push(this._readClipDescriptor(clipEl));
9173
9263
  }
9174
9264
  return {
9175
9265
  name: trackEl.name || "Untitled",
@@ -9179,228 +9269,312 @@ var DawEditorElement = class extends import_lit19.LitElement {
9179
9269
  clips
9180
9270
  };
9181
9271
  }
9272
+ _readClipDescriptor(clipEl) {
9273
+ return {
9274
+ kind: "dom",
9275
+ clipId: clipEl.clipId,
9276
+ src: clipEl.src,
9277
+ peaksSrc: clipEl.peaksSrc,
9278
+ start: clipEl.start,
9279
+ duration: clipEl.duration,
9280
+ offset: clipEl.offset,
9281
+ gain: clipEl.gain,
9282
+ name: clipEl.name,
9283
+ fadeIn: clipEl.fadeIn,
9284
+ fadeOut: clipEl.fadeOut,
9285
+ fadeType: clipEl.fadeType,
9286
+ midiNotes: clipEl.midiNotes,
9287
+ midiChannel: clipEl.midiChannel,
9288
+ midiProgram: clipEl.midiProgram
9289
+ };
9290
+ }
9291
+ // --- Entering the arrangement (#848) ---
9292
+ _isEntered(trackId) {
9293
+ return this._arrangement.getTracks().some((t) => t.id === trackId);
9294
+ }
9295
+ /** Queue a registered track for the next flush. */
9296
+ _queueEntry(trackId) {
9297
+ if (!this._entryQueue.includes(trackId)) this._entryQueue = [...this._entryQueue, trackId];
9298
+ if (this._entryFlushScheduled) return;
9299
+ this._entryFlushScheduled = true;
9300
+ queueMicrotask(() => {
9301
+ this._entryFlushScheduled = false;
9302
+ this._flushTrackEntries();
9303
+ });
9304
+ }
9182
9305
  /**
9183
- * The error for a clip whose kind is not its track's (#756), or null. A clip
9184
- * with no `src` is a MIDI clip (see _isMidiDescriptor).
9306
+ * Enter the queued tracks into the arrangement, in DOM order. Without an
9307
+ * engine they wait (the sample rate of a MIDI clip comes from the
9308
+ * adapter); the engine's build flushes again. The page's tracks entering
9309
+ * while the arrangement has no history are not undo steps: the history is
9310
+ * cleared after them, so Undo right after load removes nothing (and the
9311
+ * next page track finds it empty again).
9185
9312
  */
9186
- _clipKindError(trackName, kind, clipIsMidi, clipLabel) {
9187
- if (clipIsMidi === (kind === "midi")) return null;
9188
- return new Error(
9189
- clipIsMidi ? 'clip "' + clipLabel + '" is a MIDI clip (no src) on audio track "' + trackName + `". A track holds one kind of clip: set kind="midi" on the <daw-track> (or kind: 'midi' in addTrack) for a track of MIDI clips.` : 'clip "' + clipLabel + '" is an audio clip on MIDI track "' + trackName + '". A track holds one kind of clip: put the clip on an audio track.'
9313
+ _flushTrackEntries() {
9314
+ if (this._entryQueue.length === 0) return;
9315
+ if (!this._engine) return;
9316
+ if (this._dragInProgress) {
9317
+ this._flushAfterDrag();
9318
+ return;
9319
+ }
9320
+ const queued = this._entryQueue;
9321
+ this._entryQueue = [];
9322
+ const domOrder = [...this.querySelectorAll("daw-track")].map(
9323
+ (el) => el.trackId
9190
9324
  );
9325
+ const position = (id) => {
9326
+ const at = domOrder.indexOf(id);
9327
+ return at === -1 ? domOrder.length : at;
9328
+ };
9329
+ const ordered = [...queued].sort((a, b) => position(a) - position(b));
9330
+ const isPageTrack = (id) => {
9331
+ const el = this._trackElements.get(id);
9332
+ return el !== void 0 && !this._editorMadeTracks.has(el);
9333
+ };
9334
+ const arrangement = this._arrangement;
9335
+ const historyWasEmpty = !arrangement.canUndo && !arrangement.canRedo && !this._dragInProgress;
9336
+ let pageEntered = false;
9337
+ for (const id of ordered.filter(isPageTrack)) {
9338
+ if (this._enterTrack(id)) pageEntered = true;
9339
+ }
9340
+ if (historyWasEmpty && pageEntered) arrangement.clearHistory();
9341
+ for (const id of ordered.filter((id2) => !isPageTrack(id2))) this._enterTrack(id);
9342
+ }
9343
+ /** Flush the queue once the drag in progress has ended (its pointer or key is released). */
9344
+ _flushAfterDrag() {
9345
+ if (this._waitingForDragEnd) return;
9346
+ this._waitingForDragEnd = true;
9347
+ const events = ["pointerup", "pointercancel", "keyup"];
9348
+ const retry = () => {
9349
+ for (const type of events) window.removeEventListener(type, retry);
9350
+ this._waitingForDragEnd = false;
9351
+ setTimeout(() => this._flushTrackEntries(), 0);
9352
+ };
9353
+ for (const type of events) window.addEventListener(type, retry);
9191
9354
  }
9192
- // --- Audio Loading ---
9193
- async _loadTrack(trackId, descriptor) {
9194
- this._loadingTracks.add(trackId);
9195
- const sppAtLoadStart = this._samplesPerPixel;
9196
- try {
9197
- const clips = [];
9198
- let refusedMidiClips = 0;
9199
- for (const clipDesc of descriptor.clips) {
9200
- const clipIsMidi = this._isMidiDescriptor(clipDesc);
9201
- const kindError = this._clipKindError(
9202
- descriptor.name,
9203
- descriptor.kind,
9204
- clipIsMidi,
9205
- clipDesc.name || clipDesc.src || (isDomClip(clipDesc) ? clipDesc.clipId : "")
9206
- );
9207
- if (kindError) {
9208
- console.warn("[dawcore] _loadTrack: " + kindError.message);
9209
- if (this.isConnected) {
9210
- this.dispatchEvent(
9211
- new CustomEvent("daw-clip-error", {
9212
- bubbles: true,
9213
- composed: true,
9214
- detail: {
9215
- trackId,
9216
- clipId: isDomClip(clipDesc) ? clipDesc.clipId : "",
9217
- error: kindError
9218
- }
9219
- })
9220
- );
9221
- }
9222
- if (clipIsMidi) refusedMidiClips++;
9223
- continue;
9224
- }
9225
- if (clipIsMidi) {
9226
- clips.push(this._buildMidiClip(clipDesc));
9227
- continue;
9228
- }
9229
- try {
9230
- const waveformDataPromise = clipDesc.peaksSrc ? this._resolvePeaks(clipDesc.peaksSrc) : Promise.resolve(null);
9231
- const audioPromise = this._fetchAndDecode(clipDesc.src);
9232
- const waveformData = await waveformDataPromise;
9233
- if (waveformData) {
9234
- const wdRate = waveformData.sample_rate;
9235
- const clip2 = (0, import_core17.createClip)({
9236
- waveformData,
9237
- startSample: Math.round(clipDesc.start * wdRate),
9238
- durationSamples: Math.round((clipDesc.duration || waveformData.duration) * wdRate),
9239
- offsetSamples: Math.round(clipDesc.offset * wdRate),
9240
- gain: clipDesc.gain,
9241
- name: clipDesc.name,
9242
- sampleRate: wdRate,
9243
- sourceDurationSamples: Math.ceil(waveformData.duration * wdRate)
9244
- });
9245
- if (isDomClip(clipDesc)) clip2.id = clipDesc.clipId;
9246
- const effectiveScale = Math.max(this._renderSpp, waveformData.scale);
9247
- const peakData = extractPeaks(
9248
- waveformData,
9249
- effectiveScale,
9250
- this.mono,
9251
- clip2.offsetSamples,
9252
- clip2.durationSamples
9253
- );
9254
- this._clipOffsets.set(clip2.id, {
9255
- offsetSamples: clip2.offsetSamples,
9256
- durationSamples: clip2.durationSamples
9257
- });
9258
- this._peaksData = new Map(this._peaksData).set(clip2.id, peakData);
9259
- this._raiseZoomFloor(waveformData.scale);
9260
- if (this._tracks.has(trackId)) {
9261
- const previewTrack = (0, import_core17.createTrack)({
9262
- name: descriptor.name,
9263
- kind: descriptor.kind,
9264
- clips: [clip2],
9265
- ...this._mixOf(trackId)
9266
- });
9267
- previewTrack.id = trackId;
9268
- this._engineTracks = new Map(this._engineTracks).set(trackId, previewTrack);
9269
- this._recomputeDuration();
9270
- }
9271
- let audioBuffer2;
9272
- try {
9273
- audioBuffer2 = await audioPromise;
9274
- } catch (audioErr) {
9275
- const nextPeaks = new Map(this._peaksData);
9276
- nextPeaks.delete(clip2.id);
9277
- this._peaksData = nextPeaks;
9278
- this._clipOffsets.delete(clip2.id);
9279
- const nextEngine = new Map(this._engineTracks);
9280
- nextEngine.delete(trackId);
9281
- this._engineTracks = nextEngine;
9282
- this._recomputeZoomFloor();
9283
- this._recomputeDuration();
9284
- throw audioErr;
9285
- }
9286
- this._resolvedSampleRate = audioBuffer2.sampleRate;
9287
- const updatedClip = { ...clip2, audioBuffer: audioBuffer2 };
9288
- this._clipBuffers = new Map(this._clipBuffers).set(clip2.id, audioBuffer2);
9289
- this._peakPipeline.cacheWaveformData(audioBuffer2, waveformData);
9290
- clips.push(updatedClip);
9291
- continue;
9292
- }
9293
- const audioBuffer = await audioPromise;
9294
- this._resolvedSampleRate = audioBuffer.sampleRate;
9295
- const clip = await this._finalizeAudioClip(clipDesc, audioBuffer, null);
9296
- clips.push(clip);
9297
- } catch (clipErr) {
9298
- console.warn(
9299
- '[dawcore] _loadTrack: clip "' + clipDesc.src + '" failed: ' + String(clipErr)
9300
- );
9301
- if (this.isConnected) {
9302
- this.dispatchEvent(
9303
- new CustomEvent("daw-clip-error", {
9304
- bubbles: true,
9305
- composed: true,
9306
- detail: {
9307
- trackId,
9308
- clipId: isDomClip(clipDesc) ? clipDesc.clipId : "",
9309
- error: clipErr
9310
- }
9311
- })
9312
- );
9313
- }
9314
- }
9315
- }
9316
- const trackWasRemoved = !this._tracks.has(trackId);
9317
- if (trackWasRemoved || !this.isConnected) {
9318
- for (const clip of clips) {
9319
- this._purgeClipCaches(clip.id);
9320
- }
9321
- if (this._engineTracks.has(trackId)) {
9322
- const nextEngine = new Map(this._engineTracks);
9323
- nextEngine.delete(trackId);
9324
- this._engineTracks = nextEngine;
9325
- this._recomputeDuration();
9326
- }
9327
- this._recomputeZoomFloor();
9328
- if (this._samplesPerPixel !== sppAtLoadStart && sppAtLoadStart >= this._minSamplesPerPixel) {
9329
- this.samplesPerPixel = sppAtLoadStart;
9330
- }
9331
- throw new TrackLoadCancelledError(
9332
- trackWasRemoved ? 'track "' + trackId + '" was removed while loading' : 'editor was disconnected while track "' + trackId + '" was loading',
9333
- trackWasRemoved ? "removed" : "disconnected"
9334
- );
9335
- }
9336
- const track = (0, import_core17.createTrack)({
9337
- name: descriptor.name,
9338
- kind: descriptor.kind,
9339
- clips,
9340
- ...this._mixOf(trackId)
9341
- });
9342
- const requestedClips = descriptor.clips.filter((c) => c.src).length + refusedMidiClips;
9343
- if (requestedClips > 0 && clips.length === 0) {
9344
- throw new Error(
9345
- "all " + requestedClips + " clip(s) failed to load \u2014 see prior daw-clip-error events"
9346
- );
9347
- }
9348
- track.id = trackId;
9349
- this._engineTracks = new Map(this._engineTracks).set(trackId, track);
9350
- this._recomputeDuration();
9351
- for (const c of clips) {
9352
- this._maybeRegisterSpectrogramClipAudio(trackId, c);
9353
- }
9354
- const engine = await this._ensureEngine();
9355
- engine.setTracks(this._tracksForEngine());
9355
+ /** Enter one registered track. False when it is gone, already in, or refused. */
9356
+ _enterTrack(trackId) {
9357
+ const descriptor = this._tracks.get(trackId);
9358
+ if (!descriptor || this._isEntered(trackId)) return false;
9359
+ const el = this._trackElements.get(trackId);
9360
+ const built = buildArrangementTrack(
9361
+ trackId,
9362
+ descriptor,
9363
+ el ? mixOfElement(el) : DEFAULT_TRACK_MIX,
9364
+ this.effectiveSampleRate
9365
+ );
9366
+ if (built.descriptor !== descriptor) {
9367
+ this._tracks = new Map(this._tracks).set(trackId, built.descriptor);
9368
+ }
9369
+ for (const { clipId, error } of built.refused) {
9370
+ console.warn("[dawcore] " + error.message);
9356
9371
  this.dispatchEvent(
9357
- new CustomEvent("daw-track-ready", {
9372
+ new CustomEvent("daw-clip-error", {
9358
9373
  bubbles: true,
9359
9374
  composed: true,
9360
- detail: { trackId }
9375
+ detail: { trackId, clipId, error }
9361
9376
  })
9362
9377
  );
9378
+ }
9379
+ const index = el ? entryIndex(
9380
+ [...this.querySelectorAll("daw-track")],
9381
+ trackId,
9382
+ this._arrangement.getTracks().map((t) => t.id)
9383
+ ) : void 0;
9384
+ this._announcer.expect(trackId, built.refused.length);
9385
+ for (const clip of built.track.clips) {
9386
+ if ((0, import_core19.isLoadingClip)(clip)) this._announcer.expectClip(clip.id);
9387
+ }
9388
+ try {
9389
+ this._arrangement.addTrack(built.track, index === void 0 ? void 0 : { index });
9363
9390
  } catch (err) {
9364
- const cancelled = err instanceof TrackLoadCancelledError;
9365
- console.warn(
9366
- cancelled ? "[dawcore] Track load cancelled: " + err.message : '[dawcore] Failed to load track "' + trackId + '": ' + String(err)
9367
- );
9391
+ console.warn('[dawcore] Failed to add track "' + trackId + '": ' + String(err));
9392
+ this._settleEntry(trackId, err instanceof Error ? err : new Error(String(err)));
9368
9393
  this.dispatchEvent(
9369
9394
  new CustomEvent("daw-track-error", {
9370
9395
  bubbles: true,
9371
9396
  composed: true,
9372
- detail: {
9373
- trackId,
9374
- error: err,
9375
- ...cancelled ? { reason: err.reason } : {}
9376
- }
9397
+ detail: { trackId, error: err }
9377
9398
  })
9378
9399
  );
9379
- } finally {
9380
- this._loadingTracks.delete(trackId);
9381
- }
9382
- }
9383
- async _fetchAndDecode(src) {
9384
- if (this._audioCache.has(src)) {
9385
- return this._audioCache.get(src);
9400
+ return false;
9386
9401
  }
9387
- const promise = (async () => {
9388
- const response = await fetch(src);
9389
- if (!response.ok) {
9390
- throw new Error(
9391
- 'Failed to fetch audio "' + src + '": ' + response.status + " " + response.statusText
9392
- );
9402
+ this._settleEntry(trackId, null);
9403
+ for (const clipDesc of built.descriptor.clips) {
9404
+ if (clipDesc.peaksSrc && clipDesc.clipId && clipSourceOf(clipDesc)) {
9405
+ this._requestPreview(clipDesc.clipId, clipDesc.peaksSrc);
9393
9406
  }
9394
- const arrayBuffer = await response.arrayBuffer();
9395
- return this.audioContext.decodeAudioData(arrayBuffer);
9396
- })();
9397
- this._audioCache.set(src, promise);
9398
- try {
9399
- return await promise;
9400
- } catch (err) {
9401
- this._audioCache.delete(src);
9402
- throw err;
9403
9407
  }
9408
+ return true;
9409
+ }
9410
+ /**
9411
+ * The `<daw-track src>` shorthand changed its src: the entered track gets a
9412
+ * new loading clip for it, one undo step. A track whose clips are
9413
+ * `<daw-clip>` children keeps them. A track still queued reads the new
9414
+ * descriptor when it enters.
9415
+ */
9416
+ _replaceShorthandClips(trackId, descriptor) {
9417
+ if (!this._isEntered(trackId) || descriptor.clips.some(isDomClip)) return;
9418
+ const built = buildArrangementTrack(
9419
+ trackId,
9420
+ descriptor,
9421
+ DEFAULT_TRACK_MIX,
9422
+ this.effectiveSampleRate
9423
+ );
9424
+ this._tracks = new Map(this._tracks).set(trackId, built.descriptor);
9425
+ this._arrangement.updateTrack(trackId, (current) => ({ ...current, clips: built.track.clips }));
9426
+ }
9427
+ /** Run the load announcements over the arrangement's current state. */
9428
+ _announceLoading() {
9429
+ this._announcer.update(
9430
+ this._arrangement.getTracks(),
9431
+ this._arrangement.sources.getSnapshot().sources
9432
+ );
9433
+ }
9434
+ /**
9435
+ * Fetch a loading clip's `.dat` peaks and draw them until its audio
9436
+ * arrives (an editor-only cache, not the arrangement: writing the clip
9437
+ * after it entered would be an undo step).
9438
+ */
9439
+ async _requestPreview(clipId, peaksSrc) {
9440
+ const waveformData = await this._resolvePeaks(peaksSrc);
9441
+ if (!waveformData) return;
9442
+ const clip = this._arrangement.getTracks().flatMap((t) => t.clips).find((c) => c.id === clipId);
9443
+ if (!clip || !(0, import_core19.isLoadingClip)(clip)) return;
9444
+ const rate = waveformData.sample_rate;
9445
+ const offset = clip.offset ?? 0;
9446
+ const seconds = clip.duration ?? Math.max(0, waveformData.duration - offset);
9447
+ const peakData = extractPeaks(
9448
+ waveformData,
9449
+ Math.max(this._renderSpp, waveformData.scale),
9450
+ this.mono,
9451
+ Math.round(offset * rate),
9452
+ Math.round(seconds * rate)
9453
+ );
9454
+ this._previewPeaks = new Map(this._previewPeaks).set(clipId, peakData);
9455
+ this._previewWaveforms.set(clipId, waveformData);
9456
+ this._raiseZoomFloor(waveformData.scale);
9457
+ this._recomputeDuration();
9458
+ }
9459
+ /** The peak sync made a clip's peaks: its zoom floor holds, its preview goes. */
9460
+ _clipPeaksReady(clipId, audioBuffer) {
9461
+ this._raiseZoomFloor(this._peakPipeline.getCachedScale(audioBuffer));
9462
+ if (!this._previewPeaks.has(clipId)) return;
9463
+ const next = new Map(this._previewPeaks);
9464
+ next.delete(clipId);
9465
+ this._previewPeaks = next;
9466
+ }
9467
+ _waitForEntry(trackId) {
9468
+ return new Promise((resolve, reject) => {
9469
+ this._entryWaiters.set(trackId, { resolve, reject });
9470
+ });
9471
+ }
9472
+ /** Settle the wait for a track's entry: entered (`null`), or refused or gone. */
9473
+ _settleEntry(trackId, error) {
9474
+ const waiter = this._entryWaiters.get(trackId);
9475
+ if (!waiter) return;
9476
+ this._entryWaiters.delete(trackId);
9477
+ if (error) waiter.reject(error);
9478
+ else waiter.resolve(trackId);
9479
+ }
9480
+ /**
9481
+ * A dropped file as a track with no element (a File cannot be an attribute):
9482
+ * one loading clip whose source is the file. Resolves with the track id once
9483
+ * it has entered, an undo step like any track an editor method adds.
9484
+ */
9485
+ _addDroppedFile(file) {
9486
+ const trackId = crypto.randomUUID();
9487
+ const name = file.name.replace(/\.\w+$/, "");
9488
+ this._tracks = new Map(this._tracks).set(trackId, {
9489
+ name,
9490
+ src: "",
9491
+ kind: "audio",
9492
+ renderMode: trackDescriptorRenderMode("audio", "waveform"),
9493
+ clips: [
9494
+ {
9495
+ kind: "drop",
9496
+ file,
9497
+ src: "",
9498
+ peaksSrc: "",
9499
+ start: 0,
9500
+ duration: 0,
9501
+ offset: 0,
9502
+ gain: 1,
9503
+ name,
9504
+ fadeIn: 0,
9505
+ fadeOut: 0,
9506
+ fadeType: "linear",
9507
+ midiNotes: null,
9508
+ midiChannel: null,
9509
+ midiProgram: null
9510
+ }
9511
+ ]
9512
+ });
9513
+ const entered = this._waitForEntry(trackId);
9514
+ this._queueEntry(trackId);
9515
+ return entered;
9516
+ }
9517
+ /**
9518
+ * Take a track out for good: no undo step, and no undo or redo brings it
9519
+ * back (a dropped file that could not be loaded was never a declaration).
9520
+ */
9521
+ _discardTrack(trackId) {
9522
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9523
+ this._announcer.forget(trackId, track?.clips.map((c) => c.id) ?? []);
9524
+ this._arrangement.removeTrack(trackId, { undoable: false });
9525
+ this._onTrackRemoved(trackId);
9526
+ }
9527
+ /**
9528
+ * Resolves once the track has loaded (`daw-track-ready`), or when the
9529
+ * editor is disconnected meanwhile (the track is kept and loads after a
9530
+ * reparent); rejects when its audio failed (`daw-track-error`).
9531
+ */
9532
+ _whenTrackLoaded(trackId) {
9533
+ const state9 = this._announcer.stateOf(trackId);
9534
+ if (state9 === "ready") return Promise.resolve();
9535
+ if (state9 === "failed") return Promise.reject(this._announcer.errorOf(trackId));
9536
+ return new Promise((resolve, reject) => {
9537
+ const cleanup = () => {
9538
+ this.removeEventListener("daw-track-ready", onReady);
9539
+ this.removeEventListener("daw-track-error", onError);
9540
+ this._loadWaitEnds.delete(end);
9541
+ };
9542
+ const onReady = (e) => {
9543
+ if (e.detail.trackId !== trackId) return;
9544
+ cleanup();
9545
+ resolve();
9546
+ };
9547
+ const onError = (e) => {
9548
+ const detail = e.detail;
9549
+ if (detail.trackId !== trackId) return;
9550
+ cleanup();
9551
+ reject(detail.error instanceof Error ? detail.error : new Error(String(detail.error)));
9552
+ };
9553
+ const end = () => {
9554
+ cleanup();
9555
+ resolve();
9556
+ };
9557
+ this.addEventListener("daw-track-ready", onReady);
9558
+ this.addEventListener("daw-track-error", onError);
9559
+ this._loadWaitEnds.add(end);
9560
+ });
9561
+ }
9562
+ /**
9563
+ * Load again every failed source the track's clips name (#848). A track
9564
+ * whose audio failed stays in the editor, like a broken `<img>`;
9565
+ * `daw-track-ready` follows when it loads.
9566
+ */
9567
+ retryTrack(trackId) {
9568
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
9569
+ if (!track) {
9570
+ console.warn('[dawcore] retryTrack: no track found for id "' + trackId + '"');
9571
+ return;
9572
+ }
9573
+ const sources = this._arrangement.sources.getSnapshot().sources;
9574
+ const failed = new Set(
9575
+ track.clips.filter(import_core19.isLoadingClip).map((clip) => clip.src).filter((src) => sources.get(src)?.status === "failed")
9576
+ );
9577
+ for (const src of failed) this._arrangement.retry(src);
9404
9578
  }
9405
9579
  _fetchPeaks(src) {
9406
9580
  const cached = this._peaksCache.get(src);
@@ -9412,7 +9586,13 @@ var DawEditorElement = class extends import_lit19.LitElement {
9412
9586
  this._peaksCache.set(src, promise);
9413
9587
  return promise;
9414
9588
  }
9589
+ /**
9590
+ * The timeline's duration, the one writer of `_duration`: the loaded clips,
9591
+ * and the clips still loading whose length is known (a duration, or `.dat`
9592
+ * peaks), so the timeline is as wide as what is drawn (#848).
9593
+ */
9415
9594
  _recomputeDuration() {
9595
+ const sr = this.effectiveSampleRate;
9416
9596
  let maxSample = 0;
9417
9597
  for (const track of this._engineTracks.values()) {
9418
9598
  for (const clip of track.clips) {
@@ -9420,28 +9600,60 @@ var DawEditorElement = class extends import_lit19.LitElement {
9420
9600
  if (endSample > maxSample) maxSample = endSample;
9421
9601
  }
9422
9602
  }
9423
- this._duration = maxSample / this.effectiveSampleRate;
9603
+ for (const track of this._arrangement.getTracks()) {
9604
+ for (const clip of track.clips) {
9605
+ if (!(0, import_core19.isLoadingClip)(clip)) continue;
9606
+ const seconds = this._placeholderSeconds(clip);
9607
+ if (seconds === null) continue;
9608
+ maxSample = Math.max(maxSample, Math.round(((clip.start ?? 0) + seconds) * sr));
9609
+ }
9610
+ }
9611
+ this._duration = maxSample / sr;
9612
+ }
9613
+ /** How long a loading clip is drawn: its duration, else what its `.dat` peaks cover; null when unknown. */
9614
+ _placeholderSeconds(clip) {
9615
+ if (clip.duration != null && clip.duration > 0) return clip.duration;
9616
+ const waveformData = this._previewWaveforms.get(clip.id);
9617
+ if (!waveformData) return null;
9618
+ const seconds = waveformData.duration - (clip.offset ?? 0);
9619
+ return seconds > 0 ? seconds : null;
9424
9620
  }
9425
9621
  // --- Engine ---
9622
+ /**
9623
+ * The engine, built now when the editor is connected with an adapter.
9624
+ * Rejects without an adapter, and on a detached editor (an engine built
9625
+ * there would hold the adapter's graph with nothing to dispose it).
9626
+ */
9426
9627
  _ensureEngine() {
9427
9628
  if (this._engine) return Promise.resolve(this._engine);
9428
- if (this._enginePromise) return this._enginePromise;
9429
- this._enginePromise = this._buildEngine().catch((err) => {
9430
- this._enginePromise = null;
9431
- throw err;
9432
- });
9433
- return this._enginePromise;
9629
+ try {
9630
+ if (!this.isConnected && this._externalAdapter) {
9631
+ throw new Error("[dawcore] <daw-editor> is not connected: no engine is built for it.");
9632
+ }
9633
+ return Promise.resolve(this._buildEngine());
9634
+ } catch (err) {
9635
+ return Promise.reject(err);
9636
+ }
9434
9637
  }
9435
- async _buildEngine() {
9638
+ /** Build the engine from the adapter setter or a connect: a failure is reported, not thrown. */
9639
+ _buildEngineReporting() {
9640
+ try {
9641
+ this._buildEngine();
9642
+ } catch (err) {
9643
+ console.warn("[dawcore] Failed to build the engine: " + String(err));
9644
+ this.dispatchEvent(
9645
+ new CustomEvent("daw-error", {
9646
+ bubbles: true,
9647
+ composed: true,
9648
+ detail: { operation: "engine", error: err }
9649
+ })
9650
+ );
9651
+ }
9652
+ }
9653
+ _buildEngine() {
9436
9654
  if (!this._externalAdapter) {
9437
9655
  throw new Error(noAdapterError());
9438
9656
  }
9439
- if (this._adapterConsumedByDispose) {
9440
- throw new Error(
9441
- "[dawcore] editor.adapter was disposed by a previous disconnect \u2014 set a fresh PlayoutAdapter after reparenting <daw-editor>."
9442
- );
9443
- }
9444
- const { PlaylistEngine } = await import("@waveform-playlist/engine");
9445
9657
  const adapter = this._externalAdapter;
9446
9658
  if (!this._hasTickCallbacks) {
9447
9659
  if (adapter.setTempo) {
@@ -9454,65 +9666,94 @@ var DawEditorElement = class extends import_lit19.LitElement {
9454
9666
  }
9455
9667
  adapter.setPpqn?.(this._ppqn);
9456
9668
  this.ppqn = adapter.ppqn;
9457
- const engine = new PlaylistEngine({
9669
+ const engine = new import_engine.PlaylistEngine({
9458
9670
  adapter,
9459
- sampleRate: this.effectiveSampleRate,
9671
+ arrangement: this._arrangement,
9672
+ sampleRate: adapter.audioContext.sampleRate,
9460
9673
  samplesPerPixel: this.samplesPerPixel,
9461
9674
  bpm: this._bpm,
9462
9675
  zoomLevels: [256, 512, 1024, 2048, 4096, 8192, this.samplesPerPixel].filter((v, i, a) => a.indexOf(v) === i).sort((a, b) => a - b)
9463
9676
  });
9464
- let lastTracksVersion = -1;
9465
- let lastMixerVersion = -1;
9466
- engine.on("statechange", (engineState) => {
9467
- this._isPlaying = engineState.isPlaying;
9468
- this._duration = engineState.duration;
9469
- this._selectedTrackId = engineState.selectedTrackId;
9470
- const structuralChange = engineState.tracksVersion !== lastTracksVersion;
9471
- const mixerChange = engineState.mixerVersion !== lastMixerVersion;
9472
- if (structuralChange || mixerChange) {
9473
- lastTracksVersion = engineState.tracksVersion;
9474
- lastMixerVersion = engineState.mixerVersion;
9475
- const nextTracks = /* @__PURE__ */ new Map();
9476
- for (const track of engineState.tracks) {
9477
- nextTracks.set(track.id, track);
9478
- }
9479
- this._engineTracks = nextTracks;
9480
- this._deleteSeedMix(nextTracks.keys());
9481
- this._reconcileDescriptorsWithEngineTracks(engineState.tracks);
9482
- }
9483
- if (structuralChange) {
9484
- if (!this._inOrderSync) {
9485
- this._syncDomToEngineOrder(engineState.tracks);
9486
- }
9487
- this._effectsManager?.rewireTrackChains();
9488
- const audioTracks = engineState.tracks.filter((t) => (0, import_core17.trackKind)(t) !== "midi");
9489
- syncPeaksForChangedClips(this, audioTracks);
9490
- }
9491
- if (engineState.bpm !== this._lastAnnotationBpm) {
9492
- this._lastAnnotationBpm = engineState.bpm;
9493
- this._annotations.deriveSecondsCaches();
9494
- }
9495
- });
9677
+ this._lastTracksVersion = -1;
9678
+ this._lastMixerVersion = -1;
9679
+ engine.on("statechange", (engineState) => this._onEngineState(engineState));
9496
9680
  engine.on("pause", () => {
9497
9681
  this._currentTime = engine.getCurrentTime();
9498
9682
  });
9499
- engine.on("stop", () => {
9500
- this._currentTime = engine.getCurrentTime();
9501
- this._stopPlayhead();
9502
- this._activePlayEndTime = null;
9503
- if (!this._inConsumerStop && !this._inSeekTransition && this.isConnected) {
9504
- this.dispatchEvent(new CustomEvent("daw-stop", { bubbles: true, composed: true }));
9505
- }
9506
- });
9683
+ engine.on("stop", () => this._onEngineStop(engine));
9507
9684
  this._engine = engine;
9685
+ this._onEngineState(engine.getState());
9686
+ for (const track of this._engineTracks.values()) {
9687
+ for (const clip of track.clips) this._maybeRegisterSpectrogramClipAudio(track.id, clip);
9688
+ }
9689
+ this._flushTrackEntries();
9508
9690
  return engine;
9509
9691
  }
9692
+ /**
9693
+ * Clips whose audio has just arrived: a `.dat` preview's data goes to the
9694
+ * peak pipeline (no worker run), a spectrogram track gets the audio. The
9695
+ * peak sync then makes their peaks.
9696
+ */
9697
+ _adoptLoadedClips(tracks) {
9698
+ for (const track of tracks) {
9699
+ for (const clip of track.clips) {
9700
+ const waveformData = this._previewWaveforms.get(clip.id);
9701
+ if (waveformData && clip.audioBuffer) {
9702
+ if (waveformData.sample_rate === clip.audioBuffer.sampleRate) {
9703
+ this._peakPipeline.cacheWaveformData(clip.audioBuffer, waveformData);
9704
+ }
9705
+ this._previewWaveforms.delete(clip.id);
9706
+ }
9707
+ if (!this._clipBuffers.has(clip.id))
9708
+ this._maybeRegisterSpectrogramClipAudio(track.id, clip);
9709
+ }
9710
+ }
9711
+ }
9712
+ /** The engine's state changed: follow it (the one writer of `_engineTracks`). */
9713
+ _onEngineState(engineState) {
9714
+ this._isPlaying = engineState.isPlaying;
9715
+ this._selectedTrackId = engineState.selectedTrackId;
9716
+ const structuralChange = engineState.tracksVersion !== this._lastTracksVersion;
9717
+ const mixerChange = engineState.mixerVersion !== this._lastMixerVersion;
9718
+ if (structuralChange || mixerChange) {
9719
+ this._lastTracksVersion = engineState.tracksVersion;
9720
+ this._lastMixerVersion = engineState.mixerVersion;
9721
+ const nextTracks = /* @__PURE__ */ new Map();
9722
+ for (const track of engineState.tracks) {
9723
+ nextTracks.set(track.id, track);
9724
+ }
9725
+ this._engineTracks = nextTracks;
9726
+ this._reconcileDescriptorsWithEngineTracks(engineState.tracks);
9727
+ }
9728
+ if (structuralChange) {
9729
+ this._recomputeDuration();
9730
+ if (!this._inOrderSync) {
9731
+ this._syncDomToEngineOrder(engineState.tracks);
9732
+ }
9733
+ this._effectsManager?.rewireTrackChains();
9734
+ const audioTracks = engineState.tracks.filter((t) => (0, import_core19.trackKind)(t) !== "midi");
9735
+ this._adoptLoadedClips(audioTracks);
9736
+ syncPeaksForChangedClips(this, audioTracks);
9737
+ this._announceLoading();
9738
+ }
9739
+ if (engineState.bpm !== this._lastAnnotationBpm) {
9740
+ this._lastAnnotationBpm = engineState.bpm;
9741
+ this._annotations.deriveSecondsCaches();
9742
+ }
9743
+ }
9744
+ _onEngineStop(engine) {
9745
+ this._currentTime = engine.getCurrentTime();
9746
+ this._stopPlayhead();
9747
+ this._activePlayEndTime = null;
9748
+ if (!this._inConsumerStop && !this._inSeekTransition && this.isConnected) {
9749
+ this.dispatchEvent(new CustomEvent("daw-stop", { bubbles: true, composed: true }));
9750
+ }
9751
+ }
9510
9752
  _disposeEngine() {
9511
9753
  if (this._engine) {
9512
9754
  this._engine.dispose();
9513
9755
  this._engine = null;
9514
9756
  }
9515
- this._enginePromise = null;
9516
9757
  }
9517
9758
  async loadFiles(files) {
9518
9759
  return loadFiles(this, files);
@@ -9543,43 +9784,17 @@ var DawEditorElement = class extends import_lit19.LitElement {
9543
9784
  return this._ensureEngine();
9544
9785
  }
9545
9786
  /**
9546
- * Wait for either `readyEvent` or `errorEvent` to fire on this editor for
9547
- * the entity matching `matchesId`. Listeners are wired synchronously, then
9548
- * `setup` is called (typical: appendChild). Resolves with `resolveValue`
9549
- * on ready; rejects with a normalized Error on error. Used by addTrack and
9550
- * addClip to share their Promise-with-listener-cleanup machinery.
9551
- */
9552
- _awaitId(readyEvent, errorEvent, matchesId, resolveValue, setup) {
9553
- return new Promise((resolve, reject) => {
9554
- const onReady = (e) => {
9555
- if (!matchesId(e.detail)) return;
9556
- cleanup();
9557
- resolve(resolveValue);
9558
- };
9559
- const onError = (e) => {
9560
- const detail = e.detail;
9561
- if (!matchesId(e.detail)) return;
9562
- cleanup();
9563
- const err = detail.error;
9564
- reject(err instanceof Error ? err : new Error(String(err)));
9565
- };
9566
- const cleanup = () => {
9567
- this.removeEventListener(readyEvent, onReady);
9568
- this.removeEventListener(errorEvent, onError);
9569
- };
9570
- this.addEventListener(readyEvent, onReady);
9571
- this.addEventListener(errorEvent, onError);
9572
- setup();
9573
- });
9574
- }
9575
- /**
9576
- * Append a `<daw-track>` element built from `config` and resolve once the
9577
- * track finishes loading (or reject on `daw-track-error`). Goes through
9578
- * the same `_loadTrack` pipeline as declarative tracks, so descriptors,
9579
- * peaks, and clip buffers are populated correctly.
9787
+ * Append a `<daw-track>` element built from `config` and resolve with its
9788
+ * track id once the track has entered the arrangement (#848), before its
9789
+ * audio has loaded. To follow loading, add the `daw-track-ready` /
9790
+ * `daw-track-error` listener BEFORE calling: for a track with nothing to
9791
+ * fetch, or whose audio is already loaded, it fires before this resolves.
9792
+ * Without `editor.adapter` it waits for one. Rejects when the track is
9793
+ * refused by the arrangement or removed before it enters.
9580
9794
  */
9581
9795
  addTrack(config = {}) {
9582
9796
  const trackEl = document.createElement("daw-track");
9797
+ this._editorMadeTracks.add(trackEl);
9583
9798
  if (config.name !== void 0) trackEl.setAttribute("name", config.name);
9584
9799
  if (config.volume !== void 0) trackEl.volume = config.volume;
9585
9800
  if (config.pan !== void 0) trackEl.pan = config.pan;
@@ -9599,13 +9814,9 @@ var DawEditorElement = class extends import_lit19.LitElement {
9599
9814
  for (const clipConfig of clipConfigs) {
9600
9815
  trackEl.appendChild(this._buildClipElement(clipConfig));
9601
9816
  }
9602
- return this._awaitId(
9603
- "daw-track-ready",
9604
- "daw-track-error",
9605
- (d) => d.trackId === trackEl.trackId,
9606
- trackEl,
9607
- () => this.appendChild(trackEl)
9608
- );
9817
+ const entered = this._waitForEntry(trackEl.trackId);
9818
+ this.appendChild(trackEl);
9819
+ return entered;
9609
9820
  }
9610
9821
  /**
9611
9822
  * Remove a track by id. Equivalent to `trackElement.remove()` —
@@ -9616,7 +9827,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
9616
9827
  const trackEl = this._trackElements.get(trackId);
9617
9828
  if (trackEl) {
9618
9829
  trackEl.remove();
9619
- } else if (this._engineTracks.has(trackId)) {
9830
+ if (!this.isConnected) this._onTrackRemoved(trackId);
9831
+ } else if (this._tracks.has(trackId) || this._isEntered(trackId)) {
9620
9832
  this._onTrackRemoved(trackId);
9621
9833
  } else {
9622
9834
  console.warn('[dawcore] removeTrack: no track found for id "' + trackId + '"');
@@ -9643,8 +9855,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
9643
9855
  const anchor = els[clamped];
9644
9856
  if (clamped > from) anchor.after(el);
9645
9857
  else anchor.before(el);
9646
- } else if (this._engineTracks.has(trackId)) {
9647
- this._engine.reorderTrack(trackId, toIndex);
9858
+ } else if (this._isEntered(trackId)) {
9859
+ this._arrangement.reorderTrack(trackId, toIndex);
9648
9860
  this.requestUpdate();
9649
9861
  } else {
9650
9862
  console.warn('[dawcore] reorderTrack: no track found for id "' + trackId + '"');
@@ -9652,8 +9864,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
9652
9864
  }
9653
9865
  /**
9654
9866
  * Update reflected attributes on a track. The mixer fields go to their
9655
- * owner as one undo step (#843): the engine, or while the track is loading
9656
- * the values it will enter with (not a step). For DOM-element tracks the
9867
+ * owner, the arrangement, as one undo step (#843; also while the track
9868
+ * loads, #848). For DOM-element tracks the
9657
9869
  * changes are also written to the `<daw-track>` element; for tracks
9658
9870
  * without a DOM element (file drops) the descriptor is updated in place.
9659
9871
  */
@@ -9702,8 +9914,10 @@ var DawEditorElement = class extends import_lit19.LitElement {
9702
9914
  }
9703
9915
  /**
9704
9916
  * Append a clip to an existing track. Builds a `<daw-clip>` from `config`
9705
- * and appends it to the track's DOM element when one exists; resolves with
9706
- * the new clip's id once the audio decode + peak generation finish.
9917
+ * and appends it to the track's DOM element; resolves with the new clip's
9918
+ * id once its audio has loaded (`daw-clip-ready`, before its peaks are
9919
+ * drawn); rejects when it fails to load, is refused, or leaves the
9920
+ * arrangement before it loads (a removal, an Undo).
9707
9921
  */
9708
9922
  addClip(trackId, config) {
9709
9923
  if (!config.src) {
@@ -9721,14 +9935,54 @@ var DawEditorElement = class extends import_lit19.LitElement {
9721
9935
  )
9722
9936
  );
9723
9937
  }
9938
+ if (!this._isEntered(trackId) && !this._entryQueue.includes(trackId)) {
9939
+ return Promise.reject(
9940
+ new Error(
9941
+ 'addClip: track "' + trackId + '" is not in the editor (an Undo took it out, or the arrangement refused it)'
9942
+ )
9943
+ );
9944
+ }
9724
9945
  const clipEl = this._buildClipElement(config);
9725
- return this._awaitId(
9726
- "daw-clip-ready",
9727
- "daw-clip-error",
9728
- (d) => d.clipId === clipEl.clipId,
9729
- clipEl.clipId,
9730
- () => trackEl.appendChild(clipEl)
9731
- );
9946
+ const clipId = clipEl.clipId;
9947
+ return new Promise((resolve, reject) => {
9948
+ let seen = false;
9949
+ const onReady = (e) => {
9950
+ if (e.detail.clipId !== clipId) return;
9951
+ cleanup();
9952
+ resolve(clipId);
9953
+ };
9954
+ const onError = (e) => {
9955
+ const detail = e.detail;
9956
+ if (detail.clipId !== clipId) return;
9957
+ cleanup();
9958
+ reject(detail.error instanceof Error ? detail.error : new Error(String(detail.error)));
9959
+ };
9960
+ const stopWatching = this._arrangement.subscribe(() => {
9961
+ const present = this._arrangement.getTracks().some((t) => t.clips.some((c) => c.id === clipId));
9962
+ if (present) {
9963
+ seen = true;
9964
+ } else if (seen) {
9965
+ cleanup();
9966
+ reject(new Error('clip "' + clipId + '" was removed before its audio loaded'));
9967
+ }
9968
+ });
9969
+ const cleanup = () => {
9970
+ this.removeEventListener("daw-clip-ready", onReady);
9971
+ this.removeEventListener("daw-clip-error", onError);
9972
+ stopWatching();
9973
+ this._awaitedClips.delete(clipId);
9974
+ };
9975
+ this.addEventListener("daw-clip-ready", onReady);
9976
+ this.addEventListener("daw-clip-error", onError);
9977
+ this._awaitedClips.set(clipId, {
9978
+ trackId,
9979
+ reject: (error) => {
9980
+ cleanup();
9981
+ reject(error);
9982
+ }
9983
+ });
9984
+ trackEl.appendChild(clipEl);
9985
+ });
9732
9986
  }
9733
9987
  /**
9734
9988
  * Remove a clip by id. Removes the matching `<daw-clip>` DOM element when
@@ -9746,7 +10000,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9746
10000
  return;
9747
10001
  }
9748
10002
  }
9749
- if (this._engineTracks.has(trackId)) {
10003
+ if (this._isEntered(trackId)) {
9750
10004
  this._removeClipFromTrack(trackId, clipId);
9751
10005
  return;
9752
10006
  }
@@ -9807,10 +10061,6 @@ var DawEditorElement = class extends import_lit19.LitElement {
9807
10061
  ...partial.gain !== void 0 && { gain: partial.gain },
9808
10062
  ...partial.name !== void 0 && { name: partial.name }
9809
10063
  };
9810
- const updatedClips = [...t.clips];
9811
- updatedClips[idx] = updatedClip;
9812
- const updatedTrack = { ...t, clips: updatedClips };
9813
- this._engineTracks = new Map(this._engineTracks).set(trackId, updatedTrack);
9814
10064
  const desc = this._tracks.get(trackId);
9815
10065
  if (desc?.clips.some((c) => c.clipId === clipId)) {
9816
10066
  this._tracks = new Map(this._tracks).set(trackId, {
@@ -9827,7 +10077,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9827
10077
  )
9828
10078
  });
9829
10079
  }
9830
- this._commitTrackChange(trackId, updatedTrack);
10080
+ this._replaceClip(trackId, clipId, updatedClip);
9831
10081
  }
9832
10082
  _buildClipElement(config) {
9833
10083
  const clipEl = document.createElement("daw-clip");
@@ -10236,11 +10486,12 @@ var DawEditorElement = class extends import_lit19.LitElement {
10236
10486
  (el) => el.trackId
10237
10487
  );
10238
10488
  const engineIds = engine.getState().tracks.map((t) => t.id);
10239
- const target = [...engineIds].sort((a, b) => {
10240
- const ai = domOrder.indexOf(a);
10241
- const bi = domOrder.indexOf(b);
10242
- if (ai === -1 || bi === -1) return 0;
10243
- return ai - bi;
10489
+ const inDom = new Set(domOrder);
10490
+ const slots = engineIds.flatMap((id, i) => inDom.has(id) ? [i] : []);
10491
+ const domSorted = domOrder.filter((id) => engineIds.includes(id));
10492
+ const target = [...engineIds];
10493
+ slots.forEach((slot, k) => {
10494
+ target[slot] = domSorted[k];
10244
10495
  });
10245
10496
  if (target.every((id, i) => id === engineIds[i])) return;
10246
10497
  this._inOrderSync = true;
@@ -10283,18 +10534,67 @@ var DawEditorElement = class extends import_lit19.LitElement {
10283
10534
  slots.splice(i, 0, desired[i]);
10284
10535
  }
10285
10536
  }
10537
+ /**
10538
+ * The rows, in the arrangement's order (#848): each track's loaded clips
10539
+ * (the engine's projection, with the current mix) and the clips still loading.
10540
+ */
10286
10541
  _getOrderedTracks() {
10287
- const domOrder = [...this.querySelectorAll("daw-track")].map(
10288
- (el) => el.trackId
10289
- );
10290
- return [...this._engineTracks.entries()].sort((a, b) => {
10291
- const ai = domOrder.indexOf(a[0]);
10292
- const bi = domOrder.indexOf(b[0]);
10293
- if (ai === -1 && bi === -1) return 0;
10294
- if (ai === -1) return 1;
10295
- if (bi === -1) return -1;
10296
- return ai - bi;
10297
- });
10542
+ const rows = [];
10543
+ for (const track of this._arrangement.getTracks()) {
10544
+ const loaded = this._engineTracks.get(track.id);
10545
+ if (!loaded) continue;
10546
+ rows.push([track.id, loaded, track.clips.filter(import_core19.isLoadingClip)]);
10547
+ }
10548
+ return rows;
10549
+ }
10550
+ /**
10551
+ * A clip still loading: a placeholder box where its length is known, with
10552
+ * its `.dat` peaks when they came, drawn failed when its source failed. Its
10553
+ * header carries no clip id, so it cannot be dragged.
10554
+ */
10555
+ _renderPlaceholder(clip, row) {
10556
+ const seconds = this._placeholderSeconds(clip);
10557
+ if (seconds === null) return "";
10558
+ const sr = this.effectiveSampleRate;
10559
+ const spp = this._renderSpp;
10560
+ const startSec = clip.start ?? 0;
10561
+ let left;
10562
+ let width;
10563
+ if (this.scaleMode === "beats") {
10564
+ left = Math.round(this._secondsToTicks(startSec) / this.ticksPerPixel);
10565
+ width = Math.round(this._secondsToTicks(startSec + seconds) / this.ticksPerPixel) - left;
10566
+ } else {
10567
+ const startSample = Math.round(startSec * sr);
10568
+ left = Math.floor(startSample / spp);
10569
+ width = (0, import_core19.clipPixelWidth)(startSample, Math.round(seconds * sr), spp);
10570
+ }
10571
+ const failed = this._arrangement.sources.getSnapshot().sources.get(clip.src)?.status === "failed";
10572
+ const peakData = this._previewPeaks.get(clip.id);
10573
+ const hdrH = this.clipHeaders ? this.clipHeaderHeight : 0;
10574
+ const chH = this.waveHeight;
10575
+ return import_lit19.html`<div
10576
+ class="clip-container placeholder ${failed ? "failed" : ""}"
10577
+ style="left:${left}px;top:0;width:${width}px;height:${row.trackHeight}px;"
10578
+ data-clip-id=${clip.id}
10579
+ >
10580
+ ${hdrH > 0 ? import_lit19.html`<div class="clip-header">
10581
+ <span>${clip.name || row.descriptor?.name || ""}</span>
10582
+ </div>` : ""}
10583
+ ${(peakData?.data ?? []).map(
10584
+ (chPeaks, chIdx) => import_lit19.html`<daw-waveform
10585
+ style="position:absolute;left:0;top:${hdrH + chIdx * chH}px;"
10586
+ .peaks=${chPeaks}
10587
+ .length=${peakData?.length ?? width}
10588
+ .waveHeight=${chH}
10589
+ .barWidth=${this.barWidth}
10590
+ .barGap=${this.barGap}
10591
+ .roundedBars=${this.roundedBars}
10592
+ .visibleStart=${this._viewport.visibleStart}
10593
+ .visibleEnd=${this._viewport.visibleEnd}
10594
+ .originX=${left}
10595
+ ></daw-waveform>`
10596
+ )}
10597
+ </div>`;
10298
10598
  }
10299
10599
  // --- Render ---
10300
10600
  render() {
@@ -10311,14 +10611,15 @@ var DawEditorElement = class extends import_lit19.LitElement {
10311
10611
  selStartPx = this._selectionStartTime * sr / spp;
10312
10612
  selEndPx = this._selectionEndTime * sr / spp;
10313
10613
  }
10314
- const orderedTracks = this._getOrderedTracks().map(([trackId, track]) => {
10614
+ const orderedTracks = this._getOrderedTracks().map(([trackId, track, loading]) => {
10315
10615
  const descriptor = this._tracks.get(trackId);
10316
- const firstPeaks = track.clips.map((c) => this._peaksData.get(c.id)).find((p) => p && p.data.length > 0);
10616
+ const firstPeaks = [...track.clips, ...loading].map((c) => this._peaksData.get(c.id) ?? this._previewPeaks.get(c.id)).find((p) => p && p.data.length > 0);
10317
10617
  const recSession = this._recordingController.getSession(trackId);
10318
10618
  const numChannels = firstPeaks ? firstPeaks.data.length : recSession ? recSession.channelCount : 1;
10319
10619
  return {
10320
10620
  trackId,
10321
10621
  track,
10622
+ loading,
10322
10623
  descriptor,
10323
10624
  numChannels,
10324
10625
  trackHeight: this.waveHeight * numChannels + (this.clipHeaders ? this.clipHeaderHeight : 0)
@@ -10416,7 +10717,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
10416
10717
  data-track-id=${t.trackId}
10417
10718
  >
10418
10719
  ${t.track.clips.map((clip) => {
10419
- const peakData = this._peaksData.get(clip.id);
10720
+ const peakData = this._peaksData.get(clip.id) ?? this._previewPeaks.get(clip.id);
10420
10721
  let clipLeft;
10421
10722
  let width;
10422
10723
  if (this.scaleMode === "beats") {
@@ -10428,7 +10729,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
10428
10729
  width = Math.round(endTick / this.ticksPerPixel) - clipLeft;
10429
10730
  } else {
10430
10731
  clipLeft = Math.floor(clip.startSample / spp);
10431
- width = (0, import_core17.clipPixelWidth)(clip.startSample, clip.durationSamples, spp);
10732
+ width = (0, import_core19.clipPixelWidth)(clip.startSample, clip.durationSamples, spp);
10432
10733
  }
10433
10734
  let clipSegments;
10434
10735
  let segmentChannels;
@@ -10545,6 +10846,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
10545
10846
  ></div>` : ""}
10546
10847
  </div>`;
10547
10848
  })}
10849
+ ${t.loading.map((clip) => this._renderPlaceholder(clip, t))}
10548
10850
  ${this._renderRecordingPreview(t.trackId, channelHeight)}
10549
10851
  </div>
10550
10852
  `;
@@ -10785,10 +11087,10 @@ __decorateClass([
10785
11087
  ], DawEditorElement.prototype, "ticksToSeconds", 2);
10786
11088
  __decorateClass([
10787
11089
  (0, import_decorators16.state)()
10788
- ], DawEditorElement.prototype, "_tracks", 2);
11090
+ ], DawEditorElement.prototype, "_previewPeaks", 2);
10789
11091
  __decorateClass([
10790
11092
  (0, import_decorators16.state)()
10791
- ], DawEditorElement.prototype, "_seedMix", 2);
11093
+ ], DawEditorElement.prototype, "_tracks", 2);
10792
11094
  __decorateClass([
10793
11095
  (0, import_decorators16.state)()
10794
11096
  ], DawEditorElement.prototype, "_engineTracks", 2);
@@ -10956,7 +11258,7 @@ DawRecordButtonElement = __decorateClass([
10956
11258
  // src/elements/daw-keyboard-shortcuts.ts
10957
11259
  var import_lit22 = require("lit");
10958
11260
  var import_decorators19 = require("lit/decorators.js");
10959
- var import_core18 = require("@waveform-playlist/core");
11261
+ var import_core20 = require("@waveform-playlist/core");
10960
11262
  var DawKeyboardShortcutsElement = class extends import_lit22.LitElement {
10961
11263
  constructor() {
10962
11264
  super(...arguments);
@@ -10981,7 +11283,7 @@ var DawKeyboardShortcutsElement = class extends import_lit22.LitElement {
10981
11283
  const shortcuts = this.shortcuts;
10982
11284
  if (shortcuts.length === 0) return;
10983
11285
  try {
10984
- (0, import_core18.handleKeyboardEvent)(e, shortcuts, true);
11286
+ (0, import_core20.handleKeyboardEvent)(e, shortcuts, true);
10985
11287
  } catch (err) {
10986
11288
  console.warn("[dawcore] Keyboard shortcut failed (key=" + e.key + "): " + String(err));
10987
11289
  const target = this._editor ?? this;
@@ -11171,7 +11473,7 @@ DawKeyboardShortcutsElement = __decorateClass([
11171
11473
  // src/elements/daw-spectrogram.ts
11172
11474
  var import_lit23 = require("lit");
11173
11475
  var import_decorators20 = require("lit/decorators.js");
11174
- var import_core19 = require("@waveform-playlist/core");
11476
+ var import_core21 = require("@waveform-playlist/core");
11175
11477
  var DawSpectrogramElement = class extends import_lit23.LitElement {
11176
11478
  constructor() {
11177
11479
  super(...arguments);
@@ -11236,11 +11538,11 @@ var DawSpectrogramElement = class extends import_lit23.LitElement {
11236
11538
  this._unregisterAllCanvases();
11237
11539
  this._canvases = [];
11238
11540
  if (this.length <= 0) return;
11239
- const chunkCount = Math.ceil(this.length / import_core19.MAX_CANVAS_WIDTH);
11541
+ const chunkCount = Math.ceil(this.length / import_core21.MAX_CANVAS_WIDTH);
11240
11542
  for (let i = 0; i < chunkCount; i++) {
11241
- const widthPx = Math.min(import_core19.MAX_CANVAS_WIDTH, this.length - i * import_core19.MAX_CANVAS_WIDTH);
11543
+ const widthPx = Math.min(import_core21.MAX_CANVAS_WIDTH, this.length - i * import_core21.MAX_CANVAS_WIDTH);
11242
11544
  const canvas = document.createElement("canvas");
11243
- canvas.style.left = i * import_core19.MAX_CANVAS_WIDTH + "px";
11545
+ canvas.style.left = i * import_core21.MAX_CANVAS_WIDTH + "px";
11244
11546
  canvas.style.width = widthPx + "px";
11245
11547
  const dpr = window.devicePixelRatio || 1;
11246
11548
  canvas.width = widthPx * dpr;
@@ -11266,7 +11568,7 @@ var DawSpectrogramElement = class extends import_lit23.LitElement {
11266
11568
  }
11267
11569
  for (let i = 0; i < this._canvases.length; i++) {
11268
11570
  const canvas = this._canvases[i];
11269
- const canvasId = (0, import_core19.buildSpectrogramCanvasId)({
11571
+ const canvasId = (0, import_core21.buildSpectrogramCanvasId)({
11270
11572
  clipId: this.clipId,
11271
11573
  channelIndex: this.channelIndex,
11272
11574
  chunkIndex: i
@@ -11287,7 +11589,7 @@ var DawSpectrogramElement = class extends import_lit23.LitElement {
11287
11589
  trackId: this.trackId,
11288
11590
  channelIndex: this.channelIndex,
11289
11591
  chunkIndex: i,
11290
- globalPixelOffset: this.originX + i * import_core19.MAX_CANVAS_WIDTH,
11592
+ globalPixelOffset: this.originX + i * import_core21.MAX_CANVAS_WIDTH,
11291
11593
  widthPx: parseFloat(canvas.style.width),
11292
11594
  heightPx: this.waveHeight
11293
11595
  });