@dawcore/components 0.0.32 → 0.0.34

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
@@ -465,11 +465,9 @@ var LAYOUT_PROPS = /* @__PURE__ */ new Set([
465
465
  "roundedBars",
466
466
  "segments"
467
467
  ]);
468
- function groupDirtyByChunk(dirtyPixels, step) {
468
+ function groupDirtyByChunk(dirtyPixels, step, barWidth) {
469
469
  const dirtyByChunk = /* @__PURE__ */ new Map();
470
- for (const peakIdx of dirtyPixels) {
471
- const barPixel = Math.floor(peakIdx / step) * step;
472
- const chunkIdx = Math.floor(barPixel / MAX_CANVAS_WIDTH);
470
+ const mark = (chunkIdx, barPixel) => {
473
471
  const existing = dirtyByChunk.get(chunkIdx);
474
472
  if (existing) {
475
473
  dirtyByChunk.set(chunkIdx, {
@@ -479,6 +477,15 @@ function groupDirtyByChunk(dirtyPixels, step) {
479
477
  } else {
480
478
  dirtyByChunk.set(chunkIdx, { min: barPixel, max: barPixel });
481
479
  }
480
+ };
481
+ for (const peakIdx of dirtyPixels) {
482
+ const barPixel = Math.floor(peakIdx / step) * step;
483
+ const chunkIdx = Math.floor(barPixel / MAX_CANVAS_WIDTH);
484
+ mark(chunkIdx, barPixel);
485
+ const endChunkIdx = Math.floor((barPixel + barWidth - 1) / MAX_CANVAS_WIDTH);
486
+ if (endChunkIdx !== chunkIdx) {
487
+ mark(endChunkIdx, barPixel);
488
+ }
482
489
  }
483
490
  return dirtyByChunk;
484
491
  }
@@ -580,7 +587,7 @@ var DawWaveformElement = class extends import_lit3.LitElement {
580
587
  this._drawSegments(canvas, chunkIdx, dpr, halfHeight, bits, waveColor);
581
588
  }
582
589
  } else {
583
- const dirtyByChunk = groupDirtyByChunk(this._dirtyPixels, step);
590
+ const dirtyByChunk = groupDirtyByChunk(this._dirtyPixels, step, this.barWidth);
584
591
  for (const canvas of canvases) {
585
592
  const chunkIdx = Number(canvas.dataset.index);
586
593
  this._drawnChunks.add(chunkIdx);
@@ -1201,16 +1208,31 @@ var DawPlayButtonElement = class extends DawTransportButton {
1201
1208
  connectedCallback() {
1202
1209
  super.connectedCallback();
1203
1210
  requestAnimationFrame(() => {
1204
- const target = this.target;
1205
- if (!target) return;
1206
- this._targetRef = target;
1207
- target.addEventListener("daw-recording-start", this._onRecStart);
1208
- target.addEventListener("daw-recording-complete", this._onRecEnd);
1209
- target.addEventListener("daw-recording-error", this._onRecEnd);
1211
+ if (!this.isConnected) return;
1212
+ this._ensureTargetListeners();
1210
1213
  });
1211
1214
  }
1212
1215
  disconnectedCallback() {
1213
1216
  super.disconnectedCallback();
1217
+ this._cleanupListeners();
1218
+ }
1219
+ updated() {
1220
+ this._ensureTargetListeners();
1221
+ }
1222
+ _ensureTargetListeners() {
1223
+ const target = this.target;
1224
+ if (target === this._targetRef) return;
1225
+ if (this._targetRef) {
1226
+ this._isRecording = false;
1227
+ }
1228
+ this._cleanupListeners();
1229
+ if (!target) return;
1230
+ this._targetRef = target;
1231
+ target.addEventListener("daw-recording-start", this._onRecStart);
1232
+ target.addEventListener("daw-recording-complete", this._onRecEnd);
1233
+ target.addEventListener("daw-recording-error", this._onRecEnd);
1234
+ }
1235
+ _cleanupListeners() {
1214
1236
  if (this._targetRef) {
1215
1237
  this._targetRef.removeEventListener("daw-recording-start", this._onRecStart);
1216
1238
  this._targetRef.removeEventListener("daw-recording-complete", this._onRecEnd);
@@ -1269,18 +1291,34 @@ var DawPauseButtonElement = class extends DawTransportButton {
1269
1291
  connectedCallback() {
1270
1292
  super.connectedCallback();
1271
1293
  requestAnimationFrame(() => {
1272
- const target = this.target;
1273
- if (!target) return;
1274
- this._targetRef = target;
1275
- target.addEventListener("daw-recording-start", this._onRecStart);
1276
- target.addEventListener("daw-recording-complete", this._onRecEnd);
1277
- target.addEventListener("daw-recording-error", this._onRecEnd);
1278
- target.addEventListener("daw-recording-pause", this._onRecPause);
1279
- target.addEventListener("daw-recording-resume", this._onRecResume);
1294
+ if (!this.isConnected) return;
1295
+ this._ensureTargetListeners();
1280
1296
  });
1281
1297
  }
1282
1298
  disconnectedCallback() {
1283
1299
  super.disconnectedCallback();
1300
+ this._cleanupListeners();
1301
+ }
1302
+ updated() {
1303
+ this._ensureTargetListeners();
1304
+ }
1305
+ _ensureTargetListeners() {
1306
+ const target = this.target;
1307
+ if (target === this._targetRef) return;
1308
+ if (this._targetRef) {
1309
+ this._isRecording = false;
1310
+ this._isPaused = false;
1311
+ }
1312
+ this._cleanupListeners();
1313
+ if (!target) return;
1314
+ this._targetRef = target;
1315
+ target.addEventListener("daw-recording-start", this._onRecStart);
1316
+ target.addEventListener("daw-recording-complete", this._onRecEnd);
1317
+ target.addEventListener("daw-recording-error", this._onRecEnd);
1318
+ target.addEventListener("daw-recording-pause", this._onRecPause);
1319
+ target.addEventListener("daw-recording-resume", this._onRecResume);
1320
+ }
1321
+ _cleanupListeners() {
1284
1322
  if (this._targetRef) {
1285
1323
  this._targetRef.removeEventListener("daw-recording-start", this._onRecStart);
1286
1324
  this._targetRef.removeEventListener("daw-recording-complete", this._onRecEnd);
@@ -1553,6 +1591,12 @@ function createPeaksWorker() {
1553
1591
  )
1554
1592
  );
1555
1593
  },
1594
+ // Reports NOT terminated: CSP blocking is permanent for the page, so
1595
+ // recreating on every call would just re-attempt (and re-warn about)
1596
+ // Worker construction each time.
1597
+ isTerminated() {
1598
+ return false;
1599
+ },
1556
1600
  terminate() {
1557
1601
  }
1558
1602
  };
@@ -1590,6 +1634,9 @@ function createPeaksWorker() {
1590
1634
  pending.clear();
1591
1635
  };
1592
1636
  return {
1637
+ isTerminated() {
1638
+ return terminated;
1639
+ },
1593
1640
  generate(params) {
1594
1641
  if (terminated) return Promise.reject(new Error("Worker terminated"));
1595
1642
  const messageId = String(++idCounter2);
@@ -1805,6 +1852,12 @@ var PeakPipeline = class {
1805
1852
  scale: cached.scale
1806
1853
  };
1807
1854
  }
1855
+ /** Scale of the cached WaveformData for this buffer — 0 when not cached.
1856
+ * Worker generation caches at baseScale; injected .dat data at its own
1857
+ * scale. This is the finest zoom the buffer's peaks can render at. */
1858
+ getCachedScale(audioBuffer) {
1859
+ return this._cache.get(audioBuffer)?.scale ?? 0;
1860
+ }
1808
1861
  /**
1809
1862
  * Return the coarsest (largest) scale among cached WaveformData entries
1810
1863
  * that correspond to the given clip buffers. Returns 0 if none are cached.
@@ -1826,7 +1879,7 @@ var PeakPipeline = class {
1826
1879
  if (cached) return cached;
1827
1880
  const inflight = this._inflight.get(audioBuffer);
1828
1881
  if (inflight) return inflight;
1829
- if (!this._worker) {
1882
+ if (!this._worker || this._worker.isTerminated()) {
1830
1883
  this._worker = createPeaksWorker();
1831
1884
  }
1832
1885
  const channels = [];
@@ -2808,6 +2861,15 @@ var import_core3 = require("@waveform-playlist/core");
2808
2861
  var RecordingController = class {
2809
2862
  constructor(host) {
2810
2863
  this._sessions = /* @__PURE__ */ new Map();
2864
+ /** Track IDs with a startRecording in flight (session not yet in _sessions).
2865
+ * The session is only set after several awaits — without this, two rapid
2866
+ * start calls both pass the _sessions guard and build two capture
2867
+ * pipelines feeding one session (garbled audio + a leaked worklet). */
2868
+ this._starting = /* @__PURE__ */ new Map();
2869
+ /** True between hostDisconnected and hostConnected. An in-flight
2870
+ * startRecording consults this after its awaits so a teardown mid-setup
2871
+ * doesn't leak a live capture session on a detached editor. */
2872
+ this._hostDisconnected = false;
2811
2873
  this._workletLoadedCtx = null;
2812
2874
  /** Tracks worklet pause state explicitly so external consumers (editor,
2813
2875
  * pause button, spacebar) can share one source of truth. */
@@ -2816,15 +2878,17 @@ var RecordingController = class {
2816
2878
  host.addController(this);
2817
2879
  }
2818
2880
  hostConnected() {
2881
+ this._hostDisconnected = false;
2819
2882
  }
2820
2883
  hostDisconnected() {
2884
+ this._hostDisconnected = true;
2821
2885
  for (const trackId of [...this._sessions.keys()]) {
2822
- this._cleanupSession(trackId);
2886
+ this._cleanupSession(trackId, true);
2823
2887
  }
2824
2888
  this._workletLoadedCtx = null;
2825
2889
  }
2826
2890
  get isRecording() {
2827
- return this._sessions.size > 0;
2891
+ return this._sessions.size > 0 || this._starting.size > 0;
2828
2892
  }
2829
2893
  get isPaused() {
2830
2894
  return this._isPaused && this._sessions.size > 0;
@@ -2838,14 +2902,25 @@ var RecordingController = class {
2838
2902
  console.warn("[dawcore] RecordingController: No track selected for recording");
2839
2903
  return;
2840
2904
  }
2841
- if (this._sessions.has(trackId)) {
2905
+ if (this._sessions.has(trackId) || this._starting.has(trackId)) {
2842
2906
  console.warn('[dawcore] RecordingController: Already recording on track "' + trackId + '"');
2843
2907
  return;
2844
2908
  }
2909
+ let resolveStartSettled;
2910
+ const startEntry = {
2911
+ stopRequested: false,
2912
+ done: new Promise((resolve) => {
2913
+ resolveStartSettled = resolve;
2914
+ })
2915
+ };
2916
+ this._starting.set(trackId, startEntry);
2845
2917
  const bits = options.bits ?? 16;
2846
2918
  try {
2847
2919
  const rawCtx = this._host.audioContext;
2848
2920
  this._host.resolveAudioContextSampleRate(rawCtx.sampleRate);
2921
+ if (rawCtx.state === "suspended") {
2922
+ await rawCtx.resume();
2923
+ }
2849
2924
  if (!this._workletLoadedCtx || this._workletLoadedCtx !== rawCtx) {
2850
2925
  let addRecordingWorkletModule;
2851
2926
  try {
@@ -2859,6 +2934,15 @@ var RecordingController = class {
2859
2934
  await addRecordingWorkletModule(addModule);
2860
2935
  this._workletLoadedCtx = rawCtx;
2861
2936
  }
2937
+ if (startEntry.stopRequested || this._hostDisconnected) {
2938
+ this._dispatchRecordingError(
2939
+ trackId,
2940
+ new Error(
2941
+ this._hostDisconnected ? "Recording start cancelled: editor was disconnected during setup" : "Recording start cancelled: stop requested before setup completed"
2942
+ )
2943
+ );
2944
+ return;
2945
+ }
2862
2946
  const detectedChannelCount = stream.getAudioTracks()[0]?.getSettings()?.channelCount;
2863
2947
  if (detectedChannelCount === void 0 && options.channelCount !== void 0) {
2864
2948
  console.warn(
@@ -2866,7 +2950,7 @@ var RecordingController = class {
2866
2950
  );
2867
2951
  }
2868
2952
  const channelCount = detectedChannelCount ?? options.channelCount ?? 1;
2869
- const startSample = options.startSample ?? Math.floor(this._host._currentTime * this._host.effectiveSampleRate);
2953
+ const startSample = options.startSample ?? Math.floor(this._host.currentTime * this._host.effectiveSampleRate);
2870
2954
  const latencySamples = (0, import_core3.resolveRecordingOffsetSamples)({
2871
2955
  overrideSeconds: options.latencyOffset,
2872
2956
  outputLatency: rawCtx.outputLatency ?? 0,
@@ -2900,13 +2984,17 @@ var RecordingController = class {
2900
2984
  ),
2901
2985
  startSample,
2902
2986
  channelCount,
2987
+ captureSampleRate: rawCtx.sampleRate,
2903
2988
  bits,
2904
2989
  isFirstMessage: true,
2905
2990
  latencySamples,
2991
+ clipName: options.clipName,
2992
+ armedPrevMuted: null,
2906
2993
  wasOverdub: options.overdub ?? false,
2907
2994
  _onTrackEnded: onTrackEnded,
2908
2995
  _audioTrack: audioTrack,
2909
2996
  stopAckResolve: null,
2997
+ stopPromise: null,
2910
2998
  stopping: false
2911
2999
  };
2912
3000
  this._sessions.set(trackId, session);
@@ -2918,6 +3006,11 @@ var RecordingController = class {
2918
3006
  if (audioTrack && onTrackEnded) {
2919
3007
  audioTrack.addEventListener("ended", onTrackEnded);
2920
3008
  }
3009
+ const engine = this._host._engine;
3010
+ if (engine) {
3011
+ session.armedPrevMuted = engine.getState().tracks.find((t) => t.id === trackId)?.muted ?? false;
3012
+ engine.setTrackMute(trackId, true);
3013
+ }
2921
3014
  this._host.dispatchEvent(
2922
3015
  new CustomEvent("daw-recording-start", {
2923
3016
  bubbles: true,
@@ -2927,18 +3020,15 @@ var RecordingController = class {
2927
3020
  );
2928
3021
  this._host.requestUpdate();
2929
3022
  if (options.overdub && typeof this._host.play === "function") {
2930
- await this._host.play(this._host._currentTime);
3023
+ await this._host.play(this._host.currentTime);
2931
3024
  }
2932
3025
  } catch (err) {
2933
3026
  this._cleanupSession(trackId);
2934
3027
  console.warn("[dawcore] RecordingController: Failed to start recording: " + String(err));
2935
- this._host.dispatchEvent(
2936
- new CustomEvent("daw-recording-error", {
2937
- bubbles: true,
2938
- composed: true,
2939
- detail: { trackId, error: err }
2940
- })
2941
- );
3028
+ this._dispatchRecordingError(trackId, err);
3029
+ } finally {
3030
+ this._starting.delete(trackId);
3031
+ resolveStartSettled();
2942
3032
  }
2943
3033
  }
2944
3034
  pauseRecording(trackId) {
@@ -2972,18 +3062,47 @@ var RecordingController = class {
2972
3062
  );
2973
3063
  }
2974
3064
  async stopRecording(trackId) {
2975
- const id = trackId ?? [...this._sessions.keys()][0];
3065
+ const id = trackId ?? [...this._sessions.keys()][0] ?? [...this._starting.keys()][0];
2976
3066
  if (!id) return;
2977
3067
  const session = this._sessions.get(id);
2978
- if (!session) return;
3068
+ if (!session) {
3069
+ const starting = this._starting.get(id);
3070
+ if (starting) {
3071
+ starting.stopRequested = true;
3072
+ return starting.done;
3073
+ }
3074
+ return;
3075
+ }
3076
+ if (session.stopping) {
3077
+ return session.stopPromise ?? void 0;
3078
+ }
3079
+ session.stopping = true;
3080
+ const stopPromise = this._finishStopRecording(id, session);
3081
+ session.stopPromise = stopPromise;
3082
+ return stopPromise;
3083
+ }
3084
+ async _finishStopRecording(id, session) {
3085
+ try {
3086
+ await this._finalizeRecording(id, session);
3087
+ } catch (err) {
3088
+ const sessionWasActive = this._sessions.has(id);
3089
+ console.warn("[dawcore] RecordingController: Failed to finalize recording: " + String(err));
3090
+ this._cleanupSession(id);
3091
+ this._host.requestUpdate();
3092
+ if (sessionWasActive) {
3093
+ this._dispatchRecordingError(id, err);
3094
+ }
3095
+ }
3096
+ }
3097
+ async _finalizeRecording(id, session) {
2979
3098
  const wasPaused = this._isPaused;
2980
3099
  this._isPaused = false;
2981
- session.stopping = true;
2982
3100
  if (session.wasOverdub && typeof this._host.stop === "function") {
2983
3101
  this._host.stop();
2984
3102
  }
2985
3103
  if (wasPaused) {
2986
3104
  session.workletNode.port.postMessage({ command: "stop" });
3105
+ await this._drainWorkletQueue(session);
2987
3106
  } else {
2988
3107
  const stopAck = new Promise((resolve) => {
2989
3108
  session.stopAckResolve = resolve;
@@ -2996,32 +3115,13 @@ var RecordingController = class {
2996
3115
  await Promise.race([stopAck, timeout]);
2997
3116
  clearTimeout(timeoutId);
2998
3117
  session.stopAckResolve = null;
2999
- let lastSamples = -1;
3000
- let stable = 0;
3001
- for (let i = 0; i < 50; i++) {
3002
- if (session.totalSamples === lastSamples) {
3003
- if (++stable >= 3) break;
3004
- } else {
3005
- stable = 0;
3006
- lastSamples = session.totalSamples;
3007
- }
3008
- await new Promise((r) => setTimeout(r, 5));
3009
- }
3118
+ await this._drainWorkletQueue(session);
3010
3119
  }
3011
3120
  session.source.disconnect();
3012
3121
  session.workletNode.disconnect();
3013
3122
  this._removeTrackEndedListener(session);
3014
3123
  if (session.totalSamples === 0) {
3015
- console.warn("[dawcore] RecordingController: No audio data captured");
3016
- this._sessions.delete(id);
3017
- this._host.requestUpdate();
3018
- this._host.dispatchEvent(
3019
- new CustomEvent("daw-recording-error", {
3020
- bubbles: true,
3021
- composed: true,
3022
- detail: { trackId: id, error: new Error("No audio data captured") }
3023
- })
3024
- );
3124
+ this._abandonFinalize(id, session, "No audio data captured");
3025
3125
  return;
3026
3126
  }
3027
3127
  const stopCtx = this._host.audioContext;
@@ -3029,21 +3129,17 @@ var RecordingController = class {
3029
3129
  const audioBuffer = (0, import_core3.createAudioBuffer)(
3030
3130
  stopCtx,
3031
3131
  channelData,
3032
- this._host.effectiveSampleRate,
3132
+ session.captureSampleRate,
3033
3133
  session.channelCount
3034
3134
  );
3035
3135
  const latencyOffsetSamples = session.latencySamples;
3036
3136
  const effectiveDuration = Math.max(0, audioBuffer.length - latencyOffsetSamples);
3037
3137
  if (effectiveDuration === 0) {
3038
- console.warn("[dawcore] RecordingController: Recording too short for latency compensation");
3039
- this._sessions.delete(id);
3040
- this._host.requestUpdate();
3041
- this._host.dispatchEvent(
3042
- new CustomEvent("daw-recording-error", {
3043
- bubbles: true,
3044
- composed: true,
3045
- detail: { trackId: id, error: new Error("Recording too short to save") }
3046
- })
3138
+ this._abandonFinalize(
3139
+ id,
3140
+ session,
3141
+ "Recording too short for latency compensation",
3142
+ "Recording too short to save"
3047
3143
  );
3048
3144
  return;
3049
3145
  }
@@ -3060,6 +3156,7 @@ var RecordingController = class {
3060
3156
  }
3061
3157
  });
3062
3158
  const notPrevented = this._host.dispatchEvent(event);
3159
+ this._restoreArmedTrackMute(session);
3063
3160
  this._sessions.delete(id);
3064
3161
  this._host.requestUpdate();
3065
3162
  if (notPrevented) {
@@ -3068,10 +3165,29 @@ var RecordingController = class {
3068
3165
  audioBuffer,
3069
3166
  session.startSample,
3070
3167
  effectiveDuration,
3071
- latencyOffsetSamples
3168
+ latencyOffsetSamples,
3169
+ session.clipName
3072
3170
  );
3073
3171
  }
3074
3172
  }
3173
+ /** Drain the event-loop queue of pending worklet flush messages. During
3174
+ * recording the worklet posts a flush every ~16ms; if main was slower,
3175
+ * messages back up. Yield repeatedly until session.totalSamples stabilizes
3176
+ * (no new messages processed) for several consecutive ticks — at that
3177
+ * point the queue is empty and chunks are complete. */
3178
+ async _drainWorkletQueue(session) {
3179
+ let lastSamples = -1;
3180
+ let stable = 0;
3181
+ for (let i = 0; i < 50; i++) {
3182
+ if (session.totalSamples === lastSamples) {
3183
+ if (++stable >= 3) break;
3184
+ } else {
3185
+ stable = 0;
3186
+ lastSamples = session.totalSamples;
3187
+ }
3188
+ await new Promise((r) => setTimeout(r, 5));
3189
+ }
3190
+ }
3075
3191
  // Session fields are mutated in place on the hot path (~60fps worklet messages).
3076
3192
  // This is intentional — creating new session objects + Map entries per message
3077
3193
  // would cause significant GC pressure. Mutations are confined to the controller's
@@ -3107,7 +3223,10 @@ var RecordingController = class {
3107
3223
  session.peaks[ch] = (0, import_core3.appendPeaks)(
3108
3224
  session.peaks[ch],
3109
3225
  channels[ch],
3110
- this._host.samplesPerPixel,
3226
+ // Render-space scale — in beats mode this differs from
3227
+ // samplesPerPixel, and the preview container is laid out in
3228
+ // render space (see RecordingHost.renderSamplesPerPixel).
3229
+ this._host.renderSamplesPerPixel,
3111
3230
  samplesProcessedBefore,
3112
3231
  session.bits
3113
3232
  );
@@ -3126,22 +3245,23 @@ var RecordingController = class {
3126
3245
  }
3127
3246
  }
3128
3247
  session.isFirstMessage = false;
3129
- const newPixelWidth = Math.floor(session.totalSamples / this._host.samplesPerPixel);
3248
+ const newPixelWidth = Math.floor(session.totalSamples / this._host.renderSamplesPerPixel);
3130
3249
  const oldPixelWidth = Math.floor(
3131
- (session.totalSamples - channels[0].length) / this._host.samplesPerPixel
3250
+ (session.totalSamples - channels[0].length) / this._host.renderSamplesPerPixel
3132
3251
  );
3133
3252
  if (newPixelWidth > oldPixelWidth) {
3134
3253
  this._host.requestUpdate();
3135
3254
  }
3136
3255
  }
3137
- _createClipFromRecording(trackId, audioBuffer, startSample, durationSamples, offsetSamples = 0) {
3256
+ _createClipFromRecording(trackId, audioBuffer, startSample, durationSamples, offsetSamples = 0, clipName) {
3138
3257
  if (typeof this._host._addRecordedClip === "function") {
3139
3258
  this._host._addRecordedClip(
3140
3259
  trackId,
3141
3260
  audioBuffer,
3142
3261
  startSample,
3143
3262
  durationSamples,
3144
- offsetSamples
3263
+ offsetSamples,
3264
+ clipName
3145
3265
  );
3146
3266
  } else {
3147
3267
  console.warn(
@@ -3154,10 +3274,41 @@ var RecordingController = class {
3154
3274
  session._audioTrack.removeEventListener("ended", session._onTrackEnded);
3155
3275
  }
3156
3276
  }
3157
- _cleanupSession(trackId) {
3277
+ _dispatchRecordingError(trackId, error) {
3278
+ this._host.dispatchEvent(
3279
+ new CustomEvent("daw-recording-error", {
3280
+ bubbles: true,
3281
+ composed: true,
3282
+ detail: { trackId, error }
3283
+ })
3284
+ );
3285
+ }
3286
+ /** Shared teardown for finalize paths that end without a take (no data
3287
+ * captured / too short after latency compensation): restore the armed-track
3288
+ * mute, drop the session, and notify via daw-recording-error so record
3289
+ * buttons reset their state. */
3290
+ _abandonFinalize(id, session, warnMessage, errorMessage = warnMessage) {
3291
+ console.warn("[dawcore] RecordingController: " + warnMessage);
3292
+ this._restoreArmedTrackMute(session);
3293
+ this._sessions.delete(id);
3294
+ this._host.requestUpdate();
3295
+ this._dispatchRecordingError(id, new Error(errorMessage));
3296
+ }
3297
+ /** Restore the armed track's pre-session mute state (idempotent — safe to
3298
+ * call from both the finalize path and _cleanupSession). */
3299
+ _restoreArmedTrackMute(session) {
3300
+ if (session.armedPrevMuted === null) return;
3301
+ this._host._engine?.setTrackMute(session.trackId, session.armedPrevMuted);
3302
+ session.armedPrevMuted = null;
3303
+ }
3304
+ /** @param notifyError dispatch daw-recording-error after cleanup — used by
3305
+ * disposal paths that would otherwise discard the session silently. The
3306
+ * startRecording catch path passes false (it dispatches its own error). */
3307
+ _cleanupSession(trackId, notifyError = false) {
3158
3308
  const session = this._sessions.get(trackId);
3159
3309
  if (!session) return;
3160
3310
  try {
3311
+ this._restoreArmedTrackMute(session);
3161
3312
  this._removeTrackEndedListener(session);
3162
3313
  session.workletNode.port.postMessage({ command: "stop" });
3163
3314
  session.source.disconnect();
@@ -3168,6 +3319,15 @@ var RecordingController = class {
3168
3319
  );
3169
3320
  }
3170
3321
  this._sessions.delete(trackId);
3322
+ if (this._sessions.size === 0) {
3323
+ this._isPaused = false;
3324
+ }
3325
+ if (notifyError) {
3326
+ this._dispatchRecordingError(
3327
+ trackId,
3328
+ new Error("Recording cancelled: editor was disconnected mid-recording")
3329
+ );
3330
+ }
3171
3331
  }
3172
3332
  };
3173
3333
 
@@ -3307,6 +3467,14 @@ var PointerHandler = class {
3307
3467
  this._timeline = null;
3308
3468
  // Cached from onPointerDown to avoid forced layout reflows at 60fps during drag
3309
3469
  this._timelineRect = null;
3470
+ /** Pointer that started the current interaction — a pointercancel from any
3471
+ * OTHER pointer (palm rejection on touch) must not kill the active drag. */
3472
+ this._activePointerId = null;
3473
+ // Selection values at pointerdown — restored on cancel so an interrupted
3474
+ // drag doesn't destroy a previously committed selection (which the engine
3475
+ // still holds; zeroing only the host would desync the two).
3476
+ this._preDragSelectionStart = 0;
3477
+ this._preDragSelectionEnd = 0;
3310
3478
  this.onPointerDown = (e) => {
3311
3479
  const clipHandler = this._host._clipHandler;
3312
3480
  if (clipHandler) {
@@ -3321,12 +3489,12 @@ var PointerHandler = class {
3321
3489
  console.warn("[dawcore] setPointerCapture failed: " + String(err));
3322
3490
  }
3323
3491
  const onMove = (me) => clipHandler.onPointerMove(me);
3324
- const onUp = (ue) => {
3325
- clipHandler.onPointerUp(ue);
3492
+ const detach = (pe) => {
3326
3493
  this._timeline?.removeEventListener("pointermove", onMove);
3327
3494
  this._timeline?.removeEventListener("pointerup", onUp);
3495
+ this._timeline?.removeEventListener("pointercancel", onCancel);
3328
3496
  try {
3329
- this._timeline?.releasePointerCapture(ue.pointerId);
3497
+ this._timeline?.releasePointerCapture(pe.pointerId);
3330
3498
  } catch (err) {
3331
3499
  console.warn(
3332
3500
  "[dawcore] releasePointerCapture failed (may already be released): " + String(err)
@@ -3334,8 +3502,19 @@ var PointerHandler = class {
3334
3502
  }
3335
3503
  this._timeline = null;
3336
3504
  };
3505
+ const onUp = (ue) => {
3506
+ clipHandler.onPointerUp(ue);
3507
+ detach(ue);
3508
+ };
3509
+ const downPointerId = e.pointerId;
3510
+ const onCancel = (ce) => {
3511
+ if (ce.pointerId !== downPointerId) return;
3512
+ clipHandler.onPointerCancel(ce);
3513
+ detach(ce);
3514
+ };
3337
3515
  this._timeline.addEventListener("pointermove", onMove);
3338
3516
  this._timeline.addEventListener("pointerup", onUp);
3517
+ this._timeline.addEventListener("pointercancel", onCancel);
3339
3518
  }
3340
3519
  return;
3341
3520
  }
@@ -3350,6 +3529,9 @@ var PointerHandler = class {
3350
3529
  this._timelineRect = this._timeline.getBoundingClientRect();
3351
3530
  this._dragStartPx = this._pxFromPointer(e);
3352
3531
  this._isDragging = false;
3532
+ this._activePointerId = e.pointerId;
3533
+ this._preDragSelectionStart = this._host._selectionStartTime;
3534
+ this._preDragSelectionEnd = this._host._selectionEndTime;
3353
3535
  try {
3354
3536
  this._timeline.setPointerCapture(e.pointerId);
3355
3537
  } catch (err) {
@@ -3357,6 +3539,7 @@ var PointerHandler = class {
3357
3539
  }
3358
3540
  this._timeline.addEventListener("pointermove", this._onPointerMove);
3359
3541
  this._timeline.addEventListener("pointerup", this._onPointerUp);
3542
+ this._timeline.addEventListener("pointercancel", this._onPointerCancel);
3360
3543
  };
3361
3544
  this._onPointerMove = (e) => {
3362
3545
  if (!this._timeline) return;
@@ -3380,15 +3563,7 @@ var PointerHandler = class {
3380
3563
  };
3381
3564
  this._onPointerUp = (e) => {
3382
3565
  if (!this._timeline) return;
3383
- try {
3384
- this._timeline.releasePointerCapture(e.pointerId);
3385
- } catch (err) {
3386
- console.warn(
3387
- "[dawcore] releasePointerCapture failed (may already be released): " + String(err)
3388
- );
3389
- }
3390
- this._timeline.removeEventListener("pointermove", this._onPointerMove);
3391
- this._timeline.removeEventListener("pointerup", this._onPointerUp);
3566
+ this._detachTimeline(e);
3392
3567
  try {
3393
3568
  if (this._isDragging) {
3394
3569
  this._finalizeSelection();
@@ -3398,10 +3573,29 @@ var PointerHandler = class {
3398
3573
  } catch (err) {
3399
3574
  console.warn("[dawcore] Pointer interaction failed: " + String(err));
3400
3575
  } finally {
3401
- this._isDragging = false;
3402
- this._timeline = null;
3403
- this._timelineRect = null;
3576
+ this._resetInteractionState();
3577
+ }
3578
+ };
3579
+ /** pointercancel fires INSTEAD of pointerup on touch interruption / pen
3580
+ * leaving range / OS gestures — discard the interaction (no seek, no
3581
+ * selection finalize) and detach the drag listeners, or the still-attached
3582
+ * move handler keeps mutating the selection on hover with a stale rect. */
3583
+ this._onPointerCancel = (e) => {
3584
+ if (!this._timeline) return;
3585
+ if (e.pointerId !== this._activePointerId) return;
3586
+ this._detachTimeline(e);
3587
+ if (this._isDragging) {
3588
+ const h = this._host;
3589
+ h._selectionStartTime = this._preDragSelectionStart;
3590
+ h._selectionEndTime = this._preDragSelectionEnd;
3591
+ const sel = h.shadowRoot?.querySelector("daw-selection");
3592
+ if (sel) {
3593
+ sel.startPx = this._timeToPx(this._preDragSelectionStart);
3594
+ sel.endPx = this._timeToPx(this._preDragSelectionEnd);
3595
+ }
3596
+ h.requestUpdate();
3404
3597
  }
3598
+ this._resetInteractionState();
3405
3599
  };
3406
3600
  this._host = host;
3407
3601
  }
@@ -3429,6 +3623,28 @@ var PointerHandler = class {
3429
3623
  }
3430
3624
  return time * h.effectiveSampleRate / h.samplesPerPixel;
3431
3625
  }
3626
+ /** Detach the drag listeners and release capture — shared by the up and
3627
+ * cancel terminals so a new listener added to onPointerDown can't be
3628
+ * missed on one of them. */
3629
+ _detachTimeline(e) {
3630
+ if (!this._timeline) return;
3631
+ try {
3632
+ this._timeline.releasePointerCapture(e.pointerId);
3633
+ } catch (err) {
3634
+ console.warn(
3635
+ "[dawcore] releasePointerCapture failed (may already be released): " + String(err)
3636
+ );
3637
+ }
3638
+ this._timeline.removeEventListener("pointermove", this._onPointerMove);
3639
+ this._timeline.removeEventListener("pointerup", this._onPointerUp);
3640
+ this._timeline.removeEventListener("pointercancel", this._onPointerCancel);
3641
+ }
3642
+ _resetInteractionState() {
3643
+ this._isDragging = false;
3644
+ this._timeline = null;
3645
+ this._timelineRect = null;
3646
+ this._activePointerId = null;
3647
+ }
3432
3648
  _finalizeSelection() {
3433
3649
  const h = this._host;
3434
3650
  if (h._engine) {
@@ -3764,6 +3980,23 @@ var ClipPointerHandler = class {
3764
3980
  this._reset();
3765
3981
  }
3766
3982
  }
3983
+ /** Processes pointercancel — reverts the in-progress drag.
3984
+ *
3985
+ * pointercancel fires INSTEAD of pointerup on touch interruption, pen
3986
+ * leaving hover range, or OS gestures. Without this handler the drag stays
3987
+ * armed (hover keeps moving the clip), the engine transaction stays open
3988
+ * (every later edit becomes un-undoable until some drag commits), and the
3989
+ * per-frame skipAdapter moveClip mutations are never synced or rolled back
3990
+ * (waveform and audio permanently disagree). */
3991
+ onPointerCancel(_e) {
3992
+ if (this._mode === null) return;
3993
+ try {
3994
+ this._restoreTrimVisual();
3995
+ } finally {
3996
+ this._host.engine?.abortTransaction();
3997
+ this._reset();
3998
+ }
3999
+ }
3767
4000
  /** Re-extract peaks from cache and set on waveform elements during trim drag.
3768
4001
  * Returns true if peaks were successfully updated. */
3769
4002
  _updateWaveformPeaks(offsetSamples, durationSamples) {
@@ -3781,7 +4014,11 @@ var ClipPointerHandler = class {
3781
4014
  }
3782
4015
  return true;
3783
4016
  }
3784
- /** Restore clip container CSS to original values after trim visual preview. */
4017
+ /** Restore clip container CSS AND waveform peaks to original values after
4018
+ * a trim visual preview. Peaks matter: the drag wrote re-extracted peak
4019
+ * arrays imperatively onto the <daw-waveform> elements (bypassing Lit), and
4020
+ * a cancelled/zero-delta trim makes no engine mutation — so no statechange
4021
+ * re-render will ever repair them. */
3785
4022
  _restoreTrimVisual() {
3786
4023
  if (this._clipContainer) {
3787
4024
  this._clipContainer.style.left = this._originalLeft + "px";
@@ -3790,6 +4027,7 @@ var ClipPointerHandler = class {
3790
4027
  for (const wf of waveforms) {
3791
4028
  wf.style.left = "0px";
3792
4029
  }
4030
+ this._updateWaveformPeaks(this._originalOffsetSamples, this._originalDurationSamples);
3793
4031
  }
3794
4032
  }
3795
4033
  _reset() {
@@ -3875,8 +4113,18 @@ async function loadFiles(host, files) {
3875
4113
  const failed = [];
3876
4114
  for (const file of fileArray) {
3877
4115
  if (file.type && !file.type.startsWith("audio/")) {
3878
- failed.push({ file, error: new Error("Non-audio MIME type: " + file.type) });
4116
+ const error = new Error("Non-audio MIME type: " + file.type);
4117
+ failed.push({ file, error });
3879
4118
  console.warn("[dawcore] Skipping non-audio file: " + file.name + " (" + file.type + ")");
4119
+ if (host.isConnected) {
4120
+ host.dispatchEvent(
4121
+ new CustomEvent("daw-files-load-error", {
4122
+ bubbles: true,
4123
+ composed: true,
4124
+ detail: { file, error }
4125
+ })
4126
+ );
4127
+ }
3880
4128
  continue;
3881
4129
  }
3882
4130
  const blobUrl = URL.createObjectURL(file);
@@ -4073,7 +4321,7 @@ function stringifyReason(reason) {
4073
4321
 
4074
4322
  // src/interactions/recording-clip.ts
4075
4323
  var import_core8 = require("@waveform-playlist/core");
4076
- function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamples = 0) {
4324
+ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamples = 0, clipName) {
4077
4325
  let trimmedBuf = buf;
4078
4326
  if (offsetSamples > 0 && offsetSamples < buf.length) {
4079
4327
  const trimmed = new AudioBuffer({
@@ -4094,21 +4342,27 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
4094
4342
  offsetSamples: 0,
4095
4343
  // offset already applied by slicing
4096
4344
  gain: 1,
4097
- name: "Recording"
4345
+ name: clipName ?? "Recording"
4098
4346
  });
4099
4347
  host._clipBuffers = new Map(host._clipBuffers).set(clip.id, trimmedBuf);
4100
- host._peakPipeline.generatePeaks(trimmedBuf, host.samplesPerPixel, host.mono).then((pd) => {
4101
- host._peaksData = new Map(host._peaksData).set(clip.id, pd);
4348
+ host._clipOffsets.set(clip.id, { offsetSamples: 0, durationSamples: durSamples });
4349
+ host._peakPipeline.generatePeaks(trimmedBuf, host.renderSamplesPerPixel, host.mono).then((pd) => {
4102
4350
  const t = host._engineTracks.get(trackId);
4103
4351
  if (!t) {
4104
4352
  const next = new Map(host._clipBuffers);
4105
4353
  next.delete(clip.id);
4106
4354
  host._clipBuffers = next;
4355
+ host._clipOffsets.delete(clip.id);
4107
4356
  return;
4108
4357
  }
4358
+ host._peaksData = new Map(host._peaksData).set(clip.id, pd);
4359
+ host._raiseZoomFloor(host._peakPipeline.getCachedScale(trimmedBuf));
4109
4360
  host._engineTracks = new Map(host._engineTracks).set(trackId, {
4110
4361
  ...t,
4111
- clips: [...t.clips, clip]
4362
+ // Punch-in replace (#579): the recorded clip owns [startSample,
4363
+ // startSample + durSamples) — carve overlapped content out of the
4364
+ // existing clips before inserting (parity with the React provider).
4365
+ clips: [...(0, import_core8.carveClipRange)(t.clips, startSample, startSample + durSamples), clip]
4112
4366
  });
4113
4367
  const desc = host._tracks.get(trackId);
4114
4368
  if (desc) {
@@ -4121,7 +4375,7 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
4121
4375
  duration: durSamples / sr,
4122
4376
  offset: 0,
4123
4377
  gain: 1,
4124
- name: "Recording",
4378
+ name: clipName ?? "Recording",
4125
4379
  fadeIn: 0,
4126
4380
  fadeOut: 0,
4127
4381
  fadeType: "linear",
@@ -4146,6 +4400,7 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
4146
4400
  const next = new Map(host._clipBuffers);
4147
4401
  next.delete(clip.id);
4148
4402
  host._clipBuffers = next;
4403
+ host._clipOffsets.delete(clip.id);
4149
4404
  if (host.isConnected) {
4150
4405
  host.dispatchEvent(
4151
4406
  new CustomEvent("daw-error", {
@@ -4370,7 +4625,10 @@ var EffectsChainController = class {
4370
4625
  kind: "wam",
4371
4626
  ...sourceFields,
4372
4627
  bypassed: entry.placeholder.bypassed,
4373
- ...entry.placeholder.state !== void 0 ? { state: entry.placeholder.state } : {}
4628
+ ...entry.placeholder.state !== void 0 ? { state: entry.placeholder.state } : {},
4629
+ // Lets offline export skip this entry (live playback silently
4630
+ // skips it too); restore ignores the flag and retries.
4631
+ placeholder: true
4374
4632
  };
4375
4633
  }
4376
4634
  let state8;
@@ -4388,6 +4646,15 @@ var EffectsChainController = class {
4388
4646
  ...state8 !== void 0 ? { state: state8 } : {}
4389
4647
  };
4390
4648
  }
4649
+ if (entry.placeholder) {
4650
+ return {
4651
+ kind: "native",
4652
+ type: entry.type,
4653
+ params: { ...entry.params },
4654
+ bypassed: entry.placeholder.bypassed,
4655
+ placeholder: true
4656
+ };
4657
+ }
4391
4658
  return {
4392
4659
  kind: "native",
4393
4660
  type: entry.type,
@@ -4426,13 +4693,17 @@ var EffectsChainController = class {
4426
4693
  entry.instance.dispose?.();
4427
4694
  this._rebuild();
4428
4695
  }
4696
+ /** Returns the index the entry actually landed at (the requested index is
4697
+ * clamped to the chain bounds), or -1 for an unknown effectId — event
4698
+ * dispatchers must report the actual index, not the raw request. */
4429
4699
  move(effectId, newIndex) {
4430
4700
  const entry = this._find("move", effectId);
4431
- if (!entry) return;
4701
+ if (!entry) return -1;
4432
4702
  const without = this._entries.filter((e) => e.id !== effectId);
4433
4703
  const at = Math.max(0, Math.min(newIndex, without.length));
4434
4704
  this._entries = [...without.slice(0, at), entry, ...without.slice(at)];
4435
4705
  this._rebuild();
4706
+ return at;
4436
4707
  }
4437
4708
  setParams(effectId, params) {
4438
4709
  const entry = this._find("setParams", effectId);
@@ -4656,10 +4927,11 @@ registerBuiltIns();
4656
4927
 
4657
4928
  // src/effects/effects-manager.ts
4658
4929
  var PREFIX2 = "[waveform-playlist] ";
4659
- function makeGuiRecord(element, destroyImpl) {
4930
+ function makeGuiRecord(element, destroyImpl, isFallback = false) {
4660
4931
  let destroyed = false;
4661
4932
  return {
4662
4933
  element,
4934
+ isFallback,
4663
4935
  destroy: () => {
4664
4936
  if (destroyed) return;
4665
4937
  destroyed = true;
@@ -4838,7 +5110,7 @@ var EffectsManager = class {
4838
5110
  );
4839
5111
  }
4840
5112
  const cached = this._guis.get(effectId);
4841
- if (cached) {
5113
+ if (cached && !cached.isFallback) {
4842
5114
  container.appendChild(cached.element);
4843
5115
  return cached.element;
4844
5116
  }
@@ -4849,7 +5121,22 @@ var EffectsManager = class {
4849
5121
  });
4850
5122
  this._guiPending.set(effectId, pending);
4851
5123
  }
4852
- const record = await pending;
5124
+ let record;
5125
+ try {
5126
+ record = await pending;
5127
+ } catch (err) {
5128
+ if (cached) {
5129
+ console.warn(
5130
+ PREFIX2 + 'openEffectGui: rebuilding the parameter panel for "' + effectId + '" failed \u2014 serving the cached panel (values may be stale): ' + String(err)
5131
+ );
5132
+ container.appendChild(cached.element);
5133
+ return cached.element;
5134
+ }
5135
+ throw err;
5136
+ }
5137
+ if (cached && cached !== record) {
5138
+ cached.element.remove();
5139
+ }
4853
5140
  if (chain.disposed || !chain.getEntry(effectId)) {
4854
5141
  this._guis.delete(effectId);
4855
5142
  record.element.remove();
@@ -4884,7 +5171,7 @@ var EffectsManager = class {
4884
5171
  }
4885
5172
  const element = await this._createFallbackPanel(chain, target, entry, effectId);
4886
5173
  return makeGuiRecord(element, () => {
4887
- });
5174
+ }, true);
4888
5175
  }
4889
5176
  /** The generic parameter panel — one code path for "no custom GUI":
4890
5177
  * native entries render from the registry's params metadata, WAM entries
@@ -5127,9 +5414,23 @@ var EffectsManager = class {
5127
5414
  for (const entry of entries) {
5128
5415
  if (superseded()) return;
5129
5416
  if (entry.kind === "native") {
5130
- const id = this._addToChain(chain, target, entry.type, entry.params);
5131
- if (entry.bypassed) {
5132
- this._runOp(chain, target, "setBypassed", id, true);
5417
+ try {
5418
+ const id = this._addToChain(chain, target, entry.type, entry.params);
5419
+ if (entry.bypassed) {
5420
+ this._runOp(chain, target, "setBypassed", id, true);
5421
+ }
5422
+ } catch (err) {
5423
+ if (superseded() || chain.disposed) return;
5424
+ const message = err instanceof Error ? err.message : String(err);
5425
+ console.warn(
5426
+ PREFIX2 + 'setEffectsState: native effect "' + entry.type + '" failed to restore: ' + message
5427
+ );
5428
+ const effectId = this._addNativePlaceholder(chain, entry, message);
5429
+ this._dispatch(target, "daw-effect-error", {
5430
+ effectId,
5431
+ type: entry.type,
5432
+ message
5433
+ });
5133
5434
  }
5134
5435
  continue;
5135
5436
  }
@@ -5146,7 +5447,7 @@ var EffectsManager = class {
5146
5447
  this._runOp(chain, target, "setBypassed", id, true);
5147
5448
  }
5148
5449
  } catch (err) {
5149
- if (superseded()) return;
5450
+ if (superseded() || chain.disposed) return;
5150
5451
  const message = err instanceof Error ? err.message : String(err);
5151
5452
  const sourceLabel = entry.url ?? entry.faustName ?? "Faust effect";
5152
5453
  console.warn(
@@ -5162,6 +5463,25 @@ var EffectsManager = class {
5162
5463
  }
5163
5464
  }
5164
5465
  }
5466
+ /** A silent passthrough occupying a failed NATIVE entry's chain position.
5467
+ * Carries the saved params/bypassed so the snapshot round-trips (serialize
5468
+ * re-emits them with `placeholder: true`). */
5469
+ _addNativePlaceholder(chain, entry, message) {
5470
+ const { audioContext } = this._requireWiring();
5471
+ const node = audioContext.createGain();
5472
+ const effectId = chain.add({
5473
+ kind: "native",
5474
+ type: entry.type,
5475
+ label: entry.type,
5476
+ error: message,
5477
+ placeholder: { bypassed: entry.bypassed },
5478
+ instance: { input: node, output: node, applyParams: () => {
5479
+ } },
5480
+ params: { ...entry.params }
5481
+ });
5482
+ chain.setBypassed(effectId, true);
5483
+ return effectId;
5484
+ }
5165
5485
  /** A silent passthrough occupying the failed plugin's chain position. */
5166
5486
  _addWamPlaceholder(chain, entry, message) {
5167
5487
  const { audioContext } = this._requireWiring();
@@ -5208,10 +5528,11 @@ var EffectsManager = class {
5208
5528
  chain.setBypassed(effectId, arg);
5209
5529
  this._dispatch(target, "daw-effect-bypass", { effectId, bypassed: arg });
5210
5530
  break;
5211
- case "move":
5212
- chain.move(effectId, arg);
5213
- this._dispatch(target, "daw-effect-reorder", { effectId, fromIndex, toIndex: arg });
5531
+ case "move": {
5532
+ const toIndex = chain.move(effectId, arg);
5533
+ this._dispatch(target, "daw-effect-reorder", { effectId, fromIndex, toIndex });
5214
5534
  break;
5535
+ }
5215
5536
  }
5216
5537
  }
5217
5538
  _dispatch(target, name, detail) {
@@ -5252,6 +5573,9 @@ function validateSerializedEntries(entries) {
5252
5573
  if (typeof e.bypassed !== "boolean") {
5253
5574
  throw new Error(PREFIX2 + "setEffectsState: entry requires a boolean bypassed flag" + at);
5254
5575
  }
5576
+ if (e.placeholder !== void 0 && e.placeholder !== true) {
5577
+ throw new Error(PREFIX2 + "setEffectsState: placeholder must be true when present" + at);
5578
+ }
5255
5579
  });
5256
5580
  }
5257
5581
  function toWamParameterMap(params) {
@@ -5284,6 +5608,9 @@ async function exportAudioImpl(host, options = {}) {
5284
5608
  try {
5285
5609
  const masterChain = await buildOfflineChain(ctx, await host.getMasterEffectsState());
5286
5610
  cleanups.push(masterChain.dispose);
5611
+ const masterVolume = ctx.createGain();
5612
+ masterVolume.gain.value = host.masterVolume ?? 1;
5613
+ masterVolume.connect(masterChain.input);
5287
5614
  masterChain.output.connect(ctx.destination);
5288
5615
  const anySoloed = host.tracks.some((t) => t.soloed);
5289
5616
  for (const track of host.tracks) {
@@ -5298,7 +5625,7 @@ async function exportAudioImpl(host, options = {}) {
5298
5625
  panner.pan.value = track.pan;
5299
5626
  volume.connect(panner);
5300
5627
  panner.connect(chain.input);
5301
- chain.output.connect(masterChain.input);
5628
+ chain.output.connect(masterVolume);
5302
5629
  for (const clip of track.clips) {
5303
5630
  scheduleClip(ctx, clip, startTime, duration, volume);
5304
5631
  }
@@ -5369,6 +5696,12 @@ async function buildOfflineChain(ctx, entries) {
5369
5696
  return { input, output, dispose };
5370
5697
  async function wireEntries() {
5371
5698
  for (const entry of entries) {
5699
+ if (entry.placeholder) {
5700
+ console.warn(
5701
+ PREFIX3 + 'exportAudio: skipping failed-plugin placeholder "' + (entry.kind === "native" ? entry.type : entry.url ?? "Faust effect") + '"'
5702
+ );
5703
+ continue;
5704
+ }
5372
5705
  if (entry.kind === "native") {
5373
5706
  const created = createEffectInstance(entry.type, ctx, entry.params);
5374
5707
  if (entry.bypassed) {
@@ -5577,7 +5910,9 @@ var AnimationController = class {
5577
5910
  this._callback = callback;
5578
5911
  const loop = () => {
5579
5912
  this._callback?.();
5580
- this._rafId = requestAnimationFrame(loop);
5913
+ if (this._callback !== null) {
5914
+ this._rafId = requestAnimationFrame(loop);
5915
+ }
5581
5916
  };
5582
5917
  this._rafId = requestAnimationFrame(loop);
5583
5918
  }
@@ -5638,6 +5973,13 @@ var PlaybackAnimationController = class {
5638
5973
  var import_meta = {};
5639
5974
  var RULER_HEIGHT = 30;
5640
5975
  var NO_ADAPTER_ERROR = "No PlayoutAdapter set on <daw-editor>. Set editor.adapter before use.\n\n // Option 1: Native Web Audio (no Tone.js)\n npm install @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 npm install @waveform-playlist/playout\n import { createToneAdapter } from '@waveform-playlist/playout';\n editor.adapter = createToneAdapter();";
5976
+ var TrackLoadCancelledError = class extends Error {
5977
+ constructor(message, reason) {
5978
+ super(message);
5979
+ this.reason = reason;
5980
+ this.name = "TrackLoadCancelledError";
5981
+ }
5982
+ };
5641
5983
  var DawEditorElement = class extends import_lit15.LitElement {
5642
5984
  constructor() {
5643
5985
  super(...arguments);
@@ -5654,6 +5996,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
5654
5996
  this.clipHeaderHeight = 20;
5655
5997
  this.interactiveClips = false;
5656
5998
  this.indefinitePlayback = false;
5999
+ this.fillViewport = false;
5657
6000
  this._spectrogramConfig = null;
5658
6001
  this._spectrogramColorMap = null;
5659
6002
  this.scaleMode = "temporal";
@@ -5676,6 +6019,9 @@ var DawEditorElement = class extends import_lit15.LitElement {
5676
6019
  this._selectionEndTime = 0;
5677
6020
  this._currentTime = 0;
5678
6021
  this._externalAdapter = null;
6022
+ /** True after a disconnect disposed the consumer's adapter via the engine
6023
+ * — rebuild attempts fail loudly until a fresh adapter is set. */
6024
+ this._adapterConsumedByDispose = false;
5679
6025
  // --- Effects (master chain; per-track chains delegated from <daw-track>) ---
5680
6026
  this._effectsManager = null;
5681
6027
  this._engine = null;
@@ -5690,6 +6036,11 @@ var DawEditorElement = class extends import_lit15.LitElement {
5690
6036
  /** Coarsest scale from pre-computed peaks — zoom cannot go finer than this. 0 = no limit. */
5691
6037
  this._minSamplesPerPixel = 0;
5692
6038
  this._trackElements = /* @__PURE__ */ new Map();
6039
+ /** Track ids with a _loadTrack in flight. Distinct from `_engineTracks`
6040
+ * membership: the peaks-first path inserts a render-only PREVIEW track
6041
+ * into _engineTracks mid-load, so `has()` alone cannot answer "is this
6042
+ * track still loading?". */
6043
+ this._loadingTracks = /* @__PURE__ */ new Set();
5693
6044
  this._childObserver = null;
5694
6045
  this._audioResume = new AudioResumeController(this);
5695
6046
  this._recordingController = new RecordingController(this);
@@ -5834,11 +6185,17 @@ var DawEditorElement = class extends import_lit15.LitElement {
5834
6185
  const trackEl = clipEl.closest("daw-track");
5835
6186
  if (!trackEl) return;
5836
6187
  const trackId = trackEl.trackId;
5837
- if (!this._engineTracks.has(trackId)) {
6188
+ if (!this._engineTracks.has(trackId) || this._loadingTracks.has(trackId)) {
5838
6189
  const desc = this._tracks.get(trackId);
5839
6190
  if (desc && !desc.clips.some((c) => isDomClip(c) && c.clipId === clipEl.clipId)) {
5840
- console.warn(
5841
- '[dawcore] daw-clip-connected fired while parent track "' + trackId + '" is still loading \u2014 late-appended clip may be missed. Wait for daw-track-ready before appending more <daw-clip> children, or use editor.addClip(trackId, config) after the track finishes loading.'
6191
+ 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.';
6192
+ console.warn("[dawcore] " + message);
6193
+ this.dispatchEvent(
6194
+ new CustomEvent("daw-clip-error", {
6195
+ bubbles: true,
6196
+ composed: true,
6197
+ detail: { trackId, clipId: clipEl.clipId, error: new Error(message) }
6198
+ })
5842
6199
  );
5843
6200
  }
5844
6201
  return;
@@ -5930,12 +6287,38 @@ var DawEditorElement = class extends import_lit15.LitElement {
5930
6287
  const clamped = this._minSamplesPerPixel > 0 && value < this._minSamplesPerPixel ? this._minSamplesPerPixel : value;
5931
6288
  if (clamped !== value) {
5932
6289
  console.warn(
5933
- "[dawcore] Zoom " + value + " spp rejected \u2014 pre-computed peaks limit is " + this._minSamplesPerPixel + " spp"
6290
+ "[dawcore] Zoom " + value + " spp clamped to the peak floor (" + this._minSamplesPerPixel + " spp) \u2014 peaks for the loaded audio (worker-generated or pre-computed) can only render at or above that scale"
5934
6291
  );
5935
6292
  }
5936
6293
  this._samplesPerPixel = clamped;
5937
6294
  this.requestUpdate("samplesPerPixel", old);
5938
6295
  }
6296
+ /** Raise the zoom floor and re-clamp the LIVE samplesPerPixel when it's
6297
+ * now below the floor. Peaks can only be extracted at >= the floor scale —
6298
+ * the setter alone clamps only FUTURE sets, so without the re-clamp an
6299
+ * already-finer spp keeps sizing clip containers while the waveforms
6300
+ * render at the coarser scale: half/quarter width, misaligned against the
6301
+ * ruler and playhead. */
6302
+ _raiseZoomFloor(scale) {
6303
+ if (!Number.isFinite(scale) || scale <= 0) return;
6304
+ if (scale > this._minSamplesPerPixel) {
6305
+ this._minSamplesPerPixel = scale;
6306
+ }
6307
+ if (this._samplesPerPixel < this._minSamplesPerPixel) {
6308
+ this.samplesPerPixel = this._minSamplesPerPixel;
6309
+ }
6310
+ }
6311
+ /** Recompute the floor from the surviving cached scales (track removal /
6312
+ * load cancellation / preview cleanup). Usually LOWERS the floor, freeing
6313
+ * finer zoom — but a buffer whose scale never raised the floor (or a mix
6314
+ * of scales) can raise it above the live spp, so re-clamp like
6315
+ * _raiseZoomFloor. Never mutate _minSamplesPerPixel directly. */
6316
+ _recomputeZoomFloor() {
6317
+ this._minSamplesPerPixel = this._peakPipeline.getMaxCachedScale(this._clipBuffers);
6318
+ if (this._minSamplesPerPixel > 0 && this._samplesPerPixel < this._minSamplesPerPixel) {
6319
+ this.samplesPerPixel = this._minSamplesPerPixel;
6320
+ }
6321
+ }
5939
6322
  get timeFormat() {
5940
6323
  return this._timeFormat;
5941
6324
  }
@@ -6081,6 +6464,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
6081
6464
  console.warn("[dawcore] Adapter AudioContext is already closed. Ignoring.");
6082
6465
  return;
6083
6466
  }
6467
+ this._adapterConsumedByDispose = false;
6084
6468
  if (this._engine) {
6085
6469
  console.warn(
6086
6470
  "[dawcore] adapter set after engine is built. The engine will continue using the previous adapter."
@@ -6168,6 +6552,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
6168
6552
  effectiveSampleRate: this.effectiveSampleRate,
6169
6553
  duration: this._duration,
6170
6554
  tracks: [...this._engineTracks.values()],
6555
+ masterVolume: this._engine?.getState().masterVolume ?? 1,
6171
6556
  getMasterEffectsState: () => this.getEffectsState(),
6172
6557
  getTrackEffectsState: (trackId) => this.getTrackEffectsState(trackId)
6173
6558
  },
@@ -6351,7 +6736,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
6351
6736
  const naturalWidth = Math.ceil(
6352
6737
  this._duration * this.effectiveSampleRate / this.samplesPerPixel
6353
6738
  );
6354
- if (this.indefinitePlayback) {
6739
+ if (this.indefinitePlayback || this.fillViewport) {
6355
6740
  return Math.max(naturalWidth, this._viewport.containerWidth);
6356
6741
  }
6357
6742
  return naturalWidth;
@@ -6449,11 +6834,21 @@ var DawEditorElement = class extends import_lit15.LitElement {
6449
6834
  this._minSamplesPerPixel = 0;
6450
6835
  this._spectrogramController?.dispose();
6451
6836
  this._spectrogramController = null;
6837
+ this._lastSpectrogramViewport = null;
6838
+ const hadEngine = this._engine !== null;
6452
6839
  try {
6453
6840
  this._disposeEngine();
6454
6841
  } catch (err) {
6455
6842
  console.warn("[dawcore] Error disposing engine: " + String(err));
6456
6843
  }
6844
+ if (hadEngine) {
6845
+ this._adapterConsumedByDispose = true;
6846
+ }
6847
+ this._tracks = /* @__PURE__ */ new Map();
6848
+ this._engineTracks = /* @__PURE__ */ new Map();
6849
+ this._peaksData = /* @__PURE__ */ new Map();
6850
+ this._loadingTracks.clear();
6851
+ this._recomputeDuration();
6457
6852
  }
6458
6853
  willUpdate(changedProperties) {
6459
6854
  if (changedProperties.has("eagerResume")) {
@@ -6462,8 +6857,8 @@ var DawEditorElement = class extends import_lit15.LitElement {
6462
6857
  if ((changedProperties.has("samplesPerPixel") || changedProperties.has("ticksPerPixel") || changedProperties.has("bpm") || changedProperties.has("secondsToTicks")) && this._isPlaying) {
6463
6858
  this._startPlayhead();
6464
6859
  }
6465
- const zoomChanged = changedProperties.has("samplesPerPixel") || changedProperties.has("ticksPerPixel") || changedProperties.has("bpm") || changedProperties.has("scaleMode") || changedProperties.has("secondsToTicks");
6466
- if (zoomChanged && this._clipBuffers.size > 0) {
6860
+ const peaksInputChanged = changedProperties.has("samplesPerPixel") || changedProperties.has("ticksPerPixel") || changedProperties.has("bpm") || changedProperties.has("scaleMode") || changedProperties.has("secondsToTicks") || changedProperties.has("mono");
6861
+ if (peaksInputChanged && this._clipBuffers.size > 0) {
6467
6862
  const re = this._peakPipeline.reextractPeaks(
6468
6863
  this._clipBuffers,
6469
6864
  this._renderSpp,
@@ -6530,9 +6925,16 @@ var DawEditorElement = class extends import_lit15.LitElement {
6530
6925
  if (this._engine) {
6531
6926
  this._engine.removeTrack(trackId);
6532
6927
  }
6533
- this._minSamplesPerPixel = this._peakPipeline.getMaxCachedScale(this._clipBuffers);
6928
+ this._recomputeZoomFloor();
6534
6929
  this._disposeSpectrogramControllerIfEmpty();
6535
- if (nextEngine.size === 0) {
6930
+ if (existed && nextEngine.size === 0) {
6931
+ if (this._engine) {
6932
+ if (this._isPlaying) {
6933
+ this._withSeekSuppression(() => this._engine.stop());
6934
+ this.dispatchEvent(new CustomEvent("daw-stop", { bubbles: true, composed: true }));
6935
+ }
6936
+ this._engine.seek(0);
6937
+ }
6536
6938
  this._currentTime = 0;
6537
6939
  this._stopPlayhead();
6538
6940
  }
@@ -6555,6 +6957,45 @@ var DawEditorElement = class extends import_lit15.LitElement {
6555
6957
  if (!stillNeeded) {
6556
6958
  this._spectrogramController.dispose();
6557
6959
  this._spectrogramController = null;
6960
+ this._lastSpectrogramViewport = null;
6961
+ }
6962
+ }
6963
+ /** Reconcile `_tracks` descriptors with the engine's track list.
6964
+ *
6965
+ * ADD: engine.undo() restores removed tracks in ENGINE state only —
6966
+ * without a synthesized descriptor the track plays and renders but shows
6967
+ * "Untitled" controls and is missing from `editor.tracks`.
6968
+ * PRUNE (the symmetric half): redo removes the track from engine state
6969
+ * again — without pruning, the synthesized descriptor is a permanent
6970
+ * ghost that even removeTrack() can't clean (no element, no engine
6971
+ * entry). Never prunes tracks that are mid-load or element-backed —
6972
+ * their descriptors legitimately precede their engine entries. */
6973
+ _reconcileDescriptorsWithEngineTracks(tracks) {
6974
+ const engineIds = new Set(tracks.map((t) => t.id));
6975
+ let next = null;
6976
+ for (const track of tracks) {
6977
+ if (this._tracks.has(track.id)) continue;
6978
+ next ?? (next = new Map(this._tracks));
6979
+ next.set(track.id, {
6980
+ name: track.name ?? "",
6981
+ src: "",
6982
+ volume: track.volume ?? 1,
6983
+ pan: track.pan ?? 0,
6984
+ muted: track.muted ?? false,
6985
+ soloed: track.soloed ?? false,
6986
+ renderMode: track.clips.some((c) => c.midiNotes && c.midiNotes.length > 0) ? "piano-roll" : "waveform",
6987
+ clips: []
6988
+ });
6989
+ }
6990
+ for (const trackId of this._tracks.keys()) {
6991
+ if (engineIds.has(trackId) || this._loadingTracks.has(trackId) || this._trackElements.has(trackId)) {
6992
+ continue;
6993
+ }
6994
+ next ?? (next = new Map(this._tracks));
6995
+ next.delete(trackId);
6996
+ }
6997
+ if (next) {
6998
+ this._tracks = next;
6558
6999
  }
6559
7000
  }
6560
7001
  _onClipRemovedFromDom(clipEl) {
@@ -6700,9 +7141,8 @@ var DawEditorElement = class extends import_lit15.LitElement {
6700
7141
  throw err;
6701
7142
  }
6702
7143
  this._peaksData = new Map(this._peaksData).set(clip.id, peakData);
6703
- if (waveformData) {
6704
- this._minSamplesPerPixel = Math.max(this._minSamplesPerPixel, waveformData.scale);
6705
- }
7144
+ const cachedScale = waveformData?.scale ?? this._peakPipeline.getCachedScale(audioBuffer);
7145
+ this._raiseZoomFloor(cachedScale);
6706
7146
  return clip;
6707
7147
  }
6708
7148
  /**
@@ -6945,6 +7385,8 @@ var DawEditorElement = class extends import_lit15.LitElement {
6945
7385
  }
6946
7386
  // --- Audio Loading ---
6947
7387
  async _loadTrack(trackId, descriptor) {
7388
+ this._loadingTracks.add(trackId);
7389
+ const sppAtLoadStart = this._samplesPerPixel;
6948
7390
  try {
6949
7391
  const clips = [];
6950
7392
  for (const clipDesc of descriptor.clips) {
@@ -6982,18 +7424,20 @@ var DawEditorElement = class extends import_lit15.LitElement {
6982
7424
  durationSamples: clip2.durationSamples
6983
7425
  });
6984
7426
  this._peaksData = new Map(this._peaksData).set(clip2.id, peakData);
6985
- this._minSamplesPerPixel = Math.max(this._minSamplesPerPixel, waveformData.scale);
6986
- const previewTrack = (0, import_core9.createTrack)({
6987
- name: descriptor.name,
6988
- clips: [clip2],
6989
- volume: descriptor.volume,
6990
- pan: descriptor.pan,
6991
- muted: descriptor.muted,
6992
- soloed: descriptor.soloed
6993
- });
6994
- previewTrack.id = trackId;
6995
- this._engineTracks = new Map(this._engineTracks).set(trackId, previewTrack);
6996
- this._recomputeDuration();
7427
+ this._raiseZoomFloor(waveformData.scale);
7428
+ if (this._tracks.has(trackId)) {
7429
+ const previewTrack = (0, import_core9.createTrack)({
7430
+ name: descriptor.name,
7431
+ clips: [clip2],
7432
+ volume: descriptor.volume,
7433
+ pan: descriptor.pan,
7434
+ muted: descriptor.muted,
7435
+ soloed: descriptor.soloed
7436
+ });
7437
+ previewTrack.id = trackId;
7438
+ this._engineTracks = new Map(this._engineTracks).set(trackId, previewTrack);
7439
+ this._recomputeDuration();
7440
+ }
6997
7441
  let audioBuffer2;
6998
7442
  try {
6999
7443
  audioBuffer2 = await audioPromise;
@@ -7005,7 +7449,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
7005
7449
  const nextEngine = new Map(this._engineTracks);
7006
7450
  nextEngine.delete(trackId);
7007
7451
  this._engineTracks = nextEngine;
7008
- this._minSamplesPerPixel = this._peakPipeline.getMaxCachedScale(this._clipBuffers);
7452
+ this._recomputeZoomFloor();
7009
7453
  this._recomputeDuration();
7010
7454
  throw audioErr;
7011
7455
  }
@@ -7039,6 +7483,26 @@ var DawEditorElement = class extends import_lit15.LitElement {
7039
7483
  }
7040
7484
  }
7041
7485
  }
7486
+ const trackWasRemoved = !this._tracks.has(trackId);
7487
+ if (trackWasRemoved || !this.isConnected) {
7488
+ for (const clip of clips) {
7489
+ this._purgeClipCaches(clip.id);
7490
+ }
7491
+ if (this._engineTracks.has(trackId)) {
7492
+ const nextEngine = new Map(this._engineTracks);
7493
+ nextEngine.delete(trackId);
7494
+ this._engineTracks = nextEngine;
7495
+ this._recomputeDuration();
7496
+ }
7497
+ this._recomputeZoomFloor();
7498
+ if (this._samplesPerPixel !== sppAtLoadStart && sppAtLoadStart >= this._minSamplesPerPixel) {
7499
+ this.samplesPerPixel = sppAtLoadStart;
7500
+ }
7501
+ throw new TrackLoadCancelledError(
7502
+ trackWasRemoved ? 'track "' + trackId + '" was removed while loading' : 'editor was disconnected while track "' + trackId + '" was loading',
7503
+ trackWasRemoved ? "removed" : "disconnected"
7504
+ );
7505
+ }
7042
7506
  const track = (0, import_core9.createTrack)({
7043
7507
  name: descriptor.name,
7044
7508
  clips,
@@ -7069,15 +7533,23 @@ var DawEditorElement = class extends import_lit15.LitElement {
7069
7533
  })
7070
7534
  );
7071
7535
  } catch (err) {
7072
- if (!this.isConnected) return;
7073
- console.warn('[dawcore] Failed to load track "' + trackId + '": ' + String(err));
7536
+ const cancelled = err instanceof TrackLoadCancelledError;
7537
+ console.warn(
7538
+ cancelled ? "[dawcore] Track load cancelled: " + err.message : '[dawcore] Failed to load track "' + trackId + '": ' + String(err)
7539
+ );
7074
7540
  this.dispatchEvent(
7075
7541
  new CustomEvent("daw-track-error", {
7076
7542
  bubbles: true,
7077
7543
  composed: true,
7078
- detail: { trackId, error: err }
7544
+ detail: {
7545
+ trackId,
7546
+ error: err,
7547
+ ...cancelled ? { reason: err.reason } : {}
7548
+ }
7079
7549
  })
7080
7550
  );
7551
+ } finally {
7552
+ this._loadingTracks.delete(trackId);
7081
7553
  }
7082
7554
  }
7083
7555
  async _fetchAndDecode(src) {
@@ -7136,6 +7608,11 @@ var DawEditorElement = class extends import_lit15.LitElement {
7136
7608
  if (!this._externalAdapter) {
7137
7609
  throw new Error(NO_ADAPTER_ERROR);
7138
7610
  }
7611
+ if (this._adapterConsumedByDispose) {
7612
+ throw new Error(
7613
+ "[dawcore] editor.adapter was disposed by a previous disconnect \u2014 set a fresh PlayoutAdapter after reparenting <daw-editor>."
7614
+ );
7615
+ }
7139
7616
  const { PlaylistEngine } = await import("@waveform-playlist/engine");
7140
7617
  const adapter = this._externalAdapter;
7141
7618
  if (!this._hasTickCallbacks) {
@@ -7172,6 +7649,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
7172
7649
  nextTracks.set(track.id, track);
7173
7650
  }
7174
7651
  this._engineTracks = nextTracks;
7652
+ this._reconcileDescriptorsWithEngineTracks(engineState.tracks);
7175
7653
  }
7176
7654
  if (structuralChange) {
7177
7655
  this._effectsManager?.rewireTrackChains();
@@ -7528,24 +8006,60 @@ var DawEditorElement = class extends import_lit15.LitElement {
7528
8006
  this.play();
7529
8007
  }
7530
8008
  }
8009
+ /** Run `fn` with the stop-settle daw-timeupdate suppressed. Every
8010
+ * stop-adjacent code path that immediately re-positions (seek, split,
8011
+ * empty-timeline rewind) must use this — engine.stop() rewinds to the
8012
+ * play-start position and the settle would leak a backward-jumping
8013
+ * daw-timeupdate to consumers (CLAUDE.md seek-while-playing invariant).
8014
+ * The `finally` is load-bearing: a wedged true silently drops every
8015
+ * subsequent stop-settle dispatch. */
8016
+ _withSeekSuppression(fn) {
8017
+ this._inSeekTransition = true;
8018
+ try {
8019
+ fn();
8020
+ } finally {
8021
+ this._inSeekTransition = false;
8022
+ }
8023
+ }
7531
8024
  seekTo(time) {
7532
8025
  if (!this._engine) {
7533
8026
  console.warn("[dawcore] seekTo: engine not ready, call ignored");
7534
8027
  return;
7535
8028
  }
8029
+ if (!Number.isFinite(time)) {
8030
+ console.warn("[dawcore] seekTo: ignoring non-finite time " + String(time));
8031
+ return;
8032
+ }
8033
+ const target = Math.max(0, time);
7536
8034
  if (this._isPlaying) {
7537
- this._inSeekTransition = true;
7538
8035
  try {
7539
- this.stop();
7540
- } finally {
7541
- this._inSeekTransition = false;
8036
+ this._withSeekSuppression(() => this._engine.stop());
8037
+ this._engine.play(target);
8038
+ } catch (err) {
8039
+ console.warn("[dawcore] seekTo: engine reschedule failed: " + String(err));
8040
+ this.dispatchEvent(
8041
+ new CustomEvent("daw-error", {
8042
+ bubbles: true,
8043
+ composed: true,
8044
+ detail: { operation: "seek", error: err }
8045
+ })
8046
+ );
8047
+ return;
7542
8048
  }
7543
- this.play(time);
8049
+ this._currentTime = target;
8050
+ this._startPlayhead();
7544
8051
  } else {
7545
- this._engine.seek(time);
7546
- this._currentTime = time;
8052
+ this._engine.seek(target);
8053
+ this._currentTime = target;
7547
8054
  this._stopPlayhead();
7548
8055
  }
8056
+ this.dispatchEvent(
8057
+ new CustomEvent("daw-seek", {
8058
+ bubbles: true,
8059
+ composed: true,
8060
+ detail: { time: target }
8061
+ })
8062
+ );
7549
8063
  }
7550
8064
  /** Undo the last structural edit. */
7551
8065
  undo() {
@@ -7580,8 +8094,10 @@ var DawEditorElement = class extends import_lit15.LitElement {
7580
8094
  engine: this._engine,
7581
8095
  dispatchEvent: (e) => this.dispatchEvent(e),
7582
8096
  stop: () => {
7583
- this._engine?.stop();
7584
- this._stopPlayhead();
8097
+ this._withSeekSuppression(() => {
8098
+ this._engine?.stop();
8099
+ this._stopPlayhead();
8100
+ });
7585
8101
  },
7586
8102
  // Call engine.play directly (synchronous) — not the async editor play()
7587
8103
  // which yields to microtask queue via await engine.init(). Engine is
@@ -7645,8 +8161,8 @@ var DawEditorElement = class extends import_lit15.LitElement {
7645
8161
  this._wasPlayingDuringRecording = false;
7646
8162
  return this._recordingController.stopRecording();
7647
8163
  }
7648
- _addRecordedClip(trackId, buf, startSample, durSamples, offsetSamples = 0) {
7649
- addRecordedClip(this, trackId, buf, startSample, durSamples, offsetSamples);
8164
+ _addRecordedClip(trackId, buf, startSample, durSamples, offsetSamples = 0, clipName) {
8165
+ addRecordedClip(this, trackId, buf, startSample, durSamples, offsetSamples, clipName);
7650
8166
  }
7651
8167
  // --- RecordingHost bridge methods for cross-context worklet support ---
7652
8168
  // These delegate to the adapter's context type (native or standardized-audio-context).
@@ -7668,6 +8184,25 @@ var DawEditorElement = class extends import_lit15.LitElement {
7668
8184
  }
7669
8185
  await this._recordingController.startRecording(s, options);
7670
8186
  }
8187
+ /** Live-recording preview left/width. Beats mode uses the same tick-space
8188
+ * math as finalized clips — the sample÷renderSpp path is ceil-quantized,
8189
+ * so the take would visibly jump sideways on finalization (drift grows
8190
+ * with distance from t=0; CLAUDE.md live-preview parity invariant). */
8191
+ _previewPosition(startSample, audibleSamples) {
8192
+ if (this.scaleMode === "beats") {
8193
+ const sr = this.effectiveSampleRate;
8194
+ const startSec = startSample / sr;
8195
+ const startTick = this._secondsToTicks(startSec);
8196
+ const endTick = this._secondsToTicks(startSec + audibleSamples / sr);
8197
+ const left = Math.round(startTick / this.ticksPerPixel);
8198
+ return { left, width: Math.round(endTick / this.ticksPerPixel) - left };
8199
+ }
8200
+ const renderSpp = this._renderSpp;
8201
+ return {
8202
+ left: Math.floor(startSample / renderSpp),
8203
+ width: Math.floor(audibleSamples / renderSpp)
8204
+ };
8205
+ }
7671
8206
  _renderRecordingPreview(trackId, chH) {
7672
8207
  const rs = this._recordingController.getSession(trackId);
7673
8208
  if (!rs) return "";
@@ -7675,32 +8210,48 @@ var DawEditorElement = class extends import_lit15.LitElement {
7675
8210
  if (audibleSamples === 0) return "";
7676
8211
  const renderSpp = this._renderSpp;
7677
8212
  const latencyPixels = Math.floor(rs.latencySamples / renderSpp);
7678
- const left = Math.floor(rs.startSample / renderSpp);
7679
- const w = Math.floor(audibleSamples / renderSpp);
7680
- return rs.peaks.map((chPeaks, ch) => {
8213
+ const { left, width: w } = this._previewPosition(rs.startSample, audibleSamples);
8214
+ const hdrH = this.clipHeaders ? this.clipHeaderHeight : 0;
8215
+ const height = hdrH + chH * rs.peaks.length;
8216
+ return import_lit15.html`<div
8217
+ class="clip-container recording-preview"
8218
+ style="left:${left}px;top:0;width:${w}px;height:${height}px;"
8219
+ >
8220
+ ${hdrH > 0 ? import_lit15.html`<div class="clip-header" data-track-id=${trackId}>
8221
+ <span>${rs.clipName ?? "Recording\u2026"}</span>
8222
+ </div>` : ""}
8223
+ ${rs.peaks.map((chPeaks, ch) => {
7681
8224
  const slicedPeaks = latencyPixels > 0 ? chPeaks.slice(latencyPixels * 2) : chPeaks;
7682
8225
  return import_lit15.html`
7683
- <daw-waveform
7684
- data-recording-track=${trackId}
7685
- data-recording-channel=${ch}
7686
- style="position:absolute;left:${left}px;top:${ch * chH}px;"
7687
- .peaks=${slicedPeaks}
7688
- .length=${w}
7689
- .waveHeight=${chH}
7690
- .barWidth=${this.barWidth}
7691
- .barGap=${this.barGap}
7692
- .roundedBars=${this.roundedBars}
7693
- .visibleStart=${this._viewport.visibleStart}
7694
- .visibleEnd=${this._viewport.visibleEnd}
7695
- .originX=${left}
7696
- ></daw-waveform>
7697
- `;
7698
- });
8226
+ <daw-waveform
8227
+ data-recording-track=${trackId}
8228
+ data-recording-channel=${ch}
8229
+ style="position:absolute;left:0;top:${hdrH + ch * chH}px;"
8230
+ .peaks=${slicedPeaks}
8231
+ .length=${w}
8232
+ .waveHeight=${chH}
8233
+ .barWidth=${this.barWidth}
8234
+ .barGap=${this.barGap}
8235
+ .roundedBars=${this.roundedBars}
8236
+ .visibleStart=${this._viewport.visibleStart}
8237
+ .visibleEnd=${this._viewport.visibleEnd}
8238
+ .originX=${left}
8239
+ ></daw-waveform>
8240
+ `;
8241
+ })}
8242
+ </div>`;
7699
8243
  }
7700
8244
  _startPlayhead() {
7701
8245
  if (!this._engine) return;
7702
8246
  const engine = this._engine;
7703
- this._playbackAnimation.start(() => engine.getAudibleTime());
8247
+ this._playbackAnimation.start(() => {
8248
+ if (!this.indefinitePlayback && !this.isRecording && engine.getCurrentTime() >= this._duration) {
8249
+ this.stop();
8250
+ const t = this._currentTime;
8251
+ return Number.isFinite(t) ? Math.max(0, t) : 0;
8252
+ }
8253
+ return engine.getAudibleTime();
8254
+ });
7704
8255
  }
7705
8256
  _stopPlayhead() {
7706
8257
  const t = this._currentTime;
@@ -7712,11 +8263,11 @@ var DawEditorElement = class extends import_lit15.LitElement {
7712
8263
  }
7713
8264
  /** True when the controls column should be rendered (and its selector is valid). */
7714
8265
  get _showControls() {
7715
- return this._getOrderedTracks().length > 0 || this.indefinitePlayback;
8266
+ return this._getOrderedTracks().length > 0 || this.indefinitePlayback || this.fillViewport;
7716
8267
  }
7717
8268
  /** True when the ruler header band should be rendered (and its selector is valid). */
7718
8269
  get _showRuler() {
7719
- return (this._getOrderedTracks().length > 0 || this.scaleMode === "beats" || this.indefinitePlayback) && this.timescale;
8270
+ return (this._getOrderedTracks().length > 0 || this.scaleMode === "beats" || this.indefinitePlayback || this.fillViewport) && this.timescale;
7720
8271
  }
7721
8272
  _getOrderedTracks() {
7722
8273
  const domOrder = [...this.querySelectorAll("daw-track")].map(
@@ -7821,7 +8372,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
7821
8372
  .length=${this._totalWidth}
7822
8373
  .height=${orderedTracks.length > 0 ? orderedTracks.reduce((sum, t) => sum + t.trackHeight, 0) : this._emptyGridHeight}
7823
8374
  ></daw-grid>` : ""}
7824
- ${orderedTracks.length > 0 || this.scaleMode === "beats" || this.indefinitePlayback ? import_lit15.html`<daw-selection .startPx=${selStartPx} .endPx=${selEndPx}></daw-selection>
8375
+ ${orderedTracks.length > 0 || this.scaleMode === "beats" || this.indefinitePlayback || this.fillViewport ? import_lit15.html`<daw-selection .startPx=${selStartPx} .endPx=${selEndPx}></daw-selection>
7825
8376
  <daw-playhead></daw-playhead>` : ""}
7826
8377
  ${orderedTracks.map((t) => {
7827
8378
  const channelHeight = this.waveHeight;
@@ -8087,6 +8638,9 @@ __decorateClass([
8087
8638
  __decorateClass([
8088
8639
  (0, import_decorators13.property)({ type: Boolean, attribute: "indefinite-playback" })
8089
8640
  ], DawEditorElement.prototype, "indefinitePlayback", 2);
8641
+ __decorateClass([
8642
+ (0, import_decorators13.property)({ type: Boolean, attribute: "fill-viewport" })
8643
+ ], DawEditorElement.prototype, "fillViewport", 2);
8090
8644
  __decorateClass([
8091
8645
  (0, import_decorators13.property)({ attribute: false, noAccessor: true })
8092
8646
  ], DawEditorElement.prototype, "spectrogramConfig", 1);
@@ -8213,14 +8767,22 @@ var DawRecordButtonElement = class extends DawTransportButton {
8213
8767
  }
8214
8768
  connectedCallback() {
8215
8769
  super.connectedCallback();
8216
- requestAnimationFrame(() => this._listenToTarget());
8770
+ requestAnimationFrame(() => {
8771
+ if (!this.isConnected) return;
8772
+ this._ensureTargetListeners();
8773
+ });
8217
8774
  }
8218
8775
  disconnectedCallback() {
8219
8776
  super.disconnectedCallback();
8220
8777
  this._cleanupListeners();
8221
8778
  }
8222
- _listenToTarget() {
8779
+ updated() {
8780
+ this._ensureTargetListeners();
8781
+ }
8782
+ _ensureTargetListeners() {
8223
8783
  const target = this.target;
8784
+ if (target === this._targetRef) return;
8785
+ this._cleanupListeners();
8224
8786
  if (!target) return;
8225
8787
  this._targetRef = target;
8226
8788
  target.addEventListener("daw-recording-start", this._onStart);
@@ -8254,6 +8816,7 @@ var DawRecordButtonElement = class extends DawTransportButton {
8254
8816
  warnNoTargetOnce(this);
8255
8817
  return;
8256
8818
  }
8819
+ this._ensureTargetListeners();
8257
8820
  target.startRecording(target.recordingStream);
8258
8821
  }
8259
8822
  };
@@ -8289,11 +8852,16 @@ var DawKeyboardShortcutsElement = class extends import_lit18.LitElement {
8289
8852
  this.splitting = false;
8290
8853
  this.undo = false;
8291
8854
  // --- JS properties for remapping ---
8292
- this.playbackShortcuts = null;
8293
- this.splittingShortcuts = null;
8294
- this.undoShortcuts = null;
8855
+ // Accessors, not plain fields: assigning a remap after any keydown has
8856
+ // warmed _cachedShortcuts must invalidate it, or the documented remapping
8857
+ // API is silently ignored until an unrelated boolean attribute toggles.
8858
+ // (connectedCallback runs the standard upgrade-property dance so values
8859
+ // assigned BEFORE the element was defined don't shadow these accessors.)
8860
+ this._playbackShortcuts = null;
8861
+ this._splittingShortcuts = null;
8862
+ this._undoShortcuts = null;
8295
8863
  /** Additional custom shortcuts. */
8296
- this.customShortcuts = [];
8864
+ this._customShortcuts = [];
8297
8865
  this._editor = null;
8298
8866
  this._cachedShortcuts = null;
8299
8867
  // --- Event handler ---
@@ -8315,6 +8883,34 @@ var DawKeyboardShortcutsElement = class extends import_lit18.LitElement {
8315
8883
  }
8316
8884
  };
8317
8885
  }
8886
+ get playbackShortcuts() {
8887
+ return this._playbackShortcuts;
8888
+ }
8889
+ set playbackShortcuts(value) {
8890
+ this._playbackShortcuts = value;
8891
+ this._cachedShortcuts = null;
8892
+ }
8893
+ get splittingShortcuts() {
8894
+ return this._splittingShortcuts;
8895
+ }
8896
+ set splittingShortcuts(value) {
8897
+ this._splittingShortcuts = value;
8898
+ this._cachedShortcuts = null;
8899
+ }
8900
+ get undoShortcuts() {
8901
+ return this._undoShortcuts;
8902
+ }
8903
+ set undoShortcuts(value) {
8904
+ this._undoShortcuts = value;
8905
+ this._cachedShortcuts = null;
8906
+ }
8907
+ get customShortcuts() {
8908
+ return this._customShortcuts;
8909
+ }
8910
+ set customShortcuts(value) {
8911
+ this._customShortcuts = value;
8912
+ this._cachedShortcuts = null;
8913
+ }
8318
8914
  /** All active shortcuts (read-only, cached). */
8319
8915
  get shortcuts() {
8320
8916
  if (!this._cachedShortcuts) {
@@ -8329,6 +8925,18 @@ var DawKeyboardShortcutsElement = class extends import_lit18.LitElement {
8329
8925
  // --- Lifecycle ---
8330
8926
  connectedCallback() {
8331
8927
  super.connectedCallback();
8928
+ for (const prop of [
8929
+ "playbackShortcuts",
8930
+ "splittingShortcuts",
8931
+ "undoShortcuts",
8932
+ "customShortcuts"
8933
+ ]) {
8934
+ if (Object.prototype.hasOwnProperty.call(this, prop)) {
8935
+ const value = this[prop];
8936
+ delete this[prop];
8937
+ this[prop] = value;
8938
+ }
8939
+ }
8332
8940
  this._editor = this.closest("daw-editor");
8333
8941
  if (!this._editor) {
8334
8942
  console.warn(
@@ -8854,6 +9462,9 @@ var DawPlayerElement = class extends import_lit22.LitElement {
8854
9462
  this.roundedBars = false;
8855
9463
  this._playbackRate = 1;
8856
9464
  this._engine = new import_media_element_playout.MediaElementPlayout();
9465
+ /** Set by disconnectedCallback — a reconnect (DOM reparent, framework
9466
+ * re-render) must rebuild the engine + track or the player is dead. */
9467
+ this._engineDisposed = false;
8857
9468
  this._trackId = null;
8858
9469
  this._anim = new AnimationController(this);
8859
9470
  this._metadataLoaded = false;
@@ -8871,7 +9482,6 @@ var DawPlayerElement = class extends import_lit22.LitElement {
8871
9482
  if (width <= 0 || d <= 0) return;
8872
9483
  const ratio = Math.max(0, Math.min(1, e.offsetX / width));
8873
9484
  this.seekTo(ratio * d);
8874
- this._updatePlayhead();
8875
9485
  };
8876
9486
  this._onLoadedMetadata = () => {
8877
9487
  this._metadataLoaded = true;
@@ -8919,6 +9529,15 @@ var DawPlayerElement = class extends import_lit22.LitElement {
8919
9529
  }
8920
9530
  connectedCallback() {
8921
9531
  super.connectedCallback();
9532
+ let rebuilt = false;
9533
+ if (this._engineDisposed) {
9534
+ const volume = this._engine.masterVolume;
9535
+ this._engine = new import_media_element_playout.MediaElementPlayout();
9536
+ this._engine.setMasterVolume(volume);
9537
+ this._engineDisposed = false;
9538
+ this._trackId = null;
9539
+ rebuilt = true;
9540
+ }
8922
9541
  this._engine.on("loadedmetadata", this._onLoadedMetadata);
8923
9542
  this._engine.on("play", this._onPlay);
8924
9543
  this._engine.on("pause", this._onPause);
@@ -8929,6 +9548,10 @@ var DawPlayerElement = class extends import_lit22.LitElement {
8929
9548
  const area = this.shadowRoot?.querySelector(".waveform-area");
8930
9549
  if (area) this._resizeObserver?.observe(area);
8931
9550
  });
9551
+ if (rebuilt && this.src) {
9552
+ this._loadSource();
9553
+ this._playhead?.setPosition(0);
9554
+ }
8932
9555
  }
8933
9556
  render() {
8934
9557
  const width = this._timelineWidth;
@@ -8988,6 +9611,7 @@ var DawPlayerElement = class extends import_lit22.LitElement {
8988
9611
  this._renderWaveform();
8989
9612
  this._maybeDispatchReady();
8990
9613
  } catch (err) {
9614
+ if (this.peaksSrc !== requested) return;
8991
9615
  console.warn("[dawcore] <daw-player> failed to load peaks-src: " + String(err));
8992
9616
  this._peaksSettled = true;
8993
9617
  this._renderWaveform();
@@ -9028,7 +9652,7 @@ var DawPlayerElement = class extends import_lit22.LitElement {
9028
9652
  }
9029
9653
  // --- Transport methods ---
9030
9654
  play() {
9031
- this._engine.play();
9655
+ this._engine.resume();
9032
9656
  }
9033
9657
  pause() {
9034
9658
  this._engine.pause();
@@ -9041,6 +9665,10 @@ var DawPlayerElement = class extends import_lit22.LitElement {
9041
9665
  }
9042
9666
  seekTo(time) {
9043
9667
  this._engine.seekTo(time);
9668
+ if (!this._engine.isPlaying) {
9669
+ this._updatePlayhead();
9670
+ this._dispatch("daw-timeupdate", { time: this._engine.getCurrentTime() });
9671
+ }
9044
9672
  }
9045
9673
  setPlaybackRate(rate) {
9046
9674
  this.playbackRate = rate;
@@ -9059,7 +9687,7 @@ var DawPlayerElement = class extends import_lit22.LitElement {
9059
9687
  return this._engine.getCurrentTime();
9060
9688
  }
9061
9689
  set currentTime(time) {
9062
- this._engine.seekTo(time);
9690
+ this.seekTo(time);
9063
9691
  }
9064
9692
  get volume() {
9065
9693
  return this._engine.masterVolume;
@@ -9081,6 +9709,7 @@ var DawPlayerElement = class extends import_lit22.LitElement {
9081
9709
  this._engine.off("ended", this._onEnded);
9082
9710
  this._engine.off("error", this._onError);
9083
9711
  this._engine.dispose();
9712
+ this._engineDisposed = true;
9084
9713
  }
9085
9714
  // --- Private event handlers (arrow fields for stable identity) ---
9086
9715
  _dispatch(name, detail) {