@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.mjs CHANGED
@@ -394,11 +394,9 @@ var LAYOUT_PROPS = /* @__PURE__ */ new Set([
394
394
  "roundedBars",
395
395
  "segments"
396
396
  ]);
397
- function groupDirtyByChunk(dirtyPixels, step) {
397
+ function groupDirtyByChunk(dirtyPixels, step, barWidth) {
398
398
  const dirtyByChunk = /* @__PURE__ */ new Map();
399
- for (const peakIdx of dirtyPixels) {
400
- const barPixel = Math.floor(peakIdx / step) * step;
401
- const chunkIdx = Math.floor(barPixel / MAX_CANVAS_WIDTH);
399
+ const mark = (chunkIdx, barPixel) => {
402
400
  const existing = dirtyByChunk.get(chunkIdx);
403
401
  if (existing) {
404
402
  dirtyByChunk.set(chunkIdx, {
@@ -408,6 +406,15 @@ function groupDirtyByChunk(dirtyPixels, step) {
408
406
  } else {
409
407
  dirtyByChunk.set(chunkIdx, { min: barPixel, max: barPixel });
410
408
  }
409
+ };
410
+ for (const peakIdx of dirtyPixels) {
411
+ const barPixel = Math.floor(peakIdx / step) * step;
412
+ const chunkIdx = Math.floor(barPixel / MAX_CANVAS_WIDTH);
413
+ mark(chunkIdx, barPixel);
414
+ const endChunkIdx = Math.floor((barPixel + barWidth - 1) / MAX_CANVAS_WIDTH);
415
+ if (endChunkIdx !== chunkIdx) {
416
+ mark(endChunkIdx, barPixel);
417
+ }
411
418
  }
412
419
  return dirtyByChunk;
413
420
  }
@@ -509,7 +516,7 @@ var DawWaveformElement = class extends LitElement3 {
509
516
  this._drawSegments(canvas, chunkIdx, dpr, halfHeight, bits, waveColor);
510
517
  }
511
518
  } else {
512
- const dirtyByChunk = groupDirtyByChunk(this._dirtyPixels, step);
519
+ const dirtyByChunk = groupDirtyByChunk(this._dirtyPixels, step, this.barWidth);
513
520
  for (const canvas of canvases) {
514
521
  const chunkIdx = Number(canvas.dataset.index);
515
522
  this._drawnChunks.add(chunkIdx);
@@ -1130,16 +1137,31 @@ var DawPlayButtonElement = class extends DawTransportButton {
1130
1137
  connectedCallback() {
1131
1138
  super.connectedCallback();
1132
1139
  requestAnimationFrame(() => {
1133
- const target = this.target;
1134
- if (!target) return;
1135
- this._targetRef = target;
1136
- target.addEventListener("daw-recording-start", this._onRecStart);
1137
- target.addEventListener("daw-recording-complete", this._onRecEnd);
1138
- target.addEventListener("daw-recording-error", this._onRecEnd);
1140
+ if (!this.isConnected) return;
1141
+ this._ensureTargetListeners();
1139
1142
  });
1140
1143
  }
1141
1144
  disconnectedCallback() {
1142
1145
  super.disconnectedCallback();
1146
+ this._cleanupListeners();
1147
+ }
1148
+ updated() {
1149
+ this._ensureTargetListeners();
1150
+ }
1151
+ _ensureTargetListeners() {
1152
+ const target = this.target;
1153
+ if (target === this._targetRef) return;
1154
+ if (this._targetRef) {
1155
+ this._isRecording = false;
1156
+ }
1157
+ this._cleanupListeners();
1158
+ if (!target) return;
1159
+ this._targetRef = target;
1160
+ target.addEventListener("daw-recording-start", this._onRecStart);
1161
+ target.addEventListener("daw-recording-complete", this._onRecEnd);
1162
+ target.addEventListener("daw-recording-error", this._onRecEnd);
1163
+ }
1164
+ _cleanupListeners() {
1143
1165
  if (this._targetRef) {
1144
1166
  this._targetRef.removeEventListener("daw-recording-start", this._onRecStart);
1145
1167
  this._targetRef.removeEventListener("daw-recording-complete", this._onRecEnd);
@@ -1198,18 +1220,34 @@ var DawPauseButtonElement = class extends DawTransportButton {
1198
1220
  connectedCallback() {
1199
1221
  super.connectedCallback();
1200
1222
  requestAnimationFrame(() => {
1201
- const target = this.target;
1202
- if (!target) return;
1203
- this._targetRef = target;
1204
- target.addEventListener("daw-recording-start", this._onRecStart);
1205
- target.addEventListener("daw-recording-complete", this._onRecEnd);
1206
- target.addEventListener("daw-recording-error", this._onRecEnd);
1207
- target.addEventListener("daw-recording-pause", this._onRecPause);
1208
- target.addEventListener("daw-recording-resume", this._onRecResume);
1223
+ if (!this.isConnected) return;
1224
+ this._ensureTargetListeners();
1209
1225
  });
1210
1226
  }
1211
1227
  disconnectedCallback() {
1212
1228
  super.disconnectedCallback();
1229
+ this._cleanupListeners();
1230
+ }
1231
+ updated() {
1232
+ this._ensureTargetListeners();
1233
+ }
1234
+ _ensureTargetListeners() {
1235
+ const target = this.target;
1236
+ if (target === this._targetRef) return;
1237
+ if (this._targetRef) {
1238
+ this._isRecording = false;
1239
+ this._isPaused = false;
1240
+ }
1241
+ this._cleanupListeners();
1242
+ if (!target) return;
1243
+ this._targetRef = target;
1244
+ target.addEventListener("daw-recording-start", this._onRecStart);
1245
+ target.addEventListener("daw-recording-complete", this._onRecEnd);
1246
+ target.addEventListener("daw-recording-error", this._onRecEnd);
1247
+ target.addEventListener("daw-recording-pause", this._onRecPause);
1248
+ target.addEventListener("daw-recording-resume", this._onRecResume);
1249
+ }
1250
+ _cleanupListeners() {
1213
1251
  if (this._targetRef) {
1214
1252
  this._targetRef.removeEventListener("daw-recording-start", this._onRecStart);
1215
1253
  this._targetRef.removeEventListener("daw-recording-complete", this._onRecEnd);
@@ -1487,6 +1525,12 @@ function createPeaksWorker() {
1487
1525
  )
1488
1526
  );
1489
1527
  },
1528
+ // Reports NOT terminated: CSP blocking is permanent for the page, so
1529
+ // recreating on every call would just re-attempt (and re-warn about)
1530
+ // Worker construction each time.
1531
+ isTerminated() {
1532
+ return false;
1533
+ },
1490
1534
  terminate() {
1491
1535
  }
1492
1536
  };
@@ -1524,6 +1568,9 @@ function createPeaksWorker() {
1524
1568
  pending.clear();
1525
1569
  };
1526
1570
  return {
1571
+ isTerminated() {
1572
+ return terminated;
1573
+ },
1527
1574
  generate(params) {
1528
1575
  if (terminated) return Promise.reject(new Error("Worker terminated"));
1529
1576
  const messageId = String(++idCounter2);
@@ -1739,6 +1786,12 @@ var PeakPipeline = class {
1739
1786
  scale: cached.scale
1740
1787
  };
1741
1788
  }
1789
+ /** Scale of the cached WaveformData for this buffer — 0 when not cached.
1790
+ * Worker generation caches at baseScale; injected .dat data at its own
1791
+ * scale. This is the finest zoom the buffer's peaks can render at. */
1792
+ getCachedScale(audioBuffer) {
1793
+ return this._cache.get(audioBuffer)?.scale ?? 0;
1794
+ }
1742
1795
  /**
1743
1796
  * Return the coarsest (largest) scale among cached WaveformData entries
1744
1797
  * that correspond to the given clip buffers. Returns 0 if none are cached.
@@ -1760,7 +1813,7 @@ var PeakPipeline = class {
1760
1813
  if (cached) return cached;
1761
1814
  const inflight = this._inflight.get(audioBuffer);
1762
1815
  if (inflight) return inflight;
1763
- if (!this._worker) {
1816
+ if (!this._worker || this._worker.isTerminated()) {
1764
1817
  this._worker = createPeaksWorker();
1765
1818
  }
1766
1819
  const channels = [];
@@ -2747,6 +2800,15 @@ import {
2747
2800
  var RecordingController = class {
2748
2801
  constructor(host) {
2749
2802
  this._sessions = /* @__PURE__ */ new Map();
2803
+ /** Track IDs with a startRecording in flight (session not yet in _sessions).
2804
+ * The session is only set after several awaits — without this, two rapid
2805
+ * start calls both pass the _sessions guard and build two capture
2806
+ * pipelines feeding one session (garbled audio + a leaked worklet). */
2807
+ this._starting = /* @__PURE__ */ new Map();
2808
+ /** True between hostDisconnected and hostConnected. An in-flight
2809
+ * startRecording consults this after its awaits so a teardown mid-setup
2810
+ * doesn't leak a live capture session on a detached editor. */
2811
+ this._hostDisconnected = false;
2750
2812
  this._workletLoadedCtx = null;
2751
2813
  /** Tracks worklet pause state explicitly so external consumers (editor,
2752
2814
  * pause button, spacebar) can share one source of truth. */
@@ -2755,15 +2817,17 @@ var RecordingController = class {
2755
2817
  host.addController(this);
2756
2818
  }
2757
2819
  hostConnected() {
2820
+ this._hostDisconnected = false;
2758
2821
  }
2759
2822
  hostDisconnected() {
2823
+ this._hostDisconnected = true;
2760
2824
  for (const trackId of [...this._sessions.keys()]) {
2761
- this._cleanupSession(trackId);
2825
+ this._cleanupSession(trackId, true);
2762
2826
  }
2763
2827
  this._workletLoadedCtx = null;
2764
2828
  }
2765
2829
  get isRecording() {
2766
- return this._sessions.size > 0;
2830
+ return this._sessions.size > 0 || this._starting.size > 0;
2767
2831
  }
2768
2832
  get isPaused() {
2769
2833
  return this._isPaused && this._sessions.size > 0;
@@ -2777,14 +2841,25 @@ var RecordingController = class {
2777
2841
  console.warn("[dawcore] RecordingController: No track selected for recording");
2778
2842
  return;
2779
2843
  }
2780
- if (this._sessions.has(trackId)) {
2844
+ if (this._sessions.has(trackId) || this._starting.has(trackId)) {
2781
2845
  console.warn('[dawcore] RecordingController: Already recording on track "' + trackId + '"');
2782
2846
  return;
2783
2847
  }
2848
+ let resolveStartSettled;
2849
+ const startEntry = {
2850
+ stopRequested: false,
2851
+ done: new Promise((resolve) => {
2852
+ resolveStartSettled = resolve;
2853
+ })
2854
+ };
2855
+ this._starting.set(trackId, startEntry);
2784
2856
  const bits = options.bits ?? 16;
2785
2857
  try {
2786
2858
  const rawCtx = this._host.audioContext;
2787
2859
  this._host.resolveAudioContextSampleRate(rawCtx.sampleRate);
2860
+ if (rawCtx.state === "suspended") {
2861
+ await rawCtx.resume();
2862
+ }
2788
2863
  if (!this._workletLoadedCtx || this._workletLoadedCtx !== rawCtx) {
2789
2864
  let addRecordingWorkletModule;
2790
2865
  try {
@@ -2798,6 +2873,15 @@ var RecordingController = class {
2798
2873
  await addRecordingWorkletModule(addModule);
2799
2874
  this._workletLoadedCtx = rawCtx;
2800
2875
  }
2876
+ if (startEntry.stopRequested || this._hostDisconnected) {
2877
+ this._dispatchRecordingError(
2878
+ trackId,
2879
+ new Error(
2880
+ this._hostDisconnected ? "Recording start cancelled: editor was disconnected during setup" : "Recording start cancelled: stop requested before setup completed"
2881
+ )
2882
+ );
2883
+ return;
2884
+ }
2801
2885
  const detectedChannelCount = stream.getAudioTracks()[0]?.getSettings()?.channelCount;
2802
2886
  if (detectedChannelCount === void 0 && options.channelCount !== void 0) {
2803
2887
  console.warn(
@@ -2805,7 +2889,7 @@ var RecordingController = class {
2805
2889
  );
2806
2890
  }
2807
2891
  const channelCount = detectedChannelCount ?? options.channelCount ?? 1;
2808
- const startSample = options.startSample ?? Math.floor(this._host._currentTime * this._host.effectiveSampleRate);
2892
+ const startSample = options.startSample ?? Math.floor(this._host.currentTime * this._host.effectiveSampleRate);
2809
2893
  const latencySamples = resolveRecordingOffsetSamples({
2810
2894
  overrideSeconds: options.latencyOffset,
2811
2895
  outputLatency: rawCtx.outputLatency ?? 0,
@@ -2839,13 +2923,17 @@ var RecordingController = class {
2839
2923
  ),
2840
2924
  startSample,
2841
2925
  channelCount,
2926
+ captureSampleRate: rawCtx.sampleRate,
2842
2927
  bits,
2843
2928
  isFirstMessage: true,
2844
2929
  latencySamples,
2930
+ clipName: options.clipName,
2931
+ armedPrevMuted: null,
2845
2932
  wasOverdub: options.overdub ?? false,
2846
2933
  _onTrackEnded: onTrackEnded,
2847
2934
  _audioTrack: audioTrack,
2848
2935
  stopAckResolve: null,
2936
+ stopPromise: null,
2849
2937
  stopping: false
2850
2938
  };
2851
2939
  this._sessions.set(trackId, session);
@@ -2857,6 +2945,11 @@ var RecordingController = class {
2857
2945
  if (audioTrack && onTrackEnded) {
2858
2946
  audioTrack.addEventListener("ended", onTrackEnded);
2859
2947
  }
2948
+ const engine = this._host._engine;
2949
+ if (engine) {
2950
+ session.armedPrevMuted = engine.getState().tracks.find((t) => t.id === trackId)?.muted ?? false;
2951
+ engine.setTrackMute(trackId, true);
2952
+ }
2860
2953
  this._host.dispatchEvent(
2861
2954
  new CustomEvent("daw-recording-start", {
2862
2955
  bubbles: true,
@@ -2866,18 +2959,15 @@ var RecordingController = class {
2866
2959
  );
2867
2960
  this._host.requestUpdate();
2868
2961
  if (options.overdub && typeof this._host.play === "function") {
2869
- await this._host.play(this._host._currentTime);
2962
+ await this._host.play(this._host.currentTime);
2870
2963
  }
2871
2964
  } catch (err) {
2872
2965
  this._cleanupSession(trackId);
2873
2966
  console.warn("[dawcore] RecordingController: Failed to start recording: " + String(err));
2874
- this._host.dispatchEvent(
2875
- new CustomEvent("daw-recording-error", {
2876
- bubbles: true,
2877
- composed: true,
2878
- detail: { trackId, error: err }
2879
- })
2880
- );
2967
+ this._dispatchRecordingError(trackId, err);
2968
+ } finally {
2969
+ this._starting.delete(trackId);
2970
+ resolveStartSettled();
2881
2971
  }
2882
2972
  }
2883
2973
  pauseRecording(trackId) {
@@ -2911,18 +3001,47 @@ var RecordingController = class {
2911
3001
  );
2912
3002
  }
2913
3003
  async stopRecording(trackId) {
2914
- const id = trackId ?? [...this._sessions.keys()][0];
3004
+ const id = trackId ?? [...this._sessions.keys()][0] ?? [...this._starting.keys()][0];
2915
3005
  if (!id) return;
2916
3006
  const session = this._sessions.get(id);
2917
- if (!session) return;
3007
+ if (!session) {
3008
+ const starting = this._starting.get(id);
3009
+ if (starting) {
3010
+ starting.stopRequested = true;
3011
+ return starting.done;
3012
+ }
3013
+ return;
3014
+ }
3015
+ if (session.stopping) {
3016
+ return session.stopPromise ?? void 0;
3017
+ }
3018
+ session.stopping = true;
3019
+ const stopPromise = this._finishStopRecording(id, session);
3020
+ session.stopPromise = stopPromise;
3021
+ return stopPromise;
3022
+ }
3023
+ async _finishStopRecording(id, session) {
3024
+ try {
3025
+ await this._finalizeRecording(id, session);
3026
+ } catch (err) {
3027
+ const sessionWasActive = this._sessions.has(id);
3028
+ console.warn("[dawcore] RecordingController: Failed to finalize recording: " + String(err));
3029
+ this._cleanupSession(id);
3030
+ this._host.requestUpdate();
3031
+ if (sessionWasActive) {
3032
+ this._dispatchRecordingError(id, err);
3033
+ }
3034
+ }
3035
+ }
3036
+ async _finalizeRecording(id, session) {
2918
3037
  const wasPaused = this._isPaused;
2919
3038
  this._isPaused = false;
2920
- session.stopping = true;
2921
3039
  if (session.wasOverdub && typeof this._host.stop === "function") {
2922
3040
  this._host.stop();
2923
3041
  }
2924
3042
  if (wasPaused) {
2925
3043
  session.workletNode.port.postMessage({ command: "stop" });
3044
+ await this._drainWorkletQueue(session);
2926
3045
  } else {
2927
3046
  const stopAck = new Promise((resolve) => {
2928
3047
  session.stopAckResolve = resolve;
@@ -2935,32 +3054,13 @@ var RecordingController = class {
2935
3054
  await Promise.race([stopAck, timeout]);
2936
3055
  clearTimeout(timeoutId);
2937
3056
  session.stopAckResolve = null;
2938
- let lastSamples = -1;
2939
- let stable = 0;
2940
- for (let i = 0; i < 50; i++) {
2941
- if (session.totalSamples === lastSamples) {
2942
- if (++stable >= 3) break;
2943
- } else {
2944
- stable = 0;
2945
- lastSamples = session.totalSamples;
2946
- }
2947
- await new Promise((r) => setTimeout(r, 5));
2948
- }
3057
+ await this._drainWorkletQueue(session);
2949
3058
  }
2950
3059
  session.source.disconnect();
2951
3060
  session.workletNode.disconnect();
2952
3061
  this._removeTrackEndedListener(session);
2953
3062
  if (session.totalSamples === 0) {
2954
- console.warn("[dawcore] RecordingController: No audio data captured");
2955
- this._sessions.delete(id);
2956
- this._host.requestUpdate();
2957
- this._host.dispatchEvent(
2958
- new CustomEvent("daw-recording-error", {
2959
- bubbles: true,
2960
- composed: true,
2961
- detail: { trackId: id, error: new Error("No audio data captured") }
2962
- })
2963
- );
3063
+ this._abandonFinalize(id, session, "No audio data captured");
2964
3064
  return;
2965
3065
  }
2966
3066
  const stopCtx = this._host.audioContext;
@@ -2968,21 +3068,17 @@ var RecordingController = class {
2968
3068
  const audioBuffer = createAudioBuffer(
2969
3069
  stopCtx,
2970
3070
  channelData,
2971
- this._host.effectiveSampleRate,
3071
+ session.captureSampleRate,
2972
3072
  session.channelCount
2973
3073
  );
2974
3074
  const latencyOffsetSamples = session.latencySamples;
2975
3075
  const effectiveDuration = Math.max(0, audioBuffer.length - latencyOffsetSamples);
2976
3076
  if (effectiveDuration === 0) {
2977
- console.warn("[dawcore] RecordingController: Recording too short for latency compensation");
2978
- this._sessions.delete(id);
2979
- this._host.requestUpdate();
2980
- this._host.dispatchEvent(
2981
- new CustomEvent("daw-recording-error", {
2982
- bubbles: true,
2983
- composed: true,
2984
- detail: { trackId: id, error: new Error("Recording too short to save") }
2985
- })
3077
+ this._abandonFinalize(
3078
+ id,
3079
+ session,
3080
+ "Recording too short for latency compensation",
3081
+ "Recording too short to save"
2986
3082
  );
2987
3083
  return;
2988
3084
  }
@@ -2999,6 +3095,7 @@ var RecordingController = class {
2999
3095
  }
3000
3096
  });
3001
3097
  const notPrevented = this._host.dispatchEvent(event);
3098
+ this._restoreArmedTrackMute(session);
3002
3099
  this._sessions.delete(id);
3003
3100
  this._host.requestUpdate();
3004
3101
  if (notPrevented) {
@@ -3007,10 +3104,29 @@ var RecordingController = class {
3007
3104
  audioBuffer,
3008
3105
  session.startSample,
3009
3106
  effectiveDuration,
3010
- latencyOffsetSamples
3107
+ latencyOffsetSamples,
3108
+ session.clipName
3011
3109
  );
3012
3110
  }
3013
3111
  }
3112
+ /** Drain the event-loop queue of pending worklet flush messages. During
3113
+ * recording the worklet posts a flush every ~16ms; if main was slower,
3114
+ * messages back up. Yield repeatedly until session.totalSamples stabilizes
3115
+ * (no new messages processed) for several consecutive ticks — at that
3116
+ * point the queue is empty and chunks are complete. */
3117
+ async _drainWorkletQueue(session) {
3118
+ let lastSamples = -1;
3119
+ let stable = 0;
3120
+ for (let i = 0; i < 50; i++) {
3121
+ if (session.totalSamples === lastSamples) {
3122
+ if (++stable >= 3) break;
3123
+ } else {
3124
+ stable = 0;
3125
+ lastSamples = session.totalSamples;
3126
+ }
3127
+ await new Promise((r) => setTimeout(r, 5));
3128
+ }
3129
+ }
3014
3130
  // Session fields are mutated in place on the hot path (~60fps worklet messages).
3015
3131
  // This is intentional — creating new session objects + Map entries per message
3016
3132
  // would cause significant GC pressure. Mutations are confined to the controller's
@@ -3046,7 +3162,10 @@ var RecordingController = class {
3046
3162
  session.peaks[ch] = appendPeaks(
3047
3163
  session.peaks[ch],
3048
3164
  channels[ch],
3049
- this._host.samplesPerPixel,
3165
+ // Render-space scale — in beats mode this differs from
3166
+ // samplesPerPixel, and the preview container is laid out in
3167
+ // render space (see RecordingHost.renderSamplesPerPixel).
3168
+ this._host.renderSamplesPerPixel,
3050
3169
  samplesProcessedBefore,
3051
3170
  session.bits
3052
3171
  );
@@ -3065,22 +3184,23 @@ var RecordingController = class {
3065
3184
  }
3066
3185
  }
3067
3186
  session.isFirstMessage = false;
3068
- const newPixelWidth = Math.floor(session.totalSamples / this._host.samplesPerPixel);
3187
+ const newPixelWidth = Math.floor(session.totalSamples / this._host.renderSamplesPerPixel);
3069
3188
  const oldPixelWidth = Math.floor(
3070
- (session.totalSamples - channels[0].length) / this._host.samplesPerPixel
3189
+ (session.totalSamples - channels[0].length) / this._host.renderSamplesPerPixel
3071
3190
  );
3072
3191
  if (newPixelWidth > oldPixelWidth) {
3073
3192
  this._host.requestUpdate();
3074
3193
  }
3075
3194
  }
3076
- _createClipFromRecording(trackId, audioBuffer, startSample, durationSamples, offsetSamples = 0) {
3195
+ _createClipFromRecording(trackId, audioBuffer, startSample, durationSamples, offsetSamples = 0, clipName) {
3077
3196
  if (typeof this._host._addRecordedClip === "function") {
3078
3197
  this._host._addRecordedClip(
3079
3198
  trackId,
3080
3199
  audioBuffer,
3081
3200
  startSample,
3082
3201
  durationSamples,
3083
- offsetSamples
3202
+ offsetSamples,
3203
+ clipName
3084
3204
  );
3085
3205
  } else {
3086
3206
  console.warn(
@@ -3093,10 +3213,41 @@ var RecordingController = class {
3093
3213
  session._audioTrack.removeEventListener("ended", session._onTrackEnded);
3094
3214
  }
3095
3215
  }
3096
- _cleanupSession(trackId) {
3216
+ _dispatchRecordingError(trackId, error) {
3217
+ this._host.dispatchEvent(
3218
+ new CustomEvent("daw-recording-error", {
3219
+ bubbles: true,
3220
+ composed: true,
3221
+ detail: { trackId, error }
3222
+ })
3223
+ );
3224
+ }
3225
+ /** Shared teardown for finalize paths that end without a take (no data
3226
+ * captured / too short after latency compensation): restore the armed-track
3227
+ * mute, drop the session, and notify via daw-recording-error so record
3228
+ * buttons reset their state. */
3229
+ _abandonFinalize(id, session, warnMessage, errorMessage = warnMessage) {
3230
+ console.warn("[dawcore] RecordingController: " + warnMessage);
3231
+ this._restoreArmedTrackMute(session);
3232
+ this._sessions.delete(id);
3233
+ this._host.requestUpdate();
3234
+ this._dispatchRecordingError(id, new Error(errorMessage));
3235
+ }
3236
+ /** Restore the armed track's pre-session mute state (idempotent — safe to
3237
+ * call from both the finalize path and _cleanupSession). */
3238
+ _restoreArmedTrackMute(session) {
3239
+ if (session.armedPrevMuted === null) return;
3240
+ this._host._engine?.setTrackMute(session.trackId, session.armedPrevMuted);
3241
+ session.armedPrevMuted = null;
3242
+ }
3243
+ /** @param notifyError dispatch daw-recording-error after cleanup — used by
3244
+ * disposal paths that would otherwise discard the session silently. The
3245
+ * startRecording catch path passes false (it dispatches its own error). */
3246
+ _cleanupSession(trackId, notifyError = false) {
3097
3247
  const session = this._sessions.get(trackId);
3098
3248
  if (!session) return;
3099
3249
  try {
3250
+ this._restoreArmedTrackMute(session);
3100
3251
  this._removeTrackEndedListener(session);
3101
3252
  session.workletNode.port.postMessage({ command: "stop" });
3102
3253
  session.source.disconnect();
@@ -3107,6 +3258,15 @@ var RecordingController = class {
3107
3258
  );
3108
3259
  }
3109
3260
  this._sessions.delete(trackId);
3261
+ if (this._sessions.size === 0) {
3262
+ this._isPaused = false;
3263
+ }
3264
+ if (notifyError) {
3265
+ this._dispatchRecordingError(
3266
+ trackId,
3267
+ new Error("Recording cancelled: editor was disconnected mid-recording")
3268
+ );
3269
+ }
3110
3270
  }
3111
3271
  };
3112
3272
 
@@ -3251,6 +3411,14 @@ var PointerHandler = class {
3251
3411
  this._timeline = null;
3252
3412
  // Cached from onPointerDown to avoid forced layout reflows at 60fps during drag
3253
3413
  this._timelineRect = null;
3414
+ /** Pointer that started the current interaction — a pointercancel from any
3415
+ * OTHER pointer (palm rejection on touch) must not kill the active drag. */
3416
+ this._activePointerId = null;
3417
+ // Selection values at pointerdown — restored on cancel so an interrupted
3418
+ // drag doesn't destroy a previously committed selection (which the engine
3419
+ // still holds; zeroing only the host would desync the two).
3420
+ this._preDragSelectionStart = 0;
3421
+ this._preDragSelectionEnd = 0;
3254
3422
  this.onPointerDown = (e) => {
3255
3423
  const clipHandler = this._host._clipHandler;
3256
3424
  if (clipHandler) {
@@ -3265,12 +3433,12 @@ var PointerHandler = class {
3265
3433
  console.warn("[dawcore] setPointerCapture failed: " + String(err));
3266
3434
  }
3267
3435
  const onMove = (me) => clipHandler.onPointerMove(me);
3268
- const onUp = (ue) => {
3269
- clipHandler.onPointerUp(ue);
3436
+ const detach = (pe) => {
3270
3437
  this._timeline?.removeEventListener("pointermove", onMove);
3271
3438
  this._timeline?.removeEventListener("pointerup", onUp);
3439
+ this._timeline?.removeEventListener("pointercancel", onCancel);
3272
3440
  try {
3273
- this._timeline?.releasePointerCapture(ue.pointerId);
3441
+ this._timeline?.releasePointerCapture(pe.pointerId);
3274
3442
  } catch (err) {
3275
3443
  console.warn(
3276
3444
  "[dawcore] releasePointerCapture failed (may already be released): " + String(err)
@@ -3278,8 +3446,19 @@ var PointerHandler = class {
3278
3446
  }
3279
3447
  this._timeline = null;
3280
3448
  };
3449
+ const onUp = (ue) => {
3450
+ clipHandler.onPointerUp(ue);
3451
+ detach(ue);
3452
+ };
3453
+ const downPointerId = e.pointerId;
3454
+ const onCancel = (ce) => {
3455
+ if (ce.pointerId !== downPointerId) return;
3456
+ clipHandler.onPointerCancel(ce);
3457
+ detach(ce);
3458
+ };
3281
3459
  this._timeline.addEventListener("pointermove", onMove);
3282
3460
  this._timeline.addEventListener("pointerup", onUp);
3461
+ this._timeline.addEventListener("pointercancel", onCancel);
3283
3462
  }
3284
3463
  return;
3285
3464
  }
@@ -3294,6 +3473,9 @@ var PointerHandler = class {
3294
3473
  this._timelineRect = this._timeline.getBoundingClientRect();
3295
3474
  this._dragStartPx = this._pxFromPointer(e);
3296
3475
  this._isDragging = false;
3476
+ this._activePointerId = e.pointerId;
3477
+ this._preDragSelectionStart = this._host._selectionStartTime;
3478
+ this._preDragSelectionEnd = this._host._selectionEndTime;
3297
3479
  try {
3298
3480
  this._timeline.setPointerCapture(e.pointerId);
3299
3481
  } catch (err) {
@@ -3301,6 +3483,7 @@ var PointerHandler = class {
3301
3483
  }
3302
3484
  this._timeline.addEventListener("pointermove", this._onPointerMove);
3303
3485
  this._timeline.addEventListener("pointerup", this._onPointerUp);
3486
+ this._timeline.addEventListener("pointercancel", this._onPointerCancel);
3304
3487
  };
3305
3488
  this._onPointerMove = (e) => {
3306
3489
  if (!this._timeline) return;
@@ -3324,15 +3507,7 @@ var PointerHandler = class {
3324
3507
  };
3325
3508
  this._onPointerUp = (e) => {
3326
3509
  if (!this._timeline) return;
3327
- try {
3328
- this._timeline.releasePointerCapture(e.pointerId);
3329
- } catch (err) {
3330
- console.warn(
3331
- "[dawcore] releasePointerCapture failed (may already be released): " + String(err)
3332
- );
3333
- }
3334
- this._timeline.removeEventListener("pointermove", this._onPointerMove);
3335
- this._timeline.removeEventListener("pointerup", this._onPointerUp);
3510
+ this._detachTimeline(e);
3336
3511
  try {
3337
3512
  if (this._isDragging) {
3338
3513
  this._finalizeSelection();
@@ -3342,10 +3517,29 @@ var PointerHandler = class {
3342
3517
  } catch (err) {
3343
3518
  console.warn("[dawcore] Pointer interaction failed: " + String(err));
3344
3519
  } finally {
3345
- this._isDragging = false;
3346
- this._timeline = null;
3347
- this._timelineRect = null;
3520
+ this._resetInteractionState();
3521
+ }
3522
+ };
3523
+ /** pointercancel fires INSTEAD of pointerup on touch interruption / pen
3524
+ * leaving range / OS gestures — discard the interaction (no seek, no
3525
+ * selection finalize) and detach the drag listeners, or the still-attached
3526
+ * move handler keeps mutating the selection on hover with a stale rect. */
3527
+ this._onPointerCancel = (e) => {
3528
+ if (!this._timeline) return;
3529
+ if (e.pointerId !== this._activePointerId) return;
3530
+ this._detachTimeline(e);
3531
+ if (this._isDragging) {
3532
+ const h = this._host;
3533
+ h._selectionStartTime = this._preDragSelectionStart;
3534
+ h._selectionEndTime = this._preDragSelectionEnd;
3535
+ const sel = h.shadowRoot?.querySelector("daw-selection");
3536
+ if (sel) {
3537
+ sel.startPx = this._timeToPx(this._preDragSelectionStart);
3538
+ sel.endPx = this._timeToPx(this._preDragSelectionEnd);
3539
+ }
3540
+ h.requestUpdate();
3348
3541
  }
3542
+ this._resetInteractionState();
3349
3543
  };
3350
3544
  this._host = host;
3351
3545
  }
@@ -3373,6 +3567,28 @@ var PointerHandler = class {
3373
3567
  }
3374
3568
  return time * h.effectiveSampleRate / h.samplesPerPixel;
3375
3569
  }
3570
+ /** Detach the drag listeners and release capture — shared by the up and
3571
+ * cancel terminals so a new listener added to onPointerDown can't be
3572
+ * missed on one of them. */
3573
+ _detachTimeline(e) {
3574
+ if (!this._timeline) return;
3575
+ try {
3576
+ this._timeline.releasePointerCapture(e.pointerId);
3577
+ } catch (err) {
3578
+ console.warn(
3579
+ "[dawcore] releasePointerCapture failed (may already be released): " + String(err)
3580
+ );
3581
+ }
3582
+ this._timeline.removeEventListener("pointermove", this._onPointerMove);
3583
+ this._timeline.removeEventListener("pointerup", this._onPointerUp);
3584
+ this._timeline.removeEventListener("pointercancel", this._onPointerCancel);
3585
+ }
3586
+ _resetInteractionState() {
3587
+ this._isDragging = false;
3588
+ this._timeline = null;
3589
+ this._timelineRect = null;
3590
+ this._activePointerId = null;
3591
+ }
3376
3592
  _finalizeSelection() {
3377
3593
  const h = this._host;
3378
3594
  if (h._engine) {
@@ -3708,6 +3924,23 @@ var ClipPointerHandler = class {
3708
3924
  this._reset();
3709
3925
  }
3710
3926
  }
3927
+ /** Processes pointercancel — reverts the in-progress drag.
3928
+ *
3929
+ * pointercancel fires INSTEAD of pointerup on touch interruption, pen
3930
+ * leaving hover range, or OS gestures. Without this handler the drag stays
3931
+ * armed (hover keeps moving the clip), the engine transaction stays open
3932
+ * (every later edit becomes un-undoable until some drag commits), and the
3933
+ * per-frame skipAdapter moveClip mutations are never synced or rolled back
3934
+ * (waveform and audio permanently disagree). */
3935
+ onPointerCancel(_e) {
3936
+ if (this._mode === null) return;
3937
+ try {
3938
+ this._restoreTrimVisual();
3939
+ } finally {
3940
+ this._host.engine?.abortTransaction();
3941
+ this._reset();
3942
+ }
3943
+ }
3711
3944
  /** Re-extract peaks from cache and set on waveform elements during trim drag.
3712
3945
  * Returns true if peaks were successfully updated. */
3713
3946
  _updateWaveformPeaks(offsetSamples, durationSamples) {
@@ -3725,7 +3958,11 @@ var ClipPointerHandler = class {
3725
3958
  }
3726
3959
  return true;
3727
3960
  }
3728
- /** Restore clip container CSS to original values after trim visual preview. */
3961
+ /** Restore clip container CSS AND waveform peaks to original values after
3962
+ * a trim visual preview. Peaks matter: the drag wrote re-extracted peak
3963
+ * arrays imperatively onto the <daw-waveform> elements (bypassing Lit), and
3964
+ * a cancelled/zero-delta trim makes no engine mutation — so no statechange
3965
+ * re-render will ever repair them. */
3729
3966
  _restoreTrimVisual() {
3730
3967
  if (this._clipContainer) {
3731
3968
  this._clipContainer.style.left = this._originalLeft + "px";
@@ -3734,6 +3971,7 @@ var ClipPointerHandler = class {
3734
3971
  for (const wf of waveforms) {
3735
3972
  wf.style.left = "0px";
3736
3973
  }
3974
+ this._updateWaveformPeaks(this._originalOffsetSamples, this._originalDurationSamples);
3737
3975
  }
3738
3976
  }
3739
3977
  _reset() {
@@ -3819,8 +4057,18 @@ async function loadFiles(host, files) {
3819
4057
  const failed = [];
3820
4058
  for (const file of fileArray) {
3821
4059
  if (file.type && !file.type.startsWith("audio/")) {
3822
- failed.push({ file, error: new Error("Non-audio MIME type: " + file.type) });
4060
+ const error = new Error("Non-audio MIME type: " + file.type);
4061
+ failed.push({ file, error });
3823
4062
  console.warn("[dawcore] Skipping non-audio file: " + file.name + " (" + file.type + ")");
4063
+ if (host.isConnected) {
4064
+ host.dispatchEvent(
4065
+ new CustomEvent("daw-files-load-error", {
4066
+ bubbles: true,
4067
+ composed: true,
4068
+ detail: { file, error }
4069
+ })
4070
+ );
4071
+ }
3824
4072
  continue;
3825
4073
  }
3826
4074
  const blobUrl = URL.createObjectURL(file);
@@ -4016,8 +4264,8 @@ function stringifyReason(reason) {
4016
4264
  }
4017
4265
 
4018
4266
  // src/interactions/recording-clip.ts
4019
- import { createClip as createClip2 } from "@waveform-playlist/core";
4020
- function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamples = 0) {
4267
+ import { carveClipRange, createClip as createClip2 } from "@waveform-playlist/core";
4268
+ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamples = 0, clipName) {
4021
4269
  let trimmedBuf = buf;
4022
4270
  if (offsetSamples > 0 && offsetSamples < buf.length) {
4023
4271
  const trimmed = new AudioBuffer({
@@ -4038,21 +4286,27 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
4038
4286
  offsetSamples: 0,
4039
4287
  // offset already applied by slicing
4040
4288
  gain: 1,
4041
- name: "Recording"
4289
+ name: clipName ?? "Recording"
4042
4290
  });
4043
4291
  host._clipBuffers = new Map(host._clipBuffers).set(clip.id, trimmedBuf);
4044
- host._peakPipeline.generatePeaks(trimmedBuf, host.samplesPerPixel, host.mono).then((pd) => {
4045
- host._peaksData = new Map(host._peaksData).set(clip.id, pd);
4292
+ host._clipOffsets.set(clip.id, { offsetSamples: 0, durationSamples: durSamples });
4293
+ host._peakPipeline.generatePeaks(trimmedBuf, host.renderSamplesPerPixel, host.mono).then((pd) => {
4046
4294
  const t = host._engineTracks.get(trackId);
4047
4295
  if (!t) {
4048
4296
  const next = new Map(host._clipBuffers);
4049
4297
  next.delete(clip.id);
4050
4298
  host._clipBuffers = next;
4299
+ host._clipOffsets.delete(clip.id);
4051
4300
  return;
4052
4301
  }
4302
+ host._peaksData = new Map(host._peaksData).set(clip.id, pd);
4303
+ host._raiseZoomFloor(host._peakPipeline.getCachedScale(trimmedBuf));
4053
4304
  host._engineTracks = new Map(host._engineTracks).set(trackId, {
4054
4305
  ...t,
4055
- clips: [...t.clips, clip]
4306
+ // Punch-in replace (#579): the recorded clip owns [startSample,
4307
+ // startSample + durSamples) — carve overlapped content out of the
4308
+ // existing clips before inserting (parity with the React provider).
4309
+ clips: [...carveClipRange(t.clips, startSample, startSample + durSamples), clip]
4056
4310
  });
4057
4311
  const desc = host._tracks.get(trackId);
4058
4312
  if (desc) {
@@ -4065,7 +4319,7 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
4065
4319
  duration: durSamples / sr,
4066
4320
  offset: 0,
4067
4321
  gain: 1,
4068
- name: "Recording",
4322
+ name: clipName ?? "Recording",
4069
4323
  fadeIn: 0,
4070
4324
  fadeOut: 0,
4071
4325
  fadeType: "linear",
@@ -4090,6 +4344,7 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
4090
4344
  const next = new Map(host._clipBuffers);
4091
4345
  next.delete(clip.id);
4092
4346
  host._clipBuffers = next;
4347
+ host._clipOffsets.delete(clip.id);
4093
4348
  if (host.isConnected) {
4094
4349
  host.dispatchEvent(
4095
4350
  new CustomEvent("daw-error", {
@@ -4314,7 +4569,10 @@ var EffectsChainController = class {
4314
4569
  kind: "wam",
4315
4570
  ...sourceFields,
4316
4571
  bypassed: entry.placeholder.bypassed,
4317
- ...entry.placeholder.state !== void 0 ? { state: entry.placeholder.state } : {}
4572
+ ...entry.placeholder.state !== void 0 ? { state: entry.placeholder.state } : {},
4573
+ // Lets offline export skip this entry (live playback silently
4574
+ // skips it too); restore ignores the flag and retries.
4575
+ placeholder: true
4318
4576
  };
4319
4577
  }
4320
4578
  let state8;
@@ -4332,6 +4590,15 @@ var EffectsChainController = class {
4332
4590
  ...state8 !== void 0 ? { state: state8 } : {}
4333
4591
  };
4334
4592
  }
4593
+ if (entry.placeholder) {
4594
+ return {
4595
+ kind: "native",
4596
+ type: entry.type,
4597
+ params: { ...entry.params },
4598
+ bypassed: entry.placeholder.bypassed,
4599
+ placeholder: true
4600
+ };
4601
+ }
4335
4602
  return {
4336
4603
  kind: "native",
4337
4604
  type: entry.type,
@@ -4370,13 +4637,17 @@ var EffectsChainController = class {
4370
4637
  entry.instance.dispose?.();
4371
4638
  this._rebuild();
4372
4639
  }
4640
+ /** Returns the index the entry actually landed at (the requested index is
4641
+ * clamped to the chain bounds), or -1 for an unknown effectId — event
4642
+ * dispatchers must report the actual index, not the raw request. */
4373
4643
  move(effectId, newIndex) {
4374
4644
  const entry = this._find("move", effectId);
4375
- if (!entry) return;
4645
+ if (!entry) return -1;
4376
4646
  const without = this._entries.filter((e) => e.id !== effectId);
4377
4647
  const at = Math.max(0, Math.min(newIndex, without.length));
4378
4648
  this._entries = [...without.slice(0, at), entry, ...without.slice(at)];
4379
4649
  this._rebuild();
4650
+ return at;
4380
4651
  }
4381
4652
  setParams(effectId, params) {
4382
4653
  const entry = this._find("setParams", effectId);
@@ -4600,10 +4871,11 @@ registerBuiltIns();
4600
4871
 
4601
4872
  // src/effects/effects-manager.ts
4602
4873
  var PREFIX2 = "[waveform-playlist] ";
4603
- function makeGuiRecord(element, destroyImpl) {
4874
+ function makeGuiRecord(element, destroyImpl, isFallback = false) {
4604
4875
  let destroyed = false;
4605
4876
  return {
4606
4877
  element,
4878
+ isFallback,
4607
4879
  destroy: () => {
4608
4880
  if (destroyed) return;
4609
4881
  destroyed = true;
@@ -4782,7 +5054,7 @@ var EffectsManager = class {
4782
5054
  );
4783
5055
  }
4784
5056
  const cached = this._guis.get(effectId);
4785
- if (cached) {
5057
+ if (cached && !cached.isFallback) {
4786
5058
  container.appendChild(cached.element);
4787
5059
  return cached.element;
4788
5060
  }
@@ -4793,7 +5065,22 @@ var EffectsManager = class {
4793
5065
  });
4794
5066
  this._guiPending.set(effectId, pending);
4795
5067
  }
4796
- const record = await pending;
5068
+ let record;
5069
+ try {
5070
+ record = await pending;
5071
+ } catch (err) {
5072
+ if (cached) {
5073
+ console.warn(
5074
+ PREFIX2 + 'openEffectGui: rebuilding the parameter panel for "' + effectId + '" failed \u2014 serving the cached panel (values may be stale): ' + String(err)
5075
+ );
5076
+ container.appendChild(cached.element);
5077
+ return cached.element;
5078
+ }
5079
+ throw err;
5080
+ }
5081
+ if (cached && cached !== record) {
5082
+ cached.element.remove();
5083
+ }
4797
5084
  if (chain.disposed || !chain.getEntry(effectId)) {
4798
5085
  this._guis.delete(effectId);
4799
5086
  record.element.remove();
@@ -4828,7 +5115,7 @@ var EffectsManager = class {
4828
5115
  }
4829
5116
  const element = await this._createFallbackPanel(chain, target, entry, effectId);
4830
5117
  return makeGuiRecord(element, () => {
4831
- });
5118
+ }, true);
4832
5119
  }
4833
5120
  /** The generic parameter panel — one code path for "no custom GUI":
4834
5121
  * native entries render from the registry's params metadata, WAM entries
@@ -5071,9 +5358,23 @@ var EffectsManager = class {
5071
5358
  for (const entry of entries) {
5072
5359
  if (superseded()) return;
5073
5360
  if (entry.kind === "native") {
5074
- const id = this._addToChain(chain, target, entry.type, entry.params);
5075
- if (entry.bypassed) {
5076
- this._runOp(chain, target, "setBypassed", id, true);
5361
+ try {
5362
+ const id = this._addToChain(chain, target, entry.type, entry.params);
5363
+ if (entry.bypassed) {
5364
+ this._runOp(chain, target, "setBypassed", id, true);
5365
+ }
5366
+ } catch (err) {
5367
+ if (superseded() || chain.disposed) return;
5368
+ const message = err instanceof Error ? err.message : String(err);
5369
+ console.warn(
5370
+ PREFIX2 + 'setEffectsState: native effect "' + entry.type + '" failed to restore: ' + message
5371
+ );
5372
+ const effectId = this._addNativePlaceholder(chain, entry, message);
5373
+ this._dispatch(target, "daw-effect-error", {
5374
+ effectId,
5375
+ type: entry.type,
5376
+ message
5377
+ });
5077
5378
  }
5078
5379
  continue;
5079
5380
  }
@@ -5090,7 +5391,7 @@ var EffectsManager = class {
5090
5391
  this._runOp(chain, target, "setBypassed", id, true);
5091
5392
  }
5092
5393
  } catch (err) {
5093
- if (superseded()) return;
5394
+ if (superseded() || chain.disposed) return;
5094
5395
  const message = err instanceof Error ? err.message : String(err);
5095
5396
  const sourceLabel = entry.url ?? entry.faustName ?? "Faust effect";
5096
5397
  console.warn(
@@ -5106,6 +5407,25 @@ var EffectsManager = class {
5106
5407
  }
5107
5408
  }
5108
5409
  }
5410
+ /** A silent passthrough occupying a failed NATIVE entry's chain position.
5411
+ * Carries the saved params/bypassed so the snapshot round-trips (serialize
5412
+ * re-emits them with `placeholder: true`). */
5413
+ _addNativePlaceholder(chain, entry, message) {
5414
+ const { audioContext } = this._requireWiring();
5415
+ const node = audioContext.createGain();
5416
+ const effectId = chain.add({
5417
+ kind: "native",
5418
+ type: entry.type,
5419
+ label: entry.type,
5420
+ error: message,
5421
+ placeholder: { bypassed: entry.bypassed },
5422
+ instance: { input: node, output: node, applyParams: () => {
5423
+ } },
5424
+ params: { ...entry.params }
5425
+ });
5426
+ chain.setBypassed(effectId, true);
5427
+ return effectId;
5428
+ }
5109
5429
  /** A silent passthrough occupying the failed plugin's chain position. */
5110
5430
  _addWamPlaceholder(chain, entry, message) {
5111
5431
  const { audioContext } = this._requireWiring();
@@ -5152,10 +5472,11 @@ var EffectsManager = class {
5152
5472
  chain.setBypassed(effectId, arg);
5153
5473
  this._dispatch(target, "daw-effect-bypass", { effectId, bypassed: arg });
5154
5474
  break;
5155
- case "move":
5156
- chain.move(effectId, arg);
5157
- this._dispatch(target, "daw-effect-reorder", { effectId, fromIndex, toIndex: arg });
5475
+ case "move": {
5476
+ const toIndex = chain.move(effectId, arg);
5477
+ this._dispatch(target, "daw-effect-reorder", { effectId, fromIndex, toIndex });
5158
5478
  break;
5479
+ }
5159
5480
  }
5160
5481
  }
5161
5482
  _dispatch(target, name, detail) {
@@ -5196,6 +5517,9 @@ function validateSerializedEntries(entries) {
5196
5517
  if (typeof e.bypassed !== "boolean") {
5197
5518
  throw new Error(PREFIX2 + "setEffectsState: entry requires a boolean bypassed flag" + at);
5198
5519
  }
5520
+ if (e.placeholder !== void 0 && e.placeholder !== true) {
5521
+ throw new Error(PREFIX2 + "setEffectsState: placeholder must be true when present" + at);
5522
+ }
5199
5523
  });
5200
5524
  }
5201
5525
  function toWamParameterMap(params) {
@@ -5228,6 +5552,9 @@ async function exportAudioImpl(host, options = {}) {
5228
5552
  try {
5229
5553
  const masterChain = await buildOfflineChain(ctx, await host.getMasterEffectsState());
5230
5554
  cleanups.push(masterChain.dispose);
5555
+ const masterVolume = ctx.createGain();
5556
+ masterVolume.gain.value = host.masterVolume ?? 1;
5557
+ masterVolume.connect(masterChain.input);
5231
5558
  masterChain.output.connect(ctx.destination);
5232
5559
  const anySoloed = host.tracks.some((t) => t.soloed);
5233
5560
  for (const track of host.tracks) {
@@ -5242,7 +5569,7 @@ async function exportAudioImpl(host, options = {}) {
5242
5569
  panner.pan.value = track.pan;
5243
5570
  volume.connect(panner);
5244
5571
  panner.connect(chain.input);
5245
- chain.output.connect(masterChain.input);
5572
+ chain.output.connect(masterVolume);
5246
5573
  for (const clip of track.clips) {
5247
5574
  scheduleClip(ctx, clip, startTime, duration, volume);
5248
5575
  }
@@ -5313,6 +5640,12 @@ async function buildOfflineChain(ctx, entries) {
5313
5640
  return { input, output, dispose };
5314
5641
  async function wireEntries() {
5315
5642
  for (const entry of entries) {
5643
+ if (entry.placeholder) {
5644
+ console.warn(
5645
+ PREFIX3 + 'exportAudio: skipping failed-plugin placeholder "' + (entry.kind === "native" ? entry.type : entry.url ?? "Faust effect") + '"'
5646
+ );
5647
+ continue;
5648
+ }
5316
5649
  if (entry.kind === "native") {
5317
5650
  const created = createEffectInstance(entry.type, ctx, entry.params);
5318
5651
  if (entry.bypassed) {
@@ -5521,7 +5854,9 @@ var AnimationController = class {
5521
5854
  this._callback = callback;
5522
5855
  const loop = () => {
5523
5856
  this._callback?.();
5524
- this._rafId = requestAnimationFrame(loop);
5857
+ if (this._callback !== null) {
5858
+ this._rafId = requestAnimationFrame(loop);
5859
+ }
5525
5860
  };
5526
5861
  this._rafId = requestAnimationFrame(loop);
5527
5862
  }
@@ -5581,6 +5916,13 @@ var PlaybackAnimationController = class {
5581
5916
  // src/elements/daw-editor.ts
5582
5917
  var RULER_HEIGHT = 30;
5583
5918
  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();";
5919
+ var TrackLoadCancelledError = class extends Error {
5920
+ constructor(message, reason) {
5921
+ super(message);
5922
+ this.reason = reason;
5923
+ this.name = "TrackLoadCancelledError";
5924
+ }
5925
+ };
5584
5926
  var DawEditorElement = class extends LitElement11 {
5585
5927
  constructor() {
5586
5928
  super(...arguments);
@@ -5597,6 +5939,7 @@ var DawEditorElement = class extends LitElement11 {
5597
5939
  this.clipHeaderHeight = 20;
5598
5940
  this.interactiveClips = false;
5599
5941
  this.indefinitePlayback = false;
5942
+ this.fillViewport = false;
5600
5943
  this._spectrogramConfig = null;
5601
5944
  this._spectrogramColorMap = null;
5602
5945
  this.scaleMode = "temporal";
@@ -5619,6 +5962,9 @@ var DawEditorElement = class extends LitElement11 {
5619
5962
  this._selectionEndTime = 0;
5620
5963
  this._currentTime = 0;
5621
5964
  this._externalAdapter = null;
5965
+ /** True after a disconnect disposed the consumer's adapter via the engine
5966
+ * — rebuild attempts fail loudly until a fresh adapter is set. */
5967
+ this._adapterConsumedByDispose = false;
5622
5968
  // --- Effects (master chain; per-track chains delegated from <daw-track>) ---
5623
5969
  this._effectsManager = null;
5624
5970
  this._engine = null;
@@ -5633,6 +5979,11 @@ var DawEditorElement = class extends LitElement11 {
5633
5979
  /** Coarsest scale from pre-computed peaks — zoom cannot go finer than this. 0 = no limit. */
5634
5980
  this._minSamplesPerPixel = 0;
5635
5981
  this._trackElements = /* @__PURE__ */ new Map();
5982
+ /** Track ids with a _loadTrack in flight. Distinct from `_engineTracks`
5983
+ * membership: the peaks-first path inserts a render-only PREVIEW track
5984
+ * into _engineTracks mid-load, so `has()` alone cannot answer "is this
5985
+ * track still loading?". */
5986
+ this._loadingTracks = /* @__PURE__ */ new Set();
5636
5987
  this._childObserver = null;
5637
5988
  this._audioResume = new AudioResumeController(this);
5638
5989
  this._recordingController = new RecordingController(this);
@@ -5777,11 +6128,17 @@ var DawEditorElement = class extends LitElement11 {
5777
6128
  const trackEl = clipEl.closest("daw-track");
5778
6129
  if (!trackEl) return;
5779
6130
  const trackId = trackEl.trackId;
5780
- if (!this._engineTracks.has(trackId)) {
6131
+ if (!this._engineTracks.has(trackId) || this._loadingTracks.has(trackId)) {
5781
6132
  const desc = this._tracks.get(trackId);
5782
6133
  if (desc && !desc.clips.some((c) => isDomClip(c) && c.clipId === clipEl.clipId)) {
5783
- console.warn(
5784
- '[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.'
6134
+ 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.';
6135
+ console.warn("[dawcore] " + message);
6136
+ this.dispatchEvent(
6137
+ new CustomEvent("daw-clip-error", {
6138
+ bubbles: true,
6139
+ composed: true,
6140
+ detail: { trackId, clipId: clipEl.clipId, error: new Error(message) }
6141
+ })
5785
6142
  );
5786
6143
  }
5787
6144
  return;
@@ -5873,12 +6230,38 @@ var DawEditorElement = class extends LitElement11 {
5873
6230
  const clamped = this._minSamplesPerPixel > 0 && value < this._minSamplesPerPixel ? this._minSamplesPerPixel : value;
5874
6231
  if (clamped !== value) {
5875
6232
  console.warn(
5876
- "[dawcore] Zoom " + value + " spp rejected \u2014 pre-computed peaks limit is " + this._minSamplesPerPixel + " spp"
6233
+ "[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"
5877
6234
  );
5878
6235
  }
5879
6236
  this._samplesPerPixel = clamped;
5880
6237
  this.requestUpdate("samplesPerPixel", old);
5881
6238
  }
6239
+ /** Raise the zoom floor and re-clamp the LIVE samplesPerPixel when it's
6240
+ * now below the floor. Peaks can only be extracted at >= the floor scale —
6241
+ * the setter alone clamps only FUTURE sets, so without the re-clamp an
6242
+ * already-finer spp keeps sizing clip containers while the waveforms
6243
+ * render at the coarser scale: half/quarter width, misaligned against the
6244
+ * ruler and playhead. */
6245
+ _raiseZoomFloor(scale) {
6246
+ if (!Number.isFinite(scale) || scale <= 0) return;
6247
+ if (scale > this._minSamplesPerPixel) {
6248
+ this._minSamplesPerPixel = scale;
6249
+ }
6250
+ if (this._samplesPerPixel < this._minSamplesPerPixel) {
6251
+ this.samplesPerPixel = this._minSamplesPerPixel;
6252
+ }
6253
+ }
6254
+ /** Recompute the floor from the surviving cached scales (track removal /
6255
+ * load cancellation / preview cleanup). Usually LOWERS the floor, freeing
6256
+ * finer zoom — but a buffer whose scale never raised the floor (or a mix
6257
+ * of scales) can raise it above the live spp, so re-clamp like
6258
+ * _raiseZoomFloor. Never mutate _minSamplesPerPixel directly. */
6259
+ _recomputeZoomFloor() {
6260
+ this._minSamplesPerPixel = this._peakPipeline.getMaxCachedScale(this._clipBuffers);
6261
+ if (this._minSamplesPerPixel > 0 && this._samplesPerPixel < this._minSamplesPerPixel) {
6262
+ this.samplesPerPixel = this._minSamplesPerPixel;
6263
+ }
6264
+ }
5882
6265
  get timeFormat() {
5883
6266
  return this._timeFormat;
5884
6267
  }
@@ -6024,6 +6407,7 @@ var DawEditorElement = class extends LitElement11 {
6024
6407
  console.warn("[dawcore] Adapter AudioContext is already closed. Ignoring.");
6025
6408
  return;
6026
6409
  }
6410
+ this._adapterConsumedByDispose = false;
6027
6411
  if (this._engine) {
6028
6412
  console.warn(
6029
6413
  "[dawcore] adapter set after engine is built. The engine will continue using the previous adapter."
@@ -6111,6 +6495,7 @@ var DawEditorElement = class extends LitElement11 {
6111
6495
  effectiveSampleRate: this.effectiveSampleRate,
6112
6496
  duration: this._duration,
6113
6497
  tracks: [...this._engineTracks.values()],
6498
+ masterVolume: this._engine?.getState().masterVolume ?? 1,
6114
6499
  getMasterEffectsState: () => this.getEffectsState(),
6115
6500
  getTrackEffectsState: (trackId) => this.getTrackEffectsState(trackId)
6116
6501
  },
@@ -6294,7 +6679,7 @@ var DawEditorElement = class extends LitElement11 {
6294
6679
  const naturalWidth = Math.ceil(
6295
6680
  this._duration * this.effectiveSampleRate / this.samplesPerPixel
6296
6681
  );
6297
- if (this.indefinitePlayback) {
6682
+ if (this.indefinitePlayback || this.fillViewport) {
6298
6683
  return Math.max(naturalWidth, this._viewport.containerWidth);
6299
6684
  }
6300
6685
  return naturalWidth;
@@ -6392,11 +6777,21 @@ var DawEditorElement = class extends LitElement11 {
6392
6777
  this._minSamplesPerPixel = 0;
6393
6778
  this._spectrogramController?.dispose();
6394
6779
  this._spectrogramController = null;
6780
+ this._lastSpectrogramViewport = null;
6781
+ const hadEngine = this._engine !== null;
6395
6782
  try {
6396
6783
  this._disposeEngine();
6397
6784
  } catch (err) {
6398
6785
  console.warn("[dawcore] Error disposing engine: " + String(err));
6399
6786
  }
6787
+ if (hadEngine) {
6788
+ this._adapterConsumedByDispose = true;
6789
+ }
6790
+ this._tracks = /* @__PURE__ */ new Map();
6791
+ this._engineTracks = /* @__PURE__ */ new Map();
6792
+ this._peaksData = /* @__PURE__ */ new Map();
6793
+ this._loadingTracks.clear();
6794
+ this._recomputeDuration();
6400
6795
  }
6401
6796
  willUpdate(changedProperties) {
6402
6797
  if (changedProperties.has("eagerResume")) {
@@ -6405,8 +6800,8 @@ var DawEditorElement = class extends LitElement11 {
6405
6800
  if ((changedProperties.has("samplesPerPixel") || changedProperties.has("ticksPerPixel") || changedProperties.has("bpm") || changedProperties.has("secondsToTicks")) && this._isPlaying) {
6406
6801
  this._startPlayhead();
6407
6802
  }
6408
- const zoomChanged = changedProperties.has("samplesPerPixel") || changedProperties.has("ticksPerPixel") || changedProperties.has("bpm") || changedProperties.has("scaleMode") || changedProperties.has("secondsToTicks");
6409
- if (zoomChanged && this._clipBuffers.size > 0) {
6803
+ const peaksInputChanged = changedProperties.has("samplesPerPixel") || changedProperties.has("ticksPerPixel") || changedProperties.has("bpm") || changedProperties.has("scaleMode") || changedProperties.has("secondsToTicks") || changedProperties.has("mono");
6804
+ if (peaksInputChanged && this._clipBuffers.size > 0) {
6410
6805
  const re = this._peakPipeline.reextractPeaks(
6411
6806
  this._clipBuffers,
6412
6807
  this._renderSpp,
@@ -6473,9 +6868,16 @@ var DawEditorElement = class extends LitElement11 {
6473
6868
  if (this._engine) {
6474
6869
  this._engine.removeTrack(trackId);
6475
6870
  }
6476
- this._minSamplesPerPixel = this._peakPipeline.getMaxCachedScale(this._clipBuffers);
6871
+ this._recomputeZoomFloor();
6477
6872
  this._disposeSpectrogramControllerIfEmpty();
6478
- if (nextEngine.size === 0) {
6873
+ if (existed && nextEngine.size === 0) {
6874
+ if (this._engine) {
6875
+ if (this._isPlaying) {
6876
+ this._withSeekSuppression(() => this._engine.stop());
6877
+ this.dispatchEvent(new CustomEvent("daw-stop", { bubbles: true, composed: true }));
6878
+ }
6879
+ this._engine.seek(0);
6880
+ }
6479
6881
  this._currentTime = 0;
6480
6882
  this._stopPlayhead();
6481
6883
  }
@@ -6498,6 +6900,45 @@ var DawEditorElement = class extends LitElement11 {
6498
6900
  if (!stillNeeded) {
6499
6901
  this._spectrogramController.dispose();
6500
6902
  this._spectrogramController = null;
6903
+ this._lastSpectrogramViewport = null;
6904
+ }
6905
+ }
6906
+ /** Reconcile `_tracks` descriptors with the engine's track list.
6907
+ *
6908
+ * ADD: engine.undo() restores removed tracks in ENGINE state only —
6909
+ * without a synthesized descriptor the track plays and renders but shows
6910
+ * "Untitled" controls and is missing from `editor.tracks`.
6911
+ * PRUNE (the symmetric half): redo removes the track from engine state
6912
+ * again — without pruning, the synthesized descriptor is a permanent
6913
+ * ghost that even removeTrack() can't clean (no element, no engine
6914
+ * entry). Never prunes tracks that are mid-load or element-backed —
6915
+ * their descriptors legitimately precede their engine entries. */
6916
+ _reconcileDescriptorsWithEngineTracks(tracks) {
6917
+ const engineIds = new Set(tracks.map((t) => t.id));
6918
+ let next = null;
6919
+ for (const track of tracks) {
6920
+ if (this._tracks.has(track.id)) continue;
6921
+ next ?? (next = new Map(this._tracks));
6922
+ next.set(track.id, {
6923
+ name: track.name ?? "",
6924
+ src: "",
6925
+ volume: track.volume ?? 1,
6926
+ pan: track.pan ?? 0,
6927
+ muted: track.muted ?? false,
6928
+ soloed: track.soloed ?? false,
6929
+ renderMode: track.clips.some((c) => c.midiNotes && c.midiNotes.length > 0) ? "piano-roll" : "waveform",
6930
+ clips: []
6931
+ });
6932
+ }
6933
+ for (const trackId of this._tracks.keys()) {
6934
+ if (engineIds.has(trackId) || this._loadingTracks.has(trackId) || this._trackElements.has(trackId)) {
6935
+ continue;
6936
+ }
6937
+ next ?? (next = new Map(this._tracks));
6938
+ next.delete(trackId);
6939
+ }
6940
+ if (next) {
6941
+ this._tracks = next;
6501
6942
  }
6502
6943
  }
6503
6944
  _onClipRemovedFromDom(clipEl) {
@@ -6643,9 +7084,8 @@ var DawEditorElement = class extends LitElement11 {
6643
7084
  throw err;
6644
7085
  }
6645
7086
  this._peaksData = new Map(this._peaksData).set(clip.id, peakData);
6646
- if (waveformData) {
6647
- this._minSamplesPerPixel = Math.max(this._minSamplesPerPixel, waveformData.scale);
6648
- }
7087
+ const cachedScale = waveformData?.scale ?? this._peakPipeline.getCachedScale(audioBuffer);
7088
+ this._raiseZoomFloor(cachedScale);
6649
7089
  return clip;
6650
7090
  }
6651
7091
  /**
@@ -6888,6 +7328,8 @@ var DawEditorElement = class extends LitElement11 {
6888
7328
  }
6889
7329
  // --- Audio Loading ---
6890
7330
  async _loadTrack(trackId, descriptor) {
7331
+ this._loadingTracks.add(trackId);
7332
+ const sppAtLoadStart = this._samplesPerPixel;
6891
7333
  try {
6892
7334
  const clips = [];
6893
7335
  for (const clipDesc of descriptor.clips) {
@@ -6925,18 +7367,20 @@ var DawEditorElement = class extends LitElement11 {
6925
7367
  durationSamples: clip2.durationSamples
6926
7368
  });
6927
7369
  this._peaksData = new Map(this._peaksData).set(clip2.id, peakData);
6928
- this._minSamplesPerPixel = Math.max(this._minSamplesPerPixel, waveformData.scale);
6929
- const previewTrack = createTrack2({
6930
- name: descriptor.name,
6931
- clips: [clip2],
6932
- volume: descriptor.volume,
6933
- pan: descriptor.pan,
6934
- muted: descriptor.muted,
6935
- soloed: descriptor.soloed
6936
- });
6937
- previewTrack.id = trackId;
6938
- this._engineTracks = new Map(this._engineTracks).set(trackId, previewTrack);
6939
- this._recomputeDuration();
7370
+ this._raiseZoomFloor(waveformData.scale);
7371
+ if (this._tracks.has(trackId)) {
7372
+ const previewTrack = createTrack2({
7373
+ name: descriptor.name,
7374
+ clips: [clip2],
7375
+ volume: descriptor.volume,
7376
+ pan: descriptor.pan,
7377
+ muted: descriptor.muted,
7378
+ soloed: descriptor.soloed
7379
+ });
7380
+ previewTrack.id = trackId;
7381
+ this._engineTracks = new Map(this._engineTracks).set(trackId, previewTrack);
7382
+ this._recomputeDuration();
7383
+ }
6940
7384
  let audioBuffer2;
6941
7385
  try {
6942
7386
  audioBuffer2 = await audioPromise;
@@ -6948,7 +7392,7 @@ var DawEditorElement = class extends LitElement11 {
6948
7392
  const nextEngine = new Map(this._engineTracks);
6949
7393
  nextEngine.delete(trackId);
6950
7394
  this._engineTracks = nextEngine;
6951
- this._minSamplesPerPixel = this._peakPipeline.getMaxCachedScale(this._clipBuffers);
7395
+ this._recomputeZoomFloor();
6952
7396
  this._recomputeDuration();
6953
7397
  throw audioErr;
6954
7398
  }
@@ -6982,6 +7426,26 @@ var DawEditorElement = class extends LitElement11 {
6982
7426
  }
6983
7427
  }
6984
7428
  }
7429
+ const trackWasRemoved = !this._tracks.has(trackId);
7430
+ if (trackWasRemoved || !this.isConnected) {
7431
+ for (const clip of clips) {
7432
+ this._purgeClipCaches(clip.id);
7433
+ }
7434
+ if (this._engineTracks.has(trackId)) {
7435
+ const nextEngine = new Map(this._engineTracks);
7436
+ nextEngine.delete(trackId);
7437
+ this._engineTracks = nextEngine;
7438
+ this._recomputeDuration();
7439
+ }
7440
+ this._recomputeZoomFloor();
7441
+ if (this._samplesPerPixel !== sppAtLoadStart && sppAtLoadStart >= this._minSamplesPerPixel) {
7442
+ this.samplesPerPixel = sppAtLoadStart;
7443
+ }
7444
+ throw new TrackLoadCancelledError(
7445
+ trackWasRemoved ? 'track "' + trackId + '" was removed while loading' : 'editor was disconnected while track "' + trackId + '" was loading',
7446
+ trackWasRemoved ? "removed" : "disconnected"
7447
+ );
7448
+ }
6985
7449
  const track = createTrack2({
6986
7450
  name: descriptor.name,
6987
7451
  clips,
@@ -7012,15 +7476,23 @@ var DawEditorElement = class extends LitElement11 {
7012
7476
  })
7013
7477
  );
7014
7478
  } catch (err) {
7015
- if (!this.isConnected) return;
7016
- console.warn('[dawcore] Failed to load track "' + trackId + '": ' + String(err));
7479
+ const cancelled = err instanceof TrackLoadCancelledError;
7480
+ console.warn(
7481
+ cancelled ? "[dawcore] Track load cancelled: " + err.message : '[dawcore] Failed to load track "' + trackId + '": ' + String(err)
7482
+ );
7017
7483
  this.dispatchEvent(
7018
7484
  new CustomEvent("daw-track-error", {
7019
7485
  bubbles: true,
7020
7486
  composed: true,
7021
- detail: { trackId, error: err }
7487
+ detail: {
7488
+ trackId,
7489
+ error: err,
7490
+ ...cancelled ? { reason: err.reason } : {}
7491
+ }
7022
7492
  })
7023
7493
  );
7494
+ } finally {
7495
+ this._loadingTracks.delete(trackId);
7024
7496
  }
7025
7497
  }
7026
7498
  async _fetchAndDecode(src) {
@@ -7079,6 +7551,11 @@ var DawEditorElement = class extends LitElement11 {
7079
7551
  if (!this._externalAdapter) {
7080
7552
  throw new Error(NO_ADAPTER_ERROR);
7081
7553
  }
7554
+ if (this._adapterConsumedByDispose) {
7555
+ throw new Error(
7556
+ "[dawcore] editor.adapter was disposed by a previous disconnect \u2014 set a fresh PlayoutAdapter after reparenting <daw-editor>."
7557
+ );
7558
+ }
7082
7559
  const { PlaylistEngine } = await import("@waveform-playlist/engine");
7083
7560
  const adapter = this._externalAdapter;
7084
7561
  if (!this._hasTickCallbacks) {
@@ -7115,6 +7592,7 @@ var DawEditorElement = class extends LitElement11 {
7115
7592
  nextTracks.set(track.id, track);
7116
7593
  }
7117
7594
  this._engineTracks = nextTracks;
7595
+ this._reconcileDescriptorsWithEngineTracks(engineState.tracks);
7118
7596
  }
7119
7597
  if (structuralChange) {
7120
7598
  this._effectsManager?.rewireTrackChains();
@@ -7471,24 +7949,60 @@ var DawEditorElement = class extends LitElement11 {
7471
7949
  this.play();
7472
7950
  }
7473
7951
  }
7952
+ /** Run `fn` with the stop-settle daw-timeupdate suppressed. Every
7953
+ * stop-adjacent code path that immediately re-positions (seek, split,
7954
+ * empty-timeline rewind) must use this — engine.stop() rewinds to the
7955
+ * play-start position and the settle would leak a backward-jumping
7956
+ * daw-timeupdate to consumers (CLAUDE.md seek-while-playing invariant).
7957
+ * The `finally` is load-bearing: a wedged true silently drops every
7958
+ * subsequent stop-settle dispatch. */
7959
+ _withSeekSuppression(fn) {
7960
+ this._inSeekTransition = true;
7961
+ try {
7962
+ fn();
7963
+ } finally {
7964
+ this._inSeekTransition = false;
7965
+ }
7966
+ }
7474
7967
  seekTo(time) {
7475
7968
  if (!this._engine) {
7476
7969
  console.warn("[dawcore] seekTo: engine not ready, call ignored");
7477
7970
  return;
7478
7971
  }
7972
+ if (!Number.isFinite(time)) {
7973
+ console.warn("[dawcore] seekTo: ignoring non-finite time " + String(time));
7974
+ return;
7975
+ }
7976
+ const target = Math.max(0, time);
7479
7977
  if (this._isPlaying) {
7480
- this._inSeekTransition = true;
7481
7978
  try {
7482
- this.stop();
7483
- } finally {
7484
- this._inSeekTransition = false;
7979
+ this._withSeekSuppression(() => this._engine.stop());
7980
+ this._engine.play(target);
7981
+ } catch (err) {
7982
+ console.warn("[dawcore] seekTo: engine reschedule failed: " + String(err));
7983
+ this.dispatchEvent(
7984
+ new CustomEvent("daw-error", {
7985
+ bubbles: true,
7986
+ composed: true,
7987
+ detail: { operation: "seek", error: err }
7988
+ })
7989
+ );
7990
+ return;
7485
7991
  }
7486
- this.play(time);
7992
+ this._currentTime = target;
7993
+ this._startPlayhead();
7487
7994
  } else {
7488
- this._engine.seek(time);
7489
- this._currentTime = time;
7995
+ this._engine.seek(target);
7996
+ this._currentTime = target;
7490
7997
  this._stopPlayhead();
7491
7998
  }
7999
+ this.dispatchEvent(
8000
+ new CustomEvent("daw-seek", {
8001
+ bubbles: true,
8002
+ composed: true,
8003
+ detail: { time: target }
8004
+ })
8005
+ );
7492
8006
  }
7493
8007
  /** Undo the last structural edit. */
7494
8008
  undo() {
@@ -7523,8 +8037,10 @@ var DawEditorElement = class extends LitElement11 {
7523
8037
  engine: this._engine,
7524
8038
  dispatchEvent: (e) => this.dispatchEvent(e),
7525
8039
  stop: () => {
7526
- this._engine?.stop();
7527
- this._stopPlayhead();
8040
+ this._withSeekSuppression(() => {
8041
+ this._engine?.stop();
8042
+ this._stopPlayhead();
8043
+ });
7528
8044
  },
7529
8045
  // Call engine.play directly (synchronous) — not the async editor play()
7530
8046
  // which yields to microtask queue via await engine.init(). Engine is
@@ -7588,8 +8104,8 @@ var DawEditorElement = class extends LitElement11 {
7588
8104
  this._wasPlayingDuringRecording = false;
7589
8105
  return this._recordingController.stopRecording();
7590
8106
  }
7591
- _addRecordedClip(trackId, buf, startSample, durSamples, offsetSamples = 0) {
7592
- addRecordedClip(this, trackId, buf, startSample, durSamples, offsetSamples);
8107
+ _addRecordedClip(trackId, buf, startSample, durSamples, offsetSamples = 0, clipName) {
8108
+ addRecordedClip(this, trackId, buf, startSample, durSamples, offsetSamples, clipName);
7593
8109
  }
7594
8110
  // --- RecordingHost bridge methods for cross-context worklet support ---
7595
8111
  // These delegate to the adapter's context type (native or standardized-audio-context).
@@ -7611,6 +8127,25 @@ var DawEditorElement = class extends LitElement11 {
7611
8127
  }
7612
8128
  await this._recordingController.startRecording(s, options);
7613
8129
  }
8130
+ /** Live-recording preview left/width. Beats mode uses the same tick-space
8131
+ * math as finalized clips — the sample÷renderSpp path is ceil-quantized,
8132
+ * so the take would visibly jump sideways on finalization (drift grows
8133
+ * with distance from t=0; CLAUDE.md live-preview parity invariant). */
8134
+ _previewPosition(startSample, audibleSamples) {
8135
+ if (this.scaleMode === "beats") {
8136
+ const sr = this.effectiveSampleRate;
8137
+ const startSec = startSample / sr;
8138
+ const startTick = this._secondsToTicks(startSec);
8139
+ const endTick = this._secondsToTicks(startSec + audibleSamples / sr);
8140
+ const left = Math.round(startTick / this.ticksPerPixel);
8141
+ return { left, width: Math.round(endTick / this.ticksPerPixel) - left };
8142
+ }
8143
+ const renderSpp = this._renderSpp;
8144
+ return {
8145
+ left: Math.floor(startSample / renderSpp),
8146
+ width: Math.floor(audibleSamples / renderSpp)
8147
+ };
8148
+ }
7614
8149
  _renderRecordingPreview(trackId, chH) {
7615
8150
  const rs = this._recordingController.getSession(trackId);
7616
8151
  if (!rs) return "";
@@ -7618,32 +8153,48 @@ var DawEditorElement = class extends LitElement11 {
7618
8153
  if (audibleSamples === 0) return "";
7619
8154
  const renderSpp = this._renderSpp;
7620
8155
  const latencyPixels = Math.floor(rs.latencySamples / renderSpp);
7621
- const left = Math.floor(rs.startSample / renderSpp);
7622
- const w = Math.floor(audibleSamples / renderSpp);
7623
- return rs.peaks.map((chPeaks, ch) => {
8156
+ const { left, width: w } = this._previewPosition(rs.startSample, audibleSamples);
8157
+ const hdrH = this.clipHeaders ? this.clipHeaderHeight : 0;
8158
+ const height = hdrH + chH * rs.peaks.length;
8159
+ return html10`<div
8160
+ class="clip-container recording-preview"
8161
+ style="left:${left}px;top:0;width:${w}px;height:${height}px;"
8162
+ >
8163
+ ${hdrH > 0 ? html10`<div class="clip-header" data-track-id=${trackId}>
8164
+ <span>${rs.clipName ?? "Recording\u2026"}</span>
8165
+ </div>` : ""}
8166
+ ${rs.peaks.map((chPeaks, ch) => {
7624
8167
  const slicedPeaks = latencyPixels > 0 ? chPeaks.slice(latencyPixels * 2) : chPeaks;
7625
8168
  return html10`
7626
- <daw-waveform
7627
- data-recording-track=${trackId}
7628
- data-recording-channel=${ch}
7629
- style="position:absolute;left:${left}px;top:${ch * chH}px;"
7630
- .peaks=${slicedPeaks}
7631
- .length=${w}
7632
- .waveHeight=${chH}
7633
- .barWidth=${this.barWidth}
7634
- .barGap=${this.barGap}
7635
- .roundedBars=${this.roundedBars}
7636
- .visibleStart=${this._viewport.visibleStart}
7637
- .visibleEnd=${this._viewport.visibleEnd}
7638
- .originX=${left}
7639
- ></daw-waveform>
7640
- `;
7641
- });
8169
+ <daw-waveform
8170
+ data-recording-track=${trackId}
8171
+ data-recording-channel=${ch}
8172
+ style="position:absolute;left:0;top:${hdrH + ch * chH}px;"
8173
+ .peaks=${slicedPeaks}
8174
+ .length=${w}
8175
+ .waveHeight=${chH}
8176
+ .barWidth=${this.barWidth}
8177
+ .barGap=${this.barGap}
8178
+ .roundedBars=${this.roundedBars}
8179
+ .visibleStart=${this._viewport.visibleStart}
8180
+ .visibleEnd=${this._viewport.visibleEnd}
8181
+ .originX=${left}
8182
+ ></daw-waveform>
8183
+ `;
8184
+ })}
8185
+ </div>`;
7642
8186
  }
7643
8187
  _startPlayhead() {
7644
8188
  if (!this._engine) return;
7645
8189
  const engine = this._engine;
7646
- this._playbackAnimation.start(() => engine.getAudibleTime());
8190
+ this._playbackAnimation.start(() => {
8191
+ if (!this.indefinitePlayback && !this.isRecording && engine.getCurrentTime() >= this._duration) {
8192
+ this.stop();
8193
+ const t = this._currentTime;
8194
+ return Number.isFinite(t) ? Math.max(0, t) : 0;
8195
+ }
8196
+ return engine.getAudibleTime();
8197
+ });
7647
8198
  }
7648
8199
  _stopPlayhead() {
7649
8200
  const t = this._currentTime;
@@ -7655,11 +8206,11 @@ var DawEditorElement = class extends LitElement11 {
7655
8206
  }
7656
8207
  /** True when the controls column should be rendered (and its selector is valid). */
7657
8208
  get _showControls() {
7658
- return this._getOrderedTracks().length > 0 || this.indefinitePlayback;
8209
+ return this._getOrderedTracks().length > 0 || this.indefinitePlayback || this.fillViewport;
7659
8210
  }
7660
8211
  /** True when the ruler header band should be rendered (and its selector is valid). */
7661
8212
  get _showRuler() {
7662
- return (this._getOrderedTracks().length > 0 || this.scaleMode === "beats" || this.indefinitePlayback) && this.timescale;
8213
+ return (this._getOrderedTracks().length > 0 || this.scaleMode === "beats" || this.indefinitePlayback || this.fillViewport) && this.timescale;
7663
8214
  }
7664
8215
  _getOrderedTracks() {
7665
8216
  const domOrder = [...this.querySelectorAll("daw-track")].map(
@@ -7764,7 +8315,7 @@ var DawEditorElement = class extends LitElement11 {
7764
8315
  .length=${this._totalWidth}
7765
8316
  .height=${orderedTracks.length > 0 ? orderedTracks.reduce((sum, t) => sum + t.trackHeight, 0) : this._emptyGridHeight}
7766
8317
  ></daw-grid>` : ""}
7767
- ${orderedTracks.length > 0 || this.scaleMode === "beats" || this.indefinitePlayback ? html10`<daw-selection .startPx=${selStartPx} .endPx=${selEndPx}></daw-selection>
8318
+ ${orderedTracks.length > 0 || this.scaleMode === "beats" || this.indefinitePlayback || this.fillViewport ? html10`<daw-selection .startPx=${selStartPx} .endPx=${selEndPx}></daw-selection>
7768
8319
  <daw-playhead></daw-playhead>` : ""}
7769
8320
  ${orderedTracks.map((t) => {
7770
8321
  const channelHeight = this.waveHeight;
@@ -8030,6 +8581,9 @@ __decorateClass([
8030
8581
  __decorateClass([
8031
8582
  property9({ type: Boolean, attribute: "indefinite-playback" })
8032
8583
  ], DawEditorElement.prototype, "indefinitePlayback", 2);
8584
+ __decorateClass([
8585
+ property9({ type: Boolean, attribute: "fill-viewport" })
8586
+ ], DawEditorElement.prototype, "fillViewport", 2);
8033
8587
  __decorateClass([
8034
8588
  property9({ attribute: false, noAccessor: true })
8035
8589
  ], DawEditorElement.prototype, "spectrogramConfig", 1);
@@ -8156,14 +8710,22 @@ var DawRecordButtonElement = class extends DawTransportButton {
8156
8710
  }
8157
8711
  connectedCallback() {
8158
8712
  super.connectedCallback();
8159
- requestAnimationFrame(() => this._listenToTarget());
8713
+ requestAnimationFrame(() => {
8714
+ if (!this.isConnected) return;
8715
+ this._ensureTargetListeners();
8716
+ });
8160
8717
  }
8161
8718
  disconnectedCallback() {
8162
8719
  super.disconnectedCallback();
8163
8720
  this._cleanupListeners();
8164
8721
  }
8165
- _listenToTarget() {
8722
+ updated() {
8723
+ this._ensureTargetListeners();
8724
+ }
8725
+ _ensureTargetListeners() {
8166
8726
  const target = this.target;
8727
+ if (target === this._targetRef) return;
8728
+ this._cleanupListeners();
8167
8729
  if (!target) return;
8168
8730
  this._targetRef = target;
8169
8731
  target.addEventListener("daw-recording-start", this._onStart);
@@ -8197,6 +8759,7 @@ var DawRecordButtonElement = class extends DawTransportButton {
8197
8759
  warnNoTargetOnce(this);
8198
8760
  return;
8199
8761
  }
8762
+ this._ensureTargetListeners();
8200
8763
  target.startRecording(target.recordingStream);
8201
8764
  }
8202
8765
  };
@@ -8232,11 +8795,16 @@ var DawKeyboardShortcutsElement = class extends LitElement13 {
8232
8795
  this.splitting = false;
8233
8796
  this.undo = false;
8234
8797
  // --- JS properties for remapping ---
8235
- this.playbackShortcuts = null;
8236
- this.splittingShortcuts = null;
8237
- this.undoShortcuts = null;
8798
+ // Accessors, not plain fields: assigning a remap after any keydown has
8799
+ // warmed _cachedShortcuts must invalidate it, or the documented remapping
8800
+ // API is silently ignored until an unrelated boolean attribute toggles.
8801
+ // (connectedCallback runs the standard upgrade-property dance so values
8802
+ // assigned BEFORE the element was defined don't shadow these accessors.)
8803
+ this._playbackShortcuts = null;
8804
+ this._splittingShortcuts = null;
8805
+ this._undoShortcuts = null;
8238
8806
  /** Additional custom shortcuts. */
8239
- this.customShortcuts = [];
8807
+ this._customShortcuts = [];
8240
8808
  this._editor = null;
8241
8809
  this._cachedShortcuts = null;
8242
8810
  // --- Event handler ---
@@ -8258,6 +8826,34 @@ var DawKeyboardShortcutsElement = class extends LitElement13 {
8258
8826
  }
8259
8827
  };
8260
8828
  }
8829
+ get playbackShortcuts() {
8830
+ return this._playbackShortcuts;
8831
+ }
8832
+ set playbackShortcuts(value) {
8833
+ this._playbackShortcuts = value;
8834
+ this._cachedShortcuts = null;
8835
+ }
8836
+ get splittingShortcuts() {
8837
+ return this._splittingShortcuts;
8838
+ }
8839
+ set splittingShortcuts(value) {
8840
+ this._splittingShortcuts = value;
8841
+ this._cachedShortcuts = null;
8842
+ }
8843
+ get undoShortcuts() {
8844
+ return this._undoShortcuts;
8845
+ }
8846
+ set undoShortcuts(value) {
8847
+ this._undoShortcuts = value;
8848
+ this._cachedShortcuts = null;
8849
+ }
8850
+ get customShortcuts() {
8851
+ return this._customShortcuts;
8852
+ }
8853
+ set customShortcuts(value) {
8854
+ this._customShortcuts = value;
8855
+ this._cachedShortcuts = null;
8856
+ }
8261
8857
  /** All active shortcuts (read-only, cached). */
8262
8858
  get shortcuts() {
8263
8859
  if (!this._cachedShortcuts) {
@@ -8272,6 +8868,18 @@ var DawKeyboardShortcutsElement = class extends LitElement13 {
8272
8868
  // --- Lifecycle ---
8273
8869
  connectedCallback() {
8274
8870
  super.connectedCallback();
8871
+ for (const prop of [
8872
+ "playbackShortcuts",
8873
+ "splittingShortcuts",
8874
+ "undoShortcuts",
8875
+ "customShortcuts"
8876
+ ]) {
8877
+ if (Object.prototype.hasOwnProperty.call(this, prop)) {
8878
+ const value = this[prop];
8879
+ delete this[prop];
8880
+ this[prop] = value;
8881
+ }
8882
+ }
8275
8883
  this._editor = this.closest("daw-editor");
8276
8884
  if (!this._editor) {
8277
8885
  console.warn(
@@ -8797,6 +9405,9 @@ var DawPlayerElement = class extends LitElement17 {
8797
9405
  this.roundedBars = false;
8798
9406
  this._playbackRate = 1;
8799
9407
  this._engine = new MediaElementPlayout();
9408
+ /** Set by disconnectedCallback — a reconnect (DOM reparent, framework
9409
+ * re-render) must rebuild the engine + track or the player is dead. */
9410
+ this._engineDisposed = false;
8800
9411
  this._trackId = null;
8801
9412
  this._anim = new AnimationController(this);
8802
9413
  this._metadataLoaded = false;
@@ -8814,7 +9425,6 @@ var DawPlayerElement = class extends LitElement17 {
8814
9425
  if (width <= 0 || d <= 0) return;
8815
9426
  const ratio = Math.max(0, Math.min(1, e.offsetX / width));
8816
9427
  this.seekTo(ratio * d);
8817
- this._updatePlayhead();
8818
9428
  };
8819
9429
  this._onLoadedMetadata = () => {
8820
9430
  this._metadataLoaded = true;
@@ -8862,6 +9472,15 @@ var DawPlayerElement = class extends LitElement17 {
8862
9472
  }
8863
9473
  connectedCallback() {
8864
9474
  super.connectedCallback();
9475
+ let rebuilt = false;
9476
+ if (this._engineDisposed) {
9477
+ const volume = this._engine.masterVolume;
9478
+ this._engine = new MediaElementPlayout();
9479
+ this._engine.setMasterVolume(volume);
9480
+ this._engineDisposed = false;
9481
+ this._trackId = null;
9482
+ rebuilt = true;
9483
+ }
8865
9484
  this._engine.on("loadedmetadata", this._onLoadedMetadata);
8866
9485
  this._engine.on("play", this._onPlay);
8867
9486
  this._engine.on("pause", this._onPause);
@@ -8872,6 +9491,10 @@ var DawPlayerElement = class extends LitElement17 {
8872
9491
  const area = this.shadowRoot?.querySelector(".waveform-area");
8873
9492
  if (area) this._resizeObserver?.observe(area);
8874
9493
  });
9494
+ if (rebuilt && this.src) {
9495
+ this._loadSource();
9496
+ this._playhead?.setPosition(0);
9497
+ }
8875
9498
  }
8876
9499
  render() {
8877
9500
  const width = this._timelineWidth;
@@ -8931,6 +9554,7 @@ var DawPlayerElement = class extends LitElement17 {
8931
9554
  this._renderWaveform();
8932
9555
  this._maybeDispatchReady();
8933
9556
  } catch (err) {
9557
+ if (this.peaksSrc !== requested) return;
8934
9558
  console.warn("[dawcore] <daw-player> failed to load peaks-src: " + String(err));
8935
9559
  this._peaksSettled = true;
8936
9560
  this._renderWaveform();
@@ -8971,7 +9595,7 @@ var DawPlayerElement = class extends LitElement17 {
8971
9595
  }
8972
9596
  // --- Transport methods ---
8973
9597
  play() {
8974
- this._engine.play();
9598
+ this._engine.resume();
8975
9599
  }
8976
9600
  pause() {
8977
9601
  this._engine.pause();
@@ -8984,6 +9608,10 @@ var DawPlayerElement = class extends LitElement17 {
8984
9608
  }
8985
9609
  seekTo(time) {
8986
9610
  this._engine.seekTo(time);
9611
+ if (!this._engine.isPlaying) {
9612
+ this._updatePlayhead();
9613
+ this._dispatch("daw-timeupdate", { time: this._engine.getCurrentTime() });
9614
+ }
8987
9615
  }
8988
9616
  setPlaybackRate(rate) {
8989
9617
  this.playbackRate = rate;
@@ -9002,7 +9630,7 @@ var DawPlayerElement = class extends LitElement17 {
9002
9630
  return this._engine.getCurrentTime();
9003
9631
  }
9004
9632
  set currentTime(time) {
9005
- this._engine.seekTo(time);
9633
+ this.seekTo(time);
9006
9634
  }
9007
9635
  get volume() {
9008
9636
  return this._engine.masterVolume;
@@ -9024,6 +9652,7 @@ var DawPlayerElement = class extends LitElement17 {
9024
9652
  this._engine.off("ended", this._onEnded);
9025
9653
  this._engine.off("error", this._onError);
9026
9654
  this._engine.dispose();
9655
+ this._engineDisposed = true;
9027
9656
  }
9028
9657
  // --- Private event handlers (arrow fields for stable identity) ---
9029
9658
  _dispatch(name, detail) {