@dawcore/components 0.0.33 → 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 = [];
@@ -2751,7 +2804,11 @@ var RecordingController = class {
2751
2804
  * The session is only set after several awaits — without this, two rapid
2752
2805
  * start calls both pass the _sessions guard and build two capture
2753
2806
  * pipelines feeding one session (garbled audio + a leaked worklet). */
2754
- this._starting = /* @__PURE__ */ new Set();
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;
2755
2812
  this._workletLoadedCtx = null;
2756
2813
  /** Tracks worklet pause state explicitly so external consumers (editor,
2757
2814
  * pause button, spacebar) can share one source of truth. */
@@ -2760,15 +2817,17 @@ var RecordingController = class {
2760
2817
  host.addController(this);
2761
2818
  }
2762
2819
  hostConnected() {
2820
+ this._hostDisconnected = false;
2763
2821
  }
2764
2822
  hostDisconnected() {
2823
+ this._hostDisconnected = true;
2765
2824
  for (const trackId of [...this._sessions.keys()]) {
2766
2825
  this._cleanupSession(trackId, true);
2767
2826
  }
2768
2827
  this._workletLoadedCtx = null;
2769
2828
  }
2770
2829
  get isRecording() {
2771
- return this._sessions.size > 0;
2830
+ return this._sessions.size > 0 || this._starting.size > 0;
2772
2831
  }
2773
2832
  get isPaused() {
2774
2833
  return this._isPaused && this._sessions.size > 0;
@@ -2786,7 +2845,14 @@ var RecordingController = class {
2786
2845
  console.warn('[dawcore] RecordingController: Already recording on track "' + trackId + '"');
2787
2846
  return;
2788
2847
  }
2789
- this._starting.add(trackId);
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);
2790
2856
  const bits = options.bits ?? 16;
2791
2857
  try {
2792
2858
  const rawCtx = this._host.audioContext;
@@ -2807,6 +2873,15 @@ var RecordingController = class {
2807
2873
  await addRecordingWorkletModule(addModule);
2808
2874
  this._workletLoadedCtx = rawCtx;
2809
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
+ }
2810
2885
  const detectedChannelCount = stream.getAudioTracks()[0]?.getSettings()?.channelCount;
2811
2886
  if (detectedChannelCount === void 0 && options.channelCount !== void 0) {
2812
2887
  console.warn(
@@ -2889,15 +2964,10 @@ var RecordingController = class {
2889
2964
  } catch (err) {
2890
2965
  this._cleanupSession(trackId);
2891
2966
  console.warn("[dawcore] RecordingController: Failed to start recording: " + String(err));
2892
- this._host.dispatchEvent(
2893
- new CustomEvent("daw-recording-error", {
2894
- bubbles: true,
2895
- composed: true,
2896
- detail: { trackId, error: err }
2897
- })
2898
- );
2967
+ this._dispatchRecordingError(trackId, err);
2899
2968
  } finally {
2900
2969
  this._starting.delete(trackId);
2970
+ resolveStartSettled();
2901
2971
  }
2902
2972
  }
2903
2973
  pauseRecording(trackId) {
@@ -2931,10 +3001,17 @@ var RecordingController = class {
2931
3001
  );
2932
3002
  }
2933
3003
  async stopRecording(trackId) {
2934
- const id = trackId ?? [...this._sessions.keys()][0];
3004
+ const id = trackId ?? [...this._sessions.keys()][0] ?? [...this._starting.keys()][0];
2935
3005
  if (!id) return;
2936
3006
  const session = this._sessions.get(id);
2937
- 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
+ }
2938
3015
  if (session.stopping) {
2939
3016
  return session.stopPromise ?? void 0;
2940
3017
  }
@@ -2944,6 +3021,19 @@ var RecordingController = class {
2944
3021
  return stopPromise;
2945
3022
  }
2946
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) {
2947
3037
  const wasPaused = this._isPaused;
2948
3038
  this._isPaused = false;
2949
3039
  if (session.wasOverdub && typeof this._host.stop === "function") {
@@ -2970,16 +3060,7 @@ var RecordingController = class {
2970
3060
  session.workletNode.disconnect();
2971
3061
  this._removeTrackEndedListener(session);
2972
3062
  if (session.totalSamples === 0) {
2973
- console.warn("[dawcore] RecordingController: No audio data captured");
2974
- this._sessions.delete(id);
2975
- this._host.requestUpdate();
2976
- this._host.dispatchEvent(
2977
- new CustomEvent("daw-recording-error", {
2978
- bubbles: true,
2979
- composed: true,
2980
- detail: { trackId: id, error: new Error("No audio data captured") }
2981
- })
2982
- );
3063
+ this._abandonFinalize(id, session, "No audio data captured");
2983
3064
  return;
2984
3065
  }
2985
3066
  const stopCtx = this._host.audioContext;
@@ -2993,16 +3074,11 @@ var RecordingController = class {
2993
3074
  const latencyOffsetSamples = session.latencySamples;
2994
3075
  const effectiveDuration = Math.max(0, audioBuffer.length - latencyOffsetSamples);
2995
3076
  if (effectiveDuration === 0) {
2996
- console.warn("[dawcore] RecordingController: Recording too short for latency compensation");
2997
- this._restoreArmedTrackMute(session);
2998
- this._sessions.delete(id);
2999
- this._host.requestUpdate();
3000
- this._host.dispatchEvent(
3001
- new CustomEvent("daw-recording-error", {
3002
- bubbles: true,
3003
- composed: true,
3004
- detail: { trackId: id, error: new Error("Recording too short to save") }
3005
- })
3077
+ this._abandonFinalize(
3078
+ id,
3079
+ session,
3080
+ "Recording too short for latency compensation",
3081
+ "Recording too short to save"
3006
3082
  );
3007
3083
  return;
3008
3084
  }
@@ -3137,6 +3213,26 @@ var RecordingController = class {
3137
3213
  session._audioTrack.removeEventListener("ended", session._onTrackEnded);
3138
3214
  }
3139
3215
  }
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
+ }
3140
3236
  /** Restore the armed track's pre-session mute state (idempotent — safe to
3141
3237
  * call from both the finalize path and _cleanupSession). */
3142
3238
  _restoreArmedTrackMute(session) {
@@ -3166,15 +3262,9 @@ var RecordingController = class {
3166
3262
  this._isPaused = false;
3167
3263
  }
3168
3264
  if (notifyError) {
3169
- this._host.dispatchEvent(
3170
- new CustomEvent("daw-recording-error", {
3171
- bubbles: true,
3172
- composed: true,
3173
- detail: {
3174
- trackId,
3175
- error: new Error("Recording cancelled: editor was disconnected mid-recording")
3176
- }
3177
- })
3265
+ this._dispatchRecordingError(
3266
+ trackId,
3267
+ new Error("Recording cancelled: editor was disconnected mid-recording")
3178
3268
  );
3179
3269
  }
3180
3270
  }
@@ -3321,6 +3411,14 @@ var PointerHandler = class {
3321
3411
  this._timeline = null;
3322
3412
  // Cached from onPointerDown to avoid forced layout reflows at 60fps during drag
3323
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;
3324
3422
  this.onPointerDown = (e) => {
3325
3423
  const clipHandler = this._host._clipHandler;
3326
3424
  if (clipHandler) {
@@ -3335,12 +3433,12 @@ var PointerHandler = class {
3335
3433
  console.warn("[dawcore] setPointerCapture failed: " + String(err));
3336
3434
  }
3337
3435
  const onMove = (me) => clipHandler.onPointerMove(me);
3338
- const onUp = (ue) => {
3339
- clipHandler.onPointerUp(ue);
3436
+ const detach = (pe) => {
3340
3437
  this._timeline?.removeEventListener("pointermove", onMove);
3341
3438
  this._timeline?.removeEventListener("pointerup", onUp);
3439
+ this._timeline?.removeEventListener("pointercancel", onCancel);
3342
3440
  try {
3343
- this._timeline?.releasePointerCapture(ue.pointerId);
3441
+ this._timeline?.releasePointerCapture(pe.pointerId);
3344
3442
  } catch (err) {
3345
3443
  console.warn(
3346
3444
  "[dawcore] releasePointerCapture failed (may already be released): " + String(err)
@@ -3348,8 +3446,19 @@ var PointerHandler = class {
3348
3446
  }
3349
3447
  this._timeline = null;
3350
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
+ };
3351
3459
  this._timeline.addEventListener("pointermove", onMove);
3352
3460
  this._timeline.addEventListener("pointerup", onUp);
3461
+ this._timeline.addEventListener("pointercancel", onCancel);
3353
3462
  }
3354
3463
  return;
3355
3464
  }
@@ -3364,6 +3473,9 @@ var PointerHandler = class {
3364
3473
  this._timelineRect = this._timeline.getBoundingClientRect();
3365
3474
  this._dragStartPx = this._pxFromPointer(e);
3366
3475
  this._isDragging = false;
3476
+ this._activePointerId = e.pointerId;
3477
+ this._preDragSelectionStart = this._host._selectionStartTime;
3478
+ this._preDragSelectionEnd = this._host._selectionEndTime;
3367
3479
  try {
3368
3480
  this._timeline.setPointerCapture(e.pointerId);
3369
3481
  } catch (err) {
@@ -3371,6 +3483,7 @@ var PointerHandler = class {
3371
3483
  }
3372
3484
  this._timeline.addEventListener("pointermove", this._onPointerMove);
3373
3485
  this._timeline.addEventListener("pointerup", this._onPointerUp);
3486
+ this._timeline.addEventListener("pointercancel", this._onPointerCancel);
3374
3487
  };
3375
3488
  this._onPointerMove = (e) => {
3376
3489
  if (!this._timeline) return;
@@ -3394,15 +3507,7 @@ var PointerHandler = class {
3394
3507
  };
3395
3508
  this._onPointerUp = (e) => {
3396
3509
  if (!this._timeline) return;
3397
- try {
3398
- this._timeline.releasePointerCapture(e.pointerId);
3399
- } catch (err) {
3400
- console.warn(
3401
- "[dawcore] releasePointerCapture failed (may already be released): " + String(err)
3402
- );
3403
- }
3404
- this._timeline.removeEventListener("pointermove", this._onPointerMove);
3405
- this._timeline.removeEventListener("pointerup", this._onPointerUp);
3510
+ this._detachTimeline(e);
3406
3511
  try {
3407
3512
  if (this._isDragging) {
3408
3513
  this._finalizeSelection();
@@ -3412,10 +3517,29 @@ var PointerHandler = class {
3412
3517
  } catch (err) {
3413
3518
  console.warn("[dawcore] Pointer interaction failed: " + String(err));
3414
3519
  } finally {
3415
- this._isDragging = false;
3416
- this._timeline = null;
3417
- 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();
3418
3541
  }
3542
+ this._resetInteractionState();
3419
3543
  };
3420
3544
  this._host = host;
3421
3545
  }
@@ -3443,6 +3567,28 @@ var PointerHandler = class {
3443
3567
  }
3444
3568
  return time * h.effectiveSampleRate / h.samplesPerPixel;
3445
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
+ }
3446
3592
  _finalizeSelection() {
3447
3593
  const h = this._host;
3448
3594
  if (h._engine) {
@@ -3778,6 +3924,23 @@ var ClipPointerHandler = class {
3778
3924
  this._reset();
3779
3925
  }
3780
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
+ }
3781
3944
  /** Re-extract peaks from cache and set on waveform elements during trim drag.
3782
3945
  * Returns true if peaks were successfully updated. */
3783
3946
  _updateWaveformPeaks(offsetSamples, durationSamples) {
@@ -3795,7 +3958,11 @@ var ClipPointerHandler = class {
3795
3958
  }
3796
3959
  return true;
3797
3960
  }
3798
- /** 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. */
3799
3966
  _restoreTrimVisual() {
3800
3967
  if (this._clipContainer) {
3801
3968
  this._clipContainer.style.left = this._originalLeft + "px";
@@ -3804,6 +3971,7 @@ var ClipPointerHandler = class {
3804
3971
  for (const wf of waveforms) {
3805
3972
  wf.style.left = "0px";
3806
3973
  }
3974
+ this._updateWaveformPeaks(this._originalOffsetSamples, this._originalDurationSamples);
3807
3975
  }
3808
3976
  }
3809
3977
  _reset() {
@@ -3889,8 +4057,18 @@ async function loadFiles(host, files) {
3889
4057
  const failed = [];
3890
4058
  for (const file of fileArray) {
3891
4059
  if (file.type && !file.type.startsWith("audio/")) {
3892
- 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 });
3893
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
+ }
3894
4072
  continue;
3895
4073
  }
3896
4074
  const blobUrl = URL.createObjectURL(file);
@@ -4111,15 +4289,18 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
4111
4289
  name: clipName ?? "Recording"
4112
4290
  });
4113
4291
  host._clipBuffers = new Map(host._clipBuffers).set(clip.id, trimmedBuf);
4114
- host._peakPipeline.generatePeaks(trimmedBuf, host.samplesPerPixel, host.mono).then((pd) => {
4292
+ host._clipOffsets.set(clip.id, { offsetSamples: 0, durationSamples: durSamples });
4293
+ host._peakPipeline.generatePeaks(trimmedBuf, host.renderSamplesPerPixel, host.mono).then((pd) => {
4115
4294
  const t = host._engineTracks.get(trackId);
4116
4295
  if (!t) {
4117
4296
  const next = new Map(host._clipBuffers);
4118
4297
  next.delete(clip.id);
4119
4298
  host._clipBuffers = next;
4299
+ host._clipOffsets.delete(clip.id);
4120
4300
  return;
4121
4301
  }
4122
4302
  host._peaksData = new Map(host._peaksData).set(clip.id, pd);
4303
+ host._raiseZoomFloor(host._peakPipeline.getCachedScale(trimmedBuf));
4123
4304
  host._engineTracks = new Map(host._engineTracks).set(trackId, {
4124
4305
  ...t,
4125
4306
  // Punch-in replace (#579): the recorded clip owns [startSample,
@@ -4163,6 +4344,7 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
4163
4344
  const next = new Map(host._clipBuffers);
4164
4345
  next.delete(clip.id);
4165
4346
  host._clipBuffers = next;
4347
+ host._clipOffsets.delete(clip.id);
4166
4348
  if (host.isConnected) {
4167
4349
  host.dispatchEvent(
4168
4350
  new CustomEvent("daw-error", {
@@ -4387,7 +4569,10 @@ var EffectsChainController = class {
4387
4569
  kind: "wam",
4388
4570
  ...sourceFields,
4389
4571
  bypassed: entry.placeholder.bypassed,
4390
- ...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
4391
4576
  };
4392
4577
  }
4393
4578
  let state8;
@@ -4405,6 +4590,15 @@ var EffectsChainController = class {
4405
4590
  ...state8 !== void 0 ? { state: state8 } : {}
4406
4591
  };
4407
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
+ }
4408
4602
  return {
4409
4603
  kind: "native",
4410
4604
  type: entry.type,
@@ -4443,13 +4637,17 @@ var EffectsChainController = class {
4443
4637
  entry.instance.dispose?.();
4444
4638
  this._rebuild();
4445
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. */
4446
4643
  move(effectId, newIndex) {
4447
4644
  const entry = this._find("move", effectId);
4448
- if (!entry) return;
4645
+ if (!entry) return -1;
4449
4646
  const without = this._entries.filter((e) => e.id !== effectId);
4450
4647
  const at = Math.max(0, Math.min(newIndex, without.length));
4451
4648
  this._entries = [...without.slice(0, at), entry, ...without.slice(at)];
4452
4649
  this._rebuild();
4650
+ return at;
4453
4651
  }
4454
4652
  setParams(effectId, params) {
4455
4653
  const entry = this._find("setParams", effectId);
@@ -4673,10 +4871,11 @@ registerBuiltIns();
4673
4871
 
4674
4872
  // src/effects/effects-manager.ts
4675
4873
  var PREFIX2 = "[waveform-playlist] ";
4676
- function makeGuiRecord(element, destroyImpl) {
4874
+ function makeGuiRecord(element, destroyImpl, isFallback = false) {
4677
4875
  let destroyed = false;
4678
4876
  return {
4679
4877
  element,
4878
+ isFallback,
4680
4879
  destroy: () => {
4681
4880
  if (destroyed) return;
4682
4881
  destroyed = true;
@@ -4855,7 +5054,7 @@ var EffectsManager = class {
4855
5054
  );
4856
5055
  }
4857
5056
  const cached = this._guis.get(effectId);
4858
- if (cached) {
5057
+ if (cached && !cached.isFallback) {
4859
5058
  container.appendChild(cached.element);
4860
5059
  return cached.element;
4861
5060
  }
@@ -4866,7 +5065,22 @@ var EffectsManager = class {
4866
5065
  });
4867
5066
  this._guiPending.set(effectId, pending);
4868
5067
  }
4869
- 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
+ }
4870
5084
  if (chain.disposed || !chain.getEntry(effectId)) {
4871
5085
  this._guis.delete(effectId);
4872
5086
  record.element.remove();
@@ -4901,7 +5115,7 @@ var EffectsManager = class {
4901
5115
  }
4902
5116
  const element = await this._createFallbackPanel(chain, target, entry, effectId);
4903
5117
  return makeGuiRecord(element, () => {
4904
- });
5118
+ }, true);
4905
5119
  }
4906
5120
  /** The generic parameter panel — one code path for "no custom GUI":
4907
5121
  * native entries render from the registry's params metadata, WAM entries
@@ -5144,9 +5358,23 @@ var EffectsManager = class {
5144
5358
  for (const entry of entries) {
5145
5359
  if (superseded()) return;
5146
5360
  if (entry.kind === "native") {
5147
- const id = this._addToChain(chain, target, entry.type, entry.params);
5148
- if (entry.bypassed) {
5149
- 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
+ });
5150
5378
  }
5151
5379
  continue;
5152
5380
  }
@@ -5163,7 +5391,7 @@ var EffectsManager = class {
5163
5391
  this._runOp(chain, target, "setBypassed", id, true);
5164
5392
  }
5165
5393
  } catch (err) {
5166
- if (superseded()) return;
5394
+ if (superseded() || chain.disposed) return;
5167
5395
  const message = err instanceof Error ? err.message : String(err);
5168
5396
  const sourceLabel = entry.url ?? entry.faustName ?? "Faust effect";
5169
5397
  console.warn(
@@ -5179,6 +5407,25 @@ var EffectsManager = class {
5179
5407
  }
5180
5408
  }
5181
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
+ }
5182
5429
  /** A silent passthrough occupying the failed plugin's chain position. */
5183
5430
  _addWamPlaceholder(chain, entry, message) {
5184
5431
  const { audioContext } = this._requireWiring();
@@ -5225,10 +5472,11 @@ var EffectsManager = class {
5225
5472
  chain.setBypassed(effectId, arg);
5226
5473
  this._dispatch(target, "daw-effect-bypass", { effectId, bypassed: arg });
5227
5474
  break;
5228
- case "move":
5229
- chain.move(effectId, arg);
5230
- 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 });
5231
5478
  break;
5479
+ }
5232
5480
  }
5233
5481
  }
5234
5482
  _dispatch(target, name, detail) {
@@ -5269,6 +5517,9 @@ function validateSerializedEntries(entries) {
5269
5517
  if (typeof e.bypassed !== "boolean") {
5270
5518
  throw new Error(PREFIX2 + "setEffectsState: entry requires a boolean bypassed flag" + at);
5271
5519
  }
5520
+ if (e.placeholder !== void 0 && e.placeholder !== true) {
5521
+ throw new Error(PREFIX2 + "setEffectsState: placeholder must be true when present" + at);
5522
+ }
5272
5523
  });
5273
5524
  }
5274
5525
  function toWamParameterMap(params) {
@@ -5301,6 +5552,9 @@ async function exportAudioImpl(host, options = {}) {
5301
5552
  try {
5302
5553
  const masterChain = await buildOfflineChain(ctx, await host.getMasterEffectsState());
5303
5554
  cleanups.push(masterChain.dispose);
5555
+ const masterVolume = ctx.createGain();
5556
+ masterVolume.gain.value = host.masterVolume ?? 1;
5557
+ masterVolume.connect(masterChain.input);
5304
5558
  masterChain.output.connect(ctx.destination);
5305
5559
  const anySoloed = host.tracks.some((t) => t.soloed);
5306
5560
  for (const track of host.tracks) {
@@ -5315,7 +5569,7 @@ async function exportAudioImpl(host, options = {}) {
5315
5569
  panner.pan.value = track.pan;
5316
5570
  volume.connect(panner);
5317
5571
  panner.connect(chain.input);
5318
- chain.output.connect(masterChain.input);
5572
+ chain.output.connect(masterVolume);
5319
5573
  for (const clip of track.clips) {
5320
5574
  scheduleClip(ctx, clip, startTime, duration, volume);
5321
5575
  }
@@ -5386,6 +5640,12 @@ async function buildOfflineChain(ctx, entries) {
5386
5640
  return { input, output, dispose };
5387
5641
  async function wireEntries() {
5388
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
+ }
5389
5649
  if (entry.kind === "native") {
5390
5650
  const created = createEffectInstance(entry.type, ctx, entry.params);
5391
5651
  if (entry.bypassed) {
@@ -5656,6 +5916,13 @@ var PlaybackAnimationController = class {
5656
5916
  // src/elements/daw-editor.ts
5657
5917
  var RULER_HEIGHT = 30;
5658
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
+ };
5659
5926
  var DawEditorElement = class extends LitElement11 {
5660
5927
  constructor() {
5661
5928
  super(...arguments);
@@ -5695,6 +5962,9 @@ var DawEditorElement = class extends LitElement11 {
5695
5962
  this._selectionEndTime = 0;
5696
5963
  this._currentTime = 0;
5697
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;
5698
5968
  // --- Effects (master chain; per-track chains delegated from <daw-track>) ---
5699
5969
  this._effectsManager = null;
5700
5970
  this._engine = null;
@@ -5709,6 +5979,11 @@ var DawEditorElement = class extends LitElement11 {
5709
5979
  /** Coarsest scale from pre-computed peaks — zoom cannot go finer than this. 0 = no limit. */
5710
5980
  this._minSamplesPerPixel = 0;
5711
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();
5712
5987
  this._childObserver = null;
5713
5988
  this._audioResume = new AudioResumeController(this);
5714
5989
  this._recordingController = new RecordingController(this);
@@ -5853,11 +6128,17 @@ var DawEditorElement = class extends LitElement11 {
5853
6128
  const trackEl = clipEl.closest("daw-track");
5854
6129
  if (!trackEl) return;
5855
6130
  const trackId = trackEl.trackId;
5856
- if (!this._engineTracks.has(trackId)) {
6131
+ if (!this._engineTracks.has(trackId) || this._loadingTracks.has(trackId)) {
5857
6132
  const desc = this._tracks.get(trackId);
5858
6133
  if (desc && !desc.clips.some((c) => isDomClip(c) && c.clipId === clipEl.clipId)) {
5859
- console.warn(
5860
- '[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
+ })
5861
6142
  );
5862
6143
  }
5863
6144
  return;
@@ -5949,12 +6230,38 @@ var DawEditorElement = class extends LitElement11 {
5949
6230
  const clamped = this._minSamplesPerPixel > 0 && value < this._minSamplesPerPixel ? this._minSamplesPerPixel : value;
5950
6231
  if (clamped !== value) {
5951
6232
  console.warn(
5952
- "[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"
5953
6234
  );
5954
6235
  }
5955
6236
  this._samplesPerPixel = clamped;
5956
6237
  this.requestUpdate("samplesPerPixel", old);
5957
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
+ }
5958
6265
  get timeFormat() {
5959
6266
  return this._timeFormat;
5960
6267
  }
@@ -6100,6 +6407,7 @@ var DawEditorElement = class extends LitElement11 {
6100
6407
  console.warn("[dawcore] Adapter AudioContext is already closed. Ignoring.");
6101
6408
  return;
6102
6409
  }
6410
+ this._adapterConsumedByDispose = false;
6103
6411
  if (this._engine) {
6104
6412
  console.warn(
6105
6413
  "[dawcore] adapter set after engine is built. The engine will continue using the previous adapter."
@@ -6187,6 +6495,7 @@ var DawEditorElement = class extends LitElement11 {
6187
6495
  effectiveSampleRate: this.effectiveSampleRate,
6188
6496
  duration: this._duration,
6189
6497
  tracks: [...this._engineTracks.values()],
6498
+ masterVolume: this._engine?.getState().masterVolume ?? 1,
6190
6499
  getMasterEffectsState: () => this.getEffectsState(),
6191
6500
  getTrackEffectsState: (trackId) => this.getTrackEffectsState(trackId)
6192
6501
  },
@@ -6468,11 +6777,21 @@ var DawEditorElement = class extends LitElement11 {
6468
6777
  this._minSamplesPerPixel = 0;
6469
6778
  this._spectrogramController?.dispose();
6470
6779
  this._spectrogramController = null;
6780
+ this._lastSpectrogramViewport = null;
6781
+ const hadEngine = this._engine !== null;
6471
6782
  try {
6472
6783
  this._disposeEngine();
6473
6784
  } catch (err) {
6474
6785
  console.warn("[dawcore] Error disposing engine: " + String(err));
6475
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();
6476
6795
  }
6477
6796
  willUpdate(changedProperties) {
6478
6797
  if (changedProperties.has("eagerResume")) {
@@ -6481,8 +6800,8 @@ var DawEditorElement = class extends LitElement11 {
6481
6800
  if ((changedProperties.has("samplesPerPixel") || changedProperties.has("ticksPerPixel") || changedProperties.has("bpm") || changedProperties.has("secondsToTicks")) && this._isPlaying) {
6482
6801
  this._startPlayhead();
6483
6802
  }
6484
- const zoomChanged = changedProperties.has("samplesPerPixel") || changedProperties.has("ticksPerPixel") || changedProperties.has("bpm") || changedProperties.has("scaleMode") || changedProperties.has("secondsToTicks");
6485
- 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) {
6486
6805
  const re = this._peakPipeline.reextractPeaks(
6487
6806
  this._clipBuffers,
6488
6807
  this._renderSpp,
@@ -6549,9 +6868,16 @@ var DawEditorElement = class extends LitElement11 {
6549
6868
  if (this._engine) {
6550
6869
  this._engine.removeTrack(trackId);
6551
6870
  }
6552
- this._minSamplesPerPixel = this._peakPipeline.getMaxCachedScale(this._clipBuffers);
6871
+ this._recomputeZoomFloor();
6553
6872
  this._disposeSpectrogramControllerIfEmpty();
6554
- 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
+ }
6555
6881
  this._currentTime = 0;
6556
6882
  this._stopPlayhead();
6557
6883
  }
@@ -6574,6 +6900,45 @@ var DawEditorElement = class extends LitElement11 {
6574
6900
  if (!stillNeeded) {
6575
6901
  this._spectrogramController.dispose();
6576
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;
6577
6942
  }
6578
6943
  }
6579
6944
  _onClipRemovedFromDom(clipEl) {
@@ -6719,9 +7084,8 @@ var DawEditorElement = class extends LitElement11 {
6719
7084
  throw err;
6720
7085
  }
6721
7086
  this._peaksData = new Map(this._peaksData).set(clip.id, peakData);
6722
- if (waveformData) {
6723
- this._minSamplesPerPixel = Math.max(this._minSamplesPerPixel, waveformData.scale);
6724
- }
7087
+ const cachedScale = waveformData?.scale ?? this._peakPipeline.getCachedScale(audioBuffer);
7088
+ this._raiseZoomFloor(cachedScale);
6725
7089
  return clip;
6726
7090
  }
6727
7091
  /**
@@ -6964,6 +7328,8 @@ var DawEditorElement = class extends LitElement11 {
6964
7328
  }
6965
7329
  // --- Audio Loading ---
6966
7330
  async _loadTrack(trackId, descriptor) {
7331
+ this._loadingTracks.add(trackId);
7332
+ const sppAtLoadStart = this._samplesPerPixel;
6967
7333
  try {
6968
7334
  const clips = [];
6969
7335
  for (const clipDesc of descriptor.clips) {
@@ -7001,18 +7367,20 @@ var DawEditorElement = class extends LitElement11 {
7001
7367
  durationSamples: clip2.durationSamples
7002
7368
  });
7003
7369
  this._peaksData = new Map(this._peaksData).set(clip2.id, peakData);
7004
- this._minSamplesPerPixel = Math.max(this._minSamplesPerPixel, waveformData.scale);
7005
- const previewTrack = createTrack2({
7006
- name: descriptor.name,
7007
- clips: [clip2],
7008
- volume: descriptor.volume,
7009
- pan: descriptor.pan,
7010
- muted: descriptor.muted,
7011
- soloed: descriptor.soloed
7012
- });
7013
- previewTrack.id = trackId;
7014
- this._engineTracks = new Map(this._engineTracks).set(trackId, previewTrack);
7015
- 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
+ }
7016
7384
  let audioBuffer2;
7017
7385
  try {
7018
7386
  audioBuffer2 = await audioPromise;
@@ -7024,7 +7392,7 @@ var DawEditorElement = class extends LitElement11 {
7024
7392
  const nextEngine = new Map(this._engineTracks);
7025
7393
  nextEngine.delete(trackId);
7026
7394
  this._engineTracks = nextEngine;
7027
- this._minSamplesPerPixel = this._peakPipeline.getMaxCachedScale(this._clipBuffers);
7395
+ this._recomputeZoomFloor();
7028
7396
  this._recomputeDuration();
7029
7397
  throw audioErr;
7030
7398
  }
@@ -7058,6 +7426,26 @@ var DawEditorElement = class extends LitElement11 {
7058
7426
  }
7059
7427
  }
7060
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
+ }
7061
7449
  const track = createTrack2({
7062
7450
  name: descriptor.name,
7063
7451
  clips,
@@ -7088,15 +7476,23 @@ var DawEditorElement = class extends LitElement11 {
7088
7476
  })
7089
7477
  );
7090
7478
  } catch (err) {
7091
- if (!this.isConnected) return;
7092
- 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
+ );
7093
7483
  this.dispatchEvent(
7094
7484
  new CustomEvent("daw-track-error", {
7095
7485
  bubbles: true,
7096
7486
  composed: true,
7097
- detail: { trackId, error: err }
7487
+ detail: {
7488
+ trackId,
7489
+ error: err,
7490
+ ...cancelled ? { reason: err.reason } : {}
7491
+ }
7098
7492
  })
7099
7493
  );
7494
+ } finally {
7495
+ this._loadingTracks.delete(trackId);
7100
7496
  }
7101
7497
  }
7102
7498
  async _fetchAndDecode(src) {
@@ -7155,6 +7551,11 @@ var DawEditorElement = class extends LitElement11 {
7155
7551
  if (!this._externalAdapter) {
7156
7552
  throw new Error(NO_ADAPTER_ERROR);
7157
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
+ }
7158
7559
  const { PlaylistEngine } = await import("@waveform-playlist/engine");
7159
7560
  const adapter = this._externalAdapter;
7160
7561
  if (!this._hasTickCallbacks) {
@@ -7191,6 +7592,7 @@ var DawEditorElement = class extends LitElement11 {
7191
7592
  nextTracks.set(track.id, track);
7192
7593
  }
7193
7594
  this._engineTracks = nextTracks;
7595
+ this._reconcileDescriptorsWithEngineTracks(engineState.tracks);
7194
7596
  }
7195
7597
  if (structuralChange) {
7196
7598
  this._effectsManager?.rewireTrackChains();
@@ -7547,24 +7949,60 @@ var DawEditorElement = class extends LitElement11 {
7547
7949
  this.play();
7548
7950
  }
7549
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
+ }
7550
7967
  seekTo(time) {
7551
7968
  if (!this._engine) {
7552
7969
  console.warn("[dawcore] seekTo: engine not ready, call ignored");
7553
7970
  return;
7554
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);
7555
7977
  if (this._isPlaying) {
7556
- this._inSeekTransition = true;
7557
7978
  try {
7558
- this.stop();
7559
- } finally {
7560
- 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;
7561
7991
  }
7562
- this.play(time);
7992
+ this._currentTime = target;
7993
+ this._startPlayhead();
7563
7994
  } else {
7564
- this._engine.seek(time);
7565
- this._currentTime = time;
7995
+ this._engine.seek(target);
7996
+ this._currentTime = target;
7566
7997
  this._stopPlayhead();
7567
7998
  }
7999
+ this.dispatchEvent(
8000
+ new CustomEvent("daw-seek", {
8001
+ bubbles: true,
8002
+ composed: true,
8003
+ detail: { time: target }
8004
+ })
8005
+ );
7568
8006
  }
7569
8007
  /** Undo the last structural edit. */
7570
8008
  undo() {
@@ -7599,8 +8037,10 @@ var DawEditorElement = class extends LitElement11 {
7599
8037
  engine: this._engine,
7600
8038
  dispatchEvent: (e) => this.dispatchEvent(e),
7601
8039
  stop: () => {
7602
- this._engine?.stop();
7603
- this._stopPlayhead();
8040
+ this._withSeekSuppression(() => {
8041
+ this._engine?.stop();
8042
+ this._stopPlayhead();
8043
+ });
7604
8044
  },
7605
8045
  // Call engine.play directly (synchronous) — not the async editor play()
7606
8046
  // which yields to microtask queue via await engine.init(). Engine is
@@ -7687,6 +8127,25 @@ var DawEditorElement = class extends LitElement11 {
7687
8127
  }
7688
8128
  await this._recordingController.startRecording(s, options);
7689
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
+ }
7690
8149
  _renderRecordingPreview(trackId, chH) {
7691
8150
  const rs = this._recordingController.getSession(trackId);
7692
8151
  if (!rs) return "";
@@ -7694,8 +8153,7 @@ var DawEditorElement = class extends LitElement11 {
7694
8153
  if (audibleSamples === 0) return "";
7695
8154
  const renderSpp = this._renderSpp;
7696
8155
  const latencyPixels = Math.floor(rs.latencySamples / renderSpp);
7697
- const left = Math.floor(rs.startSample / renderSpp);
7698
- const w = Math.floor(audibleSamples / renderSpp);
8156
+ const { left, width: w } = this._previewPosition(rs.startSample, audibleSamples);
7699
8157
  const hdrH = this.clipHeaders ? this.clipHeaderHeight : 0;
7700
8158
  const height = hdrH + chH * rs.peaks.length;
7701
8159
  return html10`<div
@@ -8337,11 +8795,16 @@ var DawKeyboardShortcutsElement = class extends LitElement13 {
8337
8795
  this.splitting = false;
8338
8796
  this.undo = false;
8339
8797
  // --- JS properties for remapping ---
8340
- this.playbackShortcuts = null;
8341
- this.splittingShortcuts = null;
8342
- 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;
8343
8806
  /** Additional custom shortcuts. */
8344
- this.customShortcuts = [];
8807
+ this._customShortcuts = [];
8345
8808
  this._editor = null;
8346
8809
  this._cachedShortcuts = null;
8347
8810
  // --- Event handler ---
@@ -8363,6 +8826,34 @@ var DawKeyboardShortcutsElement = class extends LitElement13 {
8363
8826
  }
8364
8827
  };
8365
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
+ }
8366
8857
  /** All active shortcuts (read-only, cached). */
8367
8858
  get shortcuts() {
8368
8859
  if (!this._cachedShortcuts) {
@@ -8377,6 +8868,18 @@ var DawKeyboardShortcutsElement = class extends LitElement13 {
8377
8868
  // --- Lifecycle ---
8378
8869
  connectedCallback() {
8379
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
+ }
8380
8883
  this._editor = this.closest("daw-editor");
8381
8884
  if (!this._editor) {
8382
8885
  console.warn(
@@ -8902,6 +9405,9 @@ var DawPlayerElement = class extends LitElement17 {
8902
9405
  this.roundedBars = false;
8903
9406
  this._playbackRate = 1;
8904
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;
8905
9411
  this._trackId = null;
8906
9412
  this._anim = new AnimationController(this);
8907
9413
  this._metadataLoaded = false;
@@ -8919,7 +9425,6 @@ var DawPlayerElement = class extends LitElement17 {
8919
9425
  if (width <= 0 || d <= 0) return;
8920
9426
  const ratio = Math.max(0, Math.min(1, e.offsetX / width));
8921
9427
  this.seekTo(ratio * d);
8922
- this._updatePlayhead();
8923
9428
  };
8924
9429
  this._onLoadedMetadata = () => {
8925
9430
  this._metadataLoaded = true;
@@ -8967,6 +9472,15 @@ var DawPlayerElement = class extends LitElement17 {
8967
9472
  }
8968
9473
  connectedCallback() {
8969
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
+ }
8970
9484
  this._engine.on("loadedmetadata", this._onLoadedMetadata);
8971
9485
  this._engine.on("play", this._onPlay);
8972
9486
  this._engine.on("pause", this._onPause);
@@ -8977,6 +9491,10 @@ var DawPlayerElement = class extends LitElement17 {
8977
9491
  const area = this.shadowRoot?.querySelector(".waveform-area");
8978
9492
  if (area) this._resizeObserver?.observe(area);
8979
9493
  });
9494
+ if (rebuilt && this.src) {
9495
+ this._loadSource();
9496
+ this._playhead?.setPosition(0);
9497
+ }
8980
9498
  }
8981
9499
  render() {
8982
9500
  const width = this._timelineWidth;
@@ -9036,6 +9554,7 @@ var DawPlayerElement = class extends LitElement17 {
9036
9554
  this._renderWaveform();
9037
9555
  this._maybeDispatchReady();
9038
9556
  } catch (err) {
9557
+ if (this.peaksSrc !== requested) return;
9039
9558
  console.warn("[dawcore] <daw-player> failed to load peaks-src: " + String(err));
9040
9559
  this._peaksSettled = true;
9041
9560
  this._renderWaveform();
@@ -9076,7 +9595,7 @@ var DawPlayerElement = class extends LitElement17 {
9076
9595
  }
9077
9596
  // --- Transport methods ---
9078
9597
  play() {
9079
- this._engine.play();
9598
+ this._engine.resume();
9080
9599
  }
9081
9600
  pause() {
9082
9601
  this._engine.pause();
@@ -9089,6 +9608,10 @@ var DawPlayerElement = class extends LitElement17 {
9089
9608
  }
9090
9609
  seekTo(time) {
9091
9610
  this._engine.seekTo(time);
9611
+ if (!this._engine.isPlaying) {
9612
+ this._updatePlayhead();
9613
+ this._dispatch("daw-timeupdate", { time: this._engine.getCurrentTime() });
9614
+ }
9092
9615
  }
9093
9616
  setPlaybackRate(rate) {
9094
9617
  this.playbackRate = rate;
@@ -9107,7 +9630,7 @@ var DawPlayerElement = class extends LitElement17 {
9107
9630
  return this._engine.getCurrentTime();
9108
9631
  }
9109
9632
  set currentTime(time) {
9110
- this._engine.seekTo(time);
9633
+ this.seekTo(time);
9111
9634
  }
9112
9635
  get volume() {
9113
9636
  return this._engine.masterVolume;
@@ -9129,6 +9652,7 @@ var DawPlayerElement = class extends LitElement17 {
9129
9652
  this._engine.off("ended", this._onEnded);
9130
9653
  this._engine.off("error", this._onError);
9131
9654
  this._engine.dispose();
9655
+ this._engineDisposed = true;
9132
9656
  }
9133
9657
  // --- Private event handlers (arrow fields for stable identity) ---
9134
9658
  _dispatch(name, detail) {