@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.js CHANGED
@@ -465,11 +465,9 @@ var LAYOUT_PROPS = /* @__PURE__ */ new Set([
465
465
  "roundedBars",
466
466
  "segments"
467
467
  ]);
468
- function groupDirtyByChunk(dirtyPixels, step) {
468
+ function groupDirtyByChunk(dirtyPixels, step, barWidth) {
469
469
  const dirtyByChunk = /* @__PURE__ */ new Map();
470
- for (const peakIdx of dirtyPixels) {
471
- const barPixel = Math.floor(peakIdx / step) * step;
472
- const chunkIdx = Math.floor(barPixel / MAX_CANVAS_WIDTH);
470
+ const mark = (chunkIdx, barPixel) => {
473
471
  const existing = dirtyByChunk.get(chunkIdx);
474
472
  if (existing) {
475
473
  dirtyByChunk.set(chunkIdx, {
@@ -479,6 +477,15 @@ function groupDirtyByChunk(dirtyPixels, step) {
479
477
  } else {
480
478
  dirtyByChunk.set(chunkIdx, { min: barPixel, max: barPixel });
481
479
  }
480
+ };
481
+ for (const peakIdx of dirtyPixels) {
482
+ const barPixel = Math.floor(peakIdx / step) * step;
483
+ const chunkIdx = Math.floor(barPixel / MAX_CANVAS_WIDTH);
484
+ mark(chunkIdx, barPixel);
485
+ const endChunkIdx = Math.floor((barPixel + barWidth - 1) / MAX_CANVAS_WIDTH);
486
+ if (endChunkIdx !== chunkIdx) {
487
+ mark(endChunkIdx, barPixel);
488
+ }
482
489
  }
483
490
  return dirtyByChunk;
484
491
  }
@@ -580,7 +587,7 @@ var DawWaveformElement = class extends import_lit3.LitElement {
580
587
  this._drawSegments(canvas, chunkIdx, dpr, halfHeight, bits, waveColor);
581
588
  }
582
589
  } else {
583
- const dirtyByChunk = groupDirtyByChunk(this._dirtyPixels, step);
590
+ const dirtyByChunk = groupDirtyByChunk(this._dirtyPixels, step, this.barWidth);
584
591
  for (const canvas of canvases) {
585
592
  const chunkIdx = Number(canvas.dataset.index);
586
593
  this._drawnChunks.add(chunkIdx);
@@ -1201,16 +1208,31 @@ var DawPlayButtonElement = class extends DawTransportButton {
1201
1208
  connectedCallback() {
1202
1209
  super.connectedCallback();
1203
1210
  requestAnimationFrame(() => {
1204
- const target = this.target;
1205
- if (!target) return;
1206
- this._targetRef = target;
1207
- target.addEventListener("daw-recording-start", this._onRecStart);
1208
- target.addEventListener("daw-recording-complete", this._onRecEnd);
1209
- target.addEventListener("daw-recording-error", this._onRecEnd);
1211
+ if (!this.isConnected) return;
1212
+ this._ensureTargetListeners();
1210
1213
  });
1211
1214
  }
1212
1215
  disconnectedCallback() {
1213
1216
  super.disconnectedCallback();
1217
+ this._cleanupListeners();
1218
+ }
1219
+ updated() {
1220
+ this._ensureTargetListeners();
1221
+ }
1222
+ _ensureTargetListeners() {
1223
+ const target = this.target;
1224
+ if (target === this._targetRef) return;
1225
+ if (this._targetRef) {
1226
+ this._isRecording = false;
1227
+ }
1228
+ this._cleanupListeners();
1229
+ if (!target) return;
1230
+ this._targetRef = target;
1231
+ target.addEventListener("daw-recording-start", this._onRecStart);
1232
+ target.addEventListener("daw-recording-complete", this._onRecEnd);
1233
+ target.addEventListener("daw-recording-error", this._onRecEnd);
1234
+ }
1235
+ _cleanupListeners() {
1214
1236
  if (this._targetRef) {
1215
1237
  this._targetRef.removeEventListener("daw-recording-start", this._onRecStart);
1216
1238
  this._targetRef.removeEventListener("daw-recording-complete", this._onRecEnd);
@@ -1269,18 +1291,34 @@ var DawPauseButtonElement = class extends DawTransportButton {
1269
1291
  connectedCallback() {
1270
1292
  super.connectedCallback();
1271
1293
  requestAnimationFrame(() => {
1272
- const target = this.target;
1273
- if (!target) return;
1274
- this._targetRef = target;
1275
- target.addEventListener("daw-recording-start", this._onRecStart);
1276
- target.addEventListener("daw-recording-complete", this._onRecEnd);
1277
- target.addEventListener("daw-recording-error", this._onRecEnd);
1278
- target.addEventListener("daw-recording-pause", this._onRecPause);
1279
- target.addEventListener("daw-recording-resume", this._onRecResume);
1294
+ if (!this.isConnected) return;
1295
+ this._ensureTargetListeners();
1280
1296
  });
1281
1297
  }
1282
1298
  disconnectedCallback() {
1283
1299
  super.disconnectedCallback();
1300
+ this._cleanupListeners();
1301
+ }
1302
+ updated() {
1303
+ this._ensureTargetListeners();
1304
+ }
1305
+ _ensureTargetListeners() {
1306
+ const target = this.target;
1307
+ if (target === this._targetRef) return;
1308
+ if (this._targetRef) {
1309
+ this._isRecording = false;
1310
+ this._isPaused = false;
1311
+ }
1312
+ this._cleanupListeners();
1313
+ if (!target) return;
1314
+ this._targetRef = target;
1315
+ target.addEventListener("daw-recording-start", this._onRecStart);
1316
+ target.addEventListener("daw-recording-complete", this._onRecEnd);
1317
+ target.addEventListener("daw-recording-error", this._onRecEnd);
1318
+ target.addEventListener("daw-recording-pause", this._onRecPause);
1319
+ target.addEventListener("daw-recording-resume", this._onRecResume);
1320
+ }
1321
+ _cleanupListeners() {
1284
1322
  if (this._targetRef) {
1285
1323
  this._targetRef.removeEventListener("daw-recording-start", this._onRecStart);
1286
1324
  this._targetRef.removeEventListener("daw-recording-complete", this._onRecEnd);
@@ -1553,6 +1591,12 @@ function createPeaksWorker() {
1553
1591
  )
1554
1592
  );
1555
1593
  },
1594
+ // Reports NOT terminated: CSP blocking is permanent for the page, so
1595
+ // recreating on every call would just re-attempt (and re-warn about)
1596
+ // Worker construction each time.
1597
+ isTerminated() {
1598
+ return false;
1599
+ },
1556
1600
  terminate() {
1557
1601
  }
1558
1602
  };
@@ -1590,6 +1634,9 @@ function createPeaksWorker() {
1590
1634
  pending.clear();
1591
1635
  };
1592
1636
  return {
1637
+ isTerminated() {
1638
+ return terminated;
1639
+ },
1593
1640
  generate(params) {
1594
1641
  if (terminated) return Promise.reject(new Error("Worker terminated"));
1595
1642
  const messageId = String(++idCounter2);
@@ -1805,6 +1852,12 @@ var PeakPipeline = class {
1805
1852
  scale: cached.scale
1806
1853
  };
1807
1854
  }
1855
+ /** Scale of the cached WaveformData for this buffer — 0 when not cached.
1856
+ * Worker generation caches at baseScale; injected .dat data at its own
1857
+ * scale. This is the finest zoom the buffer's peaks can render at. */
1858
+ getCachedScale(audioBuffer) {
1859
+ return this._cache.get(audioBuffer)?.scale ?? 0;
1860
+ }
1808
1861
  /**
1809
1862
  * Return the coarsest (largest) scale among cached WaveformData entries
1810
1863
  * that correspond to the given clip buffers. Returns 0 if none are cached.
@@ -1826,7 +1879,7 @@ var PeakPipeline = class {
1826
1879
  if (cached) return cached;
1827
1880
  const inflight = this._inflight.get(audioBuffer);
1828
1881
  if (inflight) return inflight;
1829
- if (!this._worker) {
1882
+ if (!this._worker || this._worker.isTerminated()) {
1830
1883
  this._worker = createPeaksWorker();
1831
1884
  }
1832
1885
  const channels = [];
@@ -2812,7 +2865,11 @@ var RecordingController = class {
2812
2865
  * The session is only set after several awaits — without this, two rapid
2813
2866
  * start calls both pass the _sessions guard and build two capture
2814
2867
  * pipelines feeding one session (garbled audio + a leaked worklet). */
2815
- this._starting = /* @__PURE__ */ new Set();
2868
+ this._starting = /* @__PURE__ */ new Map();
2869
+ /** True between hostDisconnected and hostConnected. An in-flight
2870
+ * startRecording consults this after its awaits so a teardown mid-setup
2871
+ * doesn't leak a live capture session on a detached editor. */
2872
+ this._hostDisconnected = false;
2816
2873
  this._workletLoadedCtx = null;
2817
2874
  /** Tracks worklet pause state explicitly so external consumers (editor,
2818
2875
  * pause button, spacebar) can share one source of truth. */
@@ -2821,15 +2878,17 @@ var RecordingController = class {
2821
2878
  host.addController(this);
2822
2879
  }
2823
2880
  hostConnected() {
2881
+ this._hostDisconnected = false;
2824
2882
  }
2825
2883
  hostDisconnected() {
2884
+ this._hostDisconnected = true;
2826
2885
  for (const trackId of [...this._sessions.keys()]) {
2827
2886
  this._cleanupSession(trackId, true);
2828
2887
  }
2829
2888
  this._workletLoadedCtx = null;
2830
2889
  }
2831
2890
  get isRecording() {
2832
- return this._sessions.size > 0;
2891
+ return this._sessions.size > 0 || this._starting.size > 0;
2833
2892
  }
2834
2893
  get isPaused() {
2835
2894
  return this._isPaused && this._sessions.size > 0;
@@ -2847,7 +2906,14 @@ var RecordingController = class {
2847
2906
  console.warn('[dawcore] RecordingController: Already recording on track "' + trackId + '"');
2848
2907
  return;
2849
2908
  }
2850
- this._starting.add(trackId);
2909
+ let resolveStartSettled;
2910
+ const startEntry = {
2911
+ stopRequested: false,
2912
+ done: new Promise((resolve) => {
2913
+ resolveStartSettled = resolve;
2914
+ })
2915
+ };
2916
+ this._starting.set(trackId, startEntry);
2851
2917
  const bits = options.bits ?? 16;
2852
2918
  try {
2853
2919
  const rawCtx = this._host.audioContext;
@@ -2868,6 +2934,15 @@ var RecordingController = class {
2868
2934
  await addRecordingWorkletModule(addModule);
2869
2935
  this._workletLoadedCtx = rawCtx;
2870
2936
  }
2937
+ if (startEntry.stopRequested || this._hostDisconnected) {
2938
+ this._dispatchRecordingError(
2939
+ trackId,
2940
+ new Error(
2941
+ this._hostDisconnected ? "Recording start cancelled: editor was disconnected during setup" : "Recording start cancelled: stop requested before setup completed"
2942
+ )
2943
+ );
2944
+ return;
2945
+ }
2871
2946
  const detectedChannelCount = stream.getAudioTracks()[0]?.getSettings()?.channelCount;
2872
2947
  if (detectedChannelCount === void 0 && options.channelCount !== void 0) {
2873
2948
  console.warn(
@@ -2950,15 +3025,10 @@ var RecordingController = class {
2950
3025
  } catch (err) {
2951
3026
  this._cleanupSession(trackId);
2952
3027
  console.warn("[dawcore] RecordingController: Failed to start recording: " + String(err));
2953
- this._host.dispatchEvent(
2954
- new CustomEvent("daw-recording-error", {
2955
- bubbles: true,
2956
- composed: true,
2957
- detail: { trackId, error: err }
2958
- })
2959
- );
3028
+ this._dispatchRecordingError(trackId, err);
2960
3029
  } finally {
2961
3030
  this._starting.delete(trackId);
3031
+ resolveStartSettled();
2962
3032
  }
2963
3033
  }
2964
3034
  pauseRecording(trackId) {
@@ -2992,10 +3062,17 @@ var RecordingController = class {
2992
3062
  );
2993
3063
  }
2994
3064
  async stopRecording(trackId) {
2995
- const id = trackId ?? [...this._sessions.keys()][0];
3065
+ const id = trackId ?? [...this._sessions.keys()][0] ?? [...this._starting.keys()][0];
2996
3066
  if (!id) return;
2997
3067
  const session = this._sessions.get(id);
2998
- if (!session) return;
3068
+ if (!session) {
3069
+ const starting = this._starting.get(id);
3070
+ if (starting) {
3071
+ starting.stopRequested = true;
3072
+ return starting.done;
3073
+ }
3074
+ return;
3075
+ }
2999
3076
  if (session.stopping) {
3000
3077
  return session.stopPromise ?? void 0;
3001
3078
  }
@@ -3005,6 +3082,19 @@ var RecordingController = class {
3005
3082
  return stopPromise;
3006
3083
  }
3007
3084
  async _finishStopRecording(id, session) {
3085
+ try {
3086
+ await this._finalizeRecording(id, session);
3087
+ } catch (err) {
3088
+ const sessionWasActive = this._sessions.has(id);
3089
+ console.warn("[dawcore] RecordingController: Failed to finalize recording: " + String(err));
3090
+ this._cleanupSession(id);
3091
+ this._host.requestUpdate();
3092
+ if (sessionWasActive) {
3093
+ this._dispatchRecordingError(id, err);
3094
+ }
3095
+ }
3096
+ }
3097
+ async _finalizeRecording(id, session) {
3008
3098
  const wasPaused = this._isPaused;
3009
3099
  this._isPaused = false;
3010
3100
  if (session.wasOverdub && typeof this._host.stop === "function") {
@@ -3031,16 +3121,7 @@ var RecordingController = class {
3031
3121
  session.workletNode.disconnect();
3032
3122
  this._removeTrackEndedListener(session);
3033
3123
  if (session.totalSamples === 0) {
3034
- console.warn("[dawcore] RecordingController: No audio data captured");
3035
- this._sessions.delete(id);
3036
- this._host.requestUpdate();
3037
- this._host.dispatchEvent(
3038
- new CustomEvent("daw-recording-error", {
3039
- bubbles: true,
3040
- composed: true,
3041
- detail: { trackId: id, error: new Error("No audio data captured") }
3042
- })
3043
- );
3124
+ this._abandonFinalize(id, session, "No audio data captured");
3044
3125
  return;
3045
3126
  }
3046
3127
  const stopCtx = this._host.audioContext;
@@ -3054,16 +3135,11 @@ var RecordingController = class {
3054
3135
  const latencyOffsetSamples = session.latencySamples;
3055
3136
  const effectiveDuration = Math.max(0, audioBuffer.length - latencyOffsetSamples);
3056
3137
  if (effectiveDuration === 0) {
3057
- console.warn("[dawcore] RecordingController: Recording too short for latency compensation");
3058
- this._restoreArmedTrackMute(session);
3059
- this._sessions.delete(id);
3060
- this._host.requestUpdate();
3061
- this._host.dispatchEvent(
3062
- new CustomEvent("daw-recording-error", {
3063
- bubbles: true,
3064
- composed: true,
3065
- detail: { trackId: id, error: new Error("Recording too short to save") }
3066
- })
3138
+ this._abandonFinalize(
3139
+ id,
3140
+ session,
3141
+ "Recording too short for latency compensation",
3142
+ "Recording too short to save"
3067
3143
  );
3068
3144
  return;
3069
3145
  }
@@ -3198,6 +3274,26 @@ var RecordingController = class {
3198
3274
  session._audioTrack.removeEventListener("ended", session._onTrackEnded);
3199
3275
  }
3200
3276
  }
3277
+ _dispatchRecordingError(trackId, error) {
3278
+ this._host.dispatchEvent(
3279
+ new CustomEvent("daw-recording-error", {
3280
+ bubbles: true,
3281
+ composed: true,
3282
+ detail: { trackId, error }
3283
+ })
3284
+ );
3285
+ }
3286
+ /** Shared teardown for finalize paths that end without a take (no data
3287
+ * captured / too short after latency compensation): restore the armed-track
3288
+ * mute, drop the session, and notify via daw-recording-error so record
3289
+ * buttons reset their state. */
3290
+ _abandonFinalize(id, session, warnMessage, errorMessage = warnMessage) {
3291
+ console.warn("[dawcore] RecordingController: " + warnMessage);
3292
+ this._restoreArmedTrackMute(session);
3293
+ this._sessions.delete(id);
3294
+ this._host.requestUpdate();
3295
+ this._dispatchRecordingError(id, new Error(errorMessage));
3296
+ }
3201
3297
  /** Restore the armed track's pre-session mute state (idempotent — safe to
3202
3298
  * call from both the finalize path and _cleanupSession). */
3203
3299
  _restoreArmedTrackMute(session) {
@@ -3227,15 +3323,9 @@ var RecordingController = class {
3227
3323
  this._isPaused = false;
3228
3324
  }
3229
3325
  if (notifyError) {
3230
- this._host.dispatchEvent(
3231
- new CustomEvent("daw-recording-error", {
3232
- bubbles: true,
3233
- composed: true,
3234
- detail: {
3235
- trackId,
3236
- error: new Error("Recording cancelled: editor was disconnected mid-recording")
3237
- }
3238
- })
3326
+ this._dispatchRecordingError(
3327
+ trackId,
3328
+ new Error("Recording cancelled: editor was disconnected mid-recording")
3239
3329
  );
3240
3330
  }
3241
3331
  }
@@ -3377,6 +3467,14 @@ var PointerHandler = class {
3377
3467
  this._timeline = null;
3378
3468
  // Cached from onPointerDown to avoid forced layout reflows at 60fps during drag
3379
3469
  this._timelineRect = null;
3470
+ /** Pointer that started the current interaction — a pointercancel from any
3471
+ * OTHER pointer (palm rejection on touch) must not kill the active drag. */
3472
+ this._activePointerId = null;
3473
+ // Selection values at pointerdown — restored on cancel so an interrupted
3474
+ // drag doesn't destroy a previously committed selection (which the engine
3475
+ // still holds; zeroing only the host would desync the two).
3476
+ this._preDragSelectionStart = 0;
3477
+ this._preDragSelectionEnd = 0;
3380
3478
  this.onPointerDown = (e) => {
3381
3479
  const clipHandler = this._host._clipHandler;
3382
3480
  if (clipHandler) {
@@ -3391,12 +3489,12 @@ var PointerHandler = class {
3391
3489
  console.warn("[dawcore] setPointerCapture failed: " + String(err));
3392
3490
  }
3393
3491
  const onMove = (me) => clipHandler.onPointerMove(me);
3394
- const onUp = (ue) => {
3395
- clipHandler.onPointerUp(ue);
3492
+ const detach = (pe) => {
3396
3493
  this._timeline?.removeEventListener("pointermove", onMove);
3397
3494
  this._timeline?.removeEventListener("pointerup", onUp);
3495
+ this._timeline?.removeEventListener("pointercancel", onCancel);
3398
3496
  try {
3399
- this._timeline?.releasePointerCapture(ue.pointerId);
3497
+ this._timeline?.releasePointerCapture(pe.pointerId);
3400
3498
  } catch (err) {
3401
3499
  console.warn(
3402
3500
  "[dawcore] releasePointerCapture failed (may already be released): " + String(err)
@@ -3404,8 +3502,19 @@ var PointerHandler = class {
3404
3502
  }
3405
3503
  this._timeline = null;
3406
3504
  };
3505
+ const onUp = (ue) => {
3506
+ clipHandler.onPointerUp(ue);
3507
+ detach(ue);
3508
+ };
3509
+ const downPointerId = e.pointerId;
3510
+ const onCancel = (ce) => {
3511
+ if (ce.pointerId !== downPointerId) return;
3512
+ clipHandler.onPointerCancel(ce);
3513
+ detach(ce);
3514
+ };
3407
3515
  this._timeline.addEventListener("pointermove", onMove);
3408
3516
  this._timeline.addEventListener("pointerup", onUp);
3517
+ this._timeline.addEventListener("pointercancel", onCancel);
3409
3518
  }
3410
3519
  return;
3411
3520
  }
@@ -3420,6 +3529,9 @@ var PointerHandler = class {
3420
3529
  this._timelineRect = this._timeline.getBoundingClientRect();
3421
3530
  this._dragStartPx = this._pxFromPointer(e);
3422
3531
  this._isDragging = false;
3532
+ this._activePointerId = e.pointerId;
3533
+ this._preDragSelectionStart = this._host._selectionStartTime;
3534
+ this._preDragSelectionEnd = this._host._selectionEndTime;
3423
3535
  try {
3424
3536
  this._timeline.setPointerCapture(e.pointerId);
3425
3537
  } catch (err) {
@@ -3427,6 +3539,7 @@ var PointerHandler = class {
3427
3539
  }
3428
3540
  this._timeline.addEventListener("pointermove", this._onPointerMove);
3429
3541
  this._timeline.addEventListener("pointerup", this._onPointerUp);
3542
+ this._timeline.addEventListener("pointercancel", this._onPointerCancel);
3430
3543
  };
3431
3544
  this._onPointerMove = (e) => {
3432
3545
  if (!this._timeline) return;
@@ -3450,15 +3563,7 @@ var PointerHandler = class {
3450
3563
  };
3451
3564
  this._onPointerUp = (e) => {
3452
3565
  if (!this._timeline) return;
3453
- try {
3454
- this._timeline.releasePointerCapture(e.pointerId);
3455
- } catch (err) {
3456
- console.warn(
3457
- "[dawcore] releasePointerCapture failed (may already be released): " + String(err)
3458
- );
3459
- }
3460
- this._timeline.removeEventListener("pointermove", this._onPointerMove);
3461
- this._timeline.removeEventListener("pointerup", this._onPointerUp);
3566
+ this._detachTimeline(e);
3462
3567
  try {
3463
3568
  if (this._isDragging) {
3464
3569
  this._finalizeSelection();
@@ -3468,10 +3573,29 @@ var PointerHandler = class {
3468
3573
  } catch (err) {
3469
3574
  console.warn("[dawcore] Pointer interaction failed: " + String(err));
3470
3575
  } finally {
3471
- this._isDragging = false;
3472
- this._timeline = null;
3473
- this._timelineRect = null;
3576
+ this._resetInteractionState();
3577
+ }
3578
+ };
3579
+ /** pointercancel fires INSTEAD of pointerup on touch interruption / pen
3580
+ * leaving range / OS gestures — discard the interaction (no seek, no
3581
+ * selection finalize) and detach the drag listeners, or the still-attached
3582
+ * move handler keeps mutating the selection on hover with a stale rect. */
3583
+ this._onPointerCancel = (e) => {
3584
+ if (!this._timeline) return;
3585
+ if (e.pointerId !== this._activePointerId) return;
3586
+ this._detachTimeline(e);
3587
+ if (this._isDragging) {
3588
+ const h = this._host;
3589
+ h._selectionStartTime = this._preDragSelectionStart;
3590
+ h._selectionEndTime = this._preDragSelectionEnd;
3591
+ const sel = h.shadowRoot?.querySelector("daw-selection");
3592
+ if (sel) {
3593
+ sel.startPx = this._timeToPx(this._preDragSelectionStart);
3594
+ sel.endPx = this._timeToPx(this._preDragSelectionEnd);
3595
+ }
3596
+ h.requestUpdate();
3474
3597
  }
3598
+ this._resetInteractionState();
3475
3599
  };
3476
3600
  this._host = host;
3477
3601
  }
@@ -3499,6 +3623,28 @@ var PointerHandler = class {
3499
3623
  }
3500
3624
  return time * h.effectiveSampleRate / h.samplesPerPixel;
3501
3625
  }
3626
+ /** Detach the drag listeners and release capture — shared by the up and
3627
+ * cancel terminals so a new listener added to onPointerDown can't be
3628
+ * missed on one of them. */
3629
+ _detachTimeline(e) {
3630
+ if (!this._timeline) return;
3631
+ try {
3632
+ this._timeline.releasePointerCapture(e.pointerId);
3633
+ } catch (err) {
3634
+ console.warn(
3635
+ "[dawcore] releasePointerCapture failed (may already be released): " + String(err)
3636
+ );
3637
+ }
3638
+ this._timeline.removeEventListener("pointermove", this._onPointerMove);
3639
+ this._timeline.removeEventListener("pointerup", this._onPointerUp);
3640
+ this._timeline.removeEventListener("pointercancel", this._onPointerCancel);
3641
+ }
3642
+ _resetInteractionState() {
3643
+ this._isDragging = false;
3644
+ this._timeline = null;
3645
+ this._timelineRect = null;
3646
+ this._activePointerId = null;
3647
+ }
3502
3648
  _finalizeSelection() {
3503
3649
  const h = this._host;
3504
3650
  if (h._engine) {
@@ -3834,6 +3980,23 @@ var ClipPointerHandler = class {
3834
3980
  this._reset();
3835
3981
  }
3836
3982
  }
3983
+ /** Processes pointercancel — reverts the in-progress drag.
3984
+ *
3985
+ * pointercancel fires INSTEAD of pointerup on touch interruption, pen
3986
+ * leaving hover range, or OS gestures. Without this handler the drag stays
3987
+ * armed (hover keeps moving the clip), the engine transaction stays open
3988
+ * (every later edit becomes un-undoable until some drag commits), and the
3989
+ * per-frame skipAdapter moveClip mutations are never synced or rolled back
3990
+ * (waveform and audio permanently disagree). */
3991
+ onPointerCancel(_e) {
3992
+ if (this._mode === null) return;
3993
+ try {
3994
+ this._restoreTrimVisual();
3995
+ } finally {
3996
+ this._host.engine?.abortTransaction();
3997
+ this._reset();
3998
+ }
3999
+ }
3837
4000
  /** Re-extract peaks from cache and set on waveform elements during trim drag.
3838
4001
  * Returns true if peaks were successfully updated. */
3839
4002
  _updateWaveformPeaks(offsetSamples, durationSamples) {
@@ -3851,7 +4014,11 @@ var ClipPointerHandler = class {
3851
4014
  }
3852
4015
  return true;
3853
4016
  }
3854
- /** Restore clip container CSS to original values after trim visual preview. */
4017
+ /** Restore clip container CSS AND waveform peaks to original values after
4018
+ * a trim visual preview. Peaks matter: the drag wrote re-extracted peak
4019
+ * arrays imperatively onto the <daw-waveform> elements (bypassing Lit), and
4020
+ * a cancelled/zero-delta trim makes no engine mutation — so no statechange
4021
+ * re-render will ever repair them. */
3855
4022
  _restoreTrimVisual() {
3856
4023
  if (this._clipContainer) {
3857
4024
  this._clipContainer.style.left = this._originalLeft + "px";
@@ -3860,6 +4027,7 @@ var ClipPointerHandler = class {
3860
4027
  for (const wf of waveforms) {
3861
4028
  wf.style.left = "0px";
3862
4029
  }
4030
+ this._updateWaveformPeaks(this._originalOffsetSamples, this._originalDurationSamples);
3863
4031
  }
3864
4032
  }
3865
4033
  _reset() {
@@ -3945,8 +4113,18 @@ async function loadFiles(host, files) {
3945
4113
  const failed = [];
3946
4114
  for (const file of fileArray) {
3947
4115
  if (file.type && !file.type.startsWith("audio/")) {
3948
- failed.push({ file, error: new Error("Non-audio MIME type: " + file.type) });
4116
+ const error = new Error("Non-audio MIME type: " + file.type);
4117
+ failed.push({ file, error });
3949
4118
  console.warn("[dawcore] Skipping non-audio file: " + file.name + " (" + file.type + ")");
4119
+ if (host.isConnected) {
4120
+ host.dispatchEvent(
4121
+ new CustomEvent("daw-files-load-error", {
4122
+ bubbles: true,
4123
+ composed: true,
4124
+ detail: { file, error }
4125
+ })
4126
+ );
4127
+ }
3950
4128
  continue;
3951
4129
  }
3952
4130
  const blobUrl = URL.createObjectURL(file);
@@ -4167,15 +4345,18 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
4167
4345
  name: clipName ?? "Recording"
4168
4346
  });
4169
4347
  host._clipBuffers = new Map(host._clipBuffers).set(clip.id, trimmedBuf);
4170
- host._peakPipeline.generatePeaks(trimmedBuf, host.samplesPerPixel, host.mono).then((pd) => {
4348
+ host._clipOffsets.set(clip.id, { offsetSamples: 0, durationSamples: durSamples });
4349
+ host._peakPipeline.generatePeaks(trimmedBuf, host.renderSamplesPerPixel, host.mono).then((pd) => {
4171
4350
  const t = host._engineTracks.get(trackId);
4172
4351
  if (!t) {
4173
4352
  const next = new Map(host._clipBuffers);
4174
4353
  next.delete(clip.id);
4175
4354
  host._clipBuffers = next;
4355
+ host._clipOffsets.delete(clip.id);
4176
4356
  return;
4177
4357
  }
4178
4358
  host._peaksData = new Map(host._peaksData).set(clip.id, pd);
4359
+ host._raiseZoomFloor(host._peakPipeline.getCachedScale(trimmedBuf));
4179
4360
  host._engineTracks = new Map(host._engineTracks).set(trackId, {
4180
4361
  ...t,
4181
4362
  // Punch-in replace (#579): the recorded clip owns [startSample,
@@ -4219,6 +4400,7 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
4219
4400
  const next = new Map(host._clipBuffers);
4220
4401
  next.delete(clip.id);
4221
4402
  host._clipBuffers = next;
4403
+ host._clipOffsets.delete(clip.id);
4222
4404
  if (host.isConnected) {
4223
4405
  host.dispatchEvent(
4224
4406
  new CustomEvent("daw-error", {
@@ -4443,7 +4625,10 @@ var EffectsChainController = class {
4443
4625
  kind: "wam",
4444
4626
  ...sourceFields,
4445
4627
  bypassed: entry.placeholder.bypassed,
4446
- ...entry.placeholder.state !== void 0 ? { state: entry.placeholder.state } : {}
4628
+ ...entry.placeholder.state !== void 0 ? { state: entry.placeholder.state } : {},
4629
+ // Lets offline export skip this entry (live playback silently
4630
+ // skips it too); restore ignores the flag and retries.
4631
+ placeholder: true
4447
4632
  };
4448
4633
  }
4449
4634
  let state8;
@@ -4461,6 +4646,15 @@ var EffectsChainController = class {
4461
4646
  ...state8 !== void 0 ? { state: state8 } : {}
4462
4647
  };
4463
4648
  }
4649
+ if (entry.placeholder) {
4650
+ return {
4651
+ kind: "native",
4652
+ type: entry.type,
4653
+ params: { ...entry.params },
4654
+ bypassed: entry.placeholder.bypassed,
4655
+ placeholder: true
4656
+ };
4657
+ }
4464
4658
  return {
4465
4659
  kind: "native",
4466
4660
  type: entry.type,
@@ -4499,13 +4693,17 @@ var EffectsChainController = class {
4499
4693
  entry.instance.dispose?.();
4500
4694
  this._rebuild();
4501
4695
  }
4696
+ /** Returns the index the entry actually landed at (the requested index is
4697
+ * clamped to the chain bounds), or -1 for an unknown effectId — event
4698
+ * dispatchers must report the actual index, not the raw request. */
4502
4699
  move(effectId, newIndex) {
4503
4700
  const entry = this._find("move", effectId);
4504
- if (!entry) return;
4701
+ if (!entry) return -1;
4505
4702
  const without = this._entries.filter((e) => e.id !== effectId);
4506
4703
  const at = Math.max(0, Math.min(newIndex, without.length));
4507
4704
  this._entries = [...without.slice(0, at), entry, ...without.slice(at)];
4508
4705
  this._rebuild();
4706
+ return at;
4509
4707
  }
4510
4708
  setParams(effectId, params) {
4511
4709
  const entry = this._find("setParams", effectId);
@@ -4729,10 +4927,11 @@ registerBuiltIns();
4729
4927
 
4730
4928
  // src/effects/effects-manager.ts
4731
4929
  var PREFIX2 = "[waveform-playlist] ";
4732
- function makeGuiRecord(element, destroyImpl) {
4930
+ function makeGuiRecord(element, destroyImpl, isFallback = false) {
4733
4931
  let destroyed = false;
4734
4932
  return {
4735
4933
  element,
4934
+ isFallback,
4736
4935
  destroy: () => {
4737
4936
  if (destroyed) return;
4738
4937
  destroyed = true;
@@ -4911,7 +5110,7 @@ var EffectsManager = class {
4911
5110
  );
4912
5111
  }
4913
5112
  const cached = this._guis.get(effectId);
4914
- if (cached) {
5113
+ if (cached && !cached.isFallback) {
4915
5114
  container.appendChild(cached.element);
4916
5115
  return cached.element;
4917
5116
  }
@@ -4922,7 +5121,22 @@ var EffectsManager = class {
4922
5121
  });
4923
5122
  this._guiPending.set(effectId, pending);
4924
5123
  }
4925
- const record = await pending;
5124
+ let record;
5125
+ try {
5126
+ record = await pending;
5127
+ } catch (err) {
5128
+ if (cached) {
5129
+ console.warn(
5130
+ PREFIX2 + 'openEffectGui: rebuilding the parameter panel for "' + effectId + '" failed \u2014 serving the cached panel (values may be stale): ' + String(err)
5131
+ );
5132
+ container.appendChild(cached.element);
5133
+ return cached.element;
5134
+ }
5135
+ throw err;
5136
+ }
5137
+ if (cached && cached !== record) {
5138
+ cached.element.remove();
5139
+ }
4926
5140
  if (chain.disposed || !chain.getEntry(effectId)) {
4927
5141
  this._guis.delete(effectId);
4928
5142
  record.element.remove();
@@ -4957,7 +5171,7 @@ var EffectsManager = class {
4957
5171
  }
4958
5172
  const element = await this._createFallbackPanel(chain, target, entry, effectId);
4959
5173
  return makeGuiRecord(element, () => {
4960
- });
5174
+ }, true);
4961
5175
  }
4962
5176
  /** The generic parameter panel — one code path for "no custom GUI":
4963
5177
  * native entries render from the registry's params metadata, WAM entries
@@ -5200,9 +5414,23 @@ var EffectsManager = class {
5200
5414
  for (const entry of entries) {
5201
5415
  if (superseded()) return;
5202
5416
  if (entry.kind === "native") {
5203
- const id = this._addToChain(chain, target, entry.type, entry.params);
5204
- if (entry.bypassed) {
5205
- this._runOp(chain, target, "setBypassed", id, true);
5417
+ try {
5418
+ const id = this._addToChain(chain, target, entry.type, entry.params);
5419
+ if (entry.bypassed) {
5420
+ this._runOp(chain, target, "setBypassed", id, true);
5421
+ }
5422
+ } catch (err) {
5423
+ if (superseded() || chain.disposed) return;
5424
+ const message = err instanceof Error ? err.message : String(err);
5425
+ console.warn(
5426
+ PREFIX2 + 'setEffectsState: native effect "' + entry.type + '" failed to restore: ' + message
5427
+ );
5428
+ const effectId = this._addNativePlaceholder(chain, entry, message);
5429
+ this._dispatch(target, "daw-effect-error", {
5430
+ effectId,
5431
+ type: entry.type,
5432
+ message
5433
+ });
5206
5434
  }
5207
5435
  continue;
5208
5436
  }
@@ -5219,7 +5447,7 @@ var EffectsManager = class {
5219
5447
  this._runOp(chain, target, "setBypassed", id, true);
5220
5448
  }
5221
5449
  } catch (err) {
5222
- if (superseded()) return;
5450
+ if (superseded() || chain.disposed) return;
5223
5451
  const message = err instanceof Error ? err.message : String(err);
5224
5452
  const sourceLabel = entry.url ?? entry.faustName ?? "Faust effect";
5225
5453
  console.warn(
@@ -5235,6 +5463,25 @@ var EffectsManager = class {
5235
5463
  }
5236
5464
  }
5237
5465
  }
5466
+ /** A silent passthrough occupying a failed NATIVE entry's chain position.
5467
+ * Carries the saved params/bypassed so the snapshot round-trips (serialize
5468
+ * re-emits them with `placeholder: true`). */
5469
+ _addNativePlaceholder(chain, entry, message) {
5470
+ const { audioContext } = this._requireWiring();
5471
+ const node = audioContext.createGain();
5472
+ const effectId = chain.add({
5473
+ kind: "native",
5474
+ type: entry.type,
5475
+ label: entry.type,
5476
+ error: message,
5477
+ placeholder: { bypassed: entry.bypassed },
5478
+ instance: { input: node, output: node, applyParams: () => {
5479
+ } },
5480
+ params: { ...entry.params }
5481
+ });
5482
+ chain.setBypassed(effectId, true);
5483
+ return effectId;
5484
+ }
5238
5485
  /** A silent passthrough occupying the failed plugin's chain position. */
5239
5486
  _addWamPlaceholder(chain, entry, message) {
5240
5487
  const { audioContext } = this._requireWiring();
@@ -5281,10 +5528,11 @@ var EffectsManager = class {
5281
5528
  chain.setBypassed(effectId, arg);
5282
5529
  this._dispatch(target, "daw-effect-bypass", { effectId, bypassed: arg });
5283
5530
  break;
5284
- case "move":
5285
- chain.move(effectId, arg);
5286
- this._dispatch(target, "daw-effect-reorder", { effectId, fromIndex, toIndex: arg });
5531
+ case "move": {
5532
+ const toIndex = chain.move(effectId, arg);
5533
+ this._dispatch(target, "daw-effect-reorder", { effectId, fromIndex, toIndex });
5287
5534
  break;
5535
+ }
5288
5536
  }
5289
5537
  }
5290
5538
  _dispatch(target, name, detail) {
@@ -5325,6 +5573,9 @@ function validateSerializedEntries(entries) {
5325
5573
  if (typeof e.bypassed !== "boolean") {
5326
5574
  throw new Error(PREFIX2 + "setEffectsState: entry requires a boolean bypassed flag" + at);
5327
5575
  }
5576
+ if (e.placeholder !== void 0 && e.placeholder !== true) {
5577
+ throw new Error(PREFIX2 + "setEffectsState: placeholder must be true when present" + at);
5578
+ }
5328
5579
  });
5329
5580
  }
5330
5581
  function toWamParameterMap(params) {
@@ -5357,6 +5608,9 @@ async function exportAudioImpl(host, options = {}) {
5357
5608
  try {
5358
5609
  const masterChain = await buildOfflineChain(ctx, await host.getMasterEffectsState());
5359
5610
  cleanups.push(masterChain.dispose);
5611
+ const masterVolume = ctx.createGain();
5612
+ masterVolume.gain.value = host.masterVolume ?? 1;
5613
+ masterVolume.connect(masterChain.input);
5360
5614
  masterChain.output.connect(ctx.destination);
5361
5615
  const anySoloed = host.tracks.some((t) => t.soloed);
5362
5616
  for (const track of host.tracks) {
@@ -5371,7 +5625,7 @@ async function exportAudioImpl(host, options = {}) {
5371
5625
  panner.pan.value = track.pan;
5372
5626
  volume.connect(panner);
5373
5627
  panner.connect(chain.input);
5374
- chain.output.connect(masterChain.input);
5628
+ chain.output.connect(masterVolume);
5375
5629
  for (const clip of track.clips) {
5376
5630
  scheduleClip(ctx, clip, startTime, duration, volume);
5377
5631
  }
@@ -5442,6 +5696,12 @@ async function buildOfflineChain(ctx, entries) {
5442
5696
  return { input, output, dispose };
5443
5697
  async function wireEntries() {
5444
5698
  for (const entry of entries) {
5699
+ if (entry.placeholder) {
5700
+ console.warn(
5701
+ PREFIX3 + 'exportAudio: skipping failed-plugin placeholder "' + (entry.kind === "native" ? entry.type : entry.url ?? "Faust effect") + '"'
5702
+ );
5703
+ continue;
5704
+ }
5445
5705
  if (entry.kind === "native") {
5446
5706
  const created = createEffectInstance(entry.type, ctx, entry.params);
5447
5707
  if (entry.bypassed) {
@@ -5713,6 +5973,13 @@ var PlaybackAnimationController = class {
5713
5973
  var import_meta = {};
5714
5974
  var RULER_HEIGHT = 30;
5715
5975
  var NO_ADAPTER_ERROR = "No PlayoutAdapter set on <daw-editor>. Set editor.adapter before use.\n\n // Option 1: Native Web Audio (no Tone.js)\n npm install @dawcore/transport\n import { NativePlayoutAdapter } from '@dawcore/transport';\n editor.adapter = new NativePlayoutAdapter(new AudioContext());\n\n // Option 2: Tone.js (effects, MIDI synths)\n npm install @waveform-playlist/playout\n import { createToneAdapter } from '@waveform-playlist/playout';\n editor.adapter = createToneAdapter();";
5976
+ var TrackLoadCancelledError = class extends Error {
5977
+ constructor(message, reason) {
5978
+ super(message);
5979
+ this.reason = reason;
5980
+ this.name = "TrackLoadCancelledError";
5981
+ }
5982
+ };
5716
5983
  var DawEditorElement = class extends import_lit15.LitElement {
5717
5984
  constructor() {
5718
5985
  super(...arguments);
@@ -5752,6 +6019,9 @@ var DawEditorElement = class extends import_lit15.LitElement {
5752
6019
  this._selectionEndTime = 0;
5753
6020
  this._currentTime = 0;
5754
6021
  this._externalAdapter = null;
6022
+ /** True after a disconnect disposed the consumer's adapter via the engine
6023
+ * — rebuild attempts fail loudly until a fresh adapter is set. */
6024
+ this._adapterConsumedByDispose = false;
5755
6025
  // --- Effects (master chain; per-track chains delegated from <daw-track>) ---
5756
6026
  this._effectsManager = null;
5757
6027
  this._engine = null;
@@ -5766,6 +6036,11 @@ var DawEditorElement = class extends import_lit15.LitElement {
5766
6036
  /** Coarsest scale from pre-computed peaks — zoom cannot go finer than this. 0 = no limit. */
5767
6037
  this._minSamplesPerPixel = 0;
5768
6038
  this._trackElements = /* @__PURE__ */ new Map();
6039
+ /** Track ids with a _loadTrack in flight. Distinct from `_engineTracks`
6040
+ * membership: the peaks-first path inserts a render-only PREVIEW track
6041
+ * into _engineTracks mid-load, so `has()` alone cannot answer "is this
6042
+ * track still loading?". */
6043
+ this._loadingTracks = /* @__PURE__ */ new Set();
5769
6044
  this._childObserver = null;
5770
6045
  this._audioResume = new AudioResumeController(this);
5771
6046
  this._recordingController = new RecordingController(this);
@@ -5910,11 +6185,17 @@ var DawEditorElement = class extends import_lit15.LitElement {
5910
6185
  const trackEl = clipEl.closest("daw-track");
5911
6186
  if (!trackEl) return;
5912
6187
  const trackId = trackEl.trackId;
5913
- if (!this._engineTracks.has(trackId)) {
6188
+ if (!this._engineTracks.has(trackId) || this._loadingTracks.has(trackId)) {
5914
6189
  const desc = this._tracks.get(trackId);
5915
6190
  if (desc && !desc.clips.some((c) => isDomClip(c) && c.clipId === clipEl.clipId)) {
5916
- console.warn(
5917
- '[dawcore] daw-clip-connected fired while parent track "' + trackId + '" is still loading \u2014 late-appended clip may be missed. Wait for daw-track-ready before appending more <daw-clip> children, or use editor.addClip(trackId, config) after the track finishes loading.'
6191
+ const message = 'daw-clip-connected fired while parent track "' + trackId + '" is still loading \u2014 the clip will not be loaded. Wait for daw-track-ready before appending more <daw-clip> children, or use editor.addClip(trackId, config) after the track finishes loading.';
6192
+ console.warn("[dawcore] " + message);
6193
+ this.dispatchEvent(
6194
+ new CustomEvent("daw-clip-error", {
6195
+ bubbles: true,
6196
+ composed: true,
6197
+ detail: { trackId, clipId: clipEl.clipId, error: new Error(message) }
6198
+ })
5918
6199
  );
5919
6200
  }
5920
6201
  return;
@@ -6006,12 +6287,38 @@ var DawEditorElement = class extends import_lit15.LitElement {
6006
6287
  const clamped = this._minSamplesPerPixel > 0 && value < this._minSamplesPerPixel ? this._minSamplesPerPixel : value;
6007
6288
  if (clamped !== value) {
6008
6289
  console.warn(
6009
- "[dawcore] Zoom " + value + " spp rejected \u2014 pre-computed peaks limit is " + this._minSamplesPerPixel + " spp"
6290
+ "[dawcore] Zoom " + value + " spp clamped to the peak floor (" + this._minSamplesPerPixel + " spp) \u2014 peaks for the loaded audio (worker-generated or pre-computed) can only render at or above that scale"
6010
6291
  );
6011
6292
  }
6012
6293
  this._samplesPerPixel = clamped;
6013
6294
  this.requestUpdate("samplesPerPixel", old);
6014
6295
  }
6296
+ /** Raise the zoom floor and re-clamp the LIVE samplesPerPixel when it's
6297
+ * now below the floor. Peaks can only be extracted at >= the floor scale —
6298
+ * the setter alone clamps only FUTURE sets, so without the re-clamp an
6299
+ * already-finer spp keeps sizing clip containers while the waveforms
6300
+ * render at the coarser scale: half/quarter width, misaligned against the
6301
+ * ruler and playhead. */
6302
+ _raiseZoomFloor(scale) {
6303
+ if (!Number.isFinite(scale) || scale <= 0) return;
6304
+ if (scale > this._minSamplesPerPixel) {
6305
+ this._minSamplesPerPixel = scale;
6306
+ }
6307
+ if (this._samplesPerPixel < this._minSamplesPerPixel) {
6308
+ this.samplesPerPixel = this._minSamplesPerPixel;
6309
+ }
6310
+ }
6311
+ /** Recompute the floor from the surviving cached scales (track removal /
6312
+ * load cancellation / preview cleanup). Usually LOWERS the floor, freeing
6313
+ * finer zoom — but a buffer whose scale never raised the floor (or a mix
6314
+ * of scales) can raise it above the live spp, so re-clamp like
6315
+ * _raiseZoomFloor. Never mutate _minSamplesPerPixel directly. */
6316
+ _recomputeZoomFloor() {
6317
+ this._minSamplesPerPixel = this._peakPipeline.getMaxCachedScale(this._clipBuffers);
6318
+ if (this._minSamplesPerPixel > 0 && this._samplesPerPixel < this._minSamplesPerPixel) {
6319
+ this.samplesPerPixel = this._minSamplesPerPixel;
6320
+ }
6321
+ }
6015
6322
  get timeFormat() {
6016
6323
  return this._timeFormat;
6017
6324
  }
@@ -6157,6 +6464,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
6157
6464
  console.warn("[dawcore] Adapter AudioContext is already closed. Ignoring.");
6158
6465
  return;
6159
6466
  }
6467
+ this._adapterConsumedByDispose = false;
6160
6468
  if (this._engine) {
6161
6469
  console.warn(
6162
6470
  "[dawcore] adapter set after engine is built. The engine will continue using the previous adapter."
@@ -6244,6 +6552,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
6244
6552
  effectiveSampleRate: this.effectiveSampleRate,
6245
6553
  duration: this._duration,
6246
6554
  tracks: [...this._engineTracks.values()],
6555
+ masterVolume: this._engine?.getState().masterVolume ?? 1,
6247
6556
  getMasterEffectsState: () => this.getEffectsState(),
6248
6557
  getTrackEffectsState: (trackId) => this.getTrackEffectsState(trackId)
6249
6558
  },
@@ -6525,11 +6834,21 @@ var DawEditorElement = class extends import_lit15.LitElement {
6525
6834
  this._minSamplesPerPixel = 0;
6526
6835
  this._spectrogramController?.dispose();
6527
6836
  this._spectrogramController = null;
6837
+ this._lastSpectrogramViewport = null;
6838
+ const hadEngine = this._engine !== null;
6528
6839
  try {
6529
6840
  this._disposeEngine();
6530
6841
  } catch (err) {
6531
6842
  console.warn("[dawcore] Error disposing engine: " + String(err));
6532
6843
  }
6844
+ if (hadEngine) {
6845
+ this._adapterConsumedByDispose = true;
6846
+ }
6847
+ this._tracks = /* @__PURE__ */ new Map();
6848
+ this._engineTracks = /* @__PURE__ */ new Map();
6849
+ this._peaksData = /* @__PURE__ */ new Map();
6850
+ this._loadingTracks.clear();
6851
+ this._recomputeDuration();
6533
6852
  }
6534
6853
  willUpdate(changedProperties) {
6535
6854
  if (changedProperties.has("eagerResume")) {
@@ -6538,8 +6857,8 @@ var DawEditorElement = class extends import_lit15.LitElement {
6538
6857
  if ((changedProperties.has("samplesPerPixel") || changedProperties.has("ticksPerPixel") || changedProperties.has("bpm") || changedProperties.has("secondsToTicks")) && this._isPlaying) {
6539
6858
  this._startPlayhead();
6540
6859
  }
6541
- const zoomChanged = changedProperties.has("samplesPerPixel") || changedProperties.has("ticksPerPixel") || changedProperties.has("bpm") || changedProperties.has("scaleMode") || changedProperties.has("secondsToTicks");
6542
- if (zoomChanged && this._clipBuffers.size > 0) {
6860
+ const peaksInputChanged = changedProperties.has("samplesPerPixel") || changedProperties.has("ticksPerPixel") || changedProperties.has("bpm") || changedProperties.has("scaleMode") || changedProperties.has("secondsToTicks") || changedProperties.has("mono");
6861
+ if (peaksInputChanged && this._clipBuffers.size > 0) {
6543
6862
  const re = this._peakPipeline.reextractPeaks(
6544
6863
  this._clipBuffers,
6545
6864
  this._renderSpp,
@@ -6606,9 +6925,16 @@ var DawEditorElement = class extends import_lit15.LitElement {
6606
6925
  if (this._engine) {
6607
6926
  this._engine.removeTrack(trackId);
6608
6927
  }
6609
- this._minSamplesPerPixel = this._peakPipeline.getMaxCachedScale(this._clipBuffers);
6928
+ this._recomputeZoomFloor();
6610
6929
  this._disposeSpectrogramControllerIfEmpty();
6611
- if (nextEngine.size === 0) {
6930
+ if (existed && nextEngine.size === 0) {
6931
+ if (this._engine) {
6932
+ if (this._isPlaying) {
6933
+ this._withSeekSuppression(() => this._engine.stop());
6934
+ this.dispatchEvent(new CustomEvent("daw-stop", { bubbles: true, composed: true }));
6935
+ }
6936
+ this._engine.seek(0);
6937
+ }
6612
6938
  this._currentTime = 0;
6613
6939
  this._stopPlayhead();
6614
6940
  }
@@ -6631,6 +6957,45 @@ var DawEditorElement = class extends import_lit15.LitElement {
6631
6957
  if (!stillNeeded) {
6632
6958
  this._spectrogramController.dispose();
6633
6959
  this._spectrogramController = null;
6960
+ this._lastSpectrogramViewport = null;
6961
+ }
6962
+ }
6963
+ /** Reconcile `_tracks` descriptors with the engine's track list.
6964
+ *
6965
+ * ADD: engine.undo() restores removed tracks in ENGINE state only —
6966
+ * without a synthesized descriptor the track plays and renders but shows
6967
+ * "Untitled" controls and is missing from `editor.tracks`.
6968
+ * PRUNE (the symmetric half): redo removes the track from engine state
6969
+ * again — without pruning, the synthesized descriptor is a permanent
6970
+ * ghost that even removeTrack() can't clean (no element, no engine
6971
+ * entry). Never prunes tracks that are mid-load or element-backed —
6972
+ * their descriptors legitimately precede their engine entries. */
6973
+ _reconcileDescriptorsWithEngineTracks(tracks) {
6974
+ const engineIds = new Set(tracks.map((t) => t.id));
6975
+ let next = null;
6976
+ for (const track of tracks) {
6977
+ if (this._tracks.has(track.id)) continue;
6978
+ next ?? (next = new Map(this._tracks));
6979
+ next.set(track.id, {
6980
+ name: track.name ?? "",
6981
+ src: "",
6982
+ volume: track.volume ?? 1,
6983
+ pan: track.pan ?? 0,
6984
+ muted: track.muted ?? false,
6985
+ soloed: track.soloed ?? false,
6986
+ renderMode: track.clips.some((c) => c.midiNotes && c.midiNotes.length > 0) ? "piano-roll" : "waveform",
6987
+ clips: []
6988
+ });
6989
+ }
6990
+ for (const trackId of this._tracks.keys()) {
6991
+ if (engineIds.has(trackId) || this._loadingTracks.has(trackId) || this._trackElements.has(trackId)) {
6992
+ continue;
6993
+ }
6994
+ next ?? (next = new Map(this._tracks));
6995
+ next.delete(trackId);
6996
+ }
6997
+ if (next) {
6998
+ this._tracks = next;
6634
6999
  }
6635
7000
  }
6636
7001
  _onClipRemovedFromDom(clipEl) {
@@ -6776,9 +7141,8 @@ var DawEditorElement = class extends import_lit15.LitElement {
6776
7141
  throw err;
6777
7142
  }
6778
7143
  this._peaksData = new Map(this._peaksData).set(clip.id, peakData);
6779
- if (waveformData) {
6780
- this._minSamplesPerPixel = Math.max(this._minSamplesPerPixel, waveformData.scale);
6781
- }
7144
+ const cachedScale = waveformData?.scale ?? this._peakPipeline.getCachedScale(audioBuffer);
7145
+ this._raiseZoomFloor(cachedScale);
6782
7146
  return clip;
6783
7147
  }
6784
7148
  /**
@@ -7021,6 +7385,8 @@ var DawEditorElement = class extends import_lit15.LitElement {
7021
7385
  }
7022
7386
  // --- Audio Loading ---
7023
7387
  async _loadTrack(trackId, descriptor) {
7388
+ this._loadingTracks.add(trackId);
7389
+ const sppAtLoadStart = this._samplesPerPixel;
7024
7390
  try {
7025
7391
  const clips = [];
7026
7392
  for (const clipDesc of descriptor.clips) {
@@ -7058,18 +7424,20 @@ var DawEditorElement = class extends import_lit15.LitElement {
7058
7424
  durationSamples: clip2.durationSamples
7059
7425
  });
7060
7426
  this._peaksData = new Map(this._peaksData).set(clip2.id, peakData);
7061
- this._minSamplesPerPixel = Math.max(this._minSamplesPerPixel, waveformData.scale);
7062
- const previewTrack = (0, import_core9.createTrack)({
7063
- name: descriptor.name,
7064
- clips: [clip2],
7065
- volume: descriptor.volume,
7066
- pan: descriptor.pan,
7067
- muted: descriptor.muted,
7068
- soloed: descriptor.soloed
7069
- });
7070
- previewTrack.id = trackId;
7071
- this._engineTracks = new Map(this._engineTracks).set(trackId, previewTrack);
7072
- this._recomputeDuration();
7427
+ this._raiseZoomFloor(waveformData.scale);
7428
+ if (this._tracks.has(trackId)) {
7429
+ const previewTrack = (0, import_core9.createTrack)({
7430
+ name: descriptor.name,
7431
+ clips: [clip2],
7432
+ volume: descriptor.volume,
7433
+ pan: descriptor.pan,
7434
+ muted: descriptor.muted,
7435
+ soloed: descriptor.soloed
7436
+ });
7437
+ previewTrack.id = trackId;
7438
+ this._engineTracks = new Map(this._engineTracks).set(trackId, previewTrack);
7439
+ this._recomputeDuration();
7440
+ }
7073
7441
  let audioBuffer2;
7074
7442
  try {
7075
7443
  audioBuffer2 = await audioPromise;
@@ -7081,7 +7449,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
7081
7449
  const nextEngine = new Map(this._engineTracks);
7082
7450
  nextEngine.delete(trackId);
7083
7451
  this._engineTracks = nextEngine;
7084
- this._minSamplesPerPixel = this._peakPipeline.getMaxCachedScale(this._clipBuffers);
7452
+ this._recomputeZoomFloor();
7085
7453
  this._recomputeDuration();
7086
7454
  throw audioErr;
7087
7455
  }
@@ -7115,6 +7483,26 @@ var DawEditorElement = class extends import_lit15.LitElement {
7115
7483
  }
7116
7484
  }
7117
7485
  }
7486
+ const trackWasRemoved = !this._tracks.has(trackId);
7487
+ if (trackWasRemoved || !this.isConnected) {
7488
+ for (const clip of clips) {
7489
+ this._purgeClipCaches(clip.id);
7490
+ }
7491
+ if (this._engineTracks.has(trackId)) {
7492
+ const nextEngine = new Map(this._engineTracks);
7493
+ nextEngine.delete(trackId);
7494
+ this._engineTracks = nextEngine;
7495
+ this._recomputeDuration();
7496
+ }
7497
+ this._recomputeZoomFloor();
7498
+ if (this._samplesPerPixel !== sppAtLoadStart && sppAtLoadStart >= this._minSamplesPerPixel) {
7499
+ this.samplesPerPixel = sppAtLoadStart;
7500
+ }
7501
+ throw new TrackLoadCancelledError(
7502
+ trackWasRemoved ? 'track "' + trackId + '" was removed while loading' : 'editor was disconnected while track "' + trackId + '" was loading',
7503
+ trackWasRemoved ? "removed" : "disconnected"
7504
+ );
7505
+ }
7118
7506
  const track = (0, import_core9.createTrack)({
7119
7507
  name: descriptor.name,
7120
7508
  clips,
@@ -7145,15 +7533,23 @@ var DawEditorElement = class extends import_lit15.LitElement {
7145
7533
  })
7146
7534
  );
7147
7535
  } catch (err) {
7148
- if (!this.isConnected) return;
7149
- console.warn('[dawcore] Failed to load track "' + trackId + '": ' + String(err));
7536
+ const cancelled = err instanceof TrackLoadCancelledError;
7537
+ console.warn(
7538
+ cancelled ? "[dawcore] Track load cancelled: " + err.message : '[dawcore] Failed to load track "' + trackId + '": ' + String(err)
7539
+ );
7150
7540
  this.dispatchEvent(
7151
7541
  new CustomEvent("daw-track-error", {
7152
7542
  bubbles: true,
7153
7543
  composed: true,
7154
- detail: { trackId, error: err }
7544
+ detail: {
7545
+ trackId,
7546
+ error: err,
7547
+ ...cancelled ? { reason: err.reason } : {}
7548
+ }
7155
7549
  })
7156
7550
  );
7551
+ } finally {
7552
+ this._loadingTracks.delete(trackId);
7157
7553
  }
7158
7554
  }
7159
7555
  async _fetchAndDecode(src) {
@@ -7212,6 +7608,11 @@ var DawEditorElement = class extends import_lit15.LitElement {
7212
7608
  if (!this._externalAdapter) {
7213
7609
  throw new Error(NO_ADAPTER_ERROR);
7214
7610
  }
7611
+ if (this._adapterConsumedByDispose) {
7612
+ throw new Error(
7613
+ "[dawcore] editor.adapter was disposed by a previous disconnect \u2014 set a fresh PlayoutAdapter after reparenting <daw-editor>."
7614
+ );
7615
+ }
7215
7616
  const { PlaylistEngine } = await import("@waveform-playlist/engine");
7216
7617
  const adapter = this._externalAdapter;
7217
7618
  if (!this._hasTickCallbacks) {
@@ -7248,6 +7649,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
7248
7649
  nextTracks.set(track.id, track);
7249
7650
  }
7250
7651
  this._engineTracks = nextTracks;
7652
+ this._reconcileDescriptorsWithEngineTracks(engineState.tracks);
7251
7653
  }
7252
7654
  if (structuralChange) {
7253
7655
  this._effectsManager?.rewireTrackChains();
@@ -7604,24 +8006,60 @@ var DawEditorElement = class extends import_lit15.LitElement {
7604
8006
  this.play();
7605
8007
  }
7606
8008
  }
8009
+ /** Run `fn` with the stop-settle daw-timeupdate suppressed. Every
8010
+ * stop-adjacent code path that immediately re-positions (seek, split,
8011
+ * empty-timeline rewind) must use this — engine.stop() rewinds to the
8012
+ * play-start position and the settle would leak a backward-jumping
8013
+ * daw-timeupdate to consumers (CLAUDE.md seek-while-playing invariant).
8014
+ * The `finally` is load-bearing: a wedged true silently drops every
8015
+ * subsequent stop-settle dispatch. */
8016
+ _withSeekSuppression(fn) {
8017
+ this._inSeekTransition = true;
8018
+ try {
8019
+ fn();
8020
+ } finally {
8021
+ this._inSeekTransition = false;
8022
+ }
8023
+ }
7607
8024
  seekTo(time) {
7608
8025
  if (!this._engine) {
7609
8026
  console.warn("[dawcore] seekTo: engine not ready, call ignored");
7610
8027
  return;
7611
8028
  }
8029
+ if (!Number.isFinite(time)) {
8030
+ console.warn("[dawcore] seekTo: ignoring non-finite time " + String(time));
8031
+ return;
8032
+ }
8033
+ const target = Math.max(0, time);
7612
8034
  if (this._isPlaying) {
7613
- this._inSeekTransition = true;
7614
8035
  try {
7615
- this.stop();
7616
- } finally {
7617
- this._inSeekTransition = false;
8036
+ this._withSeekSuppression(() => this._engine.stop());
8037
+ this._engine.play(target);
8038
+ } catch (err) {
8039
+ console.warn("[dawcore] seekTo: engine reschedule failed: " + String(err));
8040
+ this.dispatchEvent(
8041
+ new CustomEvent("daw-error", {
8042
+ bubbles: true,
8043
+ composed: true,
8044
+ detail: { operation: "seek", error: err }
8045
+ })
8046
+ );
8047
+ return;
7618
8048
  }
7619
- this.play(time);
8049
+ this._currentTime = target;
8050
+ this._startPlayhead();
7620
8051
  } else {
7621
- this._engine.seek(time);
7622
- this._currentTime = time;
8052
+ this._engine.seek(target);
8053
+ this._currentTime = target;
7623
8054
  this._stopPlayhead();
7624
8055
  }
8056
+ this.dispatchEvent(
8057
+ new CustomEvent("daw-seek", {
8058
+ bubbles: true,
8059
+ composed: true,
8060
+ detail: { time: target }
8061
+ })
8062
+ );
7625
8063
  }
7626
8064
  /** Undo the last structural edit. */
7627
8065
  undo() {
@@ -7656,8 +8094,10 @@ var DawEditorElement = class extends import_lit15.LitElement {
7656
8094
  engine: this._engine,
7657
8095
  dispatchEvent: (e) => this.dispatchEvent(e),
7658
8096
  stop: () => {
7659
- this._engine?.stop();
7660
- this._stopPlayhead();
8097
+ this._withSeekSuppression(() => {
8098
+ this._engine?.stop();
8099
+ this._stopPlayhead();
8100
+ });
7661
8101
  },
7662
8102
  // Call engine.play directly (synchronous) — not the async editor play()
7663
8103
  // which yields to microtask queue via await engine.init(). Engine is
@@ -7744,6 +8184,25 @@ var DawEditorElement = class extends import_lit15.LitElement {
7744
8184
  }
7745
8185
  await this._recordingController.startRecording(s, options);
7746
8186
  }
8187
+ /** Live-recording preview left/width. Beats mode uses the same tick-space
8188
+ * math as finalized clips — the sample÷renderSpp path is ceil-quantized,
8189
+ * so the take would visibly jump sideways on finalization (drift grows
8190
+ * with distance from t=0; CLAUDE.md live-preview parity invariant). */
8191
+ _previewPosition(startSample, audibleSamples) {
8192
+ if (this.scaleMode === "beats") {
8193
+ const sr = this.effectiveSampleRate;
8194
+ const startSec = startSample / sr;
8195
+ const startTick = this._secondsToTicks(startSec);
8196
+ const endTick = this._secondsToTicks(startSec + audibleSamples / sr);
8197
+ const left = Math.round(startTick / this.ticksPerPixel);
8198
+ return { left, width: Math.round(endTick / this.ticksPerPixel) - left };
8199
+ }
8200
+ const renderSpp = this._renderSpp;
8201
+ return {
8202
+ left: Math.floor(startSample / renderSpp),
8203
+ width: Math.floor(audibleSamples / renderSpp)
8204
+ };
8205
+ }
7747
8206
  _renderRecordingPreview(trackId, chH) {
7748
8207
  const rs = this._recordingController.getSession(trackId);
7749
8208
  if (!rs) return "";
@@ -7751,8 +8210,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
7751
8210
  if (audibleSamples === 0) return "";
7752
8211
  const renderSpp = this._renderSpp;
7753
8212
  const latencyPixels = Math.floor(rs.latencySamples / renderSpp);
7754
- const left = Math.floor(rs.startSample / renderSpp);
7755
- const w = Math.floor(audibleSamples / renderSpp);
8213
+ const { left, width: w } = this._previewPosition(rs.startSample, audibleSamples);
7756
8214
  const hdrH = this.clipHeaders ? this.clipHeaderHeight : 0;
7757
8215
  const height = hdrH + chH * rs.peaks.length;
7758
8216
  return import_lit15.html`<div
@@ -8394,11 +8852,16 @@ var DawKeyboardShortcutsElement = class extends import_lit18.LitElement {
8394
8852
  this.splitting = false;
8395
8853
  this.undo = false;
8396
8854
  // --- JS properties for remapping ---
8397
- this.playbackShortcuts = null;
8398
- this.splittingShortcuts = null;
8399
- this.undoShortcuts = null;
8855
+ // Accessors, not plain fields: assigning a remap after any keydown has
8856
+ // warmed _cachedShortcuts must invalidate it, or the documented remapping
8857
+ // API is silently ignored until an unrelated boolean attribute toggles.
8858
+ // (connectedCallback runs the standard upgrade-property dance so values
8859
+ // assigned BEFORE the element was defined don't shadow these accessors.)
8860
+ this._playbackShortcuts = null;
8861
+ this._splittingShortcuts = null;
8862
+ this._undoShortcuts = null;
8400
8863
  /** Additional custom shortcuts. */
8401
- this.customShortcuts = [];
8864
+ this._customShortcuts = [];
8402
8865
  this._editor = null;
8403
8866
  this._cachedShortcuts = null;
8404
8867
  // --- Event handler ---
@@ -8420,6 +8883,34 @@ var DawKeyboardShortcutsElement = class extends import_lit18.LitElement {
8420
8883
  }
8421
8884
  };
8422
8885
  }
8886
+ get playbackShortcuts() {
8887
+ return this._playbackShortcuts;
8888
+ }
8889
+ set playbackShortcuts(value) {
8890
+ this._playbackShortcuts = value;
8891
+ this._cachedShortcuts = null;
8892
+ }
8893
+ get splittingShortcuts() {
8894
+ return this._splittingShortcuts;
8895
+ }
8896
+ set splittingShortcuts(value) {
8897
+ this._splittingShortcuts = value;
8898
+ this._cachedShortcuts = null;
8899
+ }
8900
+ get undoShortcuts() {
8901
+ return this._undoShortcuts;
8902
+ }
8903
+ set undoShortcuts(value) {
8904
+ this._undoShortcuts = value;
8905
+ this._cachedShortcuts = null;
8906
+ }
8907
+ get customShortcuts() {
8908
+ return this._customShortcuts;
8909
+ }
8910
+ set customShortcuts(value) {
8911
+ this._customShortcuts = value;
8912
+ this._cachedShortcuts = null;
8913
+ }
8423
8914
  /** All active shortcuts (read-only, cached). */
8424
8915
  get shortcuts() {
8425
8916
  if (!this._cachedShortcuts) {
@@ -8434,6 +8925,18 @@ var DawKeyboardShortcutsElement = class extends import_lit18.LitElement {
8434
8925
  // --- Lifecycle ---
8435
8926
  connectedCallback() {
8436
8927
  super.connectedCallback();
8928
+ for (const prop of [
8929
+ "playbackShortcuts",
8930
+ "splittingShortcuts",
8931
+ "undoShortcuts",
8932
+ "customShortcuts"
8933
+ ]) {
8934
+ if (Object.prototype.hasOwnProperty.call(this, prop)) {
8935
+ const value = this[prop];
8936
+ delete this[prop];
8937
+ this[prop] = value;
8938
+ }
8939
+ }
8437
8940
  this._editor = this.closest("daw-editor");
8438
8941
  if (!this._editor) {
8439
8942
  console.warn(
@@ -8959,6 +9462,9 @@ var DawPlayerElement = class extends import_lit22.LitElement {
8959
9462
  this.roundedBars = false;
8960
9463
  this._playbackRate = 1;
8961
9464
  this._engine = new import_media_element_playout.MediaElementPlayout();
9465
+ /** Set by disconnectedCallback — a reconnect (DOM reparent, framework
9466
+ * re-render) must rebuild the engine + track or the player is dead. */
9467
+ this._engineDisposed = false;
8962
9468
  this._trackId = null;
8963
9469
  this._anim = new AnimationController(this);
8964
9470
  this._metadataLoaded = false;
@@ -8976,7 +9482,6 @@ var DawPlayerElement = class extends import_lit22.LitElement {
8976
9482
  if (width <= 0 || d <= 0) return;
8977
9483
  const ratio = Math.max(0, Math.min(1, e.offsetX / width));
8978
9484
  this.seekTo(ratio * d);
8979
- this._updatePlayhead();
8980
9485
  };
8981
9486
  this._onLoadedMetadata = () => {
8982
9487
  this._metadataLoaded = true;
@@ -9024,6 +9529,15 @@ var DawPlayerElement = class extends import_lit22.LitElement {
9024
9529
  }
9025
9530
  connectedCallback() {
9026
9531
  super.connectedCallback();
9532
+ let rebuilt = false;
9533
+ if (this._engineDisposed) {
9534
+ const volume = this._engine.masterVolume;
9535
+ this._engine = new import_media_element_playout.MediaElementPlayout();
9536
+ this._engine.setMasterVolume(volume);
9537
+ this._engineDisposed = false;
9538
+ this._trackId = null;
9539
+ rebuilt = true;
9540
+ }
9027
9541
  this._engine.on("loadedmetadata", this._onLoadedMetadata);
9028
9542
  this._engine.on("play", this._onPlay);
9029
9543
  this._engine.on("pause", this._onPause);
@@ -9034,6 +9548,10 @@ var DawPlayerElement = class extends import_lit22.LitElement {
9034
9548
  const area = this.shadowRoot?.querySelector(".waveform-area");
9035
9549
  if (area) this._resizeObserver?.observe(area);
9036
9550
  });
9551
+ if (rebuilt && this.src) {
9552
+ this._loadSource();
9553
+ this._playhead?.setPosition(0);
9554
+ }
9037
9555
  }
9038
9556
  render() {
9039
9557
  const width = this._timelineWidth;
@@ -9093,6 +9611,7 @@ var DawPlayerElement = class extends import_lit22.LitElement {
9093
9611
  this._renderWaveform();
9094
9612
  this._maybeDispatchReady();
9095
9613
  } catch (err) {
9614
+ if (this.peaksSrc !== requested) return;
9096
9615
  console.warn("[dawcore] <daw-player> failed to load peaks-src: " + String(err));
9097
9616
  this._peaksSettled = true;
9098
9617
  this._renderWaveform();
@@ -9133,7 +9652,7 @@ var DawPlayerElement = class extends import_lit22.LitElement {
9133
9652
  }
9134
9653
  // --- Transport methods ---
9135
9654
  play() {
9136
- this._engine.play();
9655
+ this._engine.resume();
9137
9656
  }
9138
9657
  pause() {
9139
9658
  this._engine.pause();
@@ -9146,6 +9665,10 @@ var DawPlayerElement = class extends import_lit22.LitElement {
9146
9665
  }
9147
9666
  seekTo(time) {
9148
9667
  this._engine.seekTo(time);
9668
+ if (!this._engine.isPlaying) {
9669
+ this._updatePlayhead();
9670
+ this._dispatch("daw-timeupdate", { time: this._engine.getCurrentTime() });
9671
+ }
9149
9672
  }
9150
9673
  setPlaybackRate(rate) {
9151
9674
  this.playbackRate = rate;
@@ -9164,7 +9687,7 @@ var DawPlayerElement = class extends import_lit22.LitElement {
9164
9687
  return this._engine.getCurrentTime();
9165
9688
  }
9166
9689
  set currentTime(time) {
9167
- this._engine.seekTo(time);
9690
+ this.seekTo(time);
9168
9691
  }
9169
9692
  get volume() {
9170
9693
  return this._engine.masterVolume;
@@ -9186,6 +9709,7 @@ var DawPlayerElement = class extends import_lit22.LitElement {
9186
9709
  this._engine.off("ended", this._onEnded);
9187
9710
  this._engine.off("error", this._onError);
9188
9711
  this._engine.dispose();
9712
+ this._engineDisposed = true;
9189
9713
  }
9190
9714
  // --- Private event handlers (arrow fields for stable identity) ---
9191
9715
  _dispatch(name, detail) {