@dawcore/components 0.0.33 → 0.0.35

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
@@ -38,8 +38,12 @@ var __decorateClass = (decorators, target, key, kind) => {
38
38
  // src/index.ts
39
39
  var index_exports = {};
40
40
  __export(index_exports, {
41
+ ANNOTATION_LANE_HEIGHT: () => ANNOTATION_LANE_HEIGHT,
41
42
  AudioResumeController: () => AudioResumeController,
42
43
  ClipPointerHandler: () => ClipPointerHandler,
44
+ DawAnnotationElement: () => DawAnnotationElement,
45
+ DawAnnotationListElement: () => DawAnnotationListElement,
46
+ DawAnnotationTrackElement: () => DawAnnotationTrackElement,
43
47
  DawClipElement: () => DawClipElement,
44
48
  DawEditorElement: () => DawEditorElement,
45
49
  DawGridElement: () => DawGridElement,
@@ -80,10 +84,817 @@ __export(index_exports, {
80
84
  });
81
85
  module.exports = __toCommonJS(index_exports);
82
86
 
83
- // src/elements/daw-clip.ts
87
+ // src/elements/daw-annotation.ts
84
88
  var import_lit = require("lit");
85
89
  var import_decorators = require("lit/decorators.js");
86
- var DawClipElement = class extends import_lit.LitElement {
90
+ function isValidTick(value) {
91
+ return Number.isFinite(value) && Number.isInteger(value) && value >= 0;
92
+ }
93
+ var DawAnnotationElement = class extends import_lit.LitElement {
94
+ constructor() {
95
+ super(...arguments);
96
+ this._start = 0;
97
+ this._end = 0;
98
+ this._startTick = null;
99
+ this._endTick = null;
100
+ this._warnedHalfTick = false;
101
+ this._generatedId = "annotation-" + crypto.randomUUID();
102
+ this._hasRendered = false;
103
+ }
104
+ get start() {
105
+ return this._start;
106
+ }
107
+ set start(value) {
108
+ if (!Number.isFinite(value) || value < 0) {
109
+ console.warn("[dawcore] daw-annotation start " + String(value) + " is invalid \u2014 ignored");
110
+ return;
111
+ }
112
+ const old = this._start;
113
+ this._start = value;
114
+ this.requestUpdate("start", old);
115
+ }
116
+ get end() {
117
+ return this._end;
118
+ }
119
+ set end(value) {
120
+ if (!Number.isFinite(value) || value < 0) {
121
+ console.warn("[dawcore] daw-annotation end " + String(value) + " is invalid \u2014 ignored");
122
+ return;
123
+ }
124
+ const old = this._end;
125
+ this._end = value;
126
+ this.requestUpdate("end", old);
127
+ }
128
+ get startTick() {
129
+ return this._startTick;
130
+ }
131
+ set startTick(value) {
132
+ const old = this._startTick;
133
+ if (value === null) {
134
+ this._startTick = null;
135
+ this.requestUpdate("startTick", old);
136
+ return;
137
+ }
138
+ if (!isValidTick(value)) {
139
+ console.warn(
140
+ "[dawcore] daw-annotation start-tick " + String(value) + " is invalid \u2014 ignored"
141
+ );
142
+ return;
143
+ }
144
+ this._startTick = value;
145
+ this.requestUpdate("startTick", old);
146
+ }
147
+ get endTick() {
148
+ return this._endTick;
149
+ }
150
+ set endTick(value) {
151
+ const old = this._endTick;
152
+ if (value === null) {
153
+ this._endTick = null;
154
+ this.requestUpdate("endTick", old);
155
+ return;
156
+ }
157
+ if (!isValidTick(value)) {
158
+ console.warn("[dawcore] daw-annotation end-tick " + String(value) + " is invalid \u2014 ignored");
159
+ return;
160
+ }
161
+ this._endTick = value;
162
+ this.requestUpdate("endTick", old);
163
+ }
164
+ /** Tick-based iff BOTH tick attributes are set (authority rule). */
165
+ get isTickBased() {
166
+ return this._startTick !== null && this._endTick !== null;
167
+ }
168
+ /** Stable identity: the id attribute when present, else a generated UUID. */
169
+ get annotationId() {
170
+ return this.id || this._generatedId;
171
+ }
172
+ toAnnotationData() {
173
+ const text = this.textContent?.trim() ?? "";
174
+ const data = {
175
+ id: this.annotationId,
176
+ start: this.start,
177
+ end: this.end,
178
+ lines: text.length > 0 ? text.split("\n") : [""]
179
+ };
180
+ if (this.isTickBased) {
181
+ data.startTick = this._startTick;
182
+ data.endTick = this._endTick;
183
+ }
184
+ return data;
185
+ }
186
+ // Light DOM — data container only.
187
+ createRenderRoot() {
188
+ return this;
189
+ }
190
+ connectedCallback() {
191
+ super.connectedCallback();
192
+ this.style.display = "none";
193
+ setTimeout(() => {
194
+ this.dispatchEvent(
195
+ new CustomEvent("daw-annotation-connected", {
196
+ bubbles: true,
197
+ composed: true,
198
+ detail: { annotationId: this.annotationId, element: this }
199
+ })
200
+ );
201
+ }, 0);
202
+ }
203
+ updated(changed) {
204
+ const halfTick = this._startTick !== null !== (this._endTick !== null);
205
+ if (halfTick && !this._warnedHalfTick) {
206
+ this._warnedHalfTick = true;
207
+ console.warn(
208
+ '[dawcore] daw-annotation "' + this.annotationId + '": only one of start-tick/end-tick is set \u2014 treated as seconds-based until both are present'
209
+ );
210
+ }
211
+ if (!this._hasRendered) {
212
+ this._hasRendered = true;
213
+ return;
214
+ }
215
+ if (changed.has("start") || changed.has("end") || changed.has("startTick") || changed.has("endTick")) {
216
+ this.dispatchEvent(
217
+ new CustomEvent("daw-annotation-update", {
218
+ bubbles: true,
219
+ composed: true,
220
+ detail: { annotationId: this.annotationId }
221
+ })
222
+ );
223
+ }
224
+ }
225
+ };
226
+ __decorateClass([
227
+ (0, import_decorators.property)({ type: Number, noAccessor: true, reflect: true })
228
+ ], DawAnnotationElement.prototype, "start", 1);
229
+ __decorateClass([
230
+ (0, import_decorators.property)({ type: Number, noAccessor: true, reflect: true })
231
+ ], DawAnnotationElement.prototype, "end", 1);
232
+ __decorateClass([
233
+ (0, import_decorators.property)({ type: Number, noAccessor: true, reflect: true, attribute: "start-tick" })
234
+ ], DawAnnotationElement.prototype, "startTick", 1);
235
+ __decorateClass([
236
+ (0, import_decorators.property)({ type: Number, noAccessor: true, reflect: true, attribute: "end-tick" })
237
+ ], DawAnnotationElement.prototype, "endTick", 1);
238
+ DawAnnotationElement = __decorateClass([
239
+ (0, import_decorators.customElement)("daw-annotation")
240
+ ], DawAnnotationElement);
241
+
242
+ // src/elements/daw-annotation-track.ts
243
+ var import_lit2 = require("lit");
244
+ var import_decorators2 = require("lit/decorators.js");
245
+ var import_core = require("@waveform-playlist/core");
246
+ function applyBoundaryResults(elements, after) {
247
+ const byId = new Map(elements.map((el) => [el.annotationId, el]));
248
+ for (const next of after) {
249
+ const el = byId.get(next.id);
250
+ if (!el) continue;
251
+ if (el.start !== next.start) el.start = next.start;
252
+ if (el.end !== next.end) el.end = next.end;
253
+ }
254
+ }
255
+ function applyTickBoundaryResults(elements, after, ticksToSeconds) {
256
+ const byId = new Map(elements.map((el) => [el.annotationId, el]));
257
+ for (const next of after) {
258
+ const el = byId.get(next.id);
259
+ if (!el) continue;
260
+ if (el.isTickBased) {
261
+ const startTick = Math.round(next.start);
262
+ const endTick = Math.round(next.end);
263
+ if (el.startTick !== startTick) {
264
+ el.startTick = startTick;
265
+ el.start = ticksToSeconds(startTick);
266
+ }
267
+ if (el.endTick !== endTick) {
268
+ el.endTick = endTick;
269
+ el.end = ticksToSeconds(endTick);
270
+ }
271
+ } else {
272
+ const start = ticksToSeconds(next.start);
273
+ const end = ticksToSeconds(next.end);
274
+ if (el.start !== start) el.start = start;
275
+ if (el.end !== end) el.end = end;
276
+ }
277
+ }
278
+ }
279
+ function tickSpaceData(el, editor) {
280
+ const base = el.toAnnotationData();
281
+ if (el.isTickBased) {
282
+ return { ...base, start: base.startTick, end: base.endTick };
283
+ }
284
+ return {
285
+ ...base,
286
+ start: editor._secondsToTicks(base.start),
287
+ end: editor._secondsToTicks(base.end)
288
+ };
289
+ }
290
+ var DawAnnotationTrackElement = class extends import_lit2.LitElement {
291
+ constructor() {
292
+ super(...arguments);
293
+ this.editable = false;
294
+ this.linkEndpoints = false;
295
+ this.continuousPlay = false;
296
+ this.keyboardControls = false;
297
+ this.boxLabel = "text";
298
+ this.name = "";
299
+ // --- Selection (ephemeral UI state — deliberately NOT DOM data) ---
300
+ this._activeAnnotationId = null;
301
+ // --- Keyboard remapping (accessor pair: cache invalidation on set) ---
302
+ this._annotationShortcuts = null;
303
+ this._resolvedShortcuts = null;
304
+ // Capture phase: runs before <daw-keyboard-shortcuts>' bubble-phase listener,
305
+ // giving annotation shortcuts deterministic priority (spec rule).
306
+ this._onKeyDownCapture = (e) => {
307
+ if (!this.keyboardControls) return;
308
+ if (e.repeat) return;
309
+ const target = e.target;
310
+ if (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable) {
311
+ return;
312
+ }
313
+ const match = this._shortcutEntries().find((entry) => (0, import_core.matchesKeyBinding)(e, entry.binding));
314
+ if (!match) return;
315
+ const hasSelection = this._activeAnnotationId !== null;
316
+ if (match.action === "clearSelection" && !hasSelection) return;
317
+ if (DawAnnotationTrackElement._boundaryActions.has(match.action)) {
318
+ if (!this.editable || !hasSelection) return;
319
+ }
320
+ if (match.action === "playActive" && !hasSelection) return;
321
+ e.preventDefault();
322
+ e.stopImmediatePropagation();
323
+ try {
324
+ this._runShortcutAction(match.action);
325
+ } catch (err) {
326
+ console.warn("[dawcore] Annotation shortcut failed (key=" + e.key + "): " + String(err));
327
+ this.dispatchEvent(
328
+ new CustomEvent("daw-error", {
329
+ bubbles: true,
330
+ composed: true,
331
+ detail: { operation: "annotation-shortcut", key: e.key, error: err }
332
+ })
333
+ );
334
+ }
335
+ };
336
+ // --- Lifecycle ---
337
+ this._childObserver = null;
338
+ }
339
+ get activeAnnotationId() {
340
+ return this._activeAnnotationId;
341
+ }
342
+ set activeAnnotationId(value) {
343
+ if (value !== null && !this.annotationElements.some((el) => el.annotationId === value)) {
344
+ console.warn(
345
+ '[dawcore] daw-annotation-track: unknown annotation id "' + value + '" \u2014 selection ignored'
346
+ );
347
+ return;
348
+ }
349
+ if (value === this._activeAnnotationId) return;
350
+ this._activeAnnotationId = value;
351
+ const active = this._activeElement();
352
+ this.dispatchEvent(
353
+ new CustomEvent("daw-annotation-select", {
354
+ bubbles: true,
355
+ composed: true,
356
+ detail: { annotation: active ? active.toAnnotationData() : null }
357
+ })
358
+ );
359
+ }
360
+ // --- Child access ---
361
+ /** Child annotation elements, sorted by start time. */
362
+ get annotationElements() {
363
+ return Array.from(this.querySelectorAll(":scope > daw-annotation")).sort(
364
+ (a, b) => a.start - b.start
365
+ );
366
+ }
367
+ get annotations() {
368
+ return this.annotationElements.map((el) => el.toAnnotationData());
369
+ }
370
+ // --- Navigation methods (spec API) ---
371
+ selectNext() {
372
+ this._selectByOffset(1, 0);
373
+ }
374
+ selectPrevious() {
375
+ this._selectByOffset(-1, -1);
376
+ }
377
+ selectFirst() {
378
+ const list = this.annotationElements;
379
+ if (list.length > 0) this.activeAnnotationId = list[0].annotationId;
380
+ }
381
+ selectLast() {
382
+ const list = this.annotationElements;
383
+ if (list.length > 0) this.activeAnnotationId = list[list.length - 1].annotationId;
384
+ }
385
+ clearSelection() {
386
+ this.activeAnnotationId = null;
387
+ }
388
+ /** offset: +1 next / -1 previous; noSelectionIndex: 0 → first, -1 → last. */
389
+ _selectByOffset(offset, noSelectionIndex) {
390
+ const list = this.annotationElements;
391
+ if (list.length === 0) return;
392
+ const currentIndex = list.findIndex((el) => el.annotationId === this._activeAnnotationId);
393
+ const nextIndex = currentIndex === -1 ? (noSelectionIndex + list.length) % list.length : (currentIndex + offset + list.length) % list.length;
394
+ this.activeAnnotationId = list[nextIndex].annotationId;
395
+ }
396
+ // --- Playback (spec API) ---
397
+ playActive() {
398
+ const active = this._activeElement();
399
+ if (!active) return;
400
+ const editor = this._hostEditor();
401
+ if (!editor) {
402
+ console.warn(
403
+ "[dawcore] <daw-annotation-track> playActive: no parent <daw-editor> \u2014 call ignored"
404
+ );
405
+ return;
406
+ }
407
+ const data = active.toAnnotationData();
408
+ void editor.play(data.start, this.continuousPlay ? void 0 : data.end);
409
+ }
410
+ // --- Boundary editing (spec API) ---
411
+ moveStartBoundary(deltaMs) {
412
+ this._moveBoundary(deltaMs, true);
413
+ }
414
+ moveEndBoundary(deltaMs) {
415
+ this._moveBoundary(deltaMs, false);
416
+ }
417
+ _moveBoundary(deltaMs, isStart) {
418
+ if (!this.editable) {
419
+ console.warn(
420
+ "[dawcore] daw-annotation-track: boundary editing requires the editable attribute"
421
+ );
422
+ return;
423
+ }
424
+ const elements = this.annotationElements;
425
+ const index = elements.findIndex((el) => el.annotationId === this._activeAnnotationId);
426
+ if (index === -1) return;
427
+ const active = elements[index];
428
+ if (active.isTickBased) {
429
+ const editor = this._hostEditor();
430
+ if (!editor) {
431
+ console.warn(
432
+ "[dawcore] daw-annotation-track: tick-based boundary edits need a parent <daw-editor> for tempo conversion \u2014 call ignored"
433
+ );
434
+ return;
435
+ }
436
+ const tickData = elements.map((el) => tickSpaceData(el, editor));
437
+ const edgeTick = isStart ? tickData[index].start : tickData[index].end;
438
+ const edgeSeconds = editor._ticksToSeconds(edgeTick);
439
+ const deltaTicks = editor._secondsToTicks(edgeSeconds + deltaMs / 1e3) - editor._secondsToTicks(edgeSeconds);
440
+ const clamp = this._timelineDuration();
441
+ const updated2 = (0, import_core.updateAnnotationBoundaries)(
442
+ {
443
+ annotationIndex: index,
444
+ newTime: edgeTick + deltaTicks,
445
+ isDraggingStart: isStart,
446
+ annotations: tickData,
447
+ duration: clamp === Infinity ? Infinity : editor._secondsToTicks(clamp),
448
+ linkEndpoints: this.linkEndpoints
449
+ },
450
+ {
451
+ linkThreshold: import_core.ANNOTATION_LINK_THRESHOLD_TICKS,
452
+ minDuration: (0, import_core.annotationMinDurationTicks)(editor.ppqn)
453
+ }
454
+ );
455
+ applyTickBoundaryResults(elements, updated2, (t) => editor._ticksToSeconds(t));
456
+ return;
457
+ }
458
+ const data = elements.map((el) => el.toAnnotationData());
459
+ const edge = isStart ? data[index].start : data[index].end;
460
+ const updated = (0, import_core.updateAnnotationBoundaries)({
461
+ annotationIndex: index,
462
+ newTime: edge + deltaMs / 1e3,
463
+ isDraggingStart: isStart,
464
+ annotations: data,
465
+ duration: this._timelineDuration(),
466
+ linkEndpoints: this.linkEndpoints
467
+ });
468
+ applyBoundaryResults(elements, updated);
469
+ }
470
+ _timelineDuration() {
471
+ return this._hostEditor()?._annotationClampDuration ?? Infinity;
472
+ }
473
+ _activeElement() {
474
+ if (this._activeAnnotationId === null) return null;
475
+ return this.annotationElements.find((el) => el.annotationId === this._activeAnnotationId) ?? null;
476
+ }
477
+ _hostEditor() {
478
+ return this.closest("daw-editor");
479
+ }
480
+ get annotationShortcuts() {
481
+ return this._annotationShortcuts;
482
+ }
483
+ set annotationShortcuts(value) {
484
+ this._annotationShortcuts = value;
485
+ this._resolvedShortcuts = null;
486
+ }
487
+ _shortcutEntries() {
488
+ if (!this._resolvedShortcuts) {
489
+ this._resolvedShortcuts = (0, import_core.resolveAnnotationShortcuts)(this._annotationShortcuts);
490
+ }
491
+ return this._resolvedShortcuts;
492
+ }
493
+ _runShortcutAction(action) {
494
+ switch (action) {
495
+ case "selectPrevious":
496
+ this.selectPrevious();
497
+ break;
498
+ case "selectNext":
499
+ this.selectNext();
500
+ break;
501
+ case "selectFirst":
502
+ this.selectFirst();
503
+ break;
504
+ case "selectLast":
505
+ this.selectLast();
506
+ break;
507
+ case "clearSelection":
508
+ this.clearSelection();
509
+ break;
510
+ case "moveStartEarlier":
511
+ this.moveStartBoundary(-10);
512
+ break;
513
+ case "moveStartLater":
514
+ this.moveStartBoundary(10);
515
+ break;
516
+ case "moveEndEarlier":
517
+ this.moveEndBoundary(-10);
518
+ break;
519
+ case "moveEndLater":
520
+ this.moveEndBoundary(10);
521
+ break;
522
+ case "playActive":
523
+ this.playActive();
524
+ break;
525
+ }
526
+ }
527
+ createRenderRoot() {
528
+ return this;
529
+ }
530
+ connectedCallback() {
531
+ super.connectedCallback();
532
+ this.style.display = "none";
533
+ if (Object.prototype.hasOwnProperty.call(this, "annotationShortcuts")) {
534
+ const value = this["annotationShortcuts"];
535
+ delete this["annotationShortcuts"];
536
+ this.annotationShortcuts = value;
537
+ }
538
+ document.addEventListener("keydown", this._onKeyDownCapture, true);
539
+ setTimeout(() => {
540
+ this.dispatchEvent(
541
+ new CustomEvent("daw-annotation-track-connected", {
542
+ bubbles: true,
543
+ composed: true,
544
+ detail: { element: this }
545
+ })
546
+ );
547
+ }, 0);
548
+ this._childObserver = new MutationObserver(() => {
549
+ if (this._activeAnnotationId !== null && !this.annotationElements.some((el) => el.annotationId === this._activeAnnotationId)) {
550
+ this.activeAnnotationId = null;
551
+ }
552
+ });
553
+ this._childObserver.observe(this, { childList: true });
554
+ }
555
+ disconnectedCallback() {
556
+ super.disconnectedCallback();
557
+ document.removeEventListener("keydown", this._onKeyDownCapture, true);
558
+ this._childObserver?.disconnect();
559
+ this._childObserver = null;
560
+ }
561
+ };
562
+ DawAnnotationTrackElement._boundaryActions = /* @__PURE__ */ new Set([
563
+ "moveStartEarlier",
564
+ "moveStartLater",
565
+ "moveEndEarlier",
566
+ "moveEndLater"
567
+ ]);
568
+ __decorateClass([
569
+ (0, import_decorators2.property)({ type: Boolean, reflect: true })
570
+ ], DawAnnotationTrackElement.prototype, "editable", 2);
571
+ __decorateClass([
572
+ (0, import_decorators2.property)({ type: Boolean, reflect: true, attribute: "link-endpoints" })
573
+ ], DawAnnotationTrackElement.prototype, "linkEndpoints", 2);
574
+ __decorateClass([
575
+ (0, import_decorators2.property)({ type: Boolean, reflect: true, attribute: "continuous-play" })
576
+ ], DawAnnotationTrackElement.prototype, "continuousPlay", 2);
577
+ __decorateClass([
578
+ (0, import_decorators2.property)({ type: Boolean, reflect: true, attribute: "keyboard-controls" })
579
+ ], DawAnnotationTrackElement.prototype, "keyboardControls", 2);
580
+ __decorateClass([
581
+ (0, import_decorators2.property)({ reflect: true, attribute: "box-label" })
582
+ ], DawAnnotationTrackElement.prototype, "boxLabel", 2);
583
+ __decorateClass([
584
+ (0, import_decorators2.property)({ reflect: true })
585
+ ], DawAnnotationTrackElement.prototype, "name", 2);
586
+ DawAnnotationTrackElement = __decorateClass([
587
+ (0, import_decorators2.customElement)("daw-annotation-track")
588
+ ], DawAnnotationTrackElement);
589
+
590
+ // src/elements/daw-annotation-list.ts
591
+ var import_lit3 = require("lit");
592
+ var import_decorators3 = require("lit/decorators.js");
593
+ var import_core2 = require("@waveform-playlist/core");
594
+
595
+ // src/utils/annotation-playing.ts
596
+ function computePlayingAnnotationId(annotations, time) {
597
+ const match = annotations.find((a) => a.start <= time && time < a.end);
598
+ return match?.id ?? null;
599
+ }
600
+
601
+ // src/elements/daw-annotation-list.ts
602
+ function formatAnnotationTime(seconds) {
603
+ const whole = Math.floor(seconds);
604
+ const ms = Math.round((seconds - whole) * 1e3);
605
+ const s = whole % 60;
606
+ const m = (whole - s) / 60;
607
+ return m + ":" + String(s).padStart(2, "0") + "." + String(ms).padStart(3, "0");
608
+ }
609
+ var DawAnnotationListElement = class extends import_lit3.LitElement {
610
+ constructor() {
611
+ super(...arguments);
612
+ this.for = "";
613
+ this.timeDisplay = "time";
614
+ this._editingId = null;
615
+ this._activeId = null;
616
+ /** Playback-following highlight, separate from `_activeId` (selection) so
617
+ * playback never disturbs selection/keyboard editing. Driven by
618
+ * daw-timeupdate, cleared on daw-stop, retained on pause. */
619
+ this._playingId = null;
620
+ this._observer = null;
621
+ this._observedTrack = null;
622
+ this._warnedMissing = false;
623
+ /** Warn once per resolved `for` target when bars mode can't find a host
624
+ * editor — reset alongside `_warnedMissing` on `for` change so a
625
+ * retargeted list can warn again for its new target. */
626
+ this._warnedNoEditorForBars = false;
627
+ /** Set around `_cancelEdit`'s `span.blur()` so the resulting synchronous
628
+ * blur event doesn't re-enter `_commitEdit` (cancel already restores the
629
+ * text and clears `_editingId` itself). */
630
+ this._cancelling = false;
631
+ this._onSelect = (e) => {
632
+ if (e.target !== this.track) return;
633
+ this._activeId = e.detail.annotation?.id ?? null;
634
+ this.requestUpdate();
635
+ void this.updateComplete.then(() => {
636
+ const row = this.shadowRoot?.querySelector(".annotation-row.active");
637
+ row?.scrollIntoView?.({ block: "center" });
638
+ });
639
+ };
640
+ /**
641
+ * Update only on annotation-boundary crossings, not per animation frame.
642
+ * `shouldUpdate()` suppresses the resulting render while a row is being
643
+ * edited (`_editingId`) — intentional, not bypassed here. A boundary
644
+ * crossed mid-edit is caught up on the NEXT crossing after the edit ends;
645
+ * the highlight is briefly stale in that window, which is acceptable
646
+ * (edits are rare and short-lived relative to playback).
647
+ */
648
+ this._onTimeUpdate = (e) => {
649
+ if (e.target !== this.track?.closest("daw-editor")) return;
650
+ const playingId = computePlayingAnnotationId(this.track?.annotations ?? [], e.detail.time);
651
+ if (playingId === this._playingId) return;
652
+ this._playingId = playingId;
653
+ this.requestUpdate();
654
+ void this.updateComplete.then(() => {
655
+ const row = this.shadowRoot?.querySelector(".annotation-row.playing");
656
+ row?.scrollIntoView?.({ block: "center" });
657
+ });
658
+ };
659
+ this._onStop = (e) => {
660
+ if (e.target !== this.track?.closest("daw-editor")) return;
661
+ if (this._playingId === null) return;
662
+ this._playingId = null;
663
+ this.requestUpdate();
664
+ };
665
+ }
666
+ get track() {
667
+ if (!this.for) return null;
668
+ const el = document.getElementById(this.for);
669
+ if (!el || el.tagName !== "DAW-ANNOTATION-TRACK") {
670
+ if (!this._warnedMissing) {
671
+ console.warn(
672
+ el ? '[dawcore] <daw-annotation-list for="' + this.for + '"> target is not a <daw-annotation-track>' : '[dawcore] <daw-annotation-list for="' + this.for + '"> target not found'
673
+ );
674
+ this._warnedMissing = true;
675
+ }
676
+ return null;
677
+ }
678
+ return el;
679
+ }
680
+ willUpdate(changed) {
681
+ if (changed.has("for")) {
682
+ this._warnedMissing = false;
683
+ this._warnedNoEditorForBars = false;
684
+ }
685
+ }
686
+ connectedCallback() {
687
+ super.connectedCallback();
688
+ document.addEventListener("daw-annotation-select", this._onSelect);
689
+ document.addEventListener("daw-timeupdate", this._onTimeUpdate);
690
+ document.addEventListener("daw-stop", this._onStop);
691
+ }
692
+ disconnectedCallback() {
693
+ super.disconnectedCallback();
694
+ document.removeEventListener("daw-annotation-select", this._onSelect);
695
+ document.removeEventListener("daw-timeupdate", this._onTimeUpdate);
696
+ document.removeEventListener("daw-stop", this._onStop);
697
+ this._observer?.disconnect();
698
+ this._observer = null;
699
+ this._observedTrack = null;
700
+ }
701
+ shouldUpdate() {
702
+ return this._editingId === null;
703
+ }
704
+ updated() {
705
+ this._ensureObserver();
706
+ this._syncRowText();
707
+ }
708
+ /**
709
+ * Text content is set imperatively, NOT bound as a Lit expression.
710
+ * contenteditable mutates the span's DOM directly as the user types —
711
+ * that ejects lit-html's ChildPart marker comments for any binding at
712
+ * that position, so a later Lit-driven re-render of the same row throws
713
+ * "ChildPart has no parentNode". Keeping the span's children entirely
714
+ * outside Lit's diffing sidesteps the crash; the (soon-to-commit) edited
715
+ * row is skipped via the _editingId check.
716
+ */
717
+ _syncRowText() {
718
+ const annotations = this.track?.annotations ?? [];
719
+ const spans = this.shadowRoot?.querySelectorAll(".annotation-row-text") ?? [];
720
+ spans.forEach((span) => {
721
+ const id = span.dataset.id;
722
+ if (id === void 0 || id === this._editingId) return;
723
+ const a = annotations.find((x) => x.id === id);
724
+ if (!a) return;
725
+ const text = a.lines.join(" ");
726
+ if (span.textContent !== text) span.textContent = text;
727
+ });
728
+ }
729
+ /** (Re)attach the MutationObserver when the resolved track changes. */
730
+ _ensureObserver() {
731
+ const track = this.track;
732
+ if (track === this._observedTrack) return;
733
+ this._observer?.disconnect();
734
+ this._observedTrack = track;
735
+ if (!track) return;
736
+ this._observer = new MutationObserver(() => this.requestUpdate());
737
+ this._observer.observe(track, {
738
+ childList: true,
739
+ subtree: true,
740
+ characterData: true,
741
+ attributes: true,
742
+ attributeFilter: ["start", "end", "id", "editable"]
743
+ });
744
+ }
745
+ _onRowClick(a) {
746
+ const track = this.track;
747
+ if (!track) return;
748
+ track.activeAnnotationId = a.id;
749
+ const editor = track.closest("daw-editor");
750
+ editor?.seekTo?.(a.start);
751
+ }
752
+ /** Formats a row's times span per `timeDisplay`. `'bars'` resolves the
753
+ * host editor once (shared across all rows in a render) and falls back
754
+ * to time display, warning once, when no editor is found. */
755
+ _formatTimes(a, editor) {
756
+ if (this.timeDisplay === "bars") {
757
+ if (editor) {
758
+ const isTickBased = a.startTick !== void 0 && a.endTick !== void 0;
759
+ const startTick = isTickBased ? a.startTick : editor._secondsToTicks(a.start);
760
+ const endTick = isTickBased ? a.endTick : editor._secondsToTicks(a.end);
761
+ const start = (0, import_core2.ticksToBarBeat)(startTick, editor._meterEntries, editor.ppqn);
762
+ const end = (0, import_core2.ticksToBarBeat)(endTick, editor._meterEntries, editor.ppqn);
763
+ return start.bar + "." + start.beat + " \u2013 " + end.bar + "." + end.beat;
764
+ }
765
+ if (!this._warnedNoEditorForBars) {
766
+ console.warn(
767
+ '[dawcore] <daw-annotation-list for="' + this.for + '" time-display="bars"> found no parent <daw-editor> \u2014 falling back to time display'
768
+ );
769
+ this._warnedNoEditorForBars = true;
770
+ }
771
+ }
772
+ return formatAnnotationTime(a.start) + " \u2013 " + formatAnnotationTime(a.end);
773
+ }
774
+ _annotationElement(id) {
775
+ return this.track?.annotationElements.find((el) => el.annotationId === id) ?? null;
776
+ }
777
+ _commitEdit(a, span) {
778
+ if (this._cancelling) return;
779
+ this._editingId = null;
780
+ const el = this._annotationElement(a.id);
781
+ if (el) el.textContent = span.textContent?.trim() ?? "";
782
+ this.requestUpdate();
783
+ }
784
+ _cancelEdit(a, span) {
785
+ this._editingId = null;
786
+ span.textContent = a.lines.join("\n");
787
+ this._cancelling = true;
788
+ try {
789
+ span.blur();
790
+ } finally {
791
+ this._cancelling = false;
792
+ }
793
+ this.requestUpdate();
794
+ }
795
+ render() {
796
+ const track = this.track;
797
+ const annotations = track?.annotations ?? [];
798
+ const editable = track?.editable ?? false;
799
+ const editor = this.timeDisplay === "bars" ? track?.closest("daw-editor") ?? null : null;
800
+ return import_lit3.html`
801
+ ${annotations.map(
802
+ (a) => import_lit3.html`
803
+ <div
804
+ class="annotation-row ${a.id === this._activeId ? "active" : ""} ${a.id === this._playingId ? "playing" : ""}"
805
+ @click=${(e) => {
806
+ if (this._editingId === a.id && this._activeId === a.id) return;
807
+ e.stopPropagation();
808
+ this._onRowClick(a);
809
+ }}
810
+ >
811
+ <span class="annotation-row-times"> ${this._formatTimes(a, editor)} </span>
812
+ <span
813
+ class="annotation-row-text"
814
+ data-id=${a.id}
815
+ contenteditable=${editable ? "true" : import_lit3.nothing}
816
+ @focus=${() => {
817
+ if (editable) this._editingId = a.id;
818
+ }}
819
+ @blur=${(e) => this._commitEdit(a, e.target)}
820
+ @keydown=${(e) => {
821
+ if (!editable) return;
822
+ e.stopPropagation();
823
+ if (e.key === "Enter") {
824
+ e.preventDefault();
825
+ e.target.blur();
826
+ } else if (e.key === "Escape") {
827
+ this._cancelEdit(a, e.target);
828
+ }
829
+ }}
830
+ ></span>
831
+ </div>
832
+ `
833
+ )}
834
+ `;
835
+ }
836
+ };
837
+ DawAnnotationListElement.styles = import_lit3.css`
838
+ :host {
839
+ display: block;
840
+ max-height: var(--daw-annotation-list-max-height, 240px);
841
+ overflow-y: auto;
842
+ background: var(--daw-annotation-list-background, #16213e);
843
+ color: var(--daw-annotation-text-color, #e0d4c8);
844
+ font-family: system-ui, sans-serif;
845
+ font-size: 13px;
846
+ }
847
+ .annotation-row {
848
+ display: flex;
849
+ gap: 10px;
850
+ align-items: baseline;
851
+ padding: 6px 10px;
852
+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);
853
+ cursor: pointer;
854
+ }
855
+ .annotation-row.playing {
856
+ background: var(--daw-annotation-playing-background, rgba(196, 154, 108, 0.12));
857
+ box-shadow: inset 2px 0 0 var(--daw-annotation-box-border, #c49a6c);
858
+ }
859
+ .annotation-row.active {
860
+ background: var(--daw-annotation-active-background, rgba(196, 154, 108, 0.25));
861
+ }
862
+ .annotation-row-times {
863
+ font-variant-numeric: tabular-nums;
864
+ font-size: 11px;
865
+ opacity: 0.7;
866
+ white-space: nowrap;
867
+ }
868
+ .annotation-row-text {
869
+ flex: 1;
870
+ min-width: 0;
871
+ }
872
+ .annotation-row-text[contenteditable='true'] {
873
+ cursor: text;
874
+ outline-offset: 2px;
875
+ }
876
+ .annotation-row-text:empty::before {
877
+ content: '—';
878
+ opacity: 0.4;
879
+ }
880
+ `;
881
+ __decorateClass([
882
+ (0, import_decorators3.property)()
883
+ ], DawAnnotationListElement.prototype, "for", 2);
884
+ __decorateClass([
885
+ (0, import_decorators3.property)({ type: String, attribute: "time-display", reflect: true })
886
+ ], DawAnnotationListElement.prototype, "timeDisplay", 2);
887
+ __decorateClass([
888
+ (0, import_decorators3.state)()
889
+ ], DawAnnotationListElement.prototype, "_editingId", 2);
890
+ DawAnnotationListElement = __decorateClass([
891
+ (0, import_decorators3.customElement)("daw-annotation-list")
892
+ ], DawAnnotationListElement);
893
+
894
+ // src/elements/daw-clip.ts
895
+ var import_lit4 = require("lit");
896
+ var import_decorators4 = require("lit/decorators.js");
897
+ var DawClipElement = class extends import_lit4.LitElement {
87
898
  constructor() {
88
899
  super(...arguments);
89
900
  this.src = "";
@@ -188,55 +999,55 @@ var DawClipElement = class extends import_lit.LitElement {
188
999
  }
189
1000
  };
190
1001
  __decorateClass([
191
- (0, import_decorators.property)()
1002
+ (0, import_decorators4.property)()
192
1003
  ], DawClipElement.prototype, "src", 2);
193
1004
  __decorateClass([
194
- (0, import_decorators.property)({ attribute: "peaks-src" })
1005
+ (0, import_decorators4.property)({ attribute: "peaks-src" })
195
1006
  ], DawClipElement.prototype, "peaksSrc", 2);
196
1007
  __decorateClass([
197
- (0, import_decorators.property)({ type: Number })
1008
+ (0, import_decorators4.property)({ type: Number })
198
1009
  ], DawClipElement.prototype, "start", 2);
199
1010
  __decorateClass([
200
- (0, import_decorators.property)({ type: Number })
1011
+ (0, import_decorators4.property)({ type: Number })
201
1012
  ], DawClipElement.prototype, "duration", 2);
202
1013
  __decorateClass([
203
- (0, import_decorators.property)({ type: Number })
1014
+ (0, import_decorators4.property)({ type: Number })
204
1015
  ], DawClipElement.prototype, "offset", 2);
205
1016
  __decorateClass([
206
- (0, import_decorators.property)({ type: Number })
1017
+ (0, import_decorators4.property)({ type: Number })
207
1018
  ], DawClipElement.prototype, "gain", 2);
208
1019
  __decorateClass([
209
- (0, import_decorators.property)()
1020
+ (0, import_decorators4.property)()
210
1021
  ], DawClipElement.prototype, "name", 2);
211
1022
  __decorateClass([
212
- (0, import_decorators.property)()
1023
+ (0, import_decorators4.property)()
213
1024
  ], DawClipElement.prototype, "color", 2);
214
1025
  __decorateClass([
215
- (0, import_decorators.property)({ type: Number, attribute: "fade-in" })
1026
+ (0, import_decorators4.property)({ type: Number, attribute: "fade-in" })
216
1027
  ], DawClipElement.prototype, "fadeIn", 2);
217
1028
  __decorateClass([
218
- (0, import_decorators.property)({ type: Number, attribute: "fade-out" })
1029
+ (0, import_decorators4.property)({ type: Number, attribute: "fade-out" })
219
1030
  ], DawClipElement.prototype, "fadeOut", 2);
220
1031
  __decorateClass([
221
- (0, import_decorators.property)({ attribute: "fade-type" })
1032
+ (0, import_decorators4.property)({ attribute: "fade-type" })
222
1033
  ], DawClipElement.prototype, "fadeType", 2);
223
1034
  __decorateClass([
224
- (0, import_decorators.property)({ attribute: false })
1035
+ (0, import_decorators4.property)({ attribute: false })
225
1036
  ], DawClipElement.prototype, "midiNotes", 2);
226
1037
  __decorateClass([
227
- (0, import_decorators.property)({ type: Number, attribute: "midi-channel", noAccessor: true })
1038
+ (0, import_decorators4.property)({ type: Number, attribute: "midi-channel", noAccessor: true })
228
1039
  ], DawClipElement.prototype, "midiChannel", 1);
229
1040
  __decorateClass([
230
- (0, import_decorators.property)({ type: Number, attribute: "midi-program", noAccessor: true })
1041
+ (0, import_decorators4.property)({ type: Number, attribute: "midi-program", noAccessor: true })
231
1042
  ], DawClipElement.prototype, "midiProgram", 1);
232
1043
  DawClipElement = __decorateClass([
233
- (0, import_decorators.customElement)("daw-clip")
1044
+ (0, import_decorators4.customElement)("daw-clip")
234
1045
  ], DawClipElement);
235
1046
 
236
1047
  // src/elements/daw-track.ts
237
- var import_lit2 = require("lit");
238
- var import_decorators2 = require("lit/decorators.js");
239
- var DawTrackElement = class extends import_lit2.LitElement {
1048
+ var import_lit5 = require("lit");
1049
+ var import_decorators5 = require("lit/decorators.js");
1050
+ var DawTrackElement = class extends import_lit5.LitElement {
240
1051
  constructor() {
241
1052
  super(...arguments);
242
1053
  this.src = "";
@@ -374,36 +1185,36 @@ var DawTrackElement = class extends import_lit2.LitElement {
374
1185
  }
375
1186
  };
376
1187
  __decorateClass([
377
- (0, import_decorators2.property)()
1188
+ (0, import_decorators5.property)()
378
1189
  ], DawTrackElement.prototype, "src", 2);
379
1190
  __decorateClass([
380
- (0, import_decorators2.property)()
1191
+ (0, import_decorators5.property)()
381
1192
  ], DawTrackElement.prototype, "name", 2);
382
1193
  __decorateClass([
383
- (0, import_decorators2.property)({ type: Number })
1194
+ (0, import_decorators5.property)({ type: Number })
384
1195
  ], DawTrackElement.prototype, "volume", 2);
385
1196
  __decorateClass([
386
- (0, import_decorators2.property)({ type: Number })
1197
+ (0, import_decorators5.property)({ type: Number })
387
1198
  ], DawTrackElement.prototype, "pan", 2);
388
1199
  __decorateClass([
389
- (0, import_decorators2.property)({ type: Boolean })
1200
+ (0, import_decorators5.property)({ type: Boolean })
390
1201
  ], DawTrackElement.prototype, "muted", 2);
391
1202
  __decorateClass([
392
- (0, import_decorators2.property)({ type: Boolean })
1203
+ (0, import_decorators5.property)({ type: Boolean })
393
1204
  ], DawTrackElement.prototype, "soloed", 2);
394
1205
  __decorateClass([
395
- (0, import_decorators2.property)({ attribute: "render-mode", noAccessor: true })
1206
+ (0, import_decorators5.property)({ attribute: "render-mode", noAccessor: true })
396
1207
  ], DawTrackElement.prototype, "renderMode", 1);
397
1208
  __decorateClass([
398
- (0, import_decorators2.property)({ attribute: false })
1209
+ (0, import_decorators5.property)({ attribute: false })
399
1210
  ], DawTrackElement.prototype, "spectrogramConfig", 2);
400
1211
  DawTrackElement = __decorateClass([
401
- (0, import_decorators2.customElement)("daw-track")
1212
+ (0, import_decorators5.customElement)("daw-track")
402
1213
  ], DawTrackElement);
403
1214
 
404
1215
  // src/elements/daw-waveform.ts
405
- var import_lit3 = require("lit");
406
- var import_decorators3 = require("lit/decorators.js");
1216
+ var import_lit6 = require("lit");
1217
+ var import_decorators6 = require("lit/decorators.js");
407
1218
 
408
1219
  // src/utils/peak-rendering.ts
409
1220
  function aggregatePeaks(data, bits, startIndex, endIndex) {
@@ -465,11 +1276,9 @@ var LAYOUT_PROPS = /* @__PURE__ */ new Set([
465
1276
  "roundedBars",
466
1277
  "segments"
467
1278
  ]);
468
- function groupDirtyByChunk(dirtyPixels, step) {
1279
+ function groupDirtyByChunk(dirtyPixels, step, barWidth) {
469
1280
  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);
1281
+ const mark = (chunkIdx, barPixel) => {
473
1282
  const existing = dirtyByChunk.get(chunkIdx);
474
1283
  if (existing) {
475
1284
  dirtyByChunk.set(chunkIdx, {
@@ -479,10 +1288,19 @@ function groupDirtyByChunk(dirtyPixels, step) {
479
1288
  } else {
480
1289
  dirtyByChunk.set(chunkIdx, { min: barPixel, max: barPixel });
481
1290
  }
1291
+ };
1292
+ for (const peakIdx of dirtyPixels) {
1293
+ const barPixel = Math.floor(peakIdx / step) * step;
1294
+ const chunkIdx = Math.floor(barPixel / MAX_CANVAS_WIDTH);
1295
+ mark(chunkIdx, barPixel);
1296
+ const endChunkIdx = Math.floor((barPixel + barWidth - 1) / MAX_CANVAS_WIDTH);
1297
+ if (endChunkIdx !== chunkIdx) {
1298
+ mark(endChunkIdx, barPixel);
1299
+ }
482
1300
  }
483
1301
  return dirtyByChunk;
484
1302
  }
485
- var DawWaveformElement = class extends import_lit3.LitElement {
1303
+ var DawWaveformElement = class extends import_lit6.LitElement {
486
1304
  constructor() {
487
1305
  super(...arguments);
488
1306
  this._peaks = new Int16Array(0);
@@ -580,7 +1398,7 @@ var DawWaveformElement = class extends import_lit3.LitElement {
580
1398
  this._drawSegments(canvas, chunkIdx, dpr, halfHeight, bits, waveColor);
581
1399
  }
582
1400
  } else {
583
- const dirtyByChunk = groupDirtyByChunk(this._dirtyPixels, step);
1401
+ const dirtyByChunk = groupDirtyByChunk(this._dirtyPixels, step, this.barWidth);
584
1402
  for (const canvas of canvases) {
585
1403
  const chunkIdx = Number(canvas.dataset.index);
586
1404
  this._drawnChunks.add(chunkIdx);
@@ -688,11 +1506,11 @@ var DawWaveformElement = class extends import_lit3.LitElement {
688
1506
  render() {
689
1507
  const indices = this._getVisibleChunkIndices();
690
1508
  const dpr = typeof devicePixelRatio !== "undefined" ? devicePixelRatio : 1;
691
- return import_lit3.html`
1509
+ return import_lit6.html`
692
1510
  <div class="container" style="width: ${this.length}px; height: ${this.waveHeight}px;">
693
1511
  ${indices.map((i) => {
694
1512
  const width = Math.min(MAX_CANVAS_WIDTH, this.length - i * MAX_CANVAS_WIDTH);
695
- return import_lit3.html`
1513
+ return import_lit6.html`
696
1514
  <canvas
697
1515
  data-index=${i}
698
1516
  width=${width * dpr}
@@ -732,7 +1550,7 @@ var DawWaveformElement = class extends import_lit3.LitElement {
732
1550
  }
733
1551
  }
734
1552
  };
735
- DawWaveformElement.styles = import_lit3.css`
1553
+ DawWaveformElement.styles = import_lit6.css`
736
1554
  :host {
737
1555
  display: block;
738
1556
  position: relative;
@@ -746,39 +1564,39 @@ DawWaveformElement.styles = import_lit3.css`
746
1564
  }
747
1565
  `;
748
1566
  __decorateClass([
749
- (0, import_decorators3.property)({ type: Number, attribute: false })
1567
+ (0, import_decorators6.property)({ type: Number, attribute: false })
750
1568
  ], DawWaveformElement.prototype, "length", 2);
751
1569
  __decorateClass([
752
- (0, import_decorators3.property)({ type: Number, attribute: false })
1570
+ (0, import_decorators6.property)({ type: Number, attribute: false })
753
1571
  ], DawWaveformElement.prototype, "waveHeight", 2);
754
1572
  __decorateClass([
755
- (0, import_decorators3.property)({ type: Number, attribute: false })
1573
+ (0, import_decorators6.property)({ type: Number, attribute: false })
756
1574
  ], DawWaveformElement.prototype, "barWidth", 2);
757
1575
  __decorateClass([
758
- (0, import_decorators3.property)({ type: Number, attribute: false })
1576
+ (0, import_decorators6.property)({ type: Number, attribute: false })
759
1577
  ], DawWaveformElement.prototype, "barGap", 2);
760
1578
  __decorateClass([
761
- (0, import_decorators3.property)({ type: Boolean, attribute: false })
1579
+ (0, import_decorators6.property)({ type: Boolean, attribute: false })
762
1580
  ], DawWaveformElement.prototype, "roundedBars", 2);
763
1581
  __decorateClass([
764
- (0, import_decorators3.property)({ type: Number, attribute: false })
1582
+ (0, import_decorators6.property)({ type: Number, attribute: false })
765
1583
  ], DawWaveformElement.prototype, "visibleStart", 2);
766
1584
  __decorateClass([
767
- (0, import_decorators3.property)({ type: Number, attribute: false })
1585
+ (0, import_decorators6.property)({ type: Number, attribute: false })
768
1586
  ], DawWaveformElement.prototype, "visibleEnd", 2);
769
1587
  __decorateClass([
770
- (0, import_decorators3.property)({ type: Number, attribute: false })
1588
+ (0, import_decorators6.property)({ type: Number, attribute: false })
771
1589
  ], DawWaveformElement.prototype, "originX", 2);
772
1590
  __decorateClass([
773
- (0, import_decorators3.property)({ attribute: false })
1591
+ (0, import_decorators6.property)({ attribute: false })
774
1592
  ], DawWaveformElement.prototype, "segments", 2);
775
1593
  DawWaveformElement = __decorateClass([
776
- (0, import_decorators3.customElement)("daw-waveform")
1594
+ (0, import_decorators6.customElement)("daw-waveform")
777
1595
  ], DawWaveformElement);
778
1596
 
779
1597
  // src/elements/daw-piano-roll.ts
780
- var import_lit4 = require("lit");
781
- var import_decorators4 = require("lit/decorators.js");
1598
+ var import_lit7 = require("lit");
1599
+ var import_decorators7 = require("lit/decorators.js");
782
1600
  var MAX_CANVAS_WIDTH2 = 1e3;
783
1601
  var LAYOUT_PROPS2 = /* @__PURE__ */ new Set([
784
1602
  "length",
@@ -789,7 +1607,7 @@ var LAYOUT_PROPS2 = /* @__PURE__ */ new Set([
789
1607
  "midiNotes",
790
1608
  "selected"
791
1609
  ]);
792
- var DawPianoRollElement = class extends import_lit4.LitElement {
1610
+ var DawPianoRollElement = class extends import_lit7.LitElement {
793
1611
  constructor() {
794
1612
  super(...arguments);
795
1613
  this.midiNotes = [];
@@ -921,7 +1739,7 @@ var DawPianoRollElement = class extends import_lit4.LitElement {
921
1739
  }
922
1740
  render() {
923
1741
  if (this.length <= 0)
924
- return import_lit4.html`<div class="container" style="width: 0; height: ${this.waveHeight}px;"></div>`;
1742
+ return import_lit7.html`<div class="container" style="width: 0; height: ${this.waveHeight}px;"></div>`;
925
1743
  const dpr = typeof devicePixelRatio !== "undefined" ? devicePixelRatio : 1;
926
1744
  const visibleIndices = getVisibleChunkIndices(
927
1745
  this.length,
@@ -930,12 +1748,12 @@ var DawPianoRollElement = class extends import_lit4.LitElement {
930
1748
  this.visibleEnd,
931
1749
  this.originX
932
1750
  );
933
- return import_lit4.html`
1751
+ return import_lit7.html`
934
1752
  <div class="container" style="width: ${this.length}px; height: ${this.waveHeight}px;">
935
1753
  ${visibleIndices.map((i) => {
936
1754
  const chunkLeft = i * MAX_CANVAS_WIDTH2;
937
1755
  const chunkWidth = Math.min(this.length - chunkLeft, MAX_CANVAS_WIDTH2);
938
- return import_lit4.html`<canvas
1756
+ return import_lit7.html`<canvas
939
1757
  data-index=${i}
940
1758
  width=${chunkWidth * dpr}
941
1759
  height=${this.waveHeight * dpr}
@@ -946,7 +1764,7 @@ var DawPianoRollElement = class extends import_lit4.LitElement {
946
1764
  `;
947
1765
  }
948
1766
  };
949
- DawPianoRollElement.styles = import_lit4.css`
1767
+ DawPianoRollElement.styles = import_lit7.css`
950
1768
  :host {
951
1769
  display: block;
952
1770
  position: relative;
@@ -963,49 +1781,49 @@ DawPianoRollElement.styles = import_lit4.css`
963
1781
  }
964
1782
  `;
965
1783
  __decorateClass([
966
- (0, import_decorators4.property)({ attribute: false })
1784
+ (0, import_decorators7.property)({ attribute: false })
967
1785
  ], DawPianoRollElement.prototype, "midiNotes", 2);
968
1786
  __decorateClass([
969
- (0, import_decorators4.property)({ type: Number, attribute: false })
1787
+ (0, import_decorators7.property)({ type: Number, attribute: false })
970
1788
  ], DawPianoRollElement.prototype, "length", 2);
971
1789
  __decorateClass([
972
- (0, import_decorators4.property)({ type: Number, attribute: false })
1790
+ (0, import_decorators7.property)({ type: Number, attribute: false })
973
1791
  ], DawPianoRollElement.prototype, "waveHeight", 2);
974
1792
  __decorateClass([
975
- (0, import_decorators4.property)({ type: Number, attribute: "samples-per-pixel", noAccessor: true })
1793
+ (0, import_decorators7.property)({ type: Number, attribute: "samples-per-pixel", noAccessor: true })
976
1794
  ], DawPianoRollElement.prototype, "samplesPerPixel", 1);
977
1795
  __decorateClass([
978
- (0, import_decorators4.property)({ type: Number, attribute: "sample-rate", noAccessor: true })
1796
+ (0, import_decorators7.property)({ type: Number, attribute: "sample-rate", noAccessor: true })
979
1797
  ], DawPianoRollElement.prototype, "sampleRate", 1);
980
1798
  __decorateClass([
981
- (0, import_decorators4.property)({ type: Number, attribute: false })
1799
+ (0, import_decorators7.property)({ type: Number, attribute: false })
982
1800
  ], DawPianoRollElement.prototype, "clipOffsetSeconds", 2);
983
1801
  __decorateClass([
984
- (0, import_decorators4.property)({ type: Number, attribute: false })
1802
+ (0, import_decorators7.property)({ type: Number, attribute: false })
985
1803
  ], DawPianoRollElement.prototype, "visibleStart", 2);
986
1804
  __decorateClass([
987
- (0, import_decorators4.property)({ type: Number, attribute: false })
1805
+ (0, import_decorators7.property)({ type: Number, attribute: false })
988
1806
  ], DawPianoRollElement.prototype, "visibleEnd", 2);
989
1807
  __decorateClass([
990
- (0, import_decorators4.property)({ type: Number, attribute: false })
1808
+ (0, import_decorators7.property)({ type: Number, attribute: false })
991
1809
  ], DawPianoRollElement.prototype, "originX", 2);
992
1810
  __decorateClass([
993
- (0, import_decorators4.property)({ type: Boolean, reflect: true })
1811
+ (0, import_decorators7.property)({ type: Boolean, reflect: true })
994
1812
  ], DawPianoRollElement.prototype, "selected", 2);
995
1813
  DawPianoRollElement = __decorateClass([
996
- (0, import_decorators4.customElement)("daw-piano-roll")
1814
+ (0, import_decorators7.customElement)("daw-piano-roll")
997
1815
  ], DawPianoRollElement);
998
1816
 
999
1817
  // src/elements/daw-playhead.ts
1000
- var import_lit5 = require("lit");
1001
- var import_decorators5 = require("lit/decorators.js");
1002
- var DawPlayheadElement = class extends import_lit5.LitElement {
1818
+ var import_lit8 = require("lit");
1819
+ var import_decorators8 = require("lit/decorators.js");
1820
+ var DawPlayheadElement = class extends import_lit8.LitElement {
1003
1821
  constructor() {
1004
1822
  super(...arguments);
1005
1823
  this._line = null;
1006
1824
  }
1007
1825
  render() {
1008
- return import_lit5.html`<div></div>`;
1826
+ return import_lit8.html`<div></div>`;
1009
1827
  }
1010
1828
  firstUpdated() {
1011
1829
  this._line = this.shadowRoot.querySelector("div");
@@ -1019,7 +1837,7 @@ var DawPlayheadElement = class extends import_lit5.LitElement {
1019
1837
  }
1020
1838
  }
1021
1839
  };
1022
- DawPlayheadElement.styles = import_lit5.css`
1840
+ DawPlayheadElement.styles = import_lit8.css`
1023
1841
  :host {
1024
1842
  position: absolute;
1025
1843
  top: 0;
@@ -1038,13 +1856,13 @@ DawPlayheadElement.styles = import_lit5.css`
1038
1856
  }
1039
1857
  `;
1040
1858
  DawPlayheadElement = __decorateClass([
1041
- (0, import_decorators5.customElement)("daw-playhead")
1859
+ (0, import_decorators8.customElement)("daw-playhead")
1042
1860
  ], DawPlayheadElement);
1043
1861
 
1044
1862
  // src/elements/daw-transport.ts
1045
- var import_lit6 = require("lit");
1046
- var import_decorators6 = require("lit/decorators.js");
1047
- var DawTransportElement = class extends import_lit6.LitElement {
1863
+ var import_lit9 = require("lit");
1864
+ var import_decorators9 = require("lit/decorators.js");
1865
+ var DawTransportElement = class extends import_lit9.LitElement {
1048
1866
  constructor() {
1049
1867
  super(...arguments);
1050
1868
  this.for = "";
@@ -1059,18 +1877,18 @@ var DawTransportElement = class extends import_lit6.LitElement {
1059
1877
  }
1060
1878
  };
1061
1879
  __decorateClass([
1062
- (0, import_decorators6.property)()
1880
+ (0, import_decorators9.property)()
1063
1881
  ], DawTransportElement.prototype, "for", 2);
1064
1882
  DawTransportElement = __decorateClass([
1065
- (0, import_decorators6.customElement)("daw-transport")
1883
+ (0, import_decorators9.customElement)("daw-transport")
1066
1884
  ], DawTransportElement);
1067
1885
 
1068
1886
  // src/elements/daw-play-button.ts
1069
- var import_lit8 = require("lit");
1070
- var import_decorators7 = require("lit/decorators.js");
1887
+ var import_lit11 = require("lit");
1888
+ var import_decorators10 = require("lit/decorators.js");
1071
1889
 
1072
1890
  // src/elements/daw-transport-button.ts
1073
- var import_lit7 = require("lit");
1891
+ var import_lit10 = require("lit");
1074
1892
 
1075
1893
  // src/utils/transport-capability.ts
1076
1894
  function resolveTransportTarget(el) {
@@ -1111,7 +1929,7 @@ function warnUnsupportedOnce(element, methods) {
1111
1929
  }
1112
1930
 
1113
1931
  // src/elements/daw-transport-button.ts
1114
- var DawTransportButton = class extends import_lit7.LitElement {
1932
+ var DawTransportButton = class extends import_lit10.LitElement {
1115
1933
  constructor() {
1116
1934
  super(...arguments);
1117
1935
  this._onCapabilityPointerEnter = () => {
@@ -1167,7 +1985,7 @@ var DawTransportButton = class extends import_lit7.LitElement {
1167
1985
  /** Methods the transport target must implement for this control to be
1168
1986
  * enabled. Empty = works with any target. */
1169
1987
  DawTransportButton.requiredTargetMethods = [];
1170
- DawTransportButton.styles = import_lit7.css`
1988
+ DawTransportButton.styles = import_lit10.css`
1171
1989
  button {
1172
1990
  cursor: pointer;
1173
1991
  background: var(--daw-controls-background, #1a1a2e);
@@ -1201,16 +2019,31 @@ var DawPlayButtonElement = class extends DawTransportButton {
1201
2019
  connectedCallback() {
1202
2020
  super.connectedCallback();
1203
2021
  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);
2022
+ if (!this.isConnected) return;
2023
+ this._ensureTargetListeners();
1210
2024
  });
1211
2025
  }
1212
2026
  disconnectedCallback() {
1213
2027
  super.disconnectedCallback();
2028
+ this._cleanupListeners();
2029
+ }
2030
+ updated() {
2031
+ this._ensureTargetListeners();
2032
+ }
2033
+ _ensureTargetListeners() {
2034
+ const target = this.target;
2035
+ if (target === this._targetRef) return;
2036
+ if (this._targetRef) {
2037
+ this._isRecording = false;
2038
+ }
2039
+ this._cleanupListeners();
2040
+ if (!target) return;
2041
+ this._targetRef = target;
2042
+ target.addEventListener("daw-recording-start", this._onRecStart);
2043
+ target.addEventListener("daw-recording-complete", this._onRecEnd);
2044
+ target.addEventListener("daw-recording-error", this._onRecEnd);
2045
+ }
2046
+ _cleanupListeners() {
1214
2047
  if (this._targetRef) {
1215
2048
  this._targetRef.removeEventListener("daw-recording-start", this._onRecStart);
1216
2049
  this._targetRef.removeEventListener("daw-recording-complete", this._onRecEnd);
@@ -1219,7 +2052,7 @@ var DawPlayButtonElement = class extends DawTransportButton {
1219
2052
  }
1220
2053
  }
1221
2054
  render() {
1222
- return import_lit8.html`
2055
+ return import_lit11.html`
1223
2056
  <button part="button" ?disabled=${this._isRecording} @click=${this._onClick}>
1224
2057
  <slot>Play</slot>
1225
2058
  </button>
@@ -1237,15 +2070,15 @@ var DawPlayButtonElement = class extends DawTransportButton {
1237
2070
  }
1238
2071
  };
1239
2072
  __decorateClass([
1240
- (0, import_decorators7.state)()
2073
+ (0, import_decorators10.state)()
1241
2074
  ], DawPlayButtonElement.prototype, "_isRecording", 2);
1242
2075
  DawPlayButtonElement = __decorateClass([
1243
- (0, import_decorators7.customElement)("daw-play-button")
2076
+ (0, import_decorators10.customElement)("daw-play-button")
1244
2077
  ], DawPlayButtonElement);
1245
2078
 
1246
2079
  // src/elements/daw-pause-button.ts
1247
- var import_lit9 = require("lit");
1248
- var import_decorators8 = require("lit/decorators.js");
2080
+ var import_lit12 = require("lit");
2081
+ var import_decorators11 = require("lit/decorators.js");
1249
2082
  var DawPauseButtonElement = class extends DawTransportButton {
1250
2083
  constructor() {
1251
2084
  super(...arguments);
@@ -1269,18 +2102,34 @@ var DawPauseButtonElement = class extends DawTransportButton {
1269
2102
  connectedCallback() {
1270
2103
  super.connectedCallback();
1271
2104
  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);
2105
+ if (!this.isConnected) return;
2106
+ this._ensureTargetListeners();
1280
2107
  });
1281
2108
  }
1282
2109
  disconnectedCallback() {
1283
2110
  super.disconnectedCallback();
2111
+ this._cleanupListeners();
2112
+ }
2113
+ updated() {
2114
+ this._ensureTargetListeners();
2115
+ }
2116
+ _ensureTargetListeners() {
2117
+ const target = this.target;
2118
+ if (target === this._targetRef) return;
2119
+ if (this._targetRef) {
2120
+ this._isRecording = false;
2121
+ this._isPaused = false;
2122
+ }
2123
+ this._cleanupListeners();
2124
+ if (!target) return;
2125
+ this._targetRef = target;
2126
+ target.addEventListener("daw-recording-start", this._onRecStart);
2127
+ target.addEventListener("daw-recording-complete", this._onRecEnd);
2128
+ target.addEventListener("daw-recording-error", this._onRecEnd);
2129
+ target.addEventListener("daw-recording-pause", this._onRecPause);
2130
+ target.addEventListener("daw-recording-resume", this._onRecResume);
2131
+ }
2132
+ _cleanupListeners() {
1284
2133
  if (this._targetRef) {
1285
2134
  this._targetRef.removeEventListener("daw-recording-start", this._onRecStart);
1286
2135
  this._targetRef.removeEventListener("daw-recording-complete", this._onRecEnd);
@@ -1291,7 +2140,7 @@ var DawPauseButtonElement = class extends DawTransportButton {
1291
2140
  }
1292
2141
  }
1293
2142
  render() {
1294
- return import_lit9.html`
2143
+ return import_lit12.html`
1295
2144
  <button part="button" ?data-paused=${this._isPaused} @click=${this._onClick}>
1296
2145
  <slot>Pause</slot>
1297
2146
  </button>
@@ -1314,7 +2163,7 @@ var DawPauseButtonElement = class extends DawTransportButton {
1314
2163
  };
1315
2164
  DawPauseButtonElement.styles = [
1316
2165
  DawTransportButton.styles,
1317
- import_lit9.css`
2166
+ import_lit12.css`
1318
2167
  button[data-paused] {
1319
2168
  background: rgba(255, 255, 255, 0.1);
1320
2169
  border-color: var(--daw-controls-text, #e0d4c8);
@@ -1322,21 +2171,21 @@ DawPauseButtonElement.styles = [
1322
2171
  `
1323
2172
  ];
1324
2173
  __decorateClass([
1325
- (0, import_decorators8.state)()
2174
+ (0, import_decorators11.state)()
1326
2175
  ], DawPauseButtonElement.prototype, "_isPaused", 2);
1327
2176
  __decorateClass([
1328
- (0, import_decorators8.state)()
2177
+ (0, import_decorators11.state)()
1329
2178
  ], DawPauseButtonElement.prototype, "_isRecording", 2);
1330
2179
  DawPauseButtonElement = __decorateClass([
1331
- (0, import_decorators8.customElement)("daw-pause-button")
2180
+ (0, import_decorators11.customElement)("daw-pause-button")
1332
2181
  ], DawPauseButtonElement);
1333
2182
 
1334
2183
  // src/elements/daw-stop-button.ts
1335
- var import_lit10 = require("lit");
1336
- var import_decorators9 = require("lit/decorators.js");
2184
+ var import_lit13 = require("lit");
2185
+ var import_decorators12 = require("lit/decorators.js");
1337
2186
  var DawStopButtonElement = class extends DawTransportButton {
1338
2187
  render() {
1339
- return import_lit10.html`
2188
+ return import_lit13.html`
1340
2189
  <button part="button" @click=${this._onClick}>
1341
2190
  <slot>Stop</slot>
1342
2191
  </button>
@@ -1370,12 +2219,12 @@ var DawStopButtonElement = class extends DawTransportButton {
1370
2219
  }
1371
2220
  };
1372
2221
  DawStopButtonElement = __decorateClass([
1373
- (0, import_decorators9.customElement)("daw-stop-button")
2222
+ (0, import_decorators12.customElement)("daw-stop-button")
1374
2223
  ], DawStopButtonElement);
1375
2224
 
1376
2225
  // src/elements/daw-editor.ts
1377
- var import_lit15 = require("lit");
1378
- var import_decorators13 = require("lit/decorators.js");
2226
+ var import_lit19 = require("lit");
2227
+ var import_decorators16 = require("lit/decorators.js");
1379
2228
 
1380
2229
  // src/types.ts
1381
2230
  function isDomClip(desc) {
@@ -1383,7 +2232,7 @@ function isDomClip(desc) {
1383
2232
  }
1384
2233
 
1385
2234
  // src/elements/daw-editor.ts
1386
- var import_core9 = require("@waveform-playlist/core");
2235
+ var import_core13 = require("@waveform-playlist/core");
1387
2236
 
1388
2237
  // src/workers/peaksWorker.ts
1389
2238
  var import_waveform_data = __toESM(require("waveform-data"));
@@ -1553,6 +2402,12 @@ function createPeaksWorker() {
1553
2402
  )
1554
2403
  );
1555
2404
  },
2405
+ // Reports NOT terminated: CSP blocking is permanent for the page, so
2406
+ // recreating on every call would just re-attempt (and re-warn about)
2407
+ // Worker construction each time.
2408
+ isTerminated() {
2409
+ return false;
2410
+ },
1556
2411
  terminate() {
1557
2412
  }
1558
2413
  };
@@ -1590,6 +2445,9 @@ function createPeaksWorker() {
1590
2445
  pending.clear();
1591
2446
  };
1592
2447
  return {
2448
+ isTerminated() {
2449
+ return terminated;
2450
+ },
1593
2451
  generate(params) {
1594
2452
  if (terminated) return Promise.reject(new Error("Worker terminated"));
1595
2453
  const messageId = String(++idCounter2);
@@ -1805,6 +2663,12 @@ var PeakPipeline = class {
1805
2663
  scale: cached.scale
1806
2664
  };
1807
2665
  }
2666
+ /** Scale of the cached WaveformData for this buffer — 0 when not cached.
2667
+ * Worker generation caches at baseScale; injected .dat data at its own
2668
+ * scale. This is the finest zoom the buffer's peaks can render at. */
2669
+ getCachedScale(audioBuffer) {
2670
+ return this._cache.get(audioBuffer)?.scale ?? 0;
2671
+ }
1808
2672
  /**
1809
2673
  * Return the coarsest (largest) scale among cached WaveformData entries
1810
2674
  * that correspond to the given clip buffers. Returns 0 if none are cached.
@@ -1826,7 +2690,7 @@ var PeakPipeline = class {
1826
2690
  if (cached) return cached;
1827
2691
  const inflight = this._inflight.get(audioBuffer);
1828
2692
  if (inflight) return inflight;
1829
- if (!this._worker) {
2693
+ if (!this._worker || this._worker.isTerminated()) {
1830
2694
  this._worker = createPeaksWorker();
1831
2695
  }
1832
2696
  const channels = [];
@@ -1855,8 +2719,8 @@ var PeakPipeline = class {
1855
2719
  };
1856
2720
 
1857
2721
  // src/elements/daw-ruler.ts
1858
- var import_lit11 = require("lit");
1859
- var import_decorators10 = require("lit/decorators.js");
2722
+ var import_lit14 = require("lit");
2723
+ var import_decorators13 = require("lit/decorators.js");
1860
2724
 
1861
2725
  // src/utils/time-format.ts
1862
2726
  function formatTime(milliseconds) {
@@ -1907,7 +2771,7 @@ function computeTemporalTicks(samplesPerPixel, sampleRate, duration, rulerHeight
1907
2771
  }
1908
2772
 
1909
2773
  // src/utils/musical-tick-cache.ts
1910
- var import_core = require("@waveform-playlist/core");
2774
+ var import_core3 = require("@waveform-playlist/core");
1911
2775
  var cachedParams = null;
1912
2776
  var cachedResult = null;
1913
2777
  function meterEntriesMatch(a, b) {
@@ -1925,7 +2789,7 @@ function getCachedMusicalTicks(params) {
1925
2789
  if (cachedParams && cachedResult && paramsMatch(cachedParams, params)) {
1926
2790
  return cachedResult;
1927
2791
  }
1928
- cachedResult = (0, import_core.computeMusicalTicks)(params);
2792
+ cachedResult = (0, import_core3.computeMusicalTicks)(params);
1929
2793
  cachedParams = {
1930
2794
  ...params,
1931
2795
  meterEntries: params.meterEntries.map((e) => ({ ...e }))
@@ -1935,7 +2799,7 @@ function getCachedMusicalTicks(params) {
1935
2799
 
1936
2800
  // src/elements/daw-ruler.ts
1937
2801
  var MAX_CANVAS_WIDTH3 = 1e3;
1938
- var DawRulerElement = class extends import_lit11.LitElement {
2802
+ var DawRulerElement = class extends import_lit14.LitElement {
1939
2803
  constructor() {
1940
2804
  super(...arguments);
1941
2805
  this.samplesPerPixel = 1024;
@@ -1979,17 +2843,17 @@ var DawRulerElement = class extends import_lit11.LitElement {
1979
2843
  }
1980
2844
  render() {
1981
2845
  const widthX = this.scaleMode === "beats" ? this.totalWidth : this._tickData?.widthX ?? 0;
1982
- if (widthX <= 0) return import_lit11.html``;
2846
+ if (widthX <= 0) return import_lit14.html``;
1983
2847
  const totalChunks = Math.ceil(widthX / MAX_CANVAS_WIDTH3);
1984
2848
  const indices = Array.from({ length: totalChunks }, (_, i) => i);
1985
2849
  const dpr = typeof devicePixelRatio !== "undefined" ? devicePixelRatio : 1;
1986
2850
  const beatsLabels = this.scaleMode === "beats" ? this._musicalTickData?.ticks.filter((t) => t.label) ?? [] : [];
1987
2851
  const temporalLabels = this.scaleMode !== "beats" ? this._tickData?.labels ?? [] : [];
1988
- return import_lit11.html`
2852
+ return import_lit14.html`
1989
2853
  <div class="container" style="width: ${widthX}px; height: ${this.rulerHeight}px;">
1990
2854
  ${indices.map((i) => {
1991
2855
  const width = Math.min(MAX_CANVAS_WIDTH3, widthX - i * MAX_CANVAS_WIDTH3);
1992
- return import_lit11.html`
2856
+ return import_lit14.html`
1993
2857
  <canvas
1994
2858
  data-index=${i}
1995
2859
  width=${width * dpr}
@@ -1999,13 +2863,13 @@ var DawRulerElement = class extends import_lit11.LitElement {
1999
2863
  `;
2000
2864
  })}
2001
2865
  ${this.scaleMode === "beats" ? beatsLabels.map(
2002
- (t) => import_lit11.html`<span
2866
+ (t) => import_lit14.html`<span
2003
2867
  class="label ${t.pixel > 0 ? "centered" : ""}"
2004
2868
  style="left: ${t.pixel > 0 ? t.pixel : t.pixel + 4}px;"
2005
2869
  >${t.label}</span
2006
2870
  >`
2007
2871
  ) : temporalLabels.map(
2008
- ({ pix, text }) => import_lit11.html`<span class="label" style="left: ${pix + 4}px;">${text}</span>`
2872
+ ({ pix, text }) => import_lit14.html`<span class="label" style="left: ${pix + 4}px;">${text}</span>`
2009
2873
  )}
2010
2874
  </div>
2011
2875
  `;
@@ -2056,7 +2920,7 @@ var DawRulerElement = class extends import_lit11.LitElement {
2056
2920
  }
2057
2921
  }
2058
2922
  };
2059
- DawRulerElement.styles = import_lit11.css`
2923
+ DawRulerElement.styles = import_lit14.css`
2060
2924
  :host {
2061
2925
  display: block;
2062
2926
  position: relative;
@@ -2082,40 +2946,40 @@ DawRulerElement.styles = import_lit11.css`
2082
2946
  }
2083
2947
  `;
2084
2948
  __decorateClass([
2085
- (0, import_decorators10.property)({ type: Number, attribute: false })
2949
+ (0, import_decorators13.property)({ type: Number, attribute: false })
2086
2950
  ], DawRulerElement.prototype, "samplesPerPixel", 2);
2087
2951
  __decorateClass([
2088
- (0, import_decorators10.property)({ type: Number, attribute: false })
2952
+ (0, import_decorators13.property)({ type: Number, attribute: false })
2089
2953
  ], DawRulerElement.prototype, "sampleRate", 2);
2090
2954
  __decorateClass([
2091
- (0, import_decorators10.property)({ type: Number, attribute: false })
2955
+ (0, import_decorators13.property)({ type: Number, attribute: false })
2092
2956
  ], DawRulerElement.prototype, "duration", 2);
2093
2957
  __decorateClass([
2094
- (0, import_decorators10.property)({ type: Number, attribute: false })
2958
+ (0, import_decorators13.property)({ type: Number, attribute: false })
2095
2959
  ], DawRulerElement.prototype, "rulerHeight", 2);
2096
2960
  __decorateClass([
2097
- (0, import_decorators10.property)({ type: String, attribute: false })
2961
+ (0, import_decorators13.property)({ type: String, attribute: false })
2098
2962
  ], DawRulerElement.prototype, "scaleMode", 2);
2099
2963
  __decorateClass([
2100
- (0, import_decorators10.property)({ type: Number, attribute: false })
2964
+ (0, import_decorators13.property)({ type: Number, attribute: false })
2101
2965
  ], DawRulerElement.prototype, "ticksPerPixel", 2);
2102
2966
  __decorateClass([
2103
- (0, import_decorators10.property)({ attribute: false })
2967
+ (0, import_decorators13.property)({ attribute: false })
2104
2968
  ], DawRulerElement.prototype, "meterEntries", 2);
2105
2969
  __decorateClass([
2106
- (0, import_decorators10.property)({ type: Number, attribute: false })
2970
+ (0, import_decorators13.property)({ type: Number, attribute: false })
2107
2971
  ], DawRulerElement.prototype, "ppqn", 2);
2108
2972
  __decorateClass([
2109
- (0, import_decorators10.property)({ type: Number, attribute: false })
2973
+ (0, import_decorators13.property)({ type: Number, attribute: false })
2110
2974
  ], DawRulerElement.prototype, "totalWidth", 2);
2111
2975
  DawRulerElement = __decorateClass([
2112
- (0, import_decorators10.customElement)("daw-ruler")
2976
+ (0, import_decorators13.customElement)("daw-ruler")
2113
2977
  ], DawRulerElement);
2114
2978
 
2115
2979
  // src/elements/daw-track-controls.ts
2116
- var import_lit12 = require("lit");
2117
- var import_decorators11 = require("lit/decorators.js");
2118
- var DawTrackControlsElement = class extends import_lit12.LitElement {
2980
+ var import_lit15 = require("lit");
2981
+ var import_decorators14 = require("lit/decorators.js");
2982
+ var DawTrackControlsElement = class extends import_lit15.LitElement {
2119
2983
  constructor() {
2120
2984
  super(...arguments);
2121
2985
  this.trackId = null;
@@ -2174,7 +3038,7 @@ var DawTrackControlsElement = class extends import_lit12.LitElement {
2174
3038
  const volPercent = Math.round(this.volume * 100);
2175
3039
  const panPercent = Math.round(Math.abs(this.pan) * 100);
2176
3040
  const panDisplay = this.pan === 0 ? "C" : (this.pan > 0 ? "R" : "L") + panPercent;
2177
- return import_lit12.html`
3041
+ return import_lit15.html`
2178
3042
  <div class="header">
2179
3043
  <span class="name" title=${this.trackName}>${this.trackName || "Untitled"}</span>
2180
3044
  <button class="remove-btn" @click=${this._onRemoveClick} title="Remove track">
@@ -2224,7 +3088,7 @@ var DawTrackControlsElement = class extends import_lit12.LitElement {
2224
3088
  `;
2225
3089
  }
2226
3090
  };
2227
- DawTrackControlsElement.styles = import_lit12.css`
3091
+ DawTrackControlsElement.styles = import_lit15.css`
2228
3092
  :host {
2229
3093
  display: flex;
2230
3094
  flex-direction: column;
@@ -2376,33 +3240,33 @@ DawTrackControlsElement.styles = import_lit12.css`
2376
3240
  }
2377
3241
  `;
2378
3242
  __decorateClass([
2379
- (0, import_decorators11.property)({ attribute: false })
3243
+ (0, import_decorators14.property)({ attribute: false })
2380
3244
  ], DawTrackControlsElement.prototype, "trackId", 2);
2381
3245
  __decorateClass([
2382
- (0, import_decorators11.property)({ attribute: false })
3246
+ (0, import_decorators14.property)({ attribute: false })
2383
3247
  ], DawTrackControlsElement.prototype, "trackName", 2);
2384
3248
  __decorateClass([
2385
- (0, import_decorators11.property)({ type: Number, attribute: false })
3249
+ (0, import_decorators14.property)({ type: Number, attribute: false })
2386
3250
  ], DawTrackControlsElement.prototype, "volume", 2);
2387
3251
  __decorateClass([
2388
- (0, import_decorators11.property)({ type: Number, attribute: false })
3252
+ (0, import_decorators14.property)({ type: Number, attribute: false })
2389
3253
  ], DawTrackControlsElement.prototype, "pan", 2);
2390
3254
  __decorateClass([
2391
- (0, import_decorators11.property)({ type: Boolean, attribute: false })
3255
+ (0, import_decorators14.property)({ type: Boolean, attribute: false })
2392
3256
  ], DawTrackControlsElement.prototype, "muted", 2);
2393
3257
  __decorateClass([
2394
- (0, import_decorators11.property)({ type: Boolean, attribute: false })
3258
+ (0, import_decorators14.property)({ type: Boolean, attribute: false })
2395
3259
  ], DawTrackControlsElement.prototype, "soloed", 2);
2396
3260
  DawTrackControlsElement = __decorateClass([
2397
- (0, import_decorators11.customElement)("daw-track-controls")
3261
+ (0, import_decorators14.customElement)("daw-track-controls")
2398
3262
  ], DawTrackControlsElement);
2399
3263
 
2400
3264
  // src/elements/daw-grid.ts
2401
- var import_lit13 = require("lit");
2402
- var import_decorators12 = require("lit/decorators.js");
2403
- var import_core2 = require("@waveform-playlist/core");
3265
+ var import_lit16 = require("lit");
3266
+ var import_decorators15 = require("lit/decorators.js");
3267
+ var import_core4 = require("@waveform-playlist/core");
2404
3268
  var MAX_CANVAS_WIDTH4 = 1e3;
2405
- var DawGridElement = class extends import_lit13.LitElement {
3269
+ var DawGridElement = class extends import_lit16.LitElement {
2406
3270
  constructor() {
2407
3271
  super(...arguments);
2408
3272
  this.ticksPerPixel = 24;
@@ -2430,7 +3294,7 @@ var DawGridElement = class extends import_lit13.LitElement {
2430
3294
  }
2431
3295
  }
2432
3296
  render() {
2433
- if (!this._tickData) return import_lit13.html``;
3297
+ if (!this._tickData) return import_lit16.html``;
2434
3298
  const totalWidth = this.length;
2435
3299
  const dpr = typeof devicePixelRatio !== "undefined" ? devicePixelRatio : 1;
2436
3300
  const indices = getVisibleChunkIndices(
@@ -2439,11 +3303,11 @@ var DawGridElement = class extends import_lit13.LitElement {
2439
3303
  this.visibleStart,
2440
3304
  this.visibleEnd
2441
3305
  );
2442
- return import_lit13.html`
3306
+ return import_lit16.html`
2443
3307
  <div class="container" style="width: ${totalWidth}px; height: ${this.height}px;">
2444
3308
  ${indices.map((i) => {
2445
3309
  const width = Math.min(MAX_CANVAS_WIDTH4, totalWidth - i * MAX_CANVAS_WIDTH4);
2446
- return import_lit13.html`
3310
+ return import_lit16.html`
2447
3311
  <canvas
2448
3312
  data-index=${i}
2449
3313
  width=${width * dpr}
@@ -2477,7 +3341,7 @@ var DawGridElement = class extends import_lit13.LitElement {
2477
3341
  ctx.resetTransform();
2478
3342
  ctx.clearRect(0, 0, canvas.width, canvas.height);
2479
3343
  ctx.scale(dpr, dpr);
2480
- if (pixelsPerQuarterNote * 4 >= import_core2.MIN_PIXELS_PER_UNIT) {
3344
+ if (pixelsPerQuarterNote * 4 >= import_core4.MIN_PIXELS_PER_UNIT) {
2481
3345
  ctx.fillStyle = barHighlight;
2482
3346
  const majorTicks = ticks.filter((t) => t.type === "major");
2483
3347
  for (let i = 0; i < majorTicks.length; i++) {
@@ -2504,7 +3368,7 @@ var DawGridElement = class extends import_lit13.LitElement {
2504
3368
  }
2505
3369
  }
2506
3370
  };
2507
- DawGridElement.styles = import_lit13.css`
3371
+ DawGridElement.styles = import_lit16.css`
2508
3372
  :host {
2509
3373
  display: block;
2510
3374
  position: absolute;
@@ -2522,33 +3386,33 @@ DawGridElement.styles = import_lit13.css`
2522
3386
  }
2523
3387
  `;
2524
3388
  __decorateClass([
2525
- (0, import_decorators12.property)({ type: Number, attribute: false })
3389
+ (0, import_decorators15.property)({ type: Number, attribute: false })
2526
3390
  ], DawGridElement.prototype, "ticksPerPixel", 2);
2527
3391
  __decorateClass([
2528
- (0, import_decorators12.property)({ attribute: false })
3392
+ (0, import_decorators15.property)({ attribute: false })
2529
3393
  ], DawGridElement.prototype, "meterEntries", 2);
2530
3394
  __decorateClass([
2531
- (0, import_decorators12.property)({ type: Number, attribute: false })
3395
+ (0, import_decorators15.property)({ type: Number, attribute: false })
2532
3396
  ], DawGridElement.prototype, "ppqn", 2);
2533
3397
  __decorateClass([
2534
- (0, import_decorators12.property)({ type: Number, attribute: false })
3398
+ (0, import_decorators15.property)({ type: Number, attribute: false })
2535
3399
  ], DawGridElement.prototype, "visibleStart", 2);
2536
3400
  __decorateClass([
2537
- (0, import_decorators12.property)({ type: Number, attribute: false })
3401
+ (0, import_decorators15.property)({ type: Number, attribute: false })
2538
3402
  ], DawGridElement.prototype, "visibleEnd", 2);
2539
3403
  __decorateClass([
2540
- (0, import_decorators12.property)({ type: Number, attribute: false })
3404
+ (0, import_decorators15.property)({ type: Number, attribute: false })
2541
3405
  ], DawGridElement.prototype, "length", 2);
2542
3406
  __decorateClass([
2543
- (0, import_decorators12.property)({ type: Number, attribute: false })
3407
+ (0, import_decorators15.property)({ type: Number, attribute: false })
2544
3408
  ], DawGridElement.prototype, "height", 2);
2545
3409
  DawGridElement = __decorateClass([
2546
- (0, import_decorators12.customElement)("daw-grid")
3410
+ (0, import_decorators15.customElement)("daw-grid")
2547
3411
  ], DawGridElement);
2548
3412
 
2549
3413
  // src/styles/theme.ts
2550
- var import_lit14 = require("lit");
2551
- var hostStyles = import_lit14.css`
3414
+ var import_lit17 = require("lit");
3415
+ var hostStyles = import_lit17.css`
2552
3416
  :host {
2553
3417
  --daw-wave-color: #c49a6c;
2554
3418
  --daw-progress-color: #63c75f;
@@ -2564,7 +3428,7 @@ var hostStyles = import_lit14.css`
2564
3428
  --daw-clip-header-text: #e0d4c8;
2565
3429
  }
2566
3430
  `;
2567
- var clipStyles = import_lit14.css`
3431
+ var clipStyles = import_lit17.css`
2568
3432
  .clip-container {
2569
3433
  position: absolute;
2570
3434
  overflow: hidden;
@@ -2804,7 +3668,7 @@ var AudioResumeController = class {
2804
3668
  };
2805
3669
 
2806
3670
  // src/controllers/recording-controller.ts
2807
- var import_core3 = require("@waveform-playlist/core");
3671
+ var import_core5 = require("@waveform-playlist/core");
2808
3672
  var RecordingController = class {
2809
3673
  constructor(host) {
2810
3674
  this._sessions = /* @__PURE__ */ new Map();
@@ -2812,7 +3676,11 @@ var RecordingController = class {
2812
3676
  * The session is only set after several awaits — without this, two rapid
2813
3677
  * start calls both pass the _sessions guard and build two capture
2814
3678
  * pipelines feeding one session (garbled audio + a leaked worklet). */
2815
- this._starting = /* @__PURE__ */ new Set();
3679
+ this._starting = /* @__PURE__ */ new Map();
3680
+ /** True between hostDisconnected and hostConnected. An in-flight
3681
+ * startRecording consults this after its awaits so a teardown mid-setup
3682
+ * doesn't leak a live capture session on a detached editor. */
3683
+ this._hostDisconnected = false;
2816
3684
  this._workletLoadedCtx = null;
2817
3685
  /** Tracks worklet pause state explicitly so external consumers (editor,
2818
3686
  * pause button, spacebar) can share one source of truth. */
@@ -2821,15 +3689,17 @@ var RecordingController = class {
2821
3689
  host.addController(this);
2822
3690
  }
2823
3691
  hostConnected() {
3692
+ this._hostDisconnected = false;
2824
3693
  }
2825
3694
  hostDisconnected() {
3695
+ this._hostDisconnected = true;
2826
3696
  for (const trackId of [...this._sessions.keys()]) {
2827
3697
  this._cleanupSession(trackId, true);
2828
3698
  }
2829
3699
  this._workletLoadedCtx = null;
2830
3700
  }
2831
3701
  get isRecording() {
2832
- return this._sessions.size > 0;
3702
+ return this._sessions.size > 0 || this._starting.size > 0;
2833
3703
  }
2834
3704
  get isPaused() {
2835
3705
  return this._isPaused && this._sessions.size > 0;
@@ -2847,7 +3717,14 @@ var RecordingController = class {
2847
3717
  console.warn('[dawcore] RecordingController: Already recording on track "' + trackId + '"');
2848
3718
  return;
2849
3719
  }
2850
- this._starting.add(trackId);
3720
+ let resolveStartSettled;
3721
+ const startEntry = {
3722
+ stopRequested: false,
3723
+ done: new Promise((resolve) => {
3724
+ resolveStartSettled = resolve;
3725
+ })
3726
+ };
3727
+ this._starting.set(trackId, startEntry);
2851
3728
  const bits = options.bits ?? 16;
2852
3729
  try {
2853
3730
  const rawCtx = this._host.audioContext;
@@ -2868,6 +3745,15 @@ var RecordingController = class {
2868
3745
  await addRecordingWorkletModule(addModule);
2869
3746
  this._workletLoadedCtx = rawCtx;
2870
3747
  }
3748
+ if (startEntry.stopRequested || this._hostDisconnected) {
3749
+ this._dispatchRecordingError(
3750
+ trackId,
3751
+ new Error(
3752
+ this._hostDisconnected ? "Recording start cancelled: editor was disconnected during setup" : "Recording start cancelled: stop requested before setup completed"
3753
+ )
3754
+ );
3755
+ return;
3756
+ }
2871
3757
  const detectedChannelCount = stream.getAudioTracks()[0]?.getSettings()?.channelCount;
2872
3758
  if (detectedChannelCount === void 0 && options.channelCount !== void 0) {
2873
3759
  console.warn(
@@ -2876,7 +3762,7 @@ var RecordingController = class {
2876
3762
  }
2877
3763
  const channelCount = detectedChannelCount ?? options.channelCount ?? 1;
2878
3764
  const startSample = options.startSample ?? Math.floor(this._host.currentTime * this._host.effectiveSampleRate);
2879
- const latencySamples = (0, import_core3.resolveRecordingOffsetSamples)({
3765
+ const latencySamples = (0, import_core5.resolveRecordingOffsetSamples)({
2880
3766
  overrideSeconds: options.latencyOffset,
2881
3767
  outputLatency: rawCtx.outputLatency ?? 0,
2882
3768
  lookAhead: 0,
@@ -2950,15 +3836,10 @@ var RecordingController = class {
2950
3836
  } catch (err) {
2951
3837
  this._cleanupSession(trackId);
2952
3838
  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
- );
3839
+ this._dispatchRecordingError(trackId, err);
2960
3840
  } finally {
2961
3841
  this._starting.delete(trackId);
3842
+ resolveStartSettled();
2962
3843
  }
2963
3844
  }
2964
3845
  pauseRecording(trackId) {
@@ -2992,10 +3873,17 @@ var RecordingController = class {
2992
3873
  );
2993
3874
  }
2994
3875
  async stopRecording(trackId) {
2995
- const id = trackId ?? [...this._sessions.keys()][0];
3876
+ const id = trackId ?? [...this._sessions.keys()][0] ?? [...this._starting.keys()][0];
2996
3877
  if (!id) return;
2997
3878
  const session = this._sessions.get(id);
2998
- if (!session) return;
3879
+ if (!session) {
3880
+ const starting = this._starting.get(id);
3881
+ if (starting) {
3882
+ starting.stopRequested = true;
3883
+ return starting.done;
3884
+ }
3885
+ return;
3886
+ }
2999
3887
  if (session.stopping) {
3000
3888
  return session.stopPromise ?? void 0;
3001
3889
  }
@@ -3005,6 +3893,19 @@ var RecordingController = class {
3005
3893
  return stopPromise;
3006
3894
  }
3007
3895
  async _finishStopRecording(id, session) {
3896
+ try {
3897
+ await this._finalizeRecording(id, session);
3898
+ } catch (err) {
3899
+ const sessionWasActive = this._sessions.has(id);
3900
+ console.warn("[dawcore] RecordingController: Failed to finalize recording: " + String(err));
3901
+ this._cleanupSession(id);
3902
+ this._host.requestUpdate();
3903
+ if (sessionWasActive) {
3904
+ this._dispatchRecordingError(id, err);
3905
+ }
3906
+ }
3907
+ }
3908
+ async _finalizeRecording(id, session) {
3008
3909
  const wasPaused = this._isPaused;
3009
3910
  this._isPaused = false;
3010
3911
  if (session.wasOverdub && typeof this._host.stop === "function") {
@@ -3031,21 +3932,12 @@ var RecordingController = class {
3031
3932
  session.workletNode.disconnect();
3032
3933
  this._removeTrackEndedListener(session);
3033
3934
  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
- );
3935
+ this._abandonFinalize(id, session, "No audio data captured");
3044
3936
  return;
3045
3937
  }
3046
3938
  const stopCtx = this._host.audioContext;
3047
- const channelData = session.chunks.map((chunkArr) => (0, import_core3.concatenateAudioData)(chunkArr));
3048
- const audioBuffer = (0, import_core3.createAudioBuffer)(
3939
+ const channelData = session.chunks.map((chunkArr) => (0, import_core5.concatenateAudioData)(chunkArr));
3940
+ const audioBuffer = (0, import_core5.createAudioBuffer)(
3049
3941
  stopCtx,
3050
3942
  channelData,
3051
3943
  session.captureSampleRate,
@@ -3054,16 +3946,11 @@ var RecordingController = class {
3054
3946
  const latencyOffsetSamples = session.latencySamples;
3055
3947
  const effectiveDuration = Math.max(0, audioBuffer.length - latencyOffsetSamples);
3056
3948
  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
- })
3949
+ this._abandonFinalize(
3950
+ id,
3951
+ session,
3952
+ "Recording too short for latency compensation",
3953
+ "Recording too short to save"
3067
3954
  );
3068
3955
  return;
3069
3956
  }
@@ -3144,7 +4031,7 @@ var RecordingController = class {
3144
4031
  for (let ch = 0; ch < session.channelCount; ch++) {
3145
4032
  if (!channels[ch]) continue;
3146
4033
  const oldPeakCount = Math.floor(session.peaks[ch].length / 2);
3147
- session.peaks[ch] = (0, import_core3.appendPeaks)(
4034
+ session.peaks[ch] = (0, import_core5.appendPeaks)(
3148
4035
  session.peaks[ch],
3149
4036
  channels[ch],
3150
4037
  // Render-space scale — in beats mode this differs from
@@ -3198,6 +4085,26 @@ var RecordingController = class {
3198
4085
  session._audioTrack.removeEventListener("ended", session._onTrackEnded);
3199
4086
  }
3200
4087
  }
4088
+ _dispatchRecordingError(trackId, error) {
4089
+ this._host.dispatchEvent(
4090
+ new CustomEvent("daw-recording-error", {
4091
+ bubbles: true,
4092
+ composed: true,
4093
+ detail: { trackId, error }
4094
+ })
4095
+ );
4096
+ }
4097
+ /** Shared teardown for finalize paths that end without a take (no data
4098
+ * captured / too short after latency compensation): restore the armed-track
4099
+ * mute, drop the session, and notify via daw-recording-error so record
4100
+ * buttons reset their state. */
4101
+ _abandonFinalize(id, session, warnMessage, errorMessage = warnMessage) {
4102
+ console.warn("[dawcore] RecordingController: " + warnMessage);
4103
+ this._restoreArmedTrackMute(session);
4104
+ this._sessions.delete(id);
4105
+ this._host.requestUpdate();
4106
+ this._dispatchRecordingError(id, new Error(errorMessage));
4107
+ }
3201
4108
  /** Restore the armed track's pre-session mute state (idempotent — safe to
3202
4109
  * call from both the finalize path and _cleanupSession). */
3203
4110
  _restoreArmedTrackMute(session) {
@@ -3227,23 +4134,199 @@ var RecordingController = class {
3227
4134
  this._isPaused = false;
3228
4135
  }
3229
4136
  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
- })
4137
+ this._dispatchRecordingError(
4138
+ trackId,
4139
+ new Error("Recording cancelled: editor was disconnected mid-recording")
3239
4140
  );
3240
4141
  }
3241
4142
  }
3242
4143
  };
3243
4144
 
4145
+ // src/controllers/annotation-controller.ts
4146
+ var import_lit18 = require("lit");
4147
+ var ANNOTATION_LANE_HEIGHT = 32;
4148
+ var AnnotationController = class {
4149
+ constructor(host) {
4150
+ this._tracks = [];
4151
+ this._removalObserver = null;
4152
+ /** Playback-following highlight per track, separate from each track's
4153
+ * `activeAnnotationId` (selection) so playback never disturbs selection.
4154
+ * Driven by daw-timeupdate, cleared on daw-stop, retained on pause.
4155
+ * Replaced immutably (a fresh Map) on every change. */
4156
+ this._playingIds = /* @__PURE__ */ new Map();
4157
+ this._onDataChange = () => {
4158
+ this.deriveSecondsCaches();
4159
+ this._host.requestUpdate();
4160
+ };
4161
+ /**
4162
+ * Update only on annotation-boundary crossings, not per animation frame.
4163
+ */
4164
+ this._onTimeUpdate = (e) => {
4165
+ const time = e.detail.time;
4166
+ let changed = false;
4167
+ const next = new Map(this._playingIds);
4168
+ for (const track of this._tracks) {
4169
+ const playingId = computePlayingAnnotationId(track.annotations, time);
4170
+ if (playingId !== (this._playingIds.get(track) ?? null)) {
4171
+ next.set(track, playingId);
4172
+ changed = true;
4173
+ }
4174
+ }
4175
+ if (!changed) return;
4176
+ this._playingIds = next;
4177
+ this._host.requestUpdate();
4178
+ };
4179
+ this._onStop = () => {
4180
+ if (this._playingIds.size === 0) return;
4181
+ this._playingIds = /* @__PURE__ */ new Map();
4182
+ this._host.requestUpdate();
4183
+ };
4184
+ this._host = host;
4185
+ host.addController(this);
4186
+ }
4187
+ get tracks() {
4188
+ return this._tracks;
4189
+ }
4190
+ /** Current playback-following highlight id for a track, or `null` when the
4191
+ * playhead isn't inside any of the track's annotations. */
4192
+ getPlayingAnnotationId(track) {
4193
+ return this._playingIds.get(track) ?? null;
4194
+ }
4195
+ get totalLaneHeight() {
4196
+ return this._tracks.length * ANNOTATION_LANE_HEIGHT;
4197
+ }
4198
+ /** Max annotation end (seconds) across registered tracks — 0 when none.
4199
+ * Lets the editor extend the timeline so annotations past the audio stay
4200
+ * reachable/scrollable. */
4201
+ get maxAnnotationEndSeconds() {
4202
+ return this._tracks.reduce(
4203
+ (max, track) => track.annotations.reduce((m, a) => Math.max(m, a.end), max),
4204
+ 0
4205
+ );
4206
+ }
4207
+ hostConnected() {
4208
+ this._host.addEventListener("daw-annotation-update", this._onDataChange);
4209
+ this._host.addEventListener("daw-annotation-select", this._onDataChange);
4210
+ this._host.addEventListener("daw-annotation-connected", this._onDataChange);
4211
+ this._host.addEventListener("daw-timeupdate", this._onTimeUpdate);
4212
+ this._host.addEventListener("daw-stop", this._onStop);
4213
+ this._removalObserver = new MutationObserver((mutations) => {
4214
+ let changed = false;
4215
+ for (const m of mutations) {
4216
+ for (const node of Array.from(m.removedNodes)) {
4217
+ if (!(node instanceof HTMLElement)) continue;
4218
+ if (node.tagName === "DAW-ANNOTATION-TRACK") {
4219
+ this._tracks = this._tracks.filter((t) => t !== node);
4220
+ changed = true;
4221
+ } else if (node.tagName === "DAW-ANNOTATION") {
4222
+ changed = true;
4223
+ }
4224
+ const nestedTracks = node.querySelectorAll?.("daw-annotation-track");
4225
+ if (nestedTracks) {
4226
+ for (const nested of nestedTracks) {
4227
+ this._tracks = this._tracks.filter((t) => t !== nested);
4228
+ changed = true;
4229
+ }
4230
+ }
4231
+ const nestedAnnotations = node.querySelectorAll?.("daw-annotation");
4232
+ if (nestedAnnotations && nestedAnnotations.length > 0) {
4233
+ changed = true;
4234
+ }
4235
+ }
4236
+ }
4237
+ if (changed) this._host.requestUpdate();
4238
+ });
4239
+ this._removalObserver.observe(this._host, { childList: true, subtree: true });
4240
+ }
4241
+ hostDisconnected() {
4242
+ this._host.removeEventListener("daw-annotation-update", this._onDataChange);
4243
+ this._host.removeEventListener("daw-annotation-select", this._onDataChange);
4244
+ this._host.removeEventListener("daw-annotation-connected", this._onDataChange);
4245
+ this._host.removeEventListener("daw-timeupdate", this._onTimeUpdate);
4246
+ this._host.removeEventListener("daw-stop", this._onStop);
4247
+ this._removalObserver?.disconnect();
4248
+ this._removalObserver = null;
4249
+ this._tracks = [];
4250
+ this._playingIds = /* @__PURE__ */ new Map();
4251
+ }
4252
+ handleTrackConnected(el) {
4253
+ if (this._tracks.includes(el)) return;
4254
+ this._tracks = [...this._tracks, el];
4255
+ this._host.requestUpdate();
4256
+ this.deriveSecondsCaches();
4257
+ }
4258
+ /**
4259
+ * Keep the seconds attributes (derived cache) of tick-based annotations in
4260
+ * sync with the host's tempo. Write-only-on-change: a write fires
4261
+ * daw-annotation-update → _onDataChange → this sweep again → values equal →
4262
+ * no write → the loop settles (idempotent).
4263
+ */
4264
+ deriveSecondsCaches() {
4265
+ for (const track of this._tracks) {
4266
+ for (const el of track.annotationElements) {
4267
+ if (!el.isTickBased) continue;
4268
+ const startSeconds = this._host._ticksToSeconds(el.startTick);
4269
+ const endSeconds = this._host._ticksToSeconds(el.endTick);
4270
+ if (el.start !== startSeconds) el.start = startSeconds;
4271
+ if (el.end !== endSeconds) el.end = endSeconds;
4272
+ }
4273
+ }
4274
+ }
4275
+ /** Pixel geometry for one annotation box. Tick-based annotations in beats
4276
+ * mode use CLIP-IDENTICAL tick math (round(tick / ticksPerPixel)) so they
4277
+ * align pixel-exactly with <daw-grid>; everything else uses the floor-based
4278
+ * seconds math (temporal mode reads the always-fresh seconds cache). */
4279
+ boxGeometry(a, spp, sampleRate, ticksPerPixel = null) {
4280
+ if (ticksPerPixel !== null && ticksPerPixel > 0 && a.startTick !== void 0 && a.endTick !== void 0) {
4281
+ const left2 = Math.round(a.startTick / ticksPerPixel);
4282
+ const width2 = Math.round(a.endTick / ticksPerPixel) - left2;
4283
+ return { left: left2, width: width2 };
4284
+ }
4285
+ const left = Math.floor(a.start * sampleRate / spp);
4286
+ const width = Math.floor(a.end * sampleRate / spp) - left;
4287
+ return { left, width };
4288
+ }
4289
+ /**
4290
+ * Lane templates for the editor's .timeline. onPointerDown is supplied by
4291
+ * the editor and dispatches into the drag interaction (Task 9).
4292
+ */
4293
+ renderLanes(spp, sampleRate, onPointerDown = () => {
4294
+ }, ticksPerPixel = null) {
4295
+ return this._tracks.map((track) => {
4296
+ const activeId = track.activeAnnotationId;
4297
+ const playingId = this._playingIds.get(track) ?? null;
4298
+ const elements = track.annotationElements;
4299
+ return import_lit18.html`
4300
+ <div
4301
+ class="annotation-lane"
4302
+ style="height: ${ANNOTATION_LANE_HEIGHT}px;"
4303
+ @pointerdown=${(e) => onPointerDown(e, track)}
4304
+ >
4305
+ ${elements.map((el, i) => {
4306
+ const a = el.toAnnotationData();
4307
+ const geo = this.boxGeometry(a, spp, sampleRate, ticksPerPixel);
4308
+ const label = track.boxLabel === "none" ? "" : track.boxLabel === "id" ? el.id || String(i + 1) : a.lines.join(" ");
4309
+ return import_lit18.html`
4310
+ <div
4311
+ class="annotation-box ${a.id === activeId ? "active" : ""} ${a.id === playingId ? "playing" : ""}"
4312
+ data-annotation-id=${a.id}
4313
+ style="left: ${geo.left}px; width: ${geo.width}px;"
4314
+ >
4315
+ ${track.editable ? import_lit18.html`<div class="annotation-boundary" data-edge="start"></div>` : ""}
4316
+ <span class="annotation-box-text">${label}</span>
4317
+ ${track.editable ? import_lit18.html`<div class="annotation-boundary" data-edge="end"></div>` : ""}
4318
+ </div>
4319
+ `;
4320
+ })}
4321
+ </div>
4322
+ `;
4323
+ });
4324
+ }
4325
+ };
4326
+
3244
4327
  // src/controllers/spectrogram-controller.ts
3245
4328
  var import_spectrogram = require("@dawcore/spectrogram");
3246
- var import_core4 = require("@waveform-playlist/core");
4329
+ var import_core6 = require("@waveform-playlist/core");
3247
4330
  var SpectrogramController = class {
3248
4331
  constructor(host, workerFactory) {
3249
4332
  this.orchestrator = null;
@@ -3296,8 +4379,8 @@ var SpectrogramController = class {
3296
4379
  unregisterCanvas(canvasId) {
3297
4380
  this.orchestrator?.unregisterCanvas(canvasId);
3298
4381
  }
3299
- setViewport(state8) {
3300
- this.orchestrator?.setViewport(state8);
4382
+ setViewport(state9) {
4383
+ this.orchestrator?.setViewport(state9);
3301
4384
  }
3302
4385
  dispose() {
3303
4386
  if (this.orchestrator) {
@@ -3352,18 +4435,18 @@ var SpectrogramController = class {
3352
4435
  track = c;
3353
4436
  break;
3354
4437
  }
3355
- return { ...import_core4.SPECTROGRAM_DEFAULTS, ...this.editorConfig ?? {}, ...track ?? {} };
4438
+ return { ...import_core6.SPECTROGRAM_DEFAULTS, ...this.editorConfig ?? {}, ...track ?? {} };
3356
4439
  }
3357
4440
  mergedColorMap() {
3358
4441
  for (const c of this.trackColorMaps.values()) {
3359
- return c ?? import_core4.DEFAULT_SPECTROGRAM_COLOR_MAP;
4442
+ return c ?? import_core6.DEFAULT_SPECTROGRAM_COLOR_MAP;
3360
4443
  }
3361
- return this.editorColorMap ?? import_core4.DEFAULT_SPECTROGRAM_COLOR_MAP;
4444
+ return this.editorColorMap ?? import_core6.DEFAULT_SPECTROGRAM_COLOR_MAP;
3362
4445
  }
3363
4446
  };
3364
4447
 
3365
4448
  // src/interactions/pointer-handler.ts
3366
- var import_core5 = require("@waveform-playlist/core");
4449
+ var import_core7 = require("@waveform-playlist/core");
3367
4450
 
3368
4451
  // src/interactions/constants.ts
3369
4452
  var DRAG_THRESHOLD = 3;
@@ -3377,6 +4460,14 @@ var PointerHandler = class {
3377
4460
  this._timeline = null;
3378
4461
  // Cached from onPointerDown to avoid forced layout reflows at 60fps during drag
3379
4462
  this._timelineRect = null;
4463
+ /** Pointer that started the current interaction — a pointercancel from any
4464
+ * OTHER pointer (palm rejection on touch) must not kill the active drag. */
4465
+ this._activePointerId = null;
4466
+ // Selection values at pointerdown — restored on cancel so an interrupted
4467
+ // drag doesn't destroy a previously committed selection (which the engine
4468
+ // still holds; zeroing only the host would desync the two).
4469
+ this._preDragSelectionStart = 0;
4470
+ this._preDragSelectionEnd = 0;
3380
4471
  this.onPointerDown = (e) => {
3381
4472
  const clipHandler = this._host._clipHandler;
3382
4473
  if (clipHandler) {
@@ -3391,12 +4482,12 @@ var PointerHandler = class {
3391
4482
  console.warn("[dawcore] setPointerCapture failed: " + String(err));
3392
4483
  }
3393
4484
  const onMove = (me) => clipHandler.onPointerMove(me);
3394
- const onUp = (ue) => {
3395
- clipHandler.onPointerUp(ue);
4485
+ const detach = (pe) => {
3396
4486
  this._timeline?.removeEventListener("pointermove", onMove);
3397
4487
  this._timeline?.removeEventListener("pointerup", onUp);
4488
+ this._timeline?.removeEventListener("pointercancel", onCancel);
3398
4489
  try {
3399
- this._timeline?.releasePointerCapture(ue.pointerId);
4490
+ this._timeline?.releasePointerCapture(pe.pointerId);
3400
4491
  } catch (err) {
3401
4492
  console.warn(
3402
4493
  "[dawcore] releasePointerCapture failed (may already be released): " + String(err)
@@ -3404,8 +4495,19 @@ var PointerHandler = class {
3404
4495
  }
3405
4496
  this._timeline = null;
3406
4497
  };
4498
+ const onUp = (ue) => {
4499
+ clipHandler.onPointerUp(ue);
4500
+ detach(ue);
4501
+ };
4502
+ const downPointerId = e.pointerId;
4503
+ const onCancel = (ce) => {
4504
+ if (ce.pointerId !== downPointerId) return;
4505
+ clipHandler.onPointerCancel(ce);
4506
+ detach(ce);
4507
+ };
3407
4508
  this._timeline.addEventListener("pointermove", onMove);
3408
4509
  this._timeline.addEventListener("pointerup", onUp);
4510
+ this._timeline.addEventListener("pointercancel", onCancel);
3409
4511
  }
3410
4512
  return;
3411
4513
  }
@@ -3420,6 +4522,9 @@ var PointerHandler = class {
3420
4522
  this._timelineRect = this._timeline.getBoundingClientRect();
3421
4523
  this._dragStartPx = this._pxFromPointer(e);
3422
4524
  this._isDragging = false;
4525
+ this._activePointerId = e.pointerId;
4526
+ this._preDragSelectionStart = this._host._selectionStartTime;
4527
+ this._preDragSelectionEnd = this._host._selectionEndTime;
3423
4528
  try {
3424
4529
  this._timeline.setPointerCapture(e.pointerId);
3425
4530
  } catch (err) {
@@ -3427,6 +4532,7 @@ var PointerHandler = class {
3427
4532
  }
3428
4533
  this._timeline.addEventListener("pointermove", this._onPointerMove);
3429
4534
  this._timeline.addEventListener("pointerup", this._onPointerUp);
4535
+ this._timeline.addEventListener("pointercancel", this._onPointerCancel);
3430
4536
  };
3431
4537
  this._onPointerMove = (e) => {
3432
4538
  if (!this._timeline) return;
@@ -3450,15 +4556,7 @@ var PointerHandler = class {
3450
4556
  };
3451
4557
  this._onPointerUp = (e) => {
3452
4558
  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);
4559
+ this._detachTimeline(e);
3462
4560
  try {
3463
4561
  if (this._isDragging) {
3464
4562
  this._finalizeSelection();
@@ -3468,10 +4566,29 @@ var PointerHandler = class {
3468
4566
  } catch (err) {
3469
4567
  console.warn("[dawcore] Pointer interaction failed: " + String(err));
3470
4568
  } finally {
3471
- this._isDragging = false;
3472
- this._timeline = null;
3473
- this._timelineRect = null;
4569
+ this._resetInteractionState();
4570
+ }
4571
+ };
4572
+ /** pointercancel fires INSTEAD of pointerup on touch interruption / pen
4573
+ * leaving range / OS gestures — discard the interaction (no seek, no
4574
+ * selection finalize) and detach the drag listeners, or the still-attached
4575
+ * move handler keeps mutating the selection on hover with a stale rect. */
4576
+ this._onPointerCancel = (e) => {
4577
+ if (!this._timeline) return;
4578
+ if (e.pointerId !== this._activePointerId) return;
4579
+ this._detachTimeline(e);
4580
+ if (this._isDragging) {
4581
+ const h = this._host;
4582
+ h._selectionStartTime = this._preDragSelectionStart;
4583
+ h._selectionEndTime = this._preDragSelectionEnd;
4584
+ const sel = h.shadowRoot?.querySelector("daw-selection");
4585
+ if (sel) {
4586
+ sel.startPx = this._timeToPx(this._preDragSelectionStart);
4587
+ sel.endPx = this._timeToPx(this._preDragSelectionEnd);
4588
+ }
4589
+ h.requestUpdate();
3474
4590
  }
4591
+ this._resetInteractionState();
3475
4592
  };
3476
4593
  this._host = host;
3477
4594
  }
@@ -3486,10 +4603,10 @@ var PointerHandler = class {
3486
4603
  const h = this._host;
3487
4604
  if (h.scaleMode === "beats") {
3488
4605
  let tick = px * h.ticksPerPixel;
3489
- tick = (0, import_core5.snapTickToGrid)(tick, h.snapTo, h._meterEntries, h.ppqn);
4606
+ tick = (0, import_core7.snapTickToGrid)(tick, h.snapTo, h._meterEntries, h.ppqn);
3490
4607
  return h._ticksToSeconds(tick);
3491
4608
  }
3492
- return (0, import_core5.pixelsToSeconds)(px, h.samplesPerPixel, h.effectiveSampleRate);
4609
+ return (0, import_core7.pixelsToSeconds)(px, h.samplesPerPixel, h.effectiveSampleRate);
3493
4610
  }
3494
4611
  _timeToPx(time) {
3495
4612
  const h = this._host;
@@ -3499,6 +4616,28 @@ var PointerHandler = class {
3499
4616
  }
3500
4617
  return time * h.effectiveSampleRate / h.samplesPerPixel;
3501
4618
  }
4619
+ /** Detach the drag listeners and release capture — shared by the up and
4620
+ * cancel terminals so a new listener added to onPointerDown can't be
4621
+ * missed on one of them. */
4622
+ _detachTimeline(e) {
4623
+ if (!this._timeline) return;
4624
+ try {
4625
+ this._timeline.releasePointerCapture(e.pointerId);
4626
+ } catch (err) {
4627
+ console.warn(
4628
+ "[dawcore] releasePointerCapture failed (may already be released): " + String(err)
4629
+ );
4630
+ }
4631
+ this._timeline.removeEventListener("pointermove", this._onPointerMove);
4632
+ this._timeline.removeEventListener("pointerup", this._onPointerUp);
4633
+ this._timeline.removeEventListener("pointercancel", this._onPointerCancel);
4634
+ }
4635
+ _resetInteractionState() {
4636
+ this._isDragging = false;
4637
+ this._timeline = null;
4638
+ this._timelineRect = null;
4639
+ this._activePointerId = null;
4640
+ }
3502
4641
  _finalizeSelection() {
3503
4642
  const h = this._host;
3504
4643
  if (h._engine) {
@@ -3586,7 +4725,7 @@ var PointerHandler = class {
3586
4725
  };
3587
4726
 
3588
4727
  // src/interactions/clip-pointer-handler.ts
3589
- var import_core6 = require("@waveform-playlist/core");
4728
+ var import_core8 = require("@waveform-playlist/core");
3590
4729
  var ClipPointerHandler = class {
3591
4730
  constructor(host) {
3592
4731
  this._mode = null;
@@ -3620,7 +4759,7 @@ var ClipPointerHandler = class {
3620
4759
  const anchorTick = h._secondsToTicks(anchorSeconds);
3621
4760
  const deltaTicks = totalDeltaPx * h.ticksPerPixel;
3622
4761
  const targetTick = anchorTick + deltaTicks;
3623
- const snappedTick = h.snapTo !== "off" ? (0, import_core6.snapTickToGrid)(targetTick, h.snapTo, h._meterEntries, h.ppqn) : targetTick;
4762
+ const snappedTick = h.snapTo !== "off" ? (0, import_core8.snapTickToGrid)(targetTick, h.snapTo, h._meterEntries, h.ppqn) : targetTick;
3624
4763
  const snappedSeconds = h._ticksToSeconds(snappedTick);
3625
4764
  const snappedSample = Math.round(snappedSeconds * h.effectiveSampleRate);
3626
4765
  return snappedSample - anchorSample;
@@ -3834,6 +4973,23 @@ var ClipPointerHandler = class {
3834
4973
  this._reset();
3835
4974
  }
3836
4975
  }
4976
+ /** Processes pointercancel — reverts the in-progress drag.
4977
+ *
4978
+ * pointercancel fires INSTEAD of pointerup on touch interruption, pen
4979
+ * leaving hover range, or OS gestures. Without this handler the drag stays
4980
+ * armed (hover keeps moving the clip), the engine transaction stays open
4981
+ * (every later edit becomes un-undoable until some drag commits), and the
4982
+ * per-frame skipAdapter moveClip mutations are never synced or rolled back
4983
+ * (waveform and audio permanently disagree). */
4984
+ onPointerCancel(_e) {
4985
+ if (this._mode === null) return;
4986
+ try {
4987
+ this._restoreTrimVisual();
4988
+ } finally {
4989
+ this._host.engine?.abortTransaction();
4990
+ this._reset();
4991
+ }
4992
+ }
3837
4993
  /** Re-extract peaks from cache and set on waveform elements during trim drag.
3838
4994
  * Returns true if peaks were successfully updated. */
3839
4995
  _updateWaveformPeaks(offsetSamples, durationSamples) {
@@ -3851,7 +5007,11 @@ var ClipPointerHandler = class {
3851
5007
  }
3852
5008
  return true;
3853
5009
  }
3854
- /** Restore clip container CSS to original values after trim visual preview. */
5010
+ /** Restore clip container CSS AND waveform peaks to original values after
5011
+ * a trim visual preview. Peaks matter: the drag wrote re-extracted peak
5012
+ * arrays imperatively onto the <daw-waveform> elements (bypassing Lit), and
5013
+ * a cancelled/zero-delta trim makes no engine mutation — so no statechange
5014
+ * re-render will ever repair them. */
3855
5015
  _restoreTrimVisual() {
3856
5016
  if (this._clipContainer) {
3857
5017
  this._clipContainer.style.left = this._originalLeft + "px";
@@ -3860,6 +5020,7 @@ var ClipPointerHandler = class {
3860
5020
  for (const wf of waveforms) {
3861
5021
  wf.style.left = "0px";
3862
5022
  }
5023
+ this._updateWaveformPeaks(this._originalOffsetSamples, this._originalDurationSamples);
3863
5024
  }
3864
5025
  }
3865
5026
  _reset() {
@@ -3867,18 +5028,157 @@ var ClipPointerHandler = class {
3867
5028
  this._boundaryEl.classList.remove("dragging");
3868
5029
  this._boundaryEl = null;
3869
5030
  }
3870
- this._mode = null;
3871
- this._clipId = "";
3872
- this._trackId = "";
3873
- this._startPx = 0;
3874
- this._isDragging = false;
3875
- this._cumulativeDeltaSamples = 0;
3876
- this._clipContainer = null;
3877
- this._originalLeft = 0;
3878
- this._originalWidth = 0;
3879
- this._originalOffsetSamples = 0;
3880
- this._originalDurationSamples = 0;
3881
- this._originalStartSample = 0;
5031
+ this._mode = null;
5032
+ this._clipId = "";
5033
+ this._trackId = "";
5034
+ this._startPx = 0;
5035
+ this._isDragging = false;
5036
+ this._cumulativeDeltaSamples = 0;
5037
+ this._clipContainer = null;
5038
+ this._originalLeft = 0;
5039
+ this._originalWidth = 0;
5040
+ this._originalOffsetSamples = 0;
5041
+ this._originalDurationSamples = 0;
5042
+ this._originalStartSample = 0;
5043
+ }
5044
+ };
5045
+
5046
+ // src/interactions/annotation-drag.ts
5047
+ var import_core9 = require("@waveform-playlist/core");
5048
+ var import_core10 = require("@waveform-playlist/core");
5049
+ var AnnotationDragHandler = class {
5050
+ constructor(host) {
5051
+ this._drag = null;
5052
+ this.onPointerDown = (e, track) => {
5053
+ const target = e.target;
5054
+ const boundary = target.closest(".annotation-boundary");
5055
+ const box = target.closest(".annotation-box");
5056
+ if (!box) return;
5057
+ const annotationId = box.getAttribute("data-annotation-id") ?? "";
5058
+ const isBoundary = boundary !== null && track.editable;
5059
+ if (boundary !== null && !track.editable) {
5060
+ return;
5061
+ }
5062
+ e.stopPropagation();
5063
+ e.preventDefault();
5064
+ const elements = track.annotationElements;
5065
+ const el = elements.find((x) => x.annotationId === annotationId);
5066
+ if (!el) return;
5067
+ const mode = el.isTickBased ? "ticks" : "seconds";
5068
+ const snapshot = mode === "ticks" ? elements.map((x) => tickSpaceData(x, this._host)) : track.annotations;
5069
+ const index = snapshot.findIndex((a) => a.id === annotationId);
5070
+ if (index === -1) return;
5071
+ const edge = isBoundary ? boundary.getAttribute("data-edge") : null;
5072
+ const captureEl = isBoundary ? boundary : box;
5073
+ this._drag = {
5074
+ track,
5075
+ captureEl,
5076
+ pointerId: e.pointerId,
5077
+ startClientX: e.clientX,
5078
+ moved: false,
5079
+ edge,
5080
+ annotationId,
5081
+ mode,
5082
+ snapshot,
5083
+ // edgeTime holds ticks in 'ticks' mode, seconds in 'seconds' mode.
5084
+ edgeTime: edge === "start" ? snapshot[index].start : snapshot[index].end
5085
+ };
5086
+ try {
5087
+ captureEl.setPointerCapture(e.pointerId);
5088
+ } catch {
5089
+ }
5090
+ captureEl.addEventListener("pointermove", this._onPointerMove);
5091
+ captureEl.addEventListener("pointerup", this._onPointerUp);
5092
+ captureEl.addEventListener("pointercancel", this._onPointerCancel);
5093
+ };
5094
+ /** Non-private (underscore convention) so tests can drive moves directly. */
5095
+ this._onPointerMove = (e) => {
5096
+ const drag = this._drag;
5097
+ if (!drag || e.pointerId !== drag.pointerId) return;
5098
+ const deltaPx = e.clientX - drag.startClientX;
5099
+ if (Math.abs(deltaPx) >= DRAG_THRESHOLD) drag.moved = true;
5100
+ if (drag.edge === null || !drag.moved) return;
5101
+ const elements = drag.track.annotationElements;
5102
+ const index = drag.snapshot.findIndex((a) => a.id === drag.annotationId);
5103
+ if (index === -1) return;
5104
+ if (drag.mode === "ticks") {
5105
+ const deltaTicks = this._host.scaleMode === "beats" ? deltaPx * this._host.ticksPerPixel : this._host._secondsToTicks(
5106
+ this._host._ticksToSeconds(drag.edgeTime) + deltaPx * this._host._renderSpp / this._host.effectiveSampleRate
5107
+ ) - drag.edgeTime;
5108
+ let newTick = drag.edgeTime + deltaTicks;
5109
+ if (this._host.scaleMode === "beats" && this._host.snapTo !== "off") {
5110
+ newTick = (0, import_core9.snapTickToGrid)(
5111
+ newTick,
5112
+ this._host.snapTo,
5113
+ this._host._meterEntries,
5114
+ this._host.ppqn
5115
+ );
5116
+ }
5117
+ const clamp = this._host._annotationClampDuration;
5118
+ const updated2 = (0, import_core9.updateAnnotationBoundaries)(
5119
+ {
5120
+ annotationIndex: index,
5121
+ newTime: newTick,
5122
+ isDraggingStart: drag.edge === "start",
5123
+ annotations: drag.snapshot,
5124
+ duration: clamp === Infinity ? Infinity : this._host._secondsToTicks(clamp),
5125
+ linkEndpoints: drag.track.linkEndpoints
5126
+ },
5127
+ {
5128
+ linkThreshold: import_core10.ANNOTATION_LINK_THRESHOLD_TICKS,
5129
+ minDuration: (0, import_core10.annotationMinDurationTicks)(this._host.ppqn)
5130
+ }
5131
+ );
5132
+ applyTickBoundaryResults(elements, updated2, (t) => this._host._ticksToSeconds(t));
5133
+ return;
5134
+ }
5135
+ const deltaSeconds = deltaPx * this._host._renderSpp / this._host.effectiveSampleRate;
5136
+ const updated = (0, import_core9.updateAnnotationBoundaries)({
5137
+ annotationIndex: index,
5138
+ newTime: drag.edgeTime + deltaSeconds,
5139
+ isDraggingStart: drag.edge === "start",
5140
+ annotations: drag.snapshot,
5141
+ duration: this._host._annotationClampDuration,
5142
+ linkEndpoints: drag.track.linkEndpoints
5143
+ });
5144
+ applyBoundaryResults(elements, updated);
5145
+ };
5146
+ this._onPointerUp = (e) => {
5147
+ const drag = this._drag;
5148
+ if (!drag || e.pointerId !== drag.pointerId) return;
5149
+ if (!drag.moved && drag.edge === null) {
5150
+ const data = drag.track.annotations.find((a) => a.id === drag.annotationId);
5151
+ if (data) {
5152
+ drag.track.activeAnnotationId = drag.annotationId;
5153
+ this._host.seekTo(data.start);
5154
+ }
5155
+ }
5156
+ this._teardown();
5157
+ };
5158
+ this._onPointerCancel = (e) => {
5159
+ const drag = this._drag;
5160
+ if (!drag || e.pointerId !== drag.pointerId) return;
5161
+ const elements = drag.track.annotationElements;
5162
+ if (drag.mode === "ticks") {
5163
+ applyTickBoundaryResults(elements, drag.snapshot, (t) => this._host._ticksToSeconds(t));
5164
+ } else {
5165
+ applyBoundaryResults(elements, drag.snapshot);
5166
+ }
5167
+ this._teardown();
5168
+ };
5169
+ this._host = host;
5170
+ }
5171
+ _teardown() {
5172
+ const drag = this._drag;
5173
+ if (!drag) return;
5174
+ try {
5175
+ drag.captureEl.releasePointerCapture(drag.pointerId);
5176
+ } catch {
5177
+ }
5178
+ drag.captureEl.removeEventListener("pointermove", this._onPointerMove);
5179
+ drag.captureEl.removeEventListener("pointerup", this._onPointerUp);
5180
+ drag.captureEl.removeEventListener("pointercancel", this._onPointerCancel);
5181
+ this._drag = null;
3882
5182
  }
3883
5183
  };
3884
5184
 
@@ -3934,7 +5234,7 @@ function parseDisplayTime(value, format) {
3934
5234
  }
3935
5235
 
3936
5236
  // src/interactions/file-loader.ts
3937
- var import_core7 = require("@waveform-playlist/core");
5237
+ var import_core11 = require("@waveform-playlist/core");
3938
5238
  async function loadFiles(host, files) {
3939
5239
  if (!files) {
3940
5240
  console.warn("[dawcore] loadFiles called with null/undefined");
@@ -3945,8 +5245,18 @@ async function loadFiles(host, files) {
3945
5245
  const failed = [];
3946
5246
  for (const file of fileArray) {
3947
5247
  if (file.type && !file.type.startsWith("audio/")) {
3948
- failed.push({ file, error: new Error("Non-audio MIME type: " + file.type) });
5248
+ const error = new Error("Non-audio MIME type: " + file.type);
5249
+ failed.push({ file, error });
3949
5250
  console.warn("[dawcore] Skipping non-audio file: " + file.name + " (" + file.type + ")");
5251
+ if (host.isConnected) {
5252
+ host.dispatchEvent(
5253
+ new CustomEvent("daw-files-load-error", {
5254
+ bubbles: true,
5255
+ composed: true,
5256
+ detail: { file, error }
5257
+ })
5258
+ );
5259
+ }
3950
5260
  continue;
3951
5261
  }
3952
5262
  const blobUrl = URL.createObjectURL(file);
@@ -3956,7 +5266,7 @@ async function loadFiles(host, files) {
3956
5266
  host._audioCache.delete(blobUrl);
3957
5267
  host._resolvedSampleRate = audioBuffer.sampleRate;
3958
5268
  const name = file.name.replace(/\.\w+$/, "");
3959
- const clip = (0, import_core7.createClip)({
5269
+ const clip = (0, import_core11.createClip)({
3960
5270
  audioBuffer,
3961
5271
  startSample: 0,
3962
5272
  durationSamples: audioBuffer.length,
@@ -3980,7 +5290,7 @@ async function loadFiles(host, files) {
3980
5290
  );
3981
5291
  host._peaksData = new Map(host._peaksData).set(clip.id, peakData);
3982
5292
  const trackId = crypto.randomUUID();
3983
- const track = (0, import_core7.createTrack)({ name, clips: [clip] });
5293
+ const track = (0, import_core11.createTrack)({ name, clips: [clip] });
3984
5294
  track.id = trackId;
3985
5295
  host._tracks = new Map(host._tracks).set(trackId, {
3986
5296
  name,
@@ -4142,7 +5452,7 @@ function stringifyReason(reason) {
4142
5452
  }
4143
5453
 
4144
5454
  // src/interactions/recording-clip.ts
4145
- var import_core8 = require("@waveform-playlist/core");
5455
+ var import_core12 = require("@waveform-playlist/core");
4146
5456
  function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamples = 0, clipName) {
4147
5457
  let trimmedBuf = buf;
4148
5458
  if (offsetSamples > 0 && offsetSamples < buf.length) {
@@ -4157,7 +5467,7 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
4157
5467
  }
4158
5468
  trimmedBuf = trimmed;
4159
5469
  }
4160
- const clip = (0, import_core8.createClip)({
5470
+ const clip = (0, import_core12.createClip)({
4161
5471
  audioBuffer: trimmedBuf,
4162
5472
  startSample,
4163
5473
  durationSamples: durSamples,
@@ -4167,21 +5477,24 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
4167
5477
  name: clipName ?? "Recording"
4168
5478
  });
4169
5479
  host._clipBuffers = new Map(host._clipBuffers).set(clip.id, trimmedBuf);
4170
- host._peakPipeline.generatePeaks(trimmedBuf, host.samplesPerPixel, host.mono).then((pd) => {
5480
+ host._clipOffsets.set(clip.id, { offsetSamples: 0, durationSamples: durSamples });
5481
+ host._peakPipeline.generatePeaks(trimmedBuf, host.renderSamplesPerPixel, host.mono).then((pd) => {
4171
5482
  const t = host._engineTracks.get(trackId);
4172
5483
  if (!t) {
4173
5484
  const next = new Map(host._clipBuffers);
4174
5485
  next.delete(clip.id);
4175
5486
  host._clipBuffers = next;
5487
+ host._clipOffsets.delete(clip.id);
4176
5488
  return;
4177
5489
  }
4178
5490
  host._peaksData = new Map(host._peaksData).set(clip.id, pd);
5491
+ host._raiseZoomFloor(host._peakPipeline.getCachedScale(trimmedBuf));
4179
5492
  host._engineTracks = new Map(host._engineTracks).set(trackId, {
4180
5493
  ...t,
4181
5494
  // Punch-in replace (#579): the recorded clip owns [startSample,
4182
5495
  // startSample + durSamples) — carve overlapped content out of the
4183
5496
  // existing clips before inserting (parity with the React provider).
4184
- clips: [...(0, import_core8.carveClipRange)(t.clips, startSample, startSample + durSamples), clip]
5497
+ clips: [...(0, import_core12.carveClipRange)(t.clips, startSample, startSample + durSamples), clip]
4185
5498
  });
4186
5499
  const desc = host._tracks.get(trackId);
4187
5500
  if (desc) {
@@ -4219,6 +5532,7 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
4219
5532
  const next = new Map(host._clipBuffers);
4220
5533
  next.delete(clip.id);
4221
5534
  host._clipBuffers = next;
5535
+ host._clipOffsets.delete(clip.id);
4222
5536
  if (host.isConnected) {
4223
5537
  host.dispatchEvent(
4224
5538
  new CustomEvent("daw-error", {
@@ -4254,9 +5568,9 @@ function splitAtPlayhead(host) {
4254
5568
  function canSplitAtTime(host, time) {
4255
5569
  const { engine } = host;
4256
5570
  if (!engine) return false;
4257
- const state8 = engine.getState();
4258
- if (!state8.selectedTrackId) return false;
4259
- const track = state8.tracks.find((t) => t.id === state8.selectedTrackId);
5571
+ const state9 = engine.getState();
5572
+ if (!state9.selectedTrackId) return false;
5573
+ const track = state9.tracks.find((t) => t.id === state9.selectedTrackId);
4260
5574
  if (!track) return false;
4261
5575
  const atSample = Math.round(time * host.effectiveSampleRate);
4262
5576
  const clip = findClipAtSample(track.clips, atSample);
@@ -4443,12 +5757,15 @@ var EffectsChainController = class {
4443
5757
  kind: "wam",
4444
5758
  ...sourceFields,
4445
5759
  bypassed: entry.placeholder.bypassed,
4446
- ...entry.placeholder.state !== void 0 ? { state: entry.placeholder.state } : {}
5760
+ ...entry.placeholder.state !== void 0 ? { state: entry.placeholder.state } : {},
5761
+ // Lets offline export skip this entry (live playback silently
5762
+ // skips it too); restore ignores the flag and retries.
5763
+ placeholder: true
4447
5764
  };
4448
5765
  }
4449
- let state8;
5766
+ let state9;
4450
5767
  try {
4451
- state8 = await entry.instance.getState?.();
5768
+ state9 = await entry.instance.getState?.();
4452
5769
  } catch (err) {
4453
5770
  console.warn(
4454
5771
  '[waveform-playlist] serialize: plugin "' + (entry.url ?? entry.label ?? entry.type) + '" getState failed: ' + String(err)
@@ -4458,7 +5775,16 @@ var EffectsChainController = class {
4458
5775
  kind: "wam",
4459
5776
  ...sourceFields,
4460
5777
  bypassed: entry.bypassed,
4461
- ...state8 !== void 0 ? { state: state8 } : {}
5778
+ ...state9 !== void 0 ? { state: state9 } : {}
5779
+ };
5780
+ }
5781
+ if (entry.placeholder) {
5782
+ return {
5783
+ kind: "native",
5784
+ type: entry.type,
5785
+ params: { ...entry.params },
5786
+ bypassed: entry.placeholder.bypassed,
5787
+ placeholder: true
4462
5788
  };
4463
5789
  }
4464
5790
  return {
@@ -4499,13 +5825,17 @@ var EffectsChainController = class {
4499
5825
  entry.instance.dispose?.();
4500
5826
  this._rebuild();
4501
5827
  }
5828
+ /** Returns the index the entry actually landed at (the requested index is
5829
+ * clamped to the chain bounds), or -1 for an unknown effectId — event
5830
+ * dispatchers must report the actual index, not the raw request. */
4502
5831
  move(effectId, newIndex) {
4503
5832
  const entry = this._find("move", effectId);
4504
- if (!entry) return;
5833
+ if (!entry) return -1;
4505
5834
  const without = this._entries.filter((e) => e.id !== effectId);
4506
5835
  const at = Math.max(0, Math.min(newIndex, without.length));
4507
5836
  this._entries = [...without.slice(0, at), entry, ...without.slice(at)];
4508
5837
  this._rebuild();
5838
+ return at;
4509
5839
  }
4510
5840
  setParams(effectId, params) {
4511
5841
  const entry = this._find("setParams", effectId);
@@ -4729,10 +6059,11 @@ registerBuiltIns();
4729
6059
 
4730
6060
  // src/effects/effects-manager.ts
4731
6061
  var PREFIX2 = "[waveform-playlist] ";
4732
- function makeGuiRecord(element, destroyImpl) {
6062
+ function makeGuiRecord(element, destroyImpl, isFallback = false) {
4733
6063
  let destroyed = false;
4734
6064
  return {
4735
6065
  element,
6066
+ isFallback,
4736
6067
  destroy: () => {
4737
6068
  if (destroyed) return;
4738
6069
  destroyed = true;
@@ -4911,7 +6242,7 @@ var EffectsManager = class {
4911
6242
  );
4912
6243
  }
4913
6244
  const cached = this._guis.get(effectId);
4914
- if (cached) {
6245
+ if (cached && !cached.isFallback) {
4915
6246
  container.appendChild(cached.element);
4916
6247
  return cached.element;
4917
6248
  }
@@ -4922,7 +6253,22 @@ var EffectsManager = class {
4922
6253
  });
4923
6254
  this._guiPending.set(effectId, pending);
4924
6255
  }
4925
- const record = await pending;
6256
+ let record;
6257
+ try {
6258
+ record = await pending;
6259
+ } catch (err) {
6260
+ if (cached) {
6261
+ console.warn(
6262
+ PREFIX2 + 'openEffectGui: rebuilding the parameter panel for "' + effectId + '" failed \u2014 serving the cached panel (values may be stale): ' + String(err)
6263
+ );
6264
+ container.appendChild(cached.element);
6265
+ return cached.element;
6266
+ }
6267
+ throw err;
6268
+ }
6269
+ if (cached && cached !== record) {
6270
+ cached.element.remove();
6271
+ }
4926
6272
  if (chain.disposed || !chain.getEntry(effectId)) {
4927
6273
  this._guis.delete(effectId);
4928
6274
  record.element.remove();
@@ -4957,7 +6303,7 @@ var EffectsManager = class {
4957
6303
  }
4958
6304
  const element = await this._createFallbackPanel(chain, target, entry, effectId);
4959
6305
  return makeGuiRecord(element, () => {
4960
- });
6306
+ }, true);
4961
6307
  }
4962
6308
  /** The generic parameter panel — one code path for "no custom GUI":
4963
6309
  * native entries render from the registry's params metadata, WAM entries
@@ -5200,9 +6546,23 @@ var EffectsManager = class {
5200
6546
  for (const entry of entries) {
5201
6547
  if (superseded()) return;
5202
6548
  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);
6549
+ try {
6550
+ const id = this._addToChain(chain, target, entry.type, entry.params);
6551
+ if (entry.bypassed) {
6552
+ this._runOp(chain, target, "setBypassed", id, true);
6553
+ }
6554
+ } catch (err) {
6555
+ if (superseded() || chain.disposed) return;
6556
+ const message = err instanceof Error ? err.message : String(err);
6557
+ console.warn(
6558
+ PREFIX2 + 'setEffectsState: native effect "' + entry.type + '" failed to restore: ' + message
6559
+ );
6560
+ const effectId = this._addNativePlaceholder(chain, entry, message);
6561
+ this._dispatch(target, "daw-effect-error", {
6562
+ effectId,
6563
+ type: entry.type,
6564
+ message
6565
+ });
5206
6566
  }
5207
6567
  continue;
5208
6568
  }
@@ -5219,7 +6579,7 @@ var EffectsManager = class {
5219
6579
  this._runOp(chain, target, "setBypassed", id, true);
5220
6580
  }
5221
6581
  } catch (err) {
5222
- if (superseded()) return;
6582
+ if (superseded() || chain.disposed) return;
5223
6583
  const message = err instanceof Error ? err.message : String(err);
5224
6584
  const sourceLabel = entry.url ?? entry.faustName ?? "Faust effect";
5225
6585
  console.warn(
@@ -5235,6 +6595,25 @@ var EffectsManager = class {
5235
6595
  }
5236
6596
  }
5237
6597
  }
6598
+ /** A silent passthrough occupying a failed NATIVE entry's chain position.
6599
+ * Carries the saved params/bypassed so the snapshot round-trips (serialize
6600
+ * re-emits them with `placeholder: true`). */
6601
+ _addNativePlaceholder(chain, entry, message) {
6602
+ const { audioContext } = this._requireWiring();
6603
+ const node = audioContext.createGain();
6604
+ const effectId = chain.add({
6605
+ kind: "native",
6606
+ type: entry.type,
6607
+ label: entry.type,
6608
+ error: message,
6609
+ placeholder: { bypassed: entry.bypassed },
6610
+ instance: { input: node, output: node, applyParams: () => {
6611
+ } },
6612
+ params: { ...entry.params }
6613
+ });
6614
+ chain.setBypassed(effectId, true);
6615
+ return effectId;
6616
+ }
5238
6617
  /** A silent passthrough occupying the failed plugin's chain position. */
5239
6618
  _addWamPlaceholder(chain, entry, message) {
5240
6619
  const { audioContext } = this._requireWiring();
@@ -5281,10 +6660,11 @@ var EffectsManager = class {
5281
6660
  chain.setBypassed(effectId, arg);
5282
6661
  this._dispatch(target, "daw-effect-bypass", { effectId, bypassed: arg });
5283
6662
  break;
5284
- case "move":
5285
- chain.move(effectId, arg);
5286
- this._dispatch(target, "daw-effect-reorder", { effectId, fromIndex, toIndex: arg });
6663
+ case "move": {
6664
+ const toIndex = chain.move(effectId, arg);
6665
+ this._dispatch(target, "daw-effect-reorder", { effectId, fromIndex, toIndex });
5287
6666
  break;
6667
+ }
5288
6668
  }
5289
6669
  }
5290
6670
  _dispatch(target, name, detail) {
@@ -5325,6 +6705,9 @@ function validateSerializedEntries(entries) {
5325
6705
  if (typeof e.bypassed !== "boolean") {
5326
6706
  throw new Error(PREFIX2 + "setEffectsState: entry requires a boolean bypassed flag" + at);
5327
6707
  }
6708
+ if (e.placeholder !== void 0 && e.placeholder !== true) {
6709
+ throw new Error(PREFIX2 + "setEffectsState: placeholder must be true when present" + at);
6710
+ }
5328
6711
  });
5329
6712
  }
5330
6713
  function toWamParameterMap(params) {
@@ -5357,6 +6740,9 @@ async function exportAudioImpl(host, options = {}) {
5357
6740
  try {
5358
6741
  const masterChain = await buildOfflineChain(ctx, await host.getMasterEffectsState());
5359
6742
  cleanups.push(masterChain.dispose);
6743
+ const masterVolume = ctx.createGain();
6744
+ masterVolume.gain.value = host.masterVolume ?? 1;
6745
+ masterVolume.connect(masterChain.input);
5360
6746
  masterChain.output.connect(ctx.destination);
5361
6747
  const anySoloed = host.tracks.some((t) => t.soloed);
5362
6748
  for (const track of host.tracks) {
@@ -5371,7 +6757,7 @@ async function exportAudioImpl(host, options = {}) {
5371
6757
  panner.pan.value = track.pan;
5372
6758
  volume.connect(panner);
5373
6759
  panner.connect(chain.input);
5374
- chain.output.connect(masterChain.input);
6760
+ chain.output.connect(masterVolume);
5375
6761
  for (const clip of track.clips) {
5376
6762
  scheduleClip(ctx, clip, startTime, duration, volume);
5377
6763
  }
@@ -5442,6 +6828,12 @@ async function buildOfflineChain(ctx, entries) {
5442
6828
  return { input, output, dispose };
5443
6829
  async function wireEntries() {
5444
6830
  for (const entry of entries) {
6831
+ if (entry.placeholder) {
6832
+ console.warn(
6833
+ PREFIX3 + 'exportAudio: skipping failed-plugin placeholder "' + (entry.kind === "native" ? entry.type : entry.url ?? "Faust effect") + '"'
6834
+ );
6835
+ continue;
6836
+ }
5445
6837
  if (entry.kind === "native") {
5446
6838
  const created = createEffectInstance(entry.type, ctx, entry.params);
5447
6839
  if (entry.bypassed) {
@@ -5683,6 +7075,7 @@ var PlaybackAnimationController = class {
5683
7075
  this._running = true;
5684
7076
  this._animation.start(() => {
5685
7077
  const time = getTime();
7078
+ if (!this._running) return;
5686
7079
  this._options.getPlayhead()?.setPosition(this._options.timeToPixels(time));
5687
7080
  this._dispatchTimeUpdate(time);
5688
7081
  });
@@ -5713,7 +7106,14 @@ var PlaybackAnimationController = class {
5713
7106
  var import_meta = {};
5714
7107
  var RULER_HEIGHT = 30;
5715
7108
  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();";
5716
- var DawEditorElement = class extends import_lit15.LitElement {
7109
+ var TrackLoadCancelledError = class extends Error {
7110
+ constructor(message, reason) {
7111
+ super(message);
7112
+ this.reason = reason;
7113
+ this.name = "TrackLoadCancelledError";
7114
+ }
7115
+ };
7116
+ var DawEditorElement = class extends import_lit19.LitElement {
5717
7117
  constructor() {
5718
7118
  super(...arguments);
5719
7119
  this._samplesPerPixel = 1024;
@@ -5751,7 +7151,17 @@ var DawEditorElement = class extends import_lit15.LitElement {
5751
7151
  this._selectionStartTime = 0;
5752
7152
  this._selectionEndTime = 0;
5753
7153
  this._currentTime = 0;
7154
+ // Bounded-playback watermark for the current play(start, end) call
7155
+ // (selection/annotation playback). The adapter's own auto-stop at
7156
+ // endTime (e.g. native Transport's internal timer) tears down audio but
7157
+ // never notifies isPlaying/daw-stop back up — the _startPlayhead rAF
7158
+ // loop below is the sole place that detects reaching it, same pattern
7159
+ // as the whole-track _duration check.
7160
+ this._activePlayEndTime = null;
5754
7161
  this._externalAdapter = null;
7162
+ /** True after a disconnect disposed the consumer's adapter via the engine
7163
+ * — rebuild attempts fail loudly until a fresh adapter is set. */
7164
+ this._adapterConsumedByDispose = false;
5755
7165
  // --- Effects (master chain; per-track chains delegated from <daw-track>) ---
5756
7166
  this._effectsManager = null;
5757
7167
  this._engine = null;
@@ -5766,9 +7176,18 @@ var DawEditorElement = class extends import_lit15.LitElement {
5766
7176
  /** Coarsest scale from pre-computed peaks — zoom cannot go finer than this. 0 = no limit. */
5767
7177
  this._minSamplesPerPixel = 0;
5768
7178
  this._trackElements = /* @__PURE__ */ new Map();
7179
+ /** Track ids with a _loadTrack in flight. Distinct from `_engineTracks`
7180
+ * membership: the peaks-first path inserts a render-only PREVIEW track
7181
+ * into _engineTracks mid-load, so `has()` alone cannot answer "is this
7182
+ * track still loading?". */
7183
+ this._loadingTracks = /* @__PURE__ */ new Set();
5769
7184
  this._childObserver = null;
5770
7185
  this._audioResume = new AudioResumeController(this);
5771
7186
  this._recordingController = new RecordingController(this);
7187
+ this._annotations = new AnnotationController(this);
7188
+ /** Last engine BPM seen by the statechange handler — re-derives tick
7189
+ * annotation seconds caches only when it actually changes. */
7190
+ this._lastAnnotationBpm = null;
5772
7191
  // Closures (not direct references) — _timeToPixels/_getPlayhead are
5773
7192
  // declared later in the class body; class-field init order would read
5774
7193
  // `undefined` for a direct reference here.
@@ -5783,8 +7202,17 @@ var DawEditorElement = class extends import_lit15.LitElement {
5783
7202
  * play-start position). Non-private: pointer-handler's seek path sets it.
5784
7203
  */
5785
7204
  this._inSeekTransition = false;
7205
+ /**
7206
+ * True while `stop()` (the public API) is actively calling `this._engine.stop()`.
7207
+ * Suppresses the engine 'stop' handler's own `daw-stop` dispatch — `stop()`
7208
+ * dispatches its own, and without this guard a consumer-initiated stop would
7209
+ * fire `daw-stop` twice. See the engine 'stop' handler for the counterpart
7210
+ * engine-initiated case this flag does NOT suppress.
7211
+ */
7212
+ this._inConsumerStop = false;
5786
7213
  this._spectrogramController = null;
5787
7214
  this._clipPointer = new ClipPointerHandler(this);
7215
+ this._annotationDrag = new AnnotationDragHandler(this);
5788
7216
  this._pointer = new PointerHandler(this);
5789
7217
  this._viewport = (() => {
5790
7218
  const v = new ViewportController(this);
@@ -5808,6 +7236,18 @@ var DawEditorElement = class extends import_lit15.LitElement {
5808
7236
  * update for properties unrelated to the viewport.
5809
7237
  */
5810
7238
  this._lastSpectrogramViewport = null;
7239
+ // --- Annotation Events ---
7240
+ this._onAnnotationTrackConnected = (e) => {
7241
+ this._annotations.handleTrackConnected(e.detail.element);
7242
+ };
7243
+ this._onAnnotationSelect = (e) => {
7244
+ const annotation = e.detail.annotation;
7245
+ if (!annotation) return;
7246
+ const scrollArea = this.shadowRoot?.querySelector(".scroll-area");
7247
+ if (!scrollArea) return;
7248
+ const px = Math.floor(annotation.start * this.effectiveSampleRate / this._renderSpp);
7249
+ scrollArea.scrollLeft = Math.max(0, px - scrollArea.clientWidth / 2);
7250
+ };
5811
7251
  // --- Track Events ---
5812
7252
  this._onTrackConnected = (e) => {
5813
7253
  const trackId = e.detail?.trackId;
@@ -5910,11 +7350,17 @@ var DawEditorElement = class extends import_lit15.LitElement {
5910
7350
  const trackEl = clipEl.closest("daw-track");
5911
7351
  if (!trackEl) return;
5912
7352
  const trackId = trackEl.trackId;
5913
- if (!this._engineTracks.has(trackId)) {
7353
+ if (!this._engineTracks.has(trackId) || this._loadingTracks.has(trackId)) {
5914
7354
  const desc = this._tracks.get(trackId);
5915
7355
  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.'
7356
+ 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.';
7357
+ console.warn("[dawcore] " + message);
7358
+ this.dispatchEvent(
7359
+ new CustomEvent("daw-clip-error", {
7360
+ bubbles: true,
7361
+ composed: true,
7362
+ detail: { trackId, clipId: clipEl.clipId, error: new Error(message) }
7363
+ })
5918
7364
  );
5919
7365
  }
5920
7366
  return;
@@ -6006,12 +7452,38 @@ var DawEditorElement = class extends import_lit15.LitElement {
6006
7452
  const clamped = this._minSamplesPerPixel > 0 && value < this._minSamplesPerPixel ? this._minSamplesPerPixel : value;
6007
7453
  if (clamped !== value) {
6008
7454
  console.warn(
6009
- "[dawcore] Zoom " + value + " spp rejected \u2014 pre-computed peaks limit is " + this._minSamplesPerPixel + " spp"
7455
+ "[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
7456
  );
6011
7457
  }
6012
7458
  this._samplesPerPixel = clamped;
6013
7459
  this.requestUpdate("samplesPerPixel", old);
6014
7460
  }
7461
+ /** Raise the zoom floor and re-clamp the LIVE samplesPerPixel when it's
7462
+ * now below the floor. Peaks can only be extracted at >= the floor scale —
7463
+ * the setter alone clamps only FUTURE sets, so without the re-clamp an
7464
+ * already-finer spp keeps sizing clip containers while the waveforms
7465
+ * render at the coarser scale: half/quarter width, misaligned against the
7466
+ * ruler and playhead. */
7467
+ _raiseZoomFloor(scale) {
7468
+ if (!Number.isFinite(scale) || scale <= 0) return;
7469
+ if (scale > this._minSamplesPerPixel) {
7470
+ this._minSamplesPerPixel = scale;
7471
+ }
7472
+ if (this._samplesPerPixel < this._minSamplesPerPixel) {
7473
+ this.samplesPerPixel = this._minSamplesPerPixel;
7474
+ }
7475
+ }
7476
+ /** Recompute the floor from the surviving cached scales (track removal /
7477
+ * load cancellation / preview cleanup). Usually LOWERS the floor, freeing
7478
+ * finer zoom — but a buffer whose scale never raised the floor (or a mix
7479
+ * of scales) can raise it above the live spp, so re-clamp like
7480
+ * _raiseZoomFloor. Never mutate _minSamplesPerPixel directly. */
7481
+ _recomputeZoomFloor() {
7482
+ this._minSamplesPerPixel = this._peakPipeline.getMaxCachedScale(this._clipBuffers);
7483
+ if (this._minSamplesPerPixel > 0 && this._samplesPerPixel < this._minSamplesPerPixel) {
7484
+ this.samplesPerPixel = this._minSamplesPerPixel;
7485
+ }
7486
+ }
6015
7487
  get timeFormat() {
6016
7488
  return this._timeFormat;
6017
7489
  }
@@ -6157,6 +7629,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
6157
7629
  console.warn("[dawcore] Adapter AudioContext is already closed. Ignoring.");
6158
7630
  return;
6159
7631
  }
7632
+ this._adapterConsumedByDispose = false;
6160
7633
  if (this._engine) {
6161
7634
  console.warn(
6162
7635
  "[dawcore] adapter set after engine is built. The engine will continue using the previous adapter."
@@ -6244,6 +7717,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
6244
7717
  effectiveSampleRate: this.effectiveSampleRate,
6245
7718
  duration: this._duration,
6246
7719
  tracks: [...this._engineTracks.values()],
7720
+ masterVolume: this._engine?.getState().masterVolume ?? 1,
6247
7721
  getMasterEffectsState: () => this.getEffectsState(),
6248
7722
  getTrackEffectsState: (trackId) => this.getTrackEffectsState(trackId)
6249
7723
  },
@@ -6417,6 +7891,12 @@ var DawEditorElement = class extends import_lit15.LitElement {
6417
7891
  }
6418
7892
  return ticks * 60 / (this.bpm * this.ppqn);
6419
7893
  }
7894
+ /** Clamp limit for annotation boundary edits. indefinite-playback removes the
7895
+ * end-of-timeline bound — annotations may extend past the audio (DAW-style
7896
+ * unbounded timeline); the shared boundary math treats Infinity as "no end cap". */
7897
+ get _annotationClampDuration() {
7898
+ return this.indefinitePlayback ? Infinity : this._duration;
7899
+ }
6420
7900
  get _totalWidth() {
6421
7901
  if (this.scaleMode === "beats") {
6422
7902
  const contentTicks = this._secondsToTicks(this._duration);
@@ -6424,8 +7904,9 @@ var DawEditorElement = class extends import_lit15.LitElement {
6424
7904
  const minTicks = 32 * num * this.ppqn;
6425
7905
  return Math.ceil(Math.max(contentTicks, minTicks) / this.ticksPerPixel);
6426
7906
  }
7907
+ const naturalDuration = Math.max(this._duration, this._annotations.maxAnnotationEndSeconds);
6427
7908
  const naturalWidth = Math.ceil(
6428
- this._duration * this.effectiveSampleRate / this.samplesPerPixel
7909
+ naturalDuration * this.effectiveSampleRate / this.samplesPerPixel
6429
7910
  );
6430
7911
  if (this.indefinitePlayback || this.fillViewport) {
6431
7912
  return Math.max(naturalWidth, this._viewport.containerWidth);
@@ -6477,6 +7958,11 @@ var DawEditorElement = class extends import_lit15.LitElement {
6477
7958
  this.addEventListener("daw-track-remove", this._onTrackRemoveRequest);
6478
7959
  this.addEventListener("daw-clip-connected", this._onClipConnected);
6479
7960
  this.addEventListener("daw-clip-update", this._onClipUpdate);
7961
+ this.addEventListener(
7962
+ "daw-annotation-track-connected",
7963
+ this._onAnnotationTrackConnected
7964
+ );
7965
+ this.addEventListener("daw-annotation-select", this._onAnnotationSelect);
6480
7966
  this._childObserver = new MutationObserver((mutations) => {
6481
7967
  for (const mutation of mutations) {
6482
7968
  for (const node of mutation.removedNodes) {
@@ -6514,6 +8000,11 @@ var DawEditorElement = class extends import_lit15.LitElement {
6514
8000
  this.removeEventListener("daw-track-remove", this._onTrackRemoveRequest);
6515
8001
  this.removeEventListener("daw-clip-connected", this._onClipConnected);
6516
8002
  this.removeEventListener("daw-clip-update", this._onClipUpdate);
8003
+ this.removeEventListener(
8004
+ "daw-annotation-track-connected",
8005
+ this._onAnnotationTrackConnected
8006
+ );
8007
+ this.removeEventListener("daw-annotation-select", this._onAnnotationSelect);
6517
8008
  this._childObserver?.disconnect();
6518
8009
  this._childObserver = null;
6519
8010
  this._trackElements.clear();
@@ -6525,11 +8016,21 @@ var DawEditorElement = class extends import_lit15.LitElement {
6525
8016
  this._minSamplesPerPixel = 0;
6526
8017
  this._spectrogramController?.dispose();
6527
8018
  this._spectrogramController = null;
8019
+ this._lastSpectrogramViewport = null;
8020
+ const hadEngine = this._engine !== null;
6528
8021
  try {
6529
8022
  this._disposeEngine();
6530
8023
  } catch (err) {
6531
8024
  console.warn("[dawcore] Error disposing engine: " + String(err));
6532
8025
  }
8026
+ if (hadEngine) {
8027
+ this._adapterConsumedByDispose = true;
8028
+ }
8029
+ this._tracks = /* @__PURE__ */ new Map();
8030
+ this._engineTracks = /* @__PURE__ */ new Map();
8031
+ this._peaksData = /* @__PURE__ */ new Map();
8032
+ this._loadingTracks.clear();
8033
+ this._recomputeDuration();
6533
8034
  }
6534
8035
  willUpdate(changedProperties) {
6535
8036
  if (changedProperties.has("eagerResume")) {
@@ -6538,8 +8039,8 @@ var DawEditorElement = class extends import_lit15.LitElement {
6538
8039
  if ((changedProperties.has("samplesPerPixel") || changedProperties.has("ticksPerPixel") || changedProperties.has("bpm") || changedProperties.has("secondsToTicks")) && this._isPlaying) {
6539
8040
  this._startPlayhead();
6540
8041
  }
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) {
8042
+ const peaksInputChanged = changedProperties.has("samplesPerPixel") || changedProperties.has("ticksPerPixel") || changedProperties.has("bpm") || changedProperties.has("scaleMode") || changedProperties.has("secondsToTicks") || changedProperties.has("mono");
8043
+ if (peaksInputChanged && this._clipBuffers.size > 0) {
6543
8044
  const re = this._peakPipeline.reextractPeaks(
6544
8045
  this._clipBuffers,
6545
8046
  this._renderSpp,
@@ -6606,9 +8107,16 @@ var DawEditorElement = class extends import_lit15.LitElement {
6606
8107
  if (this._engine) {
6607
8108
  this._engine.removeTrack(trackId);
6608
8109
  }
6609
- this._minSamplesPerPixel = this._peakPipeline.getMaxCachedScale(this._clipBuffers);
8110
+ this._recomputeZoomFloor();
6610
8111
  this._disposeSpectrogramControllerIfEmpty();
6611
- if (nextEngine.size === 0) {
8112
+ if (existed && nextEngine.size === 0) {
8113
+ if (this._engine) {
8114
+ if (this._isPlaying) {
8115
+ this._withSeekSuppression(() => this._engine.stop());
8116
+ this.dispatchEvent(new CustomEvent("daw-stop", { bubbles: true, composed: true }));
8117
+ }
8118
+ this._engine.seek(0);
8119
+ }
6612
8120
  this._currentTime = 0;
6613
8121
  this._stopPlayhead();
6614
8122
  }
@@ -6631,6 +8139,45 @@ var DawEditorElement = class extends import_lit15.LitElement {
6631
8139
  if (!stillNeeded) {
6632
8140
  this._spectrogramController.dispose();
6633
8141
  this._spectrogramController = null;
8142
+ this._lastSpectrogramViewport = null;
8143
+ }
8144
+ }
8145
+ /** Reconcile `_tracks` descriptors with the engine's track list.
8146
+ *
8147
+ * ADD: engine.undo() restores removed tracks in ENGINE state only —
8148
+ * without a synthesized descriptor the track plays and renders but shows
8149
+ * "Untitled" controls and is missing from `editor.tracks`.
8150
+ * PRUNE (the symmetric half): redo removes the track from engine state
8151
+ * again — without pruning, the synthesized descriptor is a permanent
8152
+ * ghost that even removeTrack() can't clean (no element, no engine
8153
+ * entry). Never prunes tracks that are mid-load or element-backed —
8154
+ * their descriptors legitimately precede their engine entries. */
8155
+ _reconcileDescriptorsWithEngineTracks(tracks) {
8156
+ const engineIds = new Set(tracks.map((t) => t.id));
8157
+ let next = null;
8158
+ for (const track of tracks) {
8159
+ if (this._tracks.has(track.id)) continue;
8160
+ next ?? (next = new Map(this._tracks));
8161
+ next.set(track.id, {
8162
+ name: track.name ?? "",
8163
+ src: "",
8164
+ volume: track.volume ?? 1,
8165
+ pan: track.pan ?? 0,
8166
+ muted: track.muted ?? false,
8167
+ soloed: track.soloed ?? false,
8168
+ renderMode: track.clips.some((c) => c.midiNotes && c.midiNotes.length > 0) ? "piano-roll" : "waveform",
8169
+ clips: []
8170
+ });
8171
+ }
8172
+ for (const trackId of this._tracks.keys()) {
8173
+ if (engineIds.has(trackId) || this._loadingTracks.has(trackId) || this._trackElements.has(trackId)) {
8174
+ continue;
8175
+ }
8176
+ next ?? (next = new Map(this._tracks));
8177
+ next.delete(trackId);
8178
+ }
8179
+ if (next) {
8180
+ this._tracks = next;
6634
8181
  }
6635
8182
  }
6636
8183
  _onClipRemovedFromDom(clipEl) {
@@ -6732,7 +8279,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
6732
8279
  let clip;
6733
8280
  if (waveformData) {
6734
8281
  const wdRate = waveformData.sample_rate;
6735
- clip = (0, import_core9.createClip)({
8282
+ clip = (0, import_core13.createClip)({
6736
8283
  audioBuffer,
6737
8284
  waveformData,
6738
8285
  startSample: Math.round(clipDesc.start * wdRate),
@@ -6745,7 +8292,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
6745
8292
  });
6746
8293
  this._peakPipeline.cacheWaveformData(audioBuffer, waveformData);
6747
8294
  } else {
6748
- clip = (0, import_core9.createClipFromSeconds)({
8295
+ clip = (0, import_core13.createClipFromSeconds)({
6749
8296
  audioBuffer,
6750
8297
  startTime: clipDesc.start,
6751
8298
  duration: clipDesc.duration || audioBuffer.duration,
@@ -6776,9 +8323,8 @@ var DawEditorElement = class extends import_lit15.LitElement {
6776
8323
  throw err;
6777
8324
  }
6778
8325
  this._peaksData = new Map(this._peaksData).set(clip.id, peakData);
6779
- if (waveformData) {
6780
- this._minSamplesPerPixel = Math.max(this._minSamplesPerPixel, waveformData.scale);
6781
- }
8326
+ const cachedScale = waveformData?.scale ?? this._peakPipeline.getCachedScale(audioBuffer);
8327
+ this._raiseZoomFloor(cachedScale);
6782
8328
  return clip;
6783
8329
  }
6784
8330
  /**
@@ -6825,7 +8371,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
6825
8371
  const noteSpanSeconds = notes.length ? notes.reduce((max, n) => Math.max(max, n.time + n.duration), 0) : 0;
6826
8372
  const sourceDurationSamples = Math.ceil(Math.max(noteSpanSeconds, clipDesc.duration, 1) * sr);
6827
8373
  const requestedDurationSamples = clipDesc.duration > 0 ? Math.round(clipDesc.duration * sr) : sourceDurationSamples;
6828
- const clip = (0, import_core9.createClip)({
8374
+ const clip = (0, import_core13.createClip)({
6829
8375
  startSample: Math.round(clipDesc.start * sr),
6830
8376
  durationSamples: requestedDurationSamples,
6831
8377
  offsetSamples: Math.round(clipDesc.offset * sr),
@@ -7021,6 +8567,8 @@ var DawEditorElement = class extends import_lit15.LitElement {
7021
8567
  }
7022
8568
  // --- Audio Loading ---
7023
8569
  async _loadTrack(trackId, descriptor) {
8570
+ this._loadingTracks.add(trackId);
8571
+ const sppAtLoadStart = this._samplesPerPixel;
7024
8572
  try {
7025
8573
  const clips = [];
7026
8574
  for (const clipDesc of descriptor.clips) {
@@ -7034,7 +8582,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
7034
8582
  const waveformData = await waveformDataPromise;
7035
8583
  if (waveformData) {
7036
8584
  const wdRate = waveformData.sample_rate;
7037
- const clip2 = (0, import_core9.createClip)({
8585
+ const clip2 = (0, import_core13.createClip)({
7038
8586
  waveformData,
7039
8587
  startSample: Math.round(clipDesc.start * wdRate),
7040
8588
  durationSamples: Math.round((clipDesc.duration || waveformData.duration) * wdRate),
@@ -7058,18 +8606,20 @@ var DawEditorElement = class extends import_lit15.LitElement {
7058
8606
  durationSamples: clip2.durationSamples
7059
8607
  });
7060
8608
  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();
8609
+ this._raiseZoomFloor(waveformData.scale);
8610
+ if (this._tracks.has(trackId)) {
8611
+ const previewTrack = (0, import_core13.createTrack)({
8612
+ name: descriptor.name,
8613
+ clips: [clip2],
8614
+ volume: descriptor.volume,
8615
+ pan: descriptor.pan,
8616
+ muted: descriptor.muted,
8617
+ soloed: descriptor.soloed
8618
+ });
8619
+ previewTrack.id = trackId;
8620
+ this._engineTracks = new Map(this._engineTracks).set(trackId, previewTrack);
8621
+ this._recomputeDuration();
8622
+ }
7073
8623
  let audioBuffer2;
7074
8624
  try {
7075
8625
  audioBuffer2 = await audioPromise;
@@ -7081,7 +8631,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
7081
8631
  const nextEngine = new Map(this._engineTracks);
7082
8632
  nextEngine.delete(trackId);
7083
8633
  this._engineTracks = nextEngine;
7084
- this._minSamplesPerPixel = this._peakPipeline.getMaxCachedScale(this._clipBuffers);
8634
+ this._recomputeZoomFloor();
7085
8635
  this._recomputeDuration();
7086
8636
  throw audioErr;
7087
8637
  }
@@ -7115,7 +8665,27 @@ var DawEditorElement = class extends import_lit15.LitElement {
7115
8665
  }
7116
8666
  }
7117
8667
  }
7118
- const track = (0, import_core9.createTrack)({
8668
+ const trackWasRemoved = !this._tracks.has(trackId);
8669
+ if (trackWasRemoved || !this.isConnected) {
8670
+ for (const clip of clips) {
8671
+ this._purgeClipCaches(clip.id);
8672
+ }
8673
+ if (this._engineTracks.has(trackId)) {
8674
+ const nextEngine = new Map(this._engineTracks);
8675
+ nextEngine.delete(trackId);
8676
+ this._engineTracks = nextEngine;
8677
+ this._recomputeDuration();
8678
+ }
8679
+ this._recomputeZoomFloor();
8680
+ if (this._samplesPerPixel !== sppAtLoadStart && sppAtLoadStart >= this._minSamplesPerPixel) {
8681
+ this.samplesPerPixel = sppAtLoadStart;
8682
+ }
8683
+ throw new TrackLoadCancelledError(
8684
+ trackWasRemoved ? 'track "' + trackId + '" was removed while loading' : 'editor was disconnected while track "' + trackId + '" was loading',
8685
+ trackWasRemoved ? "removed" : "disconnected"
8686
+ );
8687
+ }
8688
+ const track = (0, import_core13.createTrack)({
7119
8689
  name: descriptor.name,
7120
8690
  clips,
7121
8691
  volume: descriptor.volume,
@@ -7145,15 +8715,23 @@ var DawEditorElement = class extends import_lit15.LitElement {
7145
8715
  })
7146
8716
  );
7147
8717
  } catch (err) {
7148
- if (!this.isConnected) return;
7149
- console.warn('[dawcore] Failed to load track "' + trackId + '": ' + String(err));
8718
+ const cancelled = err instanceof TrackLoadCancelledError;
8719
+ console.warn(
8720
+ cancelled ? "[dawcore] Track load cancelled: " + err.message : '[dawcore] Failed to load track "' + trackId + '": ' + String(err)
8721
+ );
7150
8722
  this.dispatchEvent(
7151
8723
  new CustomEvent("daw-track-error", {
7152
8724
  bubbles: true,
7153
8725
  composed: true,
7154
- detail: { trackId, error: err }
8726
+ detail: {
8727
+ trackId,
8728
+ error: err,
8729
+ ...cancelled ? { reason: err.reason } : {}
8730
+ }
7155
8731
  })
7156
8732
  );
8733
+ } finally {
8734
+ this._loadingTracks.delete(trackId);
7157
8735
  }
7158
8736
  }
7159
8737
  async _fetchAndDecode(src) {
@@ -7212,6 +8790,11 @@ var DawEditorElement = class extends import_lit15.LitElement {
7212
8790
  if (!this._externalAdapter) {
7213
8791
  throw new Error(NO_ADAPTER_ERROR);
7214
8792
  }
8793
+ if (this._adapterConsumedByDispose) {
8794
+ throw new Error(
8795
+ "[dawcore] editor.adapter was disposed by a previous disconnect \u2014 set a fresh PlayoutAdapter after reparenting <daw-editor>."
8796
+ );
8797
+ }
7215
8798
  const { PlaylistEngine } = await import("@waveform-playlist/engine");
7216
8799
  const adapter = this._externalAdapter;
7217
8800
  if (!this._hasTickCallbacks) {
@@ -7248,6 +8831,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
7248
8831
  nextTracks.set(track.id, track);
7249
8832
  }
7250
8833
  this._engineTracks = nextTracks;
8834
+ this._reconcileDescriptorsWithEngineTracks(engineState.tracks);
7251
8835
  }
7252
8836
  if (structuralChange) {
7253
8837
  this._effectsManager?.rewireTrackChains();
@@ -7257,6 +8841,10 @@ var DawEditorElement = class extends import_lit15.LitElement {
7257
8841
  });
7258
8842
  syncPeaksForChangedClips(this, audioTracks);
7259
8843
  }
8844
+ if (engineState.bpm !== this._lastAnnotationBpm) {
8845
+ this._lastAnnotationBpm = engineState.bpm;
8846
+ this._annotations.deriveSecondsCaches();
8847
+ }
7260
8848
  });
7261
8849
  engine.on("pause", () => {
7262
8850
  this._currentTime = engine.getCurrentTime();
@@ -7264,6 +8852,10 @@ var DawEditorElement = class extends import_lit15.LitElement {
7264
8852
  engine.on("stop", () => {
7265
8853
  this._currentTime = engine.getCurrentTime();
7266
8854
  this._stopPlayhead();
8855
+ this._activePlayEndTime = null;
8856
+ if (!this._inConsumerStop && !this._inSeekTransition && this.isConnected) {
8857
+ this.dispatchEvent(new CustomEvent("daw-stop", { bubbles: true, composed: true }));
8858
+ }
7267
8859
  });
7268
8860
  this._engine = engine;
7269
8861
  return engine;
@@ -7564,14 +9156,21 @@ var DawEditorElement = class extends import_lit15.LitElement {
7564
9156
  return clipEl;
7565
9157
  }
7566
9158
  // --- Playback ---
7567
- async play(startTime) {
9159
+ /**
9160
+ * Start playback, optionally seeking to `startTime` first. When `endTime`
9161
+ * is provided, playback stops at that time (selection/annotation playback).
9162
+ */
9163
+ async play(startTime, endTime) {
7568
9164
  try {
7569
9165
  const engine = await this._ensureEngine();
7570
9166
  await engine.init();
7571
- engine.play(startTime);
9167
+ this._activePlayEndTime = endTime ?? null;
7572
9168
  this._startPlayhead();
9169
+ engine.play(startTime, endTime);
7573
9170
  this.dispatchEvent(new CustomEvent("daw-play", { bubbles: true, composed: true }));
7574
9171
  } catch (err) {
9172
+ this._stopPlayhead();
9173
+ this._activePlayEndTime = null;
7575
9174
  console.warn("[dawcore] Playback failed: " + String(err));
7576
9175
  this.dispatchEvent(
7577
9176
  new CustomEvent("daw-error", {
@@ -7590,7 +9189,13 @@ var DawEditorElement = class extends import_lit15.LitElement {
7590
9189
  }
7591
9190
  stop() {
7592
9191
  if (!this._engine) return;
7593
- this._engine.stop();
9192
+ this._activePlayEndTime = null;
9193
+ this._inConsumerStop = true;
9194
+ try {
9195
+ this._engine.stop();
9196
+ } finally {
9197
+ this._inConsumerStop = false;
9198
+ }
7594
9199
  this._stopPlayhead();
7595
9200
  this.dispatchEvent(new CustomEvent("daw-stop", { bubbles: true, composed: true }));
7596
9201
  }
@@ -7604,24 +9209,61 @@ var DawEditorElement = class extends import_lit15.LitElement {
7604
9209
  this.play();
7605
9210
  }
7606
9211
  }
9212
+ /** Run `fn` with the stop-settle daw-timeupdate suppressed. Every
9213
+ * stop-adjacent code path that immediately re-positions (seek, split,
9214
+ * empty-timeline rewind) must use this — engine.stop() rewinds to the
9215
+ * play-start position and the settle would leak a backward-jumping
9216
+ * daw-timeupdate to consumers (CLAUDE.md seek-while-playing invariant).
9217
+ * The `finally` is load-bearing: a wedged true silently drops every
9218
+ * subsequent stop-settle dispatch. */
9219
+ _withSeekSuppression(fn) {
9220
+ this._inSeekTransition = true;
9221
+ try {
9222
+ fn();
9223
+ } finally {
9224
+ this._inSeekTransition = false;
9225
+ }
9226
+ }
7607
9227
  seekTo(time) {
7608
9228
  if (!this._engine) {
7609
9229
  console.warn("[dawcore] seekTo: engine not ready, call ignored");
7610
9230
  return;
7611
9231
  }
9232
+ if (!Number.isFinite(time)) {
9233
+ console.warn("[dawcore] seekTo: ignoring non-finite time " + String(time));
9234
+ return;
9235
+ }
9236
+ const target = Math.max(0, time);
7612
9237
  if (this._isPlaying) {
7613
- this._inSeekTransition = true;
7614
9238
  try {
7615
- this.stop();
7616
- } finally {
7617
- this._inSeekTransition = false;
9239
+ this._withSeekSuppression(() => this._engine.stop());
9240
+ this._engine.play(target);
9241
+ } catch (err) {
9242
+ console.warn("[dawcore] seekTo: engine reschedule failed: " + String(err));
9243
+ this.dispatchEvent(
9244
+ new CustomEvent("daw-error", {
9245
+ bubbles: true,
9246
+ composed: true,
9247
+ detail: { operation: "seek", error: err }
9248
+ })
9249
+ );
9250
+ return;
7618
9251
  }
7619
- this.play(time);
9252
+ this._activePlayEndTime = null;
9253
+ this._currentTime = target;
9254
+ this._startPlayhead();
7620
9255
  } else {
7621
- this._engine.seek(time);
7622
- this._currentTime = time;
9256
+ this._engine.seek(target);
9257
+ this._currentTime = target;
7623
9258
  this._stopPlayhead();
7624
9259
  }
9260
+ this.dispatchEvent(
9261
+ new CustomEvent("daw-seek", {
9262
+ bubbles: true,
9263
+ composed: true,
9264
+ detail: { time: target }
9265
+ })
9266
+ );
7625
9267
  }
7626
9268
  /** Undo the last structural edit. */
7627
9269
  undo() {
@@ -7656,8 +9298,10 @@ var DawEditorElement = class extends import_lit15.LitElement {
7656
9298
  engine: this._engine,
7657
9299
  dispatchEvent: (e) => this.dispatchEvent(e),
7658
9300
  stop: () => {
7659
- this._engine?.stop();
7660
- this._stopPlayhead();
9301
+ this._withSeekSuppression(() => {
9302
+ this._engine?.stop();
9303
+ this._stopPlayhead();
9304
+ });
7661
9305
  },
7662
9306
  // Call engine.play directly (synchronous) — not the async editor play()
7663
9307
  // which yields to microtask queue via await engine.init(). Engine is
@@ -7744,6 +9388,25 @@ var DawEditorElement = class extends import_lit15.LitElement {
7744
9388
  }
7745
9389
  await this._recordingController.startRecording(s, options);
7746
9390
  }
9391
+ /** Live-recording preview left/width. Beats mode uses the same tick-space
9392
+ * math as finalized clips — the sample÷renderSpp path is ceil-quantized,
9393
+ * so the take would visibly jump sideways on finalization (drift grows
9394
+ * with distance from t=0; CLAUDE.md live-preview parity invariant). */
9395
+ _previewPosition(startSample, audibleSamples) {
9396
+ if (this.scaleMode === "beats") {
9397
+ const sr = this.effectiveSampleRate;
9398
+ const startSec = startSample / sr;
9399
+ const startTick = this._secondsToTicks(startSec);
9400
+ const endTick = this._secondsToTicks(startSec + audibleSamples / sr);
9401
+ const left = Math.round(startTick / this.ticksPerPixel);
9402
+ return { left, width: Math.round(endTick / this.ticksPerPixel) - left };
9403
+ }
9404
+ const renderSpp = this._renderSpp;
9405
+ return {
9406
+ left: Math.floor(startSample / renderSpp),
9407
+ width: Math.floor(audibleSamples / renderSpp)
9408
+ };
9409
+ }
7747
9410
  _renderRecordingPreview(trackId, chH) {
7748
9411
  const rs = this._recordingController.getSession(trackId);
7749
9412
  if (!rs) return "";
@@ -7751,20 +9414,19 @@ var DawEditorElement = class extends import_lit15.LitElement {
7751
9414
  if (audibleSamples === 0) return "";
7752
9415
  const renderSpp = this._renderSpp;
7753
9416
  const latencyPixels = Math.floor(rs.latencySamples / renderSpp);
7754
- const left = Math.floor(rs.startSample / renderSpp);
7755
- const w = Math.floor(audibleSamples / renderSpp);
9417
+ const { left, width: w } = this._previewPosition(rs.startSample, audibleSamples);
7756
9418
  const hdrH = this.clipHeaders ? this.clipHeaderHeight : 0;
7757
9419
  const height = hdrH + chH * rs.peaks.length;
7758
- return import_lit15.html`<div
9420
+ return import_lit19.html`<div
7759
9421
  class="clip-container recording-preview"
7760
9422
  style="left:${left}px;top:0;width:${w}px;height:${height}px;"
7761
9423
  >
7762
- ${hdrH > 0 ? import_lit15.html`<div class="clip-header" data-track-id=${trackId}>
9424
+ ${hdrH > 0 ? import_lit19.html`<div class="clip-header" data-track-id=${trackId}>
7763
9425
  <span>${rs.clipName ?? "Recording\u2026"}</span>
7764
9426
  </div>` : ""}
7765
9427
  ${rs.peaks.map((chPeaks, ch) => {
7766
9428
  const slicedPeaks = latencyPixels > 0 ? chPeaks.slice(latencyPixels * 2) : chPeaks;
7767
- return import_lit15.html`
9429
+ return import_lit19.html`
7768
9430
  <daw-waveform
7769
9431
  data-recording-track=${trackId}
7770
9432
  data-recording-channel=${ch}
@@ -7787,6 +9449,11 @@ var DawEditorElement = class extends import_lit15.LitElement {
7787
9449
  if (!this._engine) return;
7788
9450
  const engine = this._engine;
7789
9451
  this._playbackAnimation.start(() => {
9452
+ if (this._activePlayEndTime !== null && !this.isRecording && engine.getCurrentTime() >= this._activePlayEndTime) {
9453
+ this.stop();
9454
+ const t = this._currentTime;
9455
+ return Number.isFinite(t) ? Math.max(0, t) : 0;
9456
+ }
7790
9457
  if (!this.indefinitePlayback && !this.isRecording && engine.getCurrentTime() >= this._duration) {
7791
9458
  this.stop();
7792
9459
  const t = this._currentTime;
@@ -7854,9 +9521,9 @@ var DawEditorElement = class extends import_lit15.LitElement {
7854
9521
  });
7855
9522
  const showControls = this._showControls;
7856
9523
  const showRuler = this._showRuler;
7857
- return import_lit15.html`
7858
- ${showRuler ? import_lit15.html`<div class="header-row" style="height: ${RULER_HEIGHT}px;">
7859
- ${showControls ? import_lit15.html`<div class="ruler-gap"></div>` : ""}
9524
+ return import_lit19.html`
9525
+ ${showRuler ? import_lit19.html`<div class="header-row" style="height: ${RULER_HEIGHT}px;">
9526
+ ${showControls ? import_lit19.html`<div class="ruler-gap"></div>` : ""}
7860
9527
  <div class="ruler-viewport" @pointerdown=${this._pointer.onPointerDown}>
7861
9528
  <div
7862
9529
  class="ruler-content"
@@ -7877,10 +9544,18 @@ var DawEditorElement = class extends import_lit15.LitElement {
7877
9544
  </div>
7878
9545
  </div>` : ""}
7879
9546
  <div class="body">
7880
- ${showControls ? import_lit15.html`<div class="controls-viewport">
9547
+ ${showControls ? import_lit19.html`<div class="controls-viewport">
7881
9548
  <div class="controls-column">
9549
+ ${this._annotations.tracks.map(
9550
+ (track) => import_lit19.html`<div
9551
+ class="annotation-lane-spacer"
9552
+ style="height: ${ANNOTATION_LANE_HEIGHT}px;"
9553
+ >
9554
+ <span class="annotation-lane-name">${track.name}</span>
9555
+ </div>`
9556
+ )}
7882
9557
  ${orderedTracks.map(
7883
- (t) => import_lit15.html`
9558
+ (t) => import_lit19.html`
7884
9559
  <daw-track-controls
7885
9560
  style="height: ${t.trackHeight}px;"
7886
9561
  .trackId=${t.trackId}
@@ -7904,8 +9579,14 @@ var DawEditorElement = class extends import_lit15.LitElement {
7904
9579
  @dragleave=${this._onDragLeave}
7905
9580
  @drop=${this._onDrop}
7906
9581
  >
7907
- ${this.scaleMode === "beats" ? import_lit15.html`<daw-grid
7908
- style="top: 0px;"
9582
+ ${this._annotations.renderLanes(
9583
+ spp,
9584
+ this.effectiveSampleRate,
9585
+ this._annotationDrag.onPointerDown,
9586
+ this.scaleMode === "beats" ? this.ticksPerPixel : null
9587
+ )}
9588
+ ${this.scaleMode === "beats" ? import_lit19.html`<daw-grid
9589
+ style="top: ${this._annotations.totalLaneHeight}px;"
7909
9590
  .ticksPerPixel=${this.ticksPerPixel}
7910
9591
  .meterEntries=${this._meterEntries}
7911
9592
  .ppqn=${this.ppqn}
@@ -7914,11 +9595,11 @@ var DawEditorElement = class extends import_lit15.LitElement {
7914
9595
  .length=${this._totalWidth}
7915
9596
  .height=${orderedTracks.length > 0 ? orderedTracks.reduce((sum, t) => sum + t.trackHeight, 0) : this._emptyGridHeight}
7916
9597
  ></daw-grid>` : ""}
7917
- ${orderedTracks.length > 0 || this.scaleMode === "beats" || this.indefinitePlayback || this.fillViewport ? import_lit15.html`<daw-selection .startPx=${selStartPx} .endPx=${selEndPx}></daw-selection>
9598
+ ${orderedTracks.length > 0 || this.scaleMode === "beats" || this.indefinitePlayback || this.fillViewport ? import_lit19.html`<daw-selection .startPx=${selStartPx} .endPx=${selEndPx}></daw-selection>
7918
9599
  <daw-playhead></daw-playhead>` : ""}
7919
9600
  ${orderedTracks.map((t) => {
7920
9601
  const channelHeight = this.waveHeight;
7921
- return import_lit15.html`
9602
+ return import_lit19.html`
7922
9603
  <div
7923
9604
  class="track-row ${t.trackId === this._selectedTrackId ? "selected" : ""}"
7924
9605
  style="height: ${t.trackHeight}px;"
@@ -7937,7 +9618,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
7937
9618
  width = Math.round(endTick / this.ticksPerPixel) - clipLeft;
7938
9619
  } else {
7939
9620
  clipLeft = Math.floor(clip.startSample / spp);
7940
- width = (0, import_core9.clipPixelWidth)(clip.startSample, clip.durationSamples, spp);
9621
+ width = (0, import_core13.clipPixelWidth)(clip.startSample, clip.durationSamples, spp);
7941
9622
  }
7942
9623
  let clipSegments;
7943
9624
  let segmentChannels;
@@ -7984,12 +9665,12 @@ var DawEditorElement = class extends import_lit15.LitElement {
7984
9665
  const channels = segmentChannels ?? peakData?.data ?? [new Int16Array(0)];
7985
9666
  const hdrH = this.clipHeaders ? this.clipHeaderHeight : 0;
7986
9667
  const chH = this.waveHeight;
7987
- return import_lit15.html` <div
9668
+ return import_lit19.html` <div
7988
9669
  class="clip-container"
7989
9670
  style="left:${clipLeft}px;top:0;width:${width}px;height:${t.trackHeight}px;"
7990
9671
  data-clip-id=${clip.id}
7991
9672
  >
7992
- ${hdrH > 0 ? import_lit15.html`<div
9673
+ ${hdrH > 0 ? import_lit19.html`<div
7993
9674
  class="clip-header"
7994
9675
  data-clip-id=${clip.id}
7995
9676
  data-track-id=${t.trackId}
@@ -7997,7 +9678,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
7997
9678
  >
7998
9679
  <span>${clip.name || t.descriptor?.name || ""}</span>
7999
9680
  </div>` : ""}
8000
- ${t.descriptor?.renderMode === "piano-roll" ? import_lit15.html`<daw-piano-roll
9681
+ ${t.descriptor?.renderMode === "piano-roll" ? import_lit19.html`<daw-piano-roll
8001
9682
  style="position:absolute;left:0;top:${hdrH}px;"
8002
9683
  .midiNotes=${clip.midiNotes ?? []}
8003
9684
  .length=${peakData?.length ?? width}
@@ -8010,7 +9691,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
8010
9691
  .originX=${clipLeft}
8011
9692
  ?selected=${t.trackId === this._selectedTrackId}
8012
9693
  ></daw-piano-roll>` : t.descriptor?.renderMode === "spectrogram" ? channels.map(
8013
- (_chPeaks, chIdx) => import_lit15.html`<daw-spectrogram
9694
+ (_chPeaks, chIdx) => import_lit19.html`<daw-spectrogram
8014
9695
  style="position:absolute;left:0;top:${hdrH + chIdx * chH}px;height:${chH}px;width:${peakData?.length ?? width}px;"
8015
9696
  .clipId=${clip.id}
8016
9697
  .trackId=${t.trackId}
@@ -8025,7 +9706,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
8025
9706
  .originX=${clipLeft}
8026
9707
  ></daw-spectrogram>`
8027
9708
  ) : channels.map(
8028
- (chPeaks, chIdx) => import_lit15.html` <daw-waveform
9709
+ (chPeaks, chIdx) => import_lit19.html` <daw-waveform
8029
9710
  style="position:absolute;left:0;top:${hdrH + chIdx * chH}px;"
8030
9711
  .peaks=${chPeaks}
8031
9712
  .length=${peakData?.length ?? width}
@@ -8039,7 +9720,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
8039
9720
  .segments=${clipSegments}
8040
9721
  ></daw-waveform>`
8041
9722
  )}
8042
- ${this.interactiveClips ? import_lit15.html` <div
9723
+ ${this.interactiveClips ? import_lit19.html` <div
8043
9724
  class="clip-boundary"
8044
9725
  data-boundary-edge="left"
8045
9726
  data-clip-id=${clip.id}
@@ -8066,7 +9747,7 @@ var DawEditorElement = class extends import_lit15.LitElement {
8066
9747
  };
8067
9748
  DawEditorElement.styles = [
8068
9749
  hostStyles,
8069
- import_lit15.css`
9750
+ import_lit19.css`
8070
9751
  :host {
8071
9752
  display: flex;
8072
9753
  flex-direction: column;
@@ -8137,120 +9818,186 @@ DawEditorElement.styles = [
8137
9818
  outline: 2px dashed var(--daw-selection-color, rgba(99, 199, 95, 0.3));
8138
9819
  outline-offset: -2px;
8139
9820
  }
9821
+ .annotation-lane {
9822
+ position: relative;
9823
+ box-sizing: border-box;
9824
+ border-bottom: 1px solid var(--daw-annotation-lane-border, rgba(255, 255, 255, 0.08));
9825
+ background: var(--daw-annotation-lane-background, rgba(0, 0, 0, 0.15));
9826
+ user-select: none;
9827
+ -webkit-user-drag: none;
9828
+ }
9829
+ .annotation-lane-spacer {
9830
+ box-sizing: border-box;
9831
+ border-bottom: 1px solid var(--daw-annotation-lane-border, rgba(255, 255, 255, 0.08));
9832
+ display: flex;
9833
+ align-items: center;
9834
+ overflow: hidden;
9835
+ }
9836
+ .annotation-lane-name {
9837
+ padding: 0 10px;
9838
+ font-size: 11px;
9839
+ color: var(--daw-controls-text, #e0d4c8);
9840
+ opacity: 0.8;
9841
+ white-space: nowrap;
9842
+ overflow: hidden;
9843
+ text-overflow: ellipsis;
9844
+ }
9845
+ .annotation-box {
9846
+ position: absolute;
9847
+ top: 3px;
9848
+ bottom: 3px;
9849
+ overflow: hidden;
9850
+ display: flex;
9851
+ align-items: center;
9852
+ border: 1px solid var(--daw-annotation-box-border, #c49a6c);
9853
+ border-radius: 3px;
9854
+ background: var(--daw-annotation-box-background, rgba(196, 154, 108, 0.2));
9855
+ color: var(--daw-annotation-text-color, #e0d4c8);
9856
+ font-size: 11px;
9857
+ cursor: pointer;
9858
+ }
9859
+ .annotation-box.playing {
9860
+ box-shadow: inset 0 0 0 1px var(--daw-annotation-box-border, #c49a6c);
9861
+ background: var(--daw-annotation-playing-background, rgba(196, 154, 108, 0.32));
9862
+ }
9863
+ .annotation-box.active {
9864
+ background: var(--daw-annotation-active-background, rgba(196, 154, 108, 0.45));
9865
+ }
9866
+ .annotation-box-text {
9867
+ padding: 0 6px;
9868
+ white-space: nowrap;
9869
+ overflow: hidden;
9870
+ text-overflow: ellipsis;
9871
+ pointer-events: none;
9872
+ }
9873
+ .annotation-boundary {
9874
+ position: absolute;
9875
+ top: 0;
9876
+ bottom: 0;
9877
+ width: 6px;
9878
+ cursor: ew-resize;
9879
+ flex-shrink: 0;
9880
+ }
9881
+ .annotation-boundary[data-edge='start'] {
9882
+ left: 0;
9883
+ }
9884
+ .annotation-boundary[data-edge='end'] {
9885
+ right: 0;
9886
+ }
8140
9887
  `,
8141
9888
  clipStyles
8142
9889
  ];
8143
9890
  DawEditorElement._CONTROL_PROPS = /* @__PURE__ */ new Set(["volume", "pan", "muted", "soloed"]);
8144
9891
  __decorateClass([
8145
- (0, import_decorators13.property)({ type: Number, attribute: "samples-per-pixel", noAccessor: true })
9892
+ (0, import_decorators16.property)({ type: Number, attribute: "samples-per-pixel", noAccessor: true })
8146
9893
  ], DawEditorElement.prototype, "samplesPerPixel", 1);
8147
9894
  __decorateClass([
8148
- (0, import_decorators13.property)({ attribute: "time-format", reflect: true, noAccessor: true })
9895
+ (0, import_decorators16.property)({ attribute: "time-format", reflect: true, noAccessor: true })
8149
9896
  ], DawEditorElement.prototype, "timeFormat", 1);
8150
9897
  __decorateClass([
8151
- (0, import_decorators13.property)({ type: Number, attribute: "wave-height" })
9898
+ (0, import_decorators16.property)({ type: Number, attribute: "wave-height" })
8152
9899
  ], DawEditorElement.prototype, "waveHeight", 2);
8153
9900
  __decorateClass([
8154
- (0, import_decorators13.property)({ type: Boolean })
9901
+ (0, import_decorators16.property)({ type: Boolean })
8155
9902
  ], DawEditorElement.prototype, "timescale", 2);
8156
9903
  __decorateClass([
8157
- (0, import_decorators13.property)({ type: Boolean })
9904
+ (0, import_decorators16.property)({ type: Boolean })
8158
9905
  ], DawEditorElement.prototype, "mono", 2);
8159
9906
  __decorateClass([
8160
- (0, import_decorators13.property)({ type: Number, attribute: "bar-width" })
9907
+ (0, import_decorators16.property)({ type: Number, attribute: "bar-width" })
8161
9908
  ], DawEditorElement.prototype, "barWidth", 2);
8162
9909
  __decorateClass([
8163
- (0, import_decorators13.property)({ type: Number, attribute: "bar-gap" })
9910
+ (0, import_decorators16.property)({ type: Number, attribute: "bar-gap" })
8164
9911
  ], DawEditorElement.prototype, "barGap", 2);
8165
9912
  __decorateClass([
8166
- (0, import_decorators13.property)({ type: Boolean, attribute: "rounded-bars" })
9913
+ (0, import_decorators16.property)({ type: Boolean, attribute: "rounded-bars" })
8167
9914
  ], DawEditorElement.prototype, "roundedBars", 2);
8168
9915
  __decorateClass([
8169
- (0, import_decorators13.property)({ type: Boolean, attribute: "file-drop" })
9916
+ (0, import_decorators16.property)({ type: Boolean, attribute: "file-drop" })
8170
9917
  ], DawEditorElement.prototype, "fileDrop", 2);
8171
9918
  __decorateClass([
8172
- (0, import_decorators13.property)({ type: Boolean, attribute: "clip-headers" })
9919
+ (0, import_decorators16.property)({ type: Boolean, attribute: "clip-headers" })
8173
9920
  ], DawEditorElement.prototype, "clipHeaders", 2);
8174
9921
  __decorateClass([
8175
- (0, import_decorators13.property)({ type: Number, attribute: "clip-header-height" })
9922
+ (0, import_decorators16.property)({ type: Number, attribute: "clip-header-height" })
8176
9923
  ], DawEditorElement.prototype, "clipHeaderHeight", 2);
8177
9924
  __decorateClass([
8178
- (0, import_decorators13.property)({ type: Boolean, attribute: "interactive-clips" })
9925
+ (0, import_decorators16.property)({ type: Boolean, attribute: "interactive-clips" })
8179
9926
  ], DawEditorElement.prototype, "interactiveClips", 2);
8180
9927
  __decorateClass([
8181
- (0, import_decorators13.property)({ type: Boolean, attribute: "indefinite-playback" })
9928
+ (0, import_decorators16.property)({ type: Boolean, attribute: "indefinite-playback" })
8182
9929
  ], DawEditorElement.prototype, "indefinitePlayback", 2);
8183
9930
  __decorateClass([
8184
- (0, import_decorators13.property)({ type: Boolean, attribute: "fill-viewport" })
9931
+ (0, import_decorators16.property)({ type: Boolean, attribute: "fill-viewport" })
8185
9932
  ], DawEditorElement.prototype, "fillViewport", 2);
8186
9933
  __decorateClass([
8187
- (0, import_decorators13.property)({ attribute: false, noAccessor: true })
9934
+ (0, import_decorators16.property)({ attribute: false, noAccessor: true })
8188
9935
  ], DawEditorElement.prototype, "spectrogramConfig", 1);
8189
9936
  __decorateClass([
8190
- (0, import_decorators13.property)({ attribute: false, noAccessor: true })
9937
+ (0, import_decorators16.property)({ attribute: false, noAccessor: true })
8191
9938
  ], DawEditorElement.prototype, "spectrogramColorMap", 1);
8192
9939
  __decorateClass([
8193
- (0, import_decorators13.property)({ type: String, attribute: "scale-mode" })
9940
+ (0, import_decorators16.property)({ type: String, attribute: "scale-mode" })
8194
9941
  ], DawEditorElement.prototype, "scaleMode", 2);
8195
9942
  __decorateClass([
8196
- (0, import_decorators13.property)({ type: Number, attribute: "ticks-per-pixel", noAccessor: true })
9943
+ (0, import_decorators16.property)({ type: Number, attribute: "ticks-per-pixel", noAccessor: true })
8197
9944
  ], DawEditorElement.prototype, "ticksPerPixel", 1);
8198
9945
  __decorateClass([
8199
- (0, import_decorators13.property)({ type: Number, noAccessor: true })
9946
+ (0, import_decorators16.property)({ type: Number, noAccessor: true })
8200
9947
  ], DawEditorElement.prototype, "bpm", 1);
8201
9948
  __decorateClass([
8202
- (0, import_decorators13.property)({ attribute: false })
9949
+ (0, import_decorators16.property)({ attribute: false })
8203
9950
  ], DawEditorElement.prototype, "timeSignature", 2);
8204
9951
  __decorateClass([
8205
- (0, import_decorators13.property)({ attribute: false })
9952
+ (0, import_decorators16.property)({ attribute: false })
8206
9953
  ], DawEditorElement.prototype, "meterEntries", 2);
8207
9954
  __decorateClass([
8208
- (0, import_decorators13.property)({ type: Number, noAccessor: true })
9955
+ (0, import_decorators16.property)({ type: Number, noAccessor: true })
8209
9956
  ], DawEditorElement.prototype, "ppqn", 1);
8210
9957
  __decorateClass([
8211
- (0, import_decorators13.property)({ type: String, attribute: "snap-to" })
9958
+ (0, import_decorators16.property)({ type: String, attribute: "snap-to" })
8212
9959
  ], DawEditorElement.prototype, "snapTo", 2);
8213
9960
  __decorateClass([
8214
- (0, import_decorators13.property)({ attribute: false })
9961
+ (0, import_decorators16.property)({ attribute: false })
8215
9962
  ], DawEditorElement.prototype, "secondsToTicks", 2);
8216
9963
  __decorateClass([
8217
- (0, import_decorators13.property)({ attribute: false })
9964
+ (0, import_decorators16.property)({ attribute: false })
8218
9965
  ], DawEditorElement.prototype, "ticksToSeconds", 2);
8219
9966
  __decorateClass([
8220
- (0, import_decorators13.state)()
9967
+ (0, import_decorators16.state)()
8221
9968
  ], DawEditorElement.prototype, "_tracks", 2);
8222
9969
  __decorateClass([
8223
- (0, import_decorators13.state)()
9970
+ (0, import_decorators16.state)()
8224
9971
  ], DawEditorElement.prototype, "_engineTracks", 2);
8225
9972
  __decorateClass([
8226
- (0, import_decorators13.state)()
9973
+ (0, import_decorators16.state)()
8227
9974
  ], DawEditorElement.prototype, "_peaksData", 2);
8228
9975
  __decorateClass([
8229
- (0, import_decorators13.state)()
9976
+ (0, import_decorators16.state)()
8230
9977
  ], DawEditorElement.prototype, "_isPlaying", 2);
8231
9978
  __decorateClass([
8232
- (0, import_decorators13.state)()
9979
+ (0, import_decorators16.state)()
8233
9980
  ], DawEditorElement.prototype, "_duration", 2);
8234
9981
  __decorateClass([
8235
- (0, import_decorators13.state)()
9982
+ (0, import_decorators16.state)()
8236
9983
  ], DawEditorElement.prototype, "_selectedTrackId", 2);
8237
9984
  __decorateClass([
8238
- (0, import_decorators13.state)()
9985
+ (0, import_decorators16.state)()
8239
9986
  ], DawEditorElement.prototype, "_dragOver", 2);
8240
9987
  __decorateClass([
8241
- (0, import_decorators13.property)({ attribute: false })
9988
+ (0, import_decorators16.property)({ attribute: false })
8242
9989
  ], DawEditorElement.prototype, "adapter", 1);
8243
9990
  __decorateClass([
8244
- (0, import_decorators13.property)({ attribute: "eager-resume" })
9991
+ (0, import_decorators16.property)({ attribute: "eager-resume" })
8245
9992
  ], DawEditorElement.prototype, "eagerResume", 2);
8246
9993
  DawEditorElement = __decorateClass([
8247
- (0, import_decorators13.customElement)("daw-editor")
9994
+ (0, import_decorators16.customElement)("daw-editor")
8248
9995
  ], DawEditorElement);
8249
9996
 
8250
9997
  // src/elements/daw-selection.ts
8251
- var import_lit16 = require("lit");
8252
- var import_decorators14 = require("lit/decorators.js");
8253
- var DawSelectionElement = class extends import_lit16.LitElement {
9998
+ var import_lit20 = require("lit");
9999
+ var import_decorators17 = require("lit/decorators.js");
10000
+ var DawSelectionElement = class extends import_lit20.LitElement {
8254
10001
  constructor() {
8255
10002
  super(...arguments);
8256
10003
  this.startPx = 0;
@@ -8259,11 +10006,11 @@ var DawSelectionElement = class extends import_lit16.LitElement {
8259
10006
  render() {
8260
10007
  const left = Math.min(this.startPx, this.endPx);
8261
10008
  const width = Math.abs(this.endPx - this.startPx);
8262
- if (width === 0) return import_lit16.html``;
8263
- return import_lit16.html`<div style="left: ${left}px; width: ${width}px;"></div>`;
10009
+ if (width === 0) return import_lit20.html``;
10010
+ return import_lit20.html`<div style="left: ${left}px; width: ${width}px;"></div>`;
8264
10011
  }
8265
10012
  };
8266
- DawSelectionElement.styles = import_lit16.css`
10013
+ DawSelectionElement.styles = import_lit20.css`
8267
10014
  :host {
8268
10015
  position: absolute;
8269
10016
  top: 0;
@@ -8280,18 +10027,18 @@ DawSelectionElement.styles = import_lit16.css`
8280
10027
  }
8281
10028
  `;
8282
10029
  __decorateClass([
8283
- (0, import_decorators14.property)({ type: Number, attribute: false })
10030
+ (0, import_decorators17.property)({ type: Number, attribute: false })
8284
10031
  ], DawSelectionElement.prototype, "startPx", 2);
8285
10032
  __decorateClass([
8286
- (0, import_decorators14.property)({ type: Number, attribute: false })
10033
+ (0, import_decorators17.property)({ type: Number, attribute: false })
8287
10034
  ], DawSelectionElement.prototype, "endPx", 2);
8288
10035
  DawSelectionElement = __decorateClass([
8289
- (0, import_decorators14.customElement)("daw-selection")
10036
+ (0, import_decorators17.customElement)("daw-selection")
8290
10037
  ], DawSelectionElement);
8291
10038
 
8292
10039
  // src/elements/daw-record-button.ts
8293
- var import_lit17 = require("lit");
8294
- var import_decorators15 = require("lit/decorators.js");
10040
+ var import_lit21 = require("lit");
10041
+ var import_decorators18 = require("lit/decorators.js");
8295
10042
  var DawRecordButtonElement = class extends DawTransportButton {
8296
10043
  constructor() {
8297
10044
  super(...arguments);
@@ -8340,7 +10087,7 @@ var DawRecordButtonElement = class extends DawTransportButton {
8340
10087
  }
8341
10088
  }
8342
10089
  render() {
8343
- return import_lit17.html`
10090
+ return import_lit21.html`
8344
10091
  <button
8345
10092
  part="button"
8346
10093
  ?disabled=${!this.targetSupported}
@@ -8368,7 +10115,7 @@ DawRecordButtonElement.requiredTargetMethods = [
8368
10115
  ];
8369
10116
  DawRecordButtonElement.styles = [
8370
10117
  DawTransportButton.styles,
8371
- import_lit17.css`
10118
+ import_lit21.css`
8372
10119
  button[data-recording] {
8373
10120
  color: #d08070;
8374
10121
  border-color: #d08070;
@@ -8377,28 +10124,33 @@ DawRecordButtonElement.styles = [
8377
10124
  `
8378
10125
  ];
8379
10126
  __decorateClass([
8380
- (0, import_decorators15.state)()
10127
+ (0, import_decorators18.state)()
8381
10128
  ], DawRecordButtonElement.prototype, "_isRecording", 2);
8382
10129
  DawRecordButtonElement = __decorateClass([
8383
- (0, import_decorators15.customElement)("daw-record-button")
10130
+ (0, import_decorators18.customElement)("daw-record-button")
8384
10131
  ], DawRecordButtonElement);
8385
10132
 
8386
10133
  // src/elements/daw-keyboard-shortcuts.ts
8387
- var import_lit18 = require("lit");
8388
- var import_decorators16 = require("lit/decorators.js");
8389
- var import_core10 = require("@waveform-playlist/core");
8390
- var DawKeyboardShortcutsElement = class extends import_lit18.LitElement {
10134
+ var import_lit22 = require("lit");
10135
+ var import_decorators19 = require("lit/decorators.js");
10136
+ var import_core14 = require("@waveform-playlist/core");
10137
+ var DawKeyboardShortcutsElement = class extends import_lit22.LitElement {
8391
10138
  constructor() {
8392
10139
  super(...arguments);
8393
10140
  this.playback = false;
8394
10141
  this.splitting = false;
8395
10142
  this.undo = false;
8396
10143
  // --- JS properties for remapping ---
8397
- this.playbackShortcuts = null;
8398
- this.splittingShortcuts = null;
8399
- this.undoShortcuts = null;
10144
+ // Accessors, not plain fields: assigning a remap after any keydown has
10145
+ // warmed _cachedShortcuts must invalidate it, or the documented remapping
10146
+ // API is silently ignored until an unrelated boolean attribute toggles.
10147
+ // (connectedCallback runs the standard upgrade-property dance so values
10148
+ // assigned BEFORE the element was defined don't shadow these accessors.)
10149
+ this._playbackShortcuts = null;
10150
+ this._splittingShortcuts = null;
10151
+ this._undoShortcuts = null;
8400
10152
  /** Additional custom shortcuts. */
8401
- this.customShortcuts = [];
10153
+ this._customShortcuts = [];
8402
10154
  this._editor = null;
8403
10155
  this._cachedShortcuts = null;
8404
10156
  // --- Event handler ---
@@ -8406,7 +10158,7 @@ var DawKeyboardShortcutsElement = class extends import_lit18.LitElement {
8406
10158
  const shortcuts = this.shortcuts;
8407
10159
  if (shortcuts.length === 0) return;
8408
10160
  try {
8409
- (0, import_core10.handleKeyboardEvent)(e, shortcuts, true);
10161
+ (0, import_core14.handleKeyboardEvent)(e, shortcuts, true);
8410
10162
  } catch (err) {
8411
10163
  console.warn("[dawcore] Keyboard shortcut failed (key=" + e.key + "): " + String(err));
8412
10164
  const target = this._editor ?? this;
@@ -8420,6 +10172,34 @@ var DawKeyboardShortcutsElement = class extends import_lit18.LitElement {
8420
10172
  }
8421
10173
  };
8422
10174
  }
10175
+ get playbackShortcuts() {
10176
+ return this._playbackShortcuts;
10177
+ }
10178
+ set playbackShortcuts(value) {
10179
+ this._playbackShortcuts = value;
10180
+ this._cachedShortcuts = null;
10181
+ }
10182
+ get splittingShortcuts() {
10183
+ return this._splittingShortcuts;
10184
+ }
10185
+ set splittingShortcuts(value) {
10186
+ this._splittingShortcuts = value;
10187
+ this._cachedShortcuts = null;
10188
+ }
10189
+ get undoShortcuts() {
10190
+ return this._undoShortcuts;
10191
+ }
10192
+ set undoShortcuts(value) {
10193
+ this._undoShortcuts = value;
10194
+ this._cachedShortcuts = null;
10195
+ }
10196
+ get customShortcuts() {
10197
+ return this._customShortcuts;
10198
+ }
10199
+ set customShortcuts(value) {
10200
+ this._customShortcuts = value;
10201
+ this._cachedShortcuts = null;
10202
+ }
8423
10203
  /** All active shortcuts (read-only, cached). */
8424
10204
  get shortcuts() {
8425
10205
  if (!this._cachedShortcuts) {
@@ -8434,6 +10214,18 @@ var DawKeyboardShortcutsElement = class extends import_lit18.LitElement {
8434
10214
  // --- Lifecycle ---
8435
10215
  connectedCallback() {
8436
10216
  super.connectedCallback();
10217
+ for (const prop of [
10218
+ "playbackShortcuts",
10219
+ "splittingShortcuts",
10220
+ "undoShortcuts",
10221
+ "customShortcuts"
10222
+ ]) {
10223
+ if (Object.prototype.hasOwnProperty.call(this, prop)) {
10224
+ const value = this[prop];
10225
+ delete this[prop];
10226
+ this[prop] = value;
10227
+ }
10228
+ }
8437
10229
  this._editor = this.closest("daw-editor");
8438
10230
  if (!this._editor) {
8439
10231
  console.warn(
@@ -8541,23 +10333,23 @@ var DawKeyboardShortcutsElement = class extends import_lit18.LitElement {
8541
10333
  }
8542
10334
  };
8543
10335
  __decorateClass([
8544
- (0, import_decorators16.property)({ type: Boolean })
10336
+ (0, import_decorators19.property)({ type: Boolean })
8545
10337
  ], DawKeyboardShortcutsElement.prototype, "playback", 2);
8546
10338
  __decorateClass([
8547
- (0, import_decorators16.property)({ type: Boolean })
10339
+ (0, import_decorators19.property)({ type: Boolean })
8548
10340
  ], DawKeyboardShortcutsElement.prototype, "splitting", 2);
8549
10341
  __decorateClass([
8550
- (0, import_decorators16.property)({ type: Boolean })
10342
+ (0, import_decorators19.property)({ type: Boolean })
8551
10343
  ], DawKeyboardShortcutsElement.prototype, "undo", 2);
8552
10344
  DawKeyboardShortcutsElement = __decorateClass([
8553
- (0, import_decorators16.customElement)("daw-keyboard-shortcuts")
10345
+ (0, import_decorators19.customElement)("daw-keyboard-shortcuts")
8554
10346
  ], DawKeyboardShortcutsElement);
8555
10347
 
8556
10348
  // src/elements/daw-spectrogram.ts
8557
- var import_lit19 = require("lit");
8558
- var import_decorators17 = require("lit/decorators.js");
8559
- var import_core11 = require("@waveform-playlist/core");
8560
- var DawSpectrogramElement = class extends import_lit19.LitElement {
10349
+ var import_lit23 = require("lit");
10350
+ var import_decorators20 = require("lit/decorators.js");
10351
+ var import_core15 = require("@waveform-playlist/core");
10352
+ var DawSpectrogramElement = class extends import_lit23.LitElement {
8561
10353
  constructor() {
8562
10354
  super(...arguments);
8563
10355
  this.clipId = "";
@@ -8621,11 +10413,11 @@ var DawSpectrogramElement = class extends import_lit19.LitElement {
8621
10413
  this._unregisterAllCanvases();
8622
10414
  this._canvases = [];
8623
10415
  if (this.length <= 0) return;
8624
- const chunkCount = Math.ceil(this.length / import_core11.MAX_CANVAS_WIDTH);
10416
+ const chunkCount = Math.ceil(this.length / import_core15.MAX_CANVAS_WIDTH);
8625
10417
  for (let i = 0; i < chunkCount; i++) {
8626
- const widthPx = Math.min(import_core11.MAX_CANVAS_WIDTH, this.length - i * import_core11.MAX_CANVAS_WIDTH);
10418
+ const widthPx = Math.min(import_core15.MAX_CANVAS_WIDTH, this.length - i * import_core15.MAX_CANVAS_WIDTH);
8627
10419
  const canvas = document.createElement("canvas");
8628
- canvas.style.left = i * import_core11.MAX_CANVAS_WIDTH + "px";
10420
+ canvas.style.left = i * import_core15.MAX_CANVAS_WIDTH + "px";
8629
10421
  canvas.style.width = widthPx + "px";
8630
10422
  const dpr = window.devicePixelRatio || 1;
8631
10423
  canvas.width = widthPx * dpr;
@@ -8651,7 +10443,7 @@ var DawSpectrogramElement = class extends import_lit19.LitElement {
8651
10443
  }
8652
10444
  for (let i = 0; i < this._canvases.length; i++) {
8653
10445
  const canvas = this._canvases[i];
8654
- const canvasId = (0, import_core11.buildSpectrogramCanvasId)({
10446
+ const canvasId = (0, import_core15.buildSpectrogramCanvasId)({
8655
10447
  clipId: this.clipId,
8656
10448
  channelIndex: this.channelIndex,
8657
10449
  chunkIndex: i
@@ -8672,7 +10464,7 @@ var DawSpectrogramElement = class extends import_lit19.LitElement {
8672
10464
  trackId: this.trackId,
8673
10465
  channelIndex: this.channelIndex,
8674
10466
  chunkIndex: i,
8675
- globalPixelOffset: this.originX + i * import_core11.MAX_CANVAS_WIDTH,
10467
+ globalPixelOffset: this.originX + i * import_core15.MAX_CANVAS_WIDTH,
8676
10468
  widthPx: parseFloat(canvas.style.width),
8677
10469
  heightPx: this.waveHeight
8678
10470
  });
@@ -8693,10 +10485,10 @@ var DawSpectrogramElement = class extends import_lit19.LitElement {
8693
10485
  this._unregisterAllCanvases();
8694
10486
  }
8695
10487
  render() {
8696
- return import_lit19.html`${this._canvases.map((c) => c)}`;
10488
+ return import_lit23.html`${this._canvases.map((c) => c)}`;
8697
10489
  }
8698
10490
  };
8699
- DawSpectrogramElement.styles = import_lit19.css`
10491
+ DawSpectrogramElement.styles = import_lit23.css`
8700
10492
  :host {
8701
10493
  display: block;
8702
10494
  position: relative;
@@ -8711,46 +10503,46 @@ DawSpectrogramElement.styles = import_lit19.css`
8711
10503
  }
8712
10504
  `;
8713
10505
  __decorateClass([
8714
- (0, import_decorators17.property)({ attribute: false })
10506
+ (0, import_decorators20.property)({ attribute: false })
8715
10507
  ], DawSpectrogramElement.prototype, "clipId", 2);
8716
10508
  __decorateClass([
8717
- (0, import_decorators17.property)({ attribute: false })
10509
+ (0, import_decorators20.property)({ attribute: false })
8718
10510
  ], DawSpectrogramElement.prototype, "trackId", 2);
8719
10511
  __decorateClass([
8720
- (0, import_decorators17.property)({ type: Number, attribute: false })
10512
+ (0, import_decorators20.property)({ type: Number, attribute: false })
8721
10513
  ], DawSpectrogramElement.prototype, "channelIndex", 2);
8722
10514
  __decorateClass([
8723
- (0, import_decorators17.property)({ type: Number, attribute: false })
10515
+ (0, import_decorators20.property)({ type: Number, attribute: false })
8724
10516
  ], DawSpectrogramElement.prototype, "length", 2);
8725
10517
  __decorateClass([
8726
- (0, import_decorators17.property)({ type: Number, attribute: false })
10518
+ (0, import_decorators20.property)({ type: Number, attribute: false })
8727
10519
  ], DawSpectrogramElement.prototype, "waveHeight", 2);
8728
10520
  __decorateClass([
8729
- (0, import_decorators17.property)({ type: Number, attribute: false, noAccessor: true })
10521
+ (0, import_decorators20.property)({ type: Number, attribute: false, noAccessor: true })
8730
10522
  ], DawSpectrogramElement.prototype, "samplesPerPixel", 1);
8731
10523
  __decorateClass([
8732
- (0, import_decorators17.property)({ type: Number, attribute: false, noAccessor: true })
10524
+ (0, import_decorators20.property)({ type: Number, attribute: false, noAccessor: true })
8733
10525
  ], DawSpectrogramElement.prototype, "sampleRate", 1);
8734
10526
  __decorateClass([
8735
- (0, import_decorators17.property)({ type: Number, attribute: false })
10527
+ (0, import_decorators20.property)({ type: Number, attribute: false })
8736
10528
  ], DawSpectrogramElement.prototype, "clipOffsetSeconds", 2);
8737
10529
  __decorateClass([
8738
- (0, import_decorators17.property)({ type: Number, attribute: false })
10530
+ (0, import_decorators20.property)({ type: Number, attribute: false })
8739
10531
  ], DawSpectrogramElement.prototype, "visibleStart", 2);
8740
10532
  __decorateClass([
8741
- (0, import_decorators17.property)({ type: Number, attribute: false })
10533
+ (0, import_decorators20.property)({ type: Number, attribute: false })
8742
10534
  ], DawSpectrogramElement.prototype, "visibleEnd", 2);
8743
10535
  __decorateClass([
8744
- (0, import_decorators17.property)({ type: Number, attribute: false })
10536
+ (0, import_decorators20.property)({ type: Number, attribute: false })
8745
10537
  ], DawSpectrogramElement.prototype, "originX", 2);
8746
10538
  DawSpectrogramElement = __decorateClass([
8747
- (0, import_decorators17.customElement)("daw-spectrogram")
10539
+ (0, import_decorators20.customElement)("daw-spectrogram")
8748
10540
  ], DawSpectrogramElement);
8749
10541
 
8750
10542
  // src/elements/daw-time-display.ts
8751
- var import_lit20 = require("lit");
8752
- var import_decorators18 = require("lit/decorators.js");
8753
- var DawTimeDisplayElement = class extends import_lit20.LitElement {
10543
+ var import_lit24 = require("lit");
10544
+ var import_decorators21 = require("lit/decorators.js");
10545
+ var DawTimeDisplayElement = class extends import_lit24.LitElement {
8754
10546
  constructor() {
8755
10547
  super(...arguments);
8756
10548
  this._time = null;
@@ -8803,10 +10595,10 @@ var DawTimeDisplayElement = class extends import_lit20.LitElement {
8803
10595
  }
8804
10596
  render() {
8805
10597
  const text = this._time === null ? "--:--:--" : formatDisplayTime(this._time, this._format);
8806
- return import_lit20.html`<span role="status" aria-label="Playback time" aria-live="off">${text}</span>`;
10598
+ return import_lit24.html`<span role="status" aria-label="Playback time" aria-live="off">${text}</span>`;
8807
10599
  }
8808
10600
  };
8809
- DawTimeDisplayElement.styles = import_lit20.css`
10601
+ DawTimeDisplayElement.styles = import_lit24.css`
8810
10602
  span {
8811
10603
  display: inline-block;
8812
10604
  font-family: ui-monospace, 'SF Mono', Menlo, Consolas, monospace;
@@ -8818,19 +10610,19 @@ DawTimeDisplayElement.styles = import_lit20.css`
8818
10610
  }
8819
10611
  `;
8820
10612
  __decorateClass([
8821
- (0, import_decorators18.state)()
10613
+ (0, import_decorators21.state)()
8822
10614
  ], DawTimeDisplayElement.prototype, "_time", 2);
8823
10615
  __decorateClass([
8824
- (0, import_decorators18.state)()
10616
+ (0, import_decorators21.state)()
8825
10617
  ], DawTimeDisplayElement.prototype, "_format", 2);
8826
10618
  DawTimeDisplayElement = __decorateClass([
8827
- (0, import_decorators18.customElement)("daw-time-display")
10619
+ (0, import_decorators21.customElement)("daw-time-display")
8828
10620
  ], DawTimeDisplayElement);
8829
10621
 
8830
10622
  // src/elements/daw-time-format.ts
8831
- var import_lit21 = require("lit");
8832
- var import_decorators19 = require("lit/decorators.js");
8833
- var DawTimeFormatElement = class extends import_lit21.LitElement {
10623
+ var import_lit25 = require("lit");
10624
+ var import_decorators22 = require("lit/decorators.js");
10625
+ var DawTimeFormatElement = class extends import_lit25.LitElement {
8834
10626
  constructor() {
8835
10627
  super(...arguments);
8836
10628
  this._format = "hh:mm:ss.sss";
@@ -8905,20 +10697,20 @@ var DawTimeFormatElement = class extends import_lit21.LitElement {
8905
10697
  target.setTimeFormat?.(value);
8906
10698
  }
8907
10699
  render() {
8908
- return import_lit21.html`
10700
+ return import_lit25.html`
8909
10701
  <select
8910
10702
  aria-label="Time format"
8911
10703
  ?disabled=${!this._targetSupported}
8912
10704
  @change=${this._onSelectChange}
8913
10705
  >
8914
10706
  ${TIME_DISPLAY_FORMATS.map(
8915
- (f) => import_lit21.html`<option value=${f} ?selected=${f === this._format}>${f}</option>`
10707
+ (f) => import_lit25.html`<option value=${f} ?selected=${f === this._format}>${f}</option>`
8916
10708
  )}
8917
10709
  </select>
8918
10710
  `;
8919
10711
  }
8920
10712
  };
8921
- DawTimeFormatElement.styles = import_lit21.css`
10713
+ DawTimeFormatElement.styles = import_lit25.css`
8922
10714
  select {
8923
10715
  cursor: pointer;
8924
10716
  background: var(--daw-controls-background, #1a1a2e);
@@ -8933,20 +10725,20 @@ DawTimeFormatElement.styles = import_lit21.css`
8933
10725
  }
8934
10726
  `;
8935
10727
  __decorateClass([
8936
- (0, import_decorators19.state)()
10728
+ (0, import_decorators22.state)()
8937
10729
  ], DawTimeFormatElement.prototype, "_format", 2);
8938
10730
  DawTimeFormatElement = __decorateClass([
8939
- (0, import_decorators19.customElement)("daw-time-format")
10731
+ (0, import_decorators22.customElement)("daw-time-format")
8940
10732
  ], DawTimeFormatElement);
8941
10733
 
8942
10734
  // src/elements/daw-player.ts
8943
- var import_lit22 = require("lit");
8944
- var import_decorators20 = require("lit/decorators.js");
10735
+ var import_lit26 = require("lit");
10736
+ var import_decorators23 = require("lit/decorators.js");
8945
10737
  var import_repeat = require("lit/directives/repeat.js");
8946
10738
  var import_media_element_playout = require("@waveform-playlist/media-element-playout");
8947
10739
  var MIN_RATE = 0.25;
8948
10740
  var MAX_RATE = 4;
8949
- var DawPlayerElement = class extends import_lit22.LitElement {
10741
+ var DawPlayerElement = class extends import_lit26.LitElement {
8950
10742
  constructor() {
8951
10743
  super(...arguments);
8952
10744
  this.src = "";
@@ -8959,6 +10751,9 @@ var DawPlayerElement = class extends import_lit22.LitElement {
8959
10751
  this.roundedBars = false;
8960
10752
  this._playbackRate = 1;
8961
10753
  this._engine = new import_media_element_playout.MediaElementPlayout();
10754
+ /** Set by disconnectedCallback — a reconnect (DOM reparent, framework
10755
+ * re-render) must rebuild the engine + track or the player is dead. */
10756
+ this._engineDisposed = false;
8962
10757
  this._trackId = null;
8963
10758
  this._anim = new AnimationController(this);
8964
10759
  this._metadataLoaded = false;
@@ -8976,7 +10771,6 @@ var DawPlayerElement = class extends import_lit22.LitElement {
8976
10771
  if (width <= 0 || d <= 0) return;
8977
10772
  const ratio = Math.max(0, Math.min(1, e.offsetX / width));
8978
10773
  this.seekTo(ratio * d);
8979
- this._updatePlayhead();
8980
10774
  };
8981
10775
  this._onLoadedMetadata = () => {
8982
10776
  this._metadataLoaded = true;
@@ -9024,6 +10818,15 @@ var DawPlayerElement = class extends import_lit22.LitElement {
9024
10818
  }
9025
10819
  connectedCallback() {
9026
10820
  super.connectedCallback();
10821
+ let rebuilt = false;
10822
+ if (this._engineDisposed) {
10823
+ const volume = this._engine.masterVolume;
10824
+ this._engine = new import_media_element_playout.MediaElementPlayout();
10825
+ this._engine.setMasterVolume(volume);
10826
+ this._engineDisposed = false;
10827
+ this._trackId = null;
10828
+ rebuilt = true;
10829
+ }
9027
10830
  this._engine.on("loadedmetadata", this._onLoadedMetadata);
9028
10831
  this._engine.on("play", this._onPlay);
9029
10832
  this._engine.on("pause", this._onPause);
@@ -9034,13 +10837,17 @@ var DawPlayerElement = class extends import_lit22.LitElement {
9034
10837
  const area = this.shadowRoot?.querySelector(".waveform-area");
9035
10838
  if (area) this._resizeObserver?.observe(area);
9036
10839
  });
10840
+ if (rebuilt && this.src) {
10841
+ this._loadSource();
10842
+ this._playhead?.setPosition(0);
10843
+ }
9037
10844
  }
9038
10845
  render() {
9039
10846
  const width = this._timelineWidth;
9040
10847
  const channels = this._channelPeaks.length;
9041
10848
  const channelHeight = channels > 0 ? this.waveHeight / channels : this.waveHeight;
9042
- return import_lit22.html`
9043
- ${this.timescale ? import_lit22.html`<daw-ruler
10849
+ return import_lit26.html`
10850
+ ${this.timescale ? import_lit26.html`<daw-ruler
9044
10851
  .samplesPerPixel=${this._channelSpp(width)}
9045
10852
  .sampleRate=${this._sampleRate}
9046
10853
  .duration=${this._engine.duration}
@@ -9054,7 +10861,7 @@ var DawPlayerElement = class extends import_lit22.LitElement {
9054
10861
  ${(0, import_repeat.repeat)(
9055
10862
  this._channelPeaks,
9056
10863
  (_p, i) => i,
9057
- (peaks) => import_lit22.html`<daw-waveform
10864
+ (peaks) => import_lit26.html`<daw-waveform
9058
10865
  .peaks=${peaks}
9059
10866
  .length=${width}
9060
10867
  .waveHeight=${channelHeight}
@@ -9093,6 +10900,7 @@ var DawPlayerElement = class extends import_lit22.LitElement {
9093
10900
  this._renderWaveform();
9094
10901
  this._maybeDispatchReady();
9095
10902
  } catch (err) {
10903
+ if (this.peaksSrc !== requested) return;
9096
10904
  console.warn("[dawcore] <daw-player> failed to load peaks-src: " + String(err));
9097
10905
  this._peaksSettled = true;
9098
10906
  this._renderWaveform();
@@ -9133,7 +10941,7 @@ var DawPlayerElement = class extends import_lit22.LitElement {
9133
10941
  }
9134
10942
  // --- Transport methods ---
9135
10943
  play() {
9136
- this._engine.play();
10944
+ this._engine.resume();
9137
10945
  }
9138
10946
  pause() {
9139
10947
  this._engine.pause();
@@ -9146,6 +10954,10 @@ var DawPlayerElement = class extends import_lit22.LitElement {
9146
10954
  }
9147
10955
  seekTo(time) {
9148
10956
  this._engine.seekTo(time);
10957
+ if (!this._engine.isPlaying) {
10958
+ this._updatePlayhead();
10959
+ this._dispatch("daw-timeupdate", { time: this._engine.getCurrentTime() });
10960
+ }
9149
10961
  }
9150
10962
  setPlaybackRate(rate) {
9151
10963
  this.playbackRate = rate;
@@ -9164,7 +10976,7 @@ var DawPlayerElement = class extends import_lit22.LitElement {
9164
10976
  return this._engine.getCurrentTime();
9165
10977
  }
9166
10978
  set currentTime(time) {
9167
- this._engine.seekTo(time);
10979
+ this.seekTo(time);
9168
10980
  }
9169
10981
  get volume() {
9170
10982
  return this._engine.masterVolume;
@@ -9186,6 +10998,7 @@ var DawPlayerElement = class extends import_lit22.LitElement {
9186
10998
  this._engine.off("ended", this._onEnded);
9187
10999
  this._engine.off("error", this._onError);
9188
11000
  this._engine.dispose();
11001
+ this._engineDisposed = true;
9189
11002
  }
9190
11003
  // --- Private event handlers (arrow fields for stable identity) ---
9191
11004
  _dispatch(name, detail) {
@@ -9211,7 +11024,7 @@ var DawPlayerElement = class extends import_lit22.LitElement {
9211
11024
  return this.shadowRoot?.querySelector(".waveform-area")?.clientWidth ?? 0;
9212
11025
  }
9213
11026
  };
9214
- DawPlayerElement.styles = import_lit22.css`
11027
+ DawPlayerElement.styles = import_lit26.css`
9215
11028
  :host {
9216
11029
  display: block;
9217
11030
  position: relative;
@@ -9224,42 +11037,46 @@ DawPlayerElement.styles = import_lit22.css`
9224
11037
  }
9225
11038
  `;
9226
11039
  __decorateClass([
9227
- (0, import_decorators20.property)({ type: String })
11040
+ (0, import_decorators23.property)({ type: String })
9228
11041
  ], DawPlayerElement.prototype, "src", 2);
9229
11042
  __decorateClass([
9230
- (0, import_decorators20.property)({ type: String, attribute: "peaks-src" })
11043
+ (0, import_decorators23.property)({ type: String, attribute: "peaks-src" })
9231
11044
  ], DawPlayerElement.prototype, "peaksSrc", 2);
9232
11045
  __decorateClass([
9233
- (0, import_decorators20.property)({ type: Number, attribute: "wave-height" })
11046
+ (0, import_decorators23.property)({ type: Number, attribute: "wave-height" })
9234
11047
  ], DawPlayerElement.prototype, "waveHeight", 2);
9235
11048
  __decorateClass([
9236
- (0, import_decorators20.property)({ type: Boolean })
11049
+ (0, import_decorators23.property)({ type: Boolean })
9237
11050
  ], DawPlayerElement.prototype, "timescale", 2);
9238
11051
  __decorateClass([
9239
- (0, import_decorators20.property)({ type: Boolean })
11052
+ (0, import_decorators23.property)({ type: Boolean })
9240
11053
  ], DawPlayerElement.prototype, "mono", 2);
9241
11054
  __decorateClass([
9242
- (0, import_decorators20.property)({ type: Number, attribute: "bar-width" })
11055
+ (0, import_decorators23.property)({ type: Number, attribute: "bar-width" })
9243
11056
  ], DawPlayerElement.prototype, "barWidth", 2);
9244
11057
  __decorateClass([
9245
- (0, import_decorators20.property)({ type: Number, attribute: "bar-gap" })
11058
+ (0, import_decorators23.property)({ type: Number, attribute: "bar-gap" })
9246
11059
  ], DawPlayerElement.prototype, "barGap", 2);
9247
11060
  __decorateClass([
9248
- (0, import_decorators20.property)({ type: Boolean, attribute: "rounded-bars" })
11061
+ (0, import_decorators23.property)({ type: Boolean, attribute: "rounded-bars" })
9249
11062
  ], DawPlayerElement.prototype, "roundedBars", 2);
9250
11063
  __decorateClass([
9251
- (0, import_decorators20.property)({ type: Number, attribute: "playback-rate", noAccessor: true })
11064
+ (0, import_decorators23.property)({ type: Number, attribute: "playback-rate", noAccessor: true })
9252
11065
  ], DawPlayerElement.prototype, "playbackRate", 1);
9253
11066
  __decorateClass([
9254
- (0, import_decorators20.state)()
11067
+ (0, import_decorators23.state)()
9255
11068
  ], DawPlayerElement.prototype, "_channelPeaks", 2);
9256
11069
  DawPlayerElement = __decorateClass([
9257
- (0, import_decorators20.customElement)("daw-player")
11070
+ (0, import_decorators23.customElement)("daw-player")
9258
11071
  ], DawPlayerElement);
9259
11072
  // Annotate the CommonJS export names for ESM import in node:
9260
11073
  0 && (module.exports = {
11074
+ ANNOTATION_LANE_HEIGHT,
9261
11075
  AudioResumeController,
9262
11076
  ClipPointerHandler,
11077
+ DawAnnotationElement,
11078
+ DawAnnotationListElement,
11079
+ DawAnnotationTrackElement,
9263
11080
  DawClipElement,
9264
11081
  DawEditorElement,
9265
11082
  DawGridElement,