@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.mjs CHANGED
@@ -9,10 +9,823 @@ var __decorateClass = (decorators, target, key, kind) => {
9
9
  return result;
10
10
  };
11
11
 
12
- // src/elements/daw-clip.ts
12
+ // src/elements/daw-annotation.ts
13
13
  import { LitElement } from "lit";
14
14
  import { customElement, property } from "lit/decorators.js";
15
- var DawClipElement = class extends LitElement {
15
+ function isValidTick(value) {
16
+ return Number.isFinite(value) && Number.isInteger(value) && value >= 0;
17
+ }
18
+ var DawAnnotationElement = class extends LitElement {
19
+ constructor() {
20
+ super(...arguments);
21
+ this._start = 0;
22
+ this._end = 0;
23
+ this._startTick = null;
24
+ this._endTick = null;
25
+ this._warnedHalfTick = false;
26
+ this._generatedId = "annotation-" + crypto.randomUUID();
27
+ this._hasRendered = false;
28
+ }
29
+ get start() {
30
+ return this._start;
31
+ }
32
+ set start(value) {
33
+ if (!Number.isFinite(value) || value < 0) {
34
+ console.warn("[dawcore] daw-annotation start " + String(value) + " is invalid \u2014 ignored");
35
+ return;
36
+ }
37
+ const old = this._start;
38
+ this._start = value;
39
+ this.requestUpdate("start", old);
40
+ }
41
+ get end() {
42
+ return this._end;
43
+ }
44
+ set end(value) {
45
+ if (!Number.isFinite(value) || value < 0) {
46
+ console.warn("[dawcore] daw-annotation end " + String(value) + " is invalid \u2014 ignored");
47
+ return;
48
+ }
49
+ const old = this._end;
50
+ this._end = value;
51
+ this.requestUpdate("end", old);
52
+ }
53
+ get startTick() {
54
+ return this._startTick;
55
+ }
56
+ set startTick(value) {
57
+ const old = this._startTick;
58
+ if (value === null) {
59
+ this._startTick = null;
60
+ this.requestUpdate("startTick", old);
61
+ return;
62
+ }
63
+ if (!isValidTick(value)) {
64
+ console.warn(
65
+ "[dawcore] daw-annotation start-tick " + String(value) + " is invalid \u2014 ignored"
66
+ );
67
+ return;
68
+ }
69
+ this._startTick = value;
70
+ this.requestUpdate("startTick", old);
71
+ }
72
+ get endTick() {
73
+ return this._endTick;
74
+ }
75
+ set endTick(value) {
76
+ const old = this._endTick;
77
+ if (value === null) {
78
+ this._endTick = null;
79
+ this.requestUpdate("endTick", old);
80
+ return;
81
+ }
82
+ if (!isValidTick(value)) {
83
+ console.warn("[dawcore] daw-annotation end-tick " + String(value) + " is invalid \u2014 ignored");
84
+ return;
85
+ }
86
+ this._endTick = value;
87
+ this.requestUpdate("endTick", old);
88
+ }
89
+ /** Tick-based iff BOTH tick attributes are set (authority rule). */
90
+ get isTickBased() {
91
+ return this._startTick !== null && this._endTick !== null;
92
+ }
93
+ /** Stable identity: the id attribute when present, else a generated UUID. */
94
+ get annotationId() {
95
+ return this.id || this._generatedId;
96
+ }
97
+ toAnnotationData() {
98
+ const text = this.textContent?.trim() ?? "";
99
+ const data = {
100
+ id: this.annotationId,
101
+ start: this.start,
102
+ end: this.end,
103
+ lines: text.length > 0 ? text.split("\n") : [""]
104
+ };
105
+ if (this.isTickBased) {
106
+ data.startTick = this._startTick;
107
+ data.endTick = this._endTick;
108
+ }
109
+ return data;
110
+ }
111
+ // Light DOM — data container only.
112
+ createRenderRoot() {
113
+ return this;
114
+ }
115
+ connectedCallback() {
116
+ super.connectedCallback();
117
+ this.style.display = "none";
118
+ setTimeout(() => {
119
+ this.dispatchEvent(
120
+ new CustomEvent("daw-annotation-connected", {
121
+ bubbles: true,
122
+ composed: true,
123
+ detail: { annotationId: this.annotationId, element: this }
124
+ })
125
+ );
126
+ }, 0);
127
+ }
128
+ updated(changed) {
129
+ const halfTick = this._startTick !== null !== (this._endTick !== null);
130
+ if (halfTick && !this._warnedHalfTick) {
131
+ this._warnedHalfTick = true;
132
+ console.warn(
133
+ '[dawcore] daw-annotation "' + this.annotationId + '": only one of start-tick/end-tick is set \u2014 treated as seconds-based until both are present'
134
+ );
135
+ }
136
+ if (!this._hasRendered) {
137
+ this._hasRendered = true;
138
+ return;
139
+ }
140
+ if (changed.has("start") || changed.has("end") || changed.has("startTick") || changed.has("endTick")) {
141
+ this.dispatchEvent(
142
+ new CustomEvent("daw-annotation-update", {
143
+ bubbles: true,
144
+ composed: true,
145
+ detail: { annotationId: this.annotationId }
146
+ })
147
+ );
148
+ }
149
+ }
150
+ };
151
+ __decorateClass([
152
+ property({ type: Number, noAccessor: true, reflect: true })
153
+ ], DawAnnotationElement.prototype, "start", 1);
154
+ __decorateClass([
155
+ property({ type: Number, noAccessor: true, reflect: true })
156
+ ], DawAnnotationElement.prototype, "end", 1);
157
+ __decorateClass([
158
+ property({ type: Number, noAccessor: true, reflect: true, attribute: "start-tick" })
159
+ ], DawAnnotationElement.prototype, "startTick", 1);
160
+ __decorateClass([
161
+ property({ type: Number, noAccessor: true, reflect: true, attribute: "end-tick" })
162
+ ], DawAnnotationElement.prototype, "endTick", 1);
163
+ DawAnnotationElement = __decorateClass([
164
+ customElement("daw-annotation")
165
+ ], DawAnnotationElement);
166
+
167
+ // src/elements/daw-annotation-track.ts
168
+ import { LitElement as LitElement2 } from "lit";
169
+ import { customElement as customElement2, property as property2 } from "lit/decorators.js";
170
+ import {
171
+ updateAnnotationBoundaries,
172
+ resolveAnnotationShortcuts,
173
+ matchesKeyBinding,
174
+ ANNOTATION_LINK_THRESHOLD_TICKS,
175
+ annotationMinDurationTicks
176
+ } from "@waveform-playlist/core";
177
+ function applyBoundaryResults(elements, after) {
178
+ const byId = new Map(elements.map((el) => [el.annotationId, el]));
179
+ for (const next of after) {
180
+ const el = byId.get(next.id);
181
+ if (!el) continue;
182
+ if (el.start !== next.start) el.start = next.start;
183
+ if (el.end !== next.end) el.end = next.end;
184
+ }
185
+ }
186
+ function applyTickBoundaryResults(elements, after, ticksToSeconds) {
187
+ const byId = new Map(elements.map((el) => [el.annotationId, el]));
188
+ for (const next of after) {
189
+ const el = byId.get(next.id);
190
+ if (!el) continue;
191
+ if (el.isTickBased) {
192
+ const startTick = Math.round(next.start);
193
+ const endTick = Math.round(next.end);
194
+ if (el.startTick !== startTick) {
195
+ el.startTick = startTick;
196
+ el.start = ticksToSeconds(startTick);
197
+ }
198
+ if (el.endTick !== endTick) {
199
+ el.endTick = endTick;
200
+ el.end = ticksToSeconds(endTick);
201
+ }
202
+ } else {
203
+ const start = ticksToSeconds(next.start);
204
+ const end = ticksToSeconds(next.end);
205
+ if (el.start !== start) el.start = start;
206
+ if (el.end !== end) el.end = end;
207
+ }
208
+ }
209
+ }
210
+ function tickSpaceData(el, editor) {
211
+ const base = el.toAnnotationData();
212
+ if (el.isTickBased) {
213
+ return { ...base, start: base.startTick, end: base.endTick };
214
+ }
215
+ return {
216
+ ...base,
217
+ start: editor._secondsToTicks(base.start),
218
+ end: editor._secondsToTicks(base.end)
219
+ };
220
+ }
221
+ var DawAnnotationTrackElement = class extends LitElement2 {
222
+ constructor() {
223
+ super(...arguments);
224
+ this.editable = false;
225
+ this.linkEndpoints = false;
226
+ this.continuousPlay = false;
227
+ this.keyboardControls = false;
228
+ this.boxLabel = "text";
229
+ this.name = "";
230
+ // --- Selection (ephemeral UI state — deliberately NOT DOM data) ---
231
+ this._activeAnnotationId = null;
232
+ // --- Keyboard remapping (accessor pair: cache invalidation on set) ---
233
+ this._annotationShortcuts = null;
234
+ this._resolvedShortcuts = null;
235
+ // Capture phase: runs before <daw-keyboard-shortcuts>' bubble-phase listener,
236
+ // giving annotation shortcuts deterministic priority (spec rule).
237
+ this._onKeyDownCapture = (e) => {
238
+ if (!this.keyboardControls) return;
239
+ if (e.repeat) return;
240
+ const target = e.target;
241
+ if (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable) {
242
+ return;
243
+ }
244
+ const match = this._shortcutEntries().find((entry) => matchesKeyBinding(e, entry.binding));
245
+ if (!match) return;
246
+ const hasSelection = this._activeAnnotationId !== null;
247
+ if (match.action === "clearSelection" && !hasSelection) return;
248
+ if (DawAnnotationTrackElement._boundaryActions.has(match.action)) {
249
+ if (!this.editable || !hasSelection) return;
250
+ }
251
+ if (match.action === "playActive" && !hasSelection) return;
252
+ e.preventDefault();
253
+ e.stopImmediatePropagation();
254
+ try {
255
+ this._runShortcutAction(match.action);
256
+ } catch (err) {
257
+ console.warn("[dawcore] Annotation shortcut failed (key=" + e.key + "): " + String(err));
258
+ this.dispatchEvent(
259
+ new CustomEvent("daw-error", {
260
+ bubbles: true,
261
+ composed: true,
262
+ detail: { operation: "annotation-shortcut", key: e.key, error: err }
263
+ })
264
+ );
265
+ }
266
+ };
267
+ // --- Lifecycle ---
268
+ this._childObserver = null;
269
+ }
270
+ get activeAnnotationId() {
271
+ return this._activeAnnotationId;
272
+ }
273
+ set activeAnnotationId(value) {
274
+ if (value !== null && !this.annotationElements.some((el) => el.annotationId === value)) {
275
+ console.warn(
276
+ '[dawcore] daw-annotation-track: unknown annotation id "' + value + '" \u2014 selection ignored'
277
+ );
278
+ return;
279
+ }
280
+ if (value === this._activeAnnotationId) return;
281
+ this._activeAnnotationId = value;
282
+ const active = this._activeElement();
283
+ this.dispatchEvent(
284
+ new CustomEvent("daw-annotation-select", {
285
+ bubbles: true,
286
+ composed: true,
287
+ detail: { annotation: active ? active.toAnnotationData() : null }
288
+ })
289
+ );
290
+ }
291
+ // --- Child access ---
292
+ /** Child annotation elements, sorted by start time. */
293
+ get annotationElements() {
294
+ return Array.from(this.querySelectorAll(":scope > daw-annotation")).sort(
295
+ (a, b) => a.start - b.start
296
+ );
297
+ }
298
+ get annotations() {
299
+ return this.annotationElements.map((el) => el.toAnnotationData());
300
+ }
301
+ // --- Navigation methods (spec API) ---
302
+ selectNext() {
303
+ this._selectByOffset(1, 0);
304
+ }
305
+ selectPrevious() {
306
+ this._selectByOffset(-1, -1);
307
+ }
308
+ selectFirst() {
309
+ const list = this.annotationElements;
310
+ if (list.length > 0) this.activeAnnotationId = list[0].annotationId;
311
+ }
312
+ selectLast() {
313
+ const list = this.annotationElements;
314
+ if (list.length > 0) this.activeAnnotationId = list[list.length - 1].annotationId;
315
+ }
316
+ clearSelection() {
317
+ this.activeAnnotationId = null;
318
+ }
319
+ /** offset: +1 next / -1 previous; noSelectionIndex: 0 → first, -1 → last. */
320
+ _selectByOffset(offset, noSelectionIndex) {
321
+ const list = this.annotationElements;
322
+ if (list.length === 0) return;
323
+ const currentIndex = list.findIndex((el) => el.annotationId === this._activeAnnotationId);
324
+ const nextIndex = currentIndex === -1 ? (noSelectionIndex + list.length) % list.length : (currentIndex + offset + list.length) % list.length;
325
+ this.activeAnnotationId = list[nextIndex].annotationId;
326
+ }
327
+ // --- Playback (spec API) ---
328
+ playActive() {
329
+ const active = this._activeElement();
330
+ if (!active) return;
331
+ const editor = this._hostEditor();
332
+ if (!editor) {
333
+ console.warn(
334
+ "[dawcore] <daw-annotation-track> playActive: no parent <daw-editor> \u2014 call ignored"
335
+ );
336
+ return;
337
+ }
338
+ const data = active.toAnnotationData();
339
+ void editor.play(data.start, this.continuousPlay ? void 0 : data.end);
340
+ }
341
+ // --- Boundary editing (spec API) ---
342
+ moveStartBoundary(deltaMs) {
343
+ this._moveBoundary(deltaMs, true);
344
+ }
345
+ moveEndBoundary(deltaMs) {
346
+ this._moveBoundary(deltaMs, false);
347
+ }
348
+ _moveBoundary(deltaMs, isStart) {
349
+ if (!this.editable) {
350
+ console.warn(
351
+ "[dawcore] daw-annotation-track: boundary editing requires the editable attribute"
352
+ );
353
+ return;
354
+ }
355
+ const elements = this.annotationElements;
356
+ const index = elements.findIndex((el) => el.annotationId === this._activeAnnotationId);
357
+ if (index === -1) return;
358
+ const active = elements[index];
359
+ if (active.isTickBased) {
360
+ const editor = this._hostEditor();
361
+ if (!editor) {
362
+ console.warn(
363
+ "[dawcore] daw-annotation-track: tick-based boundary edits need a parent <daw-editor> for tempo conversion \u2014 call ignored"
364
+ );
365
+ return;
366
+ }
367
+ const tickData = elements.map((el) => tickSpaceData(el, editor));
368
+ const edgeTick = isStart ? tickData[index].start : tickData[index].end;
369
+ const edgeSeconds = editor._ticksToSeconds(edgeTick);
370
+ const deltaTicks = editor._secondsToTicks(edgeSeconds + deltaMs / 1e3) - editor._secondsToTicks(edgeSeconds);
371
+ const clamp = this._timelineDuration();
372
+ const updated2 = updateAnnotationBoundaries(
373
+ {
374
+ annotationIndex: index,
375
+ newTime: edgeTick + deltaTicks,
376
+ isDraggingStart: isStart,
377
+ annotations: tickData,
378
+ duration: clamp === Infinity ? Infinity : editor._secondsToTicks(clamp),
379
+ linkEndpoints: this.linkEndpoints
380
+ },
381
+ {
382
+ linkThreshold: ANNOTATION_LINK_THRESHOLD_TICKS,
383
+ minDuration: annotationMinDurationTicks(editor.ppqn)
384
+ }
385
+ );
386
+ applyTickBoundaryResults(elements, updated2, (t) => editor._ticksToSeconds(t));
387
+ return;
388
+ }
389
+ const data = elements.map((el) => el.toAnnotationData());
390
+ const edge = isStart ? data[index].start : data[index].end;
391
+ const updated = updateAnnotationBoundaries({
392
+ annotationIndex: index,
393
+ newTime: edge + deltaMs / 1e3,
394
+ isDraggingStart: isStart,
395
+ annotations: data,
396
+ duration: this._timelineDuration(),
397
+ linkEndpoints: this.linkEndpoints
398
+ });
399
+ applyBoundaryResults(elements, updated);
400
+ }
401
+ _timelineDuration() {
402
+ return this._hostEditor()?._annotationClampDuration ?? Infinity;
403
+ }
404
+ _activeElement() {
405
+ if (this._activeAnnotationId === null) return null;
406
+ return this.annotationElements.find((el) => el.annotationId === this._activeAnnotationId) ?? null;
407
+ }
408
+ _hostEditor() {
409
+ return this.closest("daw-editor");
410
+ }
411
+ get annotationShortcuts() {
412
+ return this._annotationShortcuts;
413
+ }
414
+ set annotationShortcuts(value) {
415
+ this._annotationShortcuts = value;
416
+ this._resolvedShortcuts = null;
417
+ }
418
+ _shortcutEntries() {
419
+ if (!this._resolvedShortcuts) {
420
+ this._resolvedShortcuts = resolveAnnotationShortcuts(this._annotationShortcuts);
421
+ }
422
+ return this._resolvedShortcuts;
423
+ }
424
+ _runShortcutAction(action) {
425
+ switch (action) {
426
+ case "selectPrevious":
427
+ this.selectPrevious();
428
+ break;
429
+ case "selectNext":
430
+ this.selectNext();
431
+ break;
432
+ case "selectFirst":
433
+ this.selectFirst();
434
+ break;
435
+ case "selectLast":
436
+ this.selectLast();
437
+ break;
438
+ case "clearSelection":
439
+ this.clearSelection();
440
+ break;
441
+ case "moveStartEarlier":
442
+ this.moveStartBoundary(-10);
443
+ break;
444
+ case "moveStartLater":
445
+ this.moveStartBoundary(10);
446
+ break;
447
+ case "moveEndEarlier":
448
+ this.moveEndBoundary(-10);
449
+ break;
450
+ case "moveEndLater":
451
+ this.moveEndBoundary(10);
452
+ break;
453
+ case "playActive":
454
+ this.playActive();
455
+ break;
456
+ }
457
+ }
458
+ createRenderRoot() {
459
+ return this;
460
+ }
461
+ connectedCallback() {
462
+ super.connectedCallback();
463
+ this.style.display = "none";
464
+ if (Object.prototype.hasOwnProperty.call(this, "annotationShortcuts")) {
465
+ const value = this["annotationShortcuts"];
466
+ delete this["annotationShortcuts"];
467
+ this.annotationShortcuts = value;
468
+ }
469
+ document.addEventListener("keydown", this._onKeyDownCapture, true);
470
+ setTimeout(() => {
471
+ this.dispatchEvent(
472
+ new CustomEvent("daw-annotation-track-connected", {
473
+ bubbles: true,
474
+ composed: true,
475
+ detail: { element: this }
476
+ })
477
+ );
478
+ }, 0);
479
+ this._childObserver = new MutationObserver(() => {
480
+ if (this._activeAnnotationId !== null && !this.annotationElements.some((el) => el.annotationId === this._activeAnnotationId)) {
481
+ this.activeAnnotationId = null;
482
+ }
483
+ });
484
+ this._childObserver.observe(this, { childList: true });
485
+ }
486
+ disconnectedCallback() {
487
+ super.disconnectedCallback();
488
+ document.removeEventListener("keydown", this._onKeyDownCapture, true);
489
+ this._childObserver?.disconnect();
490
+ this._childObserver = null;
491
+ }
492
+ };
493
+ DawAnnotationTrackElement._boundaryActions = /* @__PURE__ */ new Set([
494
+ "moveStartEarlier",
495
+ "moveStartLater",
496
+ "moveEndEarlier",
497
+ "moveEndLater"
498
+ ]);
499
+ __decorateClass([
500
+ property2({ type: Boolean, reflect: true })
501
+ ], DawAnnotationTrackElement.prototype, "editable", 2);
502
+ __decorateClass([
503
+ property2({ type: Boolean, reflect: true, attribute: "link-endpoints" })
504
+ ], DawAnnotationTrackElement.prototype, "linkEndpoints", 2);
505
+ __decorateClass([
506
+ property2({ type: Boolean, reflect: true, attribute: "continuous-play" })
507
+ ], DawAnnotationTrackElement.prototype, "continuousPlay", 2);
508
+ __decorateClass([
509
+ property2({ type: Boolean, reflect: true, attribute: "keyboard-controls" })
510
+ ], DawAnnotationTrackElement.prototype, "keyboardControls", 2);
511
+ __decorateClass([
512
+ property2({ reflect: true, attribute: "box-label" })
513
+ ], DawAnnotationTrackElement.prototype, "boxLabel", 2);
514
+ __decorateClass([
515
+ property2({ reflect: true })
516
+ ], DawAnnotationTrackElement.prototype, "name", 2);
517
+ DawAnnotationTrackElement = __decorateClass([
518
+ customElement2("daw-annotation-track")
519
+ ], DawAnnotationTrackElement);
520
+
521
+ // src/elements/daw-annotation-list.ts
522
+ import { LitElement as LitElement3, html, css, nothing } from "lit";
523
+ import { customElement as customElement3, property as property3, state } from "lit/decorators.js";
524
+ import { ticksToBarBeat } from "@waveform-playlist/core";
525
+
526
+ // src/utils/annotation-playing.ts
527
+ function computePlayingAnnotationId(annotations, time) {
528
+ const match = annotations.find((a) => a.start <= time && time < a.end);
529
+ return match?.id ?? null;
530
+ }
531
+
532
+ // src/elements/daw-annotation-list.ts
533
+ function formatAnnotationTime(seconds) {
534
+ const whole = Math.floor(seconds);
535
+ const ms = Math.round((seconds - whole) * 1e3);
536
+ const s = whole % 60;
537
+ const m = (whole - s) / 60;
538
+ return m + ":" + String(s).padStart(2, "0") + "." + String(ms).padStart(3, "0");
539
+ }
540
+ var DawAnnotationListElement = class extends LitElement3 {
541
+ constructor() {
542
+ super(...arguments);
543
+ this.for = "";
544
+ this.timeDisplay = "time";
545
+ this._editingId = null;
546
+ this._activeId = null;
547
+ /** Playback-following highlight, separate from `_activeId` (selection) so
548
+ * playback never disturbs selection/keyboard editing. Driven by
549
+ * daw-timeupdate, cleared on daw-stop, retained on pause. */
550
+ this._playingId = null;
551
+ this._observer = null;
552
+ this._observedTrack = null;
553
+ this._warnedMissing = false;
554
+ /** Warn once per resolved `for` target when bars mode can't find a host
555
+ * editor — reset alongside `_warnedMissing` on `for` change so a
556
+ * retargeted list can warn again for its new target. */
557
+ this._warnedNoEditorForBars = false;
558
+ /** Set around `_cancelEdit`'s `span.blur()` so the resulting synchronous
559
+ * blur event doesn't re-enter `_commitEdit` (cancel already restores the
560
+ * text and clears `_editingId` itself). */
561
+ this._cancelling = false;
562
+ this._onSelect = (e) => {
563
+ if (e.target !== this.track) return;
564
+ this._activeId = e.detail.annotation?.id ?? null;
565
+ this.requestUpdate();
566
+ void this.updateComplete.then(() => {
567
+ const row = this.shadowRoot?.querySelector(".annotation-row.active");
568
+ row?.scrollIntoView?.({ block: "center" });
569
+ });
570
+ };
571
+ /**
572
+ * Update only on annotation-boundary crossings, not per animation frame.
573
+ * `shouldUpdate()` suppresses the resulting render while a row is being
574
+ * edited (`_editingId`) — intentional, not bypassed here. A boundary
575
+ * crossed mid-edit is caught up on the NEXT crossing after the edit ends;
576
+ * the highlight is briefly stale in that window, which is acceptable
577
+ * (edits are rare and short-lived relative to playback).
578
+ */
579
+ this._onTimeUpdate = (e) => {
580
+ if (e.target !== this.track?.closest("daw-editor")) return;
581
+ const playingId = computePlayingAnnotationId(this.track?.annotations ?? [], e.detail.time);
582
+ if (playingId === this._playingId) return;
583
+ this._playingId = playingId;
584
+ this.requestUpdate();
585
+ void this.updateComplete.then(() => {
586
+ const row = this.shadowRoot?.querySelector(".annotation-row.playing");
587
+ row?.scrollIntoView?.({ block: "center" });
588
+ });
589
+ };
590
+ this._onStop = (e) => {
591
+ if (e.target !== this.track?.closest("daw-editor")) return;
592
+ if (this._playingId === null) return;
593
+ this._playingId = null;
594
+ this.requestUpdate();
595
+ };
596
+ }
597
+ get track() {
598
+ if (!this.for) return null;
599
+ const el = document.getElementById(this.for);
600
+ if (!el || el.tagName !== "DAW-ANNOTATION-TRACK") {
601
+ if (!this._warnedMissing) {
602
+ console.warn(
603
+ 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'
604
+ );
605
+ this._warnedMissing = true;
606
+ }
607
+ return null;
608
+ }
609
+ return el;
610
+ }
611
+ willUpdate(changed) {
612
+ if (changed.has("for")) {
613
+ this._warnedMissing = false;
614
+ this._warnedNoEditorForBars = false;
615
+ }
616
+ }
617
+ connectedCallback() {
618
+ super.connectedCallback();
619
+ document.addEventListener("daw-annotation-select", this._onSelect);
620
+ document.addEventListener("daw-timeupdate", this._onTimeUpdate);
621
+ document.addEventListener("daw-stop", this._onStop);
622
+ }
623
+ disconnectedCallback() {
624
+ super.disconnectedCallback();
625
+ document.removeEventListener("daw-annotation-select", this._onSelect);
626
+ document.removeEventListener("daw-timeupdate", this._onTimeUpdate);
627
+ document.removeEventListener("daw-stop", this._onStop);
628
+ this._observer?.disconnect();
629
+ this._observer = null;
630
+ this._observedTrack = null;
631
+ }
632
+ shouldUpdate() {
633
+ return this._editingId === null;
634
+ }
635
+ updated() {
636
+ this._ensureObserver();
637
+ this._syncRowText();
638
+ }
639
+ /**
640
+ * Text content is set imperatively, NOT bound as a Lit expression.
641
+ * contenteditable mutates the span's DOM directly as the user types —
642
+ * that ejects lit-html's ChildPart marker comments for any binding at
643
+ * that position, so a later Lit-driven re-render of the same row throws
644
+ * "ChildPart has no parentNode". Keeping the span's children entirely
645
+ * outside Lit's diffing sidesteps the crash; the (soon-to-commit) edited
646
+ * row is skipped via the _editingId check.
647
+ */
648
+ _syncRowText() {
649
+ const annotations = this.track?.annotations ?? [];
650
+ const spans = this.shadowRoot?.querySelectorAll(".annotation-row-text") ?? [];
651
+ spans.forEach((span) => {
652
+ const id = span.dataset.id;
653
+ if (id === void 0 || id === this._editingId) return;
654
+ const a = annotations.find((x) => x.id === id);
655
+ if (!a) return;
656
+ const text = a.lines.join(" ");
657
+ if (span.textContent !== text) span.textContent = text;
658
+ });
659
+ }
660
+ /** (Re)attach the MutationObserver when the resolved track changes. */
661
+ _ensureObserver() {
662
+ const track = this.track;
663
+ if (track === this._observedTrack) return;
664
+ this._observer?.disconnect();
665
+ this._observedTrack = track;
666
+ if (!track) return;
667
+ this._observer = new MutationObserver(() => this.requestUpdate());
668
+ this._observer.observe(track, {
669
+ childList: true,
670
+ subtree: true,
671
+ characterData: true,
672
+ attributes: true,
673
+ attributeFilter: ["start", "end", "id", "editable"]
674
+ });
675
+ }
676
+ _onRowClick(a) {
677
+ const track = this.track;
678
+ if (!track) return;
679
+ track.activeAnnotationId = a.id;
680
+ const editor = track.closest("daw-editor");
681
+ editor?.seekTo?.(a.start);
682
+ }
683
+ /** Formats a row's times span per `timeDisplay`. `'bars'` resolves the
684
+ * host editor once (shared across all rows in a render) and falls back
685
+ * to time display, warning once, when no editor is found. */
686
+ _formatTimes(a, editor) {
687
+ if (this.timeDisplay === "bars") {
688
+ if (editor) {
689
+ const isTickBased = a.startTick !== void 0 && a.endTick !== void 0;
690
+ const startTick = isTickBased ? a.startTick : editor._secondsToTicks(a.start);
691
+ const endTick = isTickBased ? a.endTick : editor._secondsToTicks(a.end);
692
+ const start = ticksToBarBeat(startTick, editor._meterEntries, editor.ppqn);
693
+ const end = ticksToBarBeat(endTick, editor._meterEntries, editor.ppqn);
694
+ return start.bar + "." + start.beat + " \u2013 " + end.bar + "." + end.beat;
695
+ }
696
+ if (!this._warnedNoEditorForBars) {
697
+ console.warn(
698
+ '[dawcore] <daw-annotation-list for="' + this.for + '" time-display="bars"> found no parent <daw-editor> \u2014 falling back to time display'
699
+ );
700
+ this._warnedNoEditorForBars = true;
701
+ }
702
+ }
703
+ return formatAnnotationTime(a.start) + " \u2013 " + formatAnnotationTime(a.end);
704
+ }
705
+ _annotationElement(id) {
706
+ return this.track?.annotationElements.find((el) => el.annotationId === id) ?? null;
707
+ }
708
+ _commitEdit(a, span) {
709
+ if (this._cancelling) return;
710
+ this._editingId = null;
711
+ const el = this._annotationElement(a.id);
712
+ if (el) el.textContent = span.textContent?.trim() ?? "";
713
+ this.requestUpdate();
714
+ }
715
+ _cancelEdit(a, span) {
716
+ this._editingId = null;
717
+ span.textContent = a.lines.join("\n");
718
+ this._cancelling = true;
719
+ try {
720
+ span.blur();
721
+ } finally {
722
+ this._cancelling = false;
723
+ }
724
+ this.requestUpdate();
725
+ }
726
+ render() {
727
+ const track = this.track;
728
+ const annotations = track?.annotations ?? [];
729
+ const editable = track?.editable ?? false;
730
+ const editor = this.timeDisplay === "bars" ? track?.closest("daw-editor") ?? null : null;
731
+ return html`
732
+ ${annotations.map(
733
+ (a) => html`
734
+ <div
735
+ class="annotation-row ${a.id === this._activeId ? "active" : ""} ${a.id === this._playingId ? "playing" : ""}"
736
+ @click=${(e) => {
737
+ if (this._editingId === a.id && this._activeId === a.id) return;
738
+ e.stopPropagation();
739
+ this._onRowClick(a);
740
+ }}
741
+ >
742
+ <span class="annotation-row-times"> ${this._formatTimes(a, editor)} </span>
743
+ <span
744
+ class="annotation-row-text"
745
+ data-id=${a.id}
746
+ contenteditable=${editable ? "true" : nothing}
747
+ @focus=${() => {
748
+ if (editable) this._editingId = a.id;
749
+ }}
750
+ @blur=${(e) => this._commitEdit(a, e.target)}
751
+ @keydown=${(e) => {
752
+ if (!editable) return;
753
+ e.stopPropagation();
754
+ if (e.key === "Enter") {
755
+ e.preventDefault();
756
+ e.target.blur();
757
+ } else if (e.key === "Escape") {
758
+ this._cancelEdit(a, e.target);
759
+ }
760
+ }}
761
+ ></span>
762
+ </div>
763
+ `
764
+ )}
765
+ `;
766
+ }
767
+ };
768
+ DawAnnotationListElement.styles = css`
769
+ :host {
770
+ display: block;
771
+ max-height: var(--daw-annotation-list-max-height, 240px);
772
+ overflow-y: auto;
773
+ background: var(--daw-annotation-list-background, #16213e);
774
+ color: var(--daw-annotation-text-color, #e0d4c8);
775
+ font-family: system-ui, sans-serif;
776
+ font-size: 13px;
777
+ }
778
+ .annotation-row {
779
+ display: flex;
780
+ gap: 10px;
781
+ align-items: baseline;
782
+ padding: 6px 10px;
783
+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);
784
+ cursor: pointer;
785
+ }
786
+ .annotation-row.playing {
787
+ background: var(--daw-annotation-playing-background, rgba(196, 154, 108, 0.12));
788
+ box-shadow: inset 2px 0 0 var(--daw-annotation-box-border, #c49a6c);
789
+ }
790
+ .annotation-row.active {
791
+ background: var(--daw-annotation-active-background, rgba(196, 154, 108, 0.25));
792
+ }
793
+ .annotation-row-times {
794
+ font-variant-numeric: tabular-nums;
795
+ font-size: 11px;
796
+ opacity: 0.7;
797
+ white-space: nowrap;
798
+ }
799
+ .annotation-row-text {
800
+ flex: 1;
801
+ min-width: 0;
802
+ }
803
+ .annotation-row-text[contenteditable='true'] {
804
+ cursor: text;
805
+ outline-offset: 2px;
806
+ }
807
+ .annotation-row-text:empty::before {
808
+ content: '—';
809
+ opacity: 0.4;
810
+ }
811
+ `;
812
+ __decorateClass([
813
+ property3()
814
+ ], DawAnnotationListElement.prototype, "for", 2);
815
+ __decorateClass([
816
+ property3({ type: String, attribute: "time-display", reflect: true })
817
+ ], DawAnnotationListElement.prototype, "timeDisplay", 2);
818
+ __decorateClass([
819
+ state()
820
+ ], DawAnnotationListElement.prototype, "_editingId", 2);
821
+ DawAnnotationListElement = __decorateClass([
822
+ customElement3("daw-annotation-list")
823
+ ], DawAnnotationListElement);
824
+
825
+ // src/elements/daw-clip.ts
826
+ import { LitElement as LitElement4 } from "lit";
827
+ import { customElement as customElement4, property as property4 } from "lit/decorators.js";
828
+ var DawClipElement = class extends LitElement4 {
16
829
  constructor() {
17
830
  super(...arguments);
18
831
  this.src = "";
@@ -117,55 +930,55 @@ var DawClipElement = class extends LitElement {
117
930
  }
118
931
  };
119
932
  __decorateClass([
120
- property()
933
+ property4()
121
934
  ], DawClipElement.prototype, "src", 2);
122
935
  __decorateClass([
123
- property({ attribute: "peaks-src" })
936
+ property4({ attribute: "peaks-src" })
124
937
  ], DawClipElement.prototype, "peaksSrc", 2);
125
938
  __decorateClass([
126
- property({ type: Number })
939
+ property4({ type: Number })
127
940
  ], DawClipElement.prototype, "start", 2);
128
941
  __decorateClass([
129
- property({ type: Number })
942
+ property4({ type: Number })
130
943
  ], DawClipElement.prototype, "duration", 2);
131
944
  __decorateClass([
132
- property({ type: Number })
945
+ property4({ type: Number })
133
946
  ], DawClipElement.prototype, "offset", 2);
134
947
  __decorateClass([
135
- property({ type: Number })
948
+ property4({ type: Number })
136
949
  ], DawClipElement.prototype, "gain", 2);
137
950
  __decorateClass([
138
- property()
951
+ property4()
139
952
  ], DawClipElement.prototype, "name", 2);
140
953
  __decorateClass([
141
- property()
954
+ property4()
142
955
  ], DawClipElement.prototype, "color", 2);
143
956
  __decorateClass([
144
- property({ type: Number, attribute: "fade-in" })
957
+ property4({ type: Number, attribute: "fade-in" })
145
958
  ], DawClipElement.prototype, "fadeIn", 2);
146
959
  __decorateClass([
147
- property({ type: Number, attribute: "fade-out" })
960
+ property4({ type: Number, attribute: "fade-out" })
148
961
  ], DawClipElement.prototype, "fadeOut", 2);
149
962
  __decorateClass([
150
- property({ attribute: "fade-type" })
963
+ property4({ attribute: "fade-type" })
151
964
  ], DawClipElement.prototype, "fadeType", 2);
152
965
  __decorateClass([
153
- property({ attribute: false })
966
+ property4({ attribute: false })
154
967
  ], DawClipElement.prototype, "midiNotes", 2);
155
968
  __decorateClass([
156
- property({ type: Number, attribute: "midi-channel", noAccessor: true })
969
+ property4({ type: Number, attribute: "midi-channel", noAccessor: true })
157
970
  ], DawClipElement.prototype, "midiChannel", 1);
158
971
  __decorateClass([
159
- property({ type: Number, attribute: "midi-program", noAccessor: true })
972
+ property4({ type: Number, attribute: "midi-program", noAccessor: true })
160
973
  ], DawClipElement.prototype, "midiProgram", 1);
161
974
  DawClipElement = __decorateClass([
162
- customElement("daw-clip")
975
+ customElement4("daw-clip")
163
976
  ], DawClipElement);
164
977
 
165
978
  // src/elements/daw-track.ts
166
- import { LitElement as LitElement2 } from "lit";
167
- import { customElement as customElement2, property as property2 } from "lit/decorators.js";
168
- var DawTrackElement = class extends LitElement2 {
979
+ import { LitElement as LitElement5 } from "lit";
980
+ import { customElement as customElement5, property as property5 } from "lit/decorators.js";
981
+ var DawTrackElement = class extends LitElement5 {
169
982
  constructor() {
170
983
  super(...arguments);
171
984
  this.src = "";
@@ -303,36 +1116,36 @@ var DawTrackElement = class extends LitElement2 {
303
1116
  }
304
1117
  };
305
1118
  __decorateClass([
306
- property2()
1119
+ property5()
307
1120
  ], DawTrackElement.prototype, "src", 2);
308
1121
  __decorateClass([
309
- property2()
1122
+ property5()
310
1123
  ], DawTrackElement.prototype, "name", 2);
311
1124
  __decorateClass([
312
- property2({ type: Number })
1125
+ property5({ type: Number })
313
1126
  ], DawTrackElement.prototype, "volume", 2);
314
1127
  __decorateClass([
315
- property2({ type: Number })
1128
+ property5({ type: Number })
316
1129
  ], DawTrackElement.prototype, "pan", 2);
317
1130
  __decorateClass([
318
- property2({ type: Boolean })
1131
+ property5({ type: Boolean })
319
1132
  ], DawTrackElement.prototype, "muted", 2);
320
1133
  __decorateClass([
321
- property2({ type: Boolean })
1134
+ property5({ type: Boolean })
322
1135
  ], DawTrackElement.prototype, "soloed", 2);
323
1136
  __decorateClass([
324
- property2({ attribute: "render-mode", noAccessor: true })
1137
+ property5({ attribute: "render-mode", noAccessor: true })
325
1138
  ], DawTrackElement.prototype, "renderMode", 1);
326
1139
  __decorateClass([
327
- property2({ attribute: false })
1140
+ property5({ attribute: false })
328
1141
  ], DawTrackElement.prototype, "spectrogramConfig", 2);
329
1142
  DawTrackElement = __decorateClass([
330
- customElement2("daw-track")
1143
+ customElement5("daw-track")
331
1144
  ], DawTrackElement);
332
1145
 
333
1146
  // src/elements/daw-waveform.ts
334
- import { LitElement as LitElement3, html, css } from "lit";
335
- import { customElement as customElement3, property as property3 } from "lit/decorators.js";
1147
+ import { LitElement as LitElement6, html as html2, css as css2 } from "lit";
1148
+ import { customElement as customElement6, property as property6 } from "lit/decorators.js";
336
1149
 
337
1150
  // src/utils/peak-rendering.ts
338
1151
  function aggregatePeaks(data, bits, startIndex, endIndex) {
@@ -394,11 +1207,9 @@ var LAYOUT_PROPS = /* @__PURE__ */ new Set([
394
1207
  "roundedBars",
395
1208
  "segments"
396
1209
  ]);
397
- function groupDirtyByChunk(dirtyPixels, step) {
1210
+ function groupDirtyByChunk(dirtyPixels, step, barWidth) {
398
1211
  const dirtyByChunk = /* @__PURE__ */ new Map();
399
- for (const peakIdx of dirtyPixels) {
400
- const barPixel = Math.floor(peakIdx / step) * step;
401
- const chunkIdx = Math.floor(barPixel / MAX_CANVAS_WIDTH);
1212
+ const mark = (chunkIdx, barPixel) => {
402
1213
  const existing = dirtyByChunk.get(chunkIdx);
403
1214
  if (existing) {
404
1215
  dirtyByChunk.set(chunkIdx, {
@@ -408,10 +1219,19 @@ function groupDirtyByChunk(dirtyPixels, step) {
408
1219
  } else {
409
1220
  dirtyByChunk.set(chunkIdx, { min: barPixel, max: barPixel });
410
1221
  }
1222
+ };
1223
+ for (const peakIdx of dirtyPixels) {
1224
+ const barPixel = Math.floor(peakIdx / step) * step;
1225
+ const chunkIdx = Math.floor(barPixel / MAX_CANVAS_WIDTH);
1226
+ mark(chunkIdx, barPixel);
1227
+ const endChunkIdx = Math.floor((barPixel + barWidth - 1) / MAX_CANVAS_WIDTH);
1228
+ if (endChunkIdx !== chunkIdx) {
1229
+ mark(endChunkIdx, barPixel);
1230
+ }
411
1231
  }
412
1232
  return dirtyByChunk;
413
1233
  }
414
- var DawWaveformElement = class extends LitElement3 {
1234
+ var DawWaveformElement = class extends LitElement6 {
415
1235
  constructor() {
416
1236
  super(...arguments);
417
1237
  this._peaks = new Int16Array(0);
@@ -509,7 +1329,7 @@ var DawWaveformElement = class extends LitElement3 {
509
1329
  this._drawSegments(canvas, chunkIdx, dpr, halfHeight, bits, waveColor);
510
1330
  }
511
1331
  } else {
512
- const dirtyByChunk = groupDirtyByChunk(this._dirtyPixels, step);
1332
+ const dirtyByChunk = groupDirtyByChunk(this._dirtyPixels, step, this.barWidth);
513
1333
  for (const canvas of canvases) {
514
1334
  const chunkIdx = Number(canvas.dataset.index);
515
1335
  this._drawnChunks.add(chunkIdx);
@@ -617,11 +1437,11 @@ var DawWaveformElement = class extends LitElement3 {
617
1437
  render() {
618
1438
  const indices = this._getVisibleChunkIndices();
619
1439
  const dpr = typeof devicePixelRatio !== "undefined" ? devicePixelRatio : 1;
620
- return html`
1440
+ return html2`
621
1441
  <div class="container" style="width: ${this.length}px; height: ${this.waveHeight}px;">
622
1442
  ${indices.map((i) => {
623
1443
  const width = Math.min(MAX_CANVAS_WIDTH, this.length - i * MAX_CANVAS_WIDTH);
624
- return html`
1444
+ return html2`
625
1445
  <canvas
626
1446
  data-index=${i}
627
1447
  width=${width * dpr}
@@ -661,7 +1481,7 @@ var DawWaveformElement = class extends LitElement3 {
661
1481
  }
662
1482
  }
663
1483
  };
664
- DawWaveformElement.styles = css`
1484
+ DawWaveformElement.styles = css2`
665
1485
  :host {
666
1486
  display: block;
667
1487
  position: relative;
@@ -675,39 +1495,39 @@ DawWaveformElement.styles = css`
675
1495
  }
676
1496
  `;
677
1497
  __decorateClass([
678
- property3({ type: Number, attribute: false })
1498
+ property6({ type: Number, attribute: false })
679
1499
  ], DawWaveformElement.prototype, "length", 2);
680
1500
  __decorateClass([
681
- property3({ type: Number, attribute: false })
1501
+ property6({ type: Number, attribute: false })
682
1502
  ], DawWaveformElement.prototype, "waveHeight", 2);
683
1503
  __decorateClass([
684
- property3({ type: Number, attribute: false })
1504
+ property6({ type: Number, attribute: false })
685
1505
  ], DawWaveformElement.prototype, "barWidth", 2);
686
1506
  __decorateClass([
687
- property3({ type: Number, attribute: false })
1507
+ property6({ type: Number, attribute: false })
688
1508
  ], DawWaveformElement.prototype, "barGap", 2);
689
1509
  __decorateClass([
690
- property3({ type: Boolean, attribute: false })
1510
+ property6({ type: Boolean, attribute: false })
691
1511
  ], DawWaveformElement.prototype, "roundedBars", 2);
692
1512
  __decorateClass([
693
- property3({ type: Number, attribute: false })
1513
+ property6({ type: Number, attribute: false })
694
1514
  ], DawWaveformElement.prototype, "visibleStart", 2);
695
1515
  __decorateClass([
696
- property3({ type: Number, attribute: false })
1516
+ property6({ type: Number, attribute: false })
697
1517
  ], DawWaveformElement.prototype, "visibleEnd", 2);
698
1518
  __decorateClass([
699
- property3({ type: Number, attribute: false })
1519
+ property6({ type: Number, attribute: false })
700
1520
  ], DawWaveformElement.prototype, "originX", 2);
701
1521
  __decorateClass([
702
- property3({ attribute: false })
1522
+ property6({ attribute: false })
703
1523
  ], DawWaveformElement.prototype, "segments", 2);
704
1524
  DawWaveformElement = __decorateClass([
705
- customElement3("daw-waveform")
1525
+ customElement6("daw-waveform")
706
1526
  ], DawWaveformElement);
707
1527
 
708
1528
  // src/elements/daw-piano-roll.ts
709
- import { LitElement as LitElement4, html as html2, css as css2 } from "lit";
710
- import { customElement as customElement4, property as property4 } from "lit/decorators.js";
1529
+ import { LitElement as LitElement7, html as html3, css as css3 } from "lit";
1530
+ import { customElement as customElement7, property as property7 } from "lit/decorators.js";
711
1531
  var MAX_CANVAS_WIDTH2 = 1e3;
712
1532
  var LAYOUT_PROPS2 = /* @__PURE__ */ new Set([
713
1533
  "length",
@@ -718,7 +1538,7 @@ var LAYOUT_PROPS2 = /* @__PURE__ */ new Set([
718
1538
  "midiNotes",
719
1539
  "selected"
720
1540
  ]);
721
- var DawPianoRollElement = class extends LitElement4 {
1541
+ var DawPianoRollElement = class extends LitElement7 {
722
1542
  constructor() {
723
1543
  super(...arguments);
724
1544
  this.midiNotes = [];
@@ -850,7 +1670,7 @@ var DawPianoRollElement = class extends LitElement4 {
850
1670
  }
851
1671
  render() {
852
1672
  if (this.length <= 0)
853
- return html2`<div class="container" style="width: 0; height: ${this.waveHeight}px;"></div>`;
1673
+ return html3`<div class="container" style="width: 0; height: ${this.waveHeight}px;"></div>`;
854
1674
  const dpr = typeof devicePixelRatio !== "undefined" ? devicePixelRatio : 1;
855
1675
  const visibleIndices = getVisibleChunkIndices(
856
1676
  this.length,
@@ -859,12 +1679,12 @@ var DawPianoRollElement = class extends LitElement4 {
859
1679
  this.visibleEnd,
860
1680
  this.originX
861
1681
  );
862
- return html2`
1682
+ return html3`
863
1683
  <div class="container" style="width: ${this.length}px; height: ${this.waveHeight}px;">
864
1684
  ${visibleIndices.map((i) => {
865
1685
  const chunkLeft = i * MAX_CANVAS_WIDTH2;
866
1686
  const chunkWidth = Math.min(this.length - chunkLeft, MAX_CANVAS_WIDTH2);
867
- return html2`<canvas
1687
+ return html3`<canvas
868
1688
  data-index=${i}
869
1689
  width=${chunkWidth * dpr}
870
1690
  height=${this.waveHeight * dpr}
@@ -875,7 +1695,7 @@ var DawPianoRollElement = class extends LitElement4 {
875
1695
  `;
876
1696
  }
877
1697
  };
878
- DawPianoRollElement.styles = css2`
1698
+ DawPianoRollElement.styles = css3`
879
1699
  :host {
880
1700
  display: block;
881
1701
  position: relative;
@@ -892,49 +1712,49 @@ DawPianoRollElement.styles = css2`
892
1712
  }
893
1713
  `;
894
1714
  __decorateClass([
895
- property4({ attribute: false })
1715
+ property7({ attribute: false })
896
1716
  ], DawPianoRollElement.prototype, "midiNotes", 2);
897
1717
  __decorateClass([
898
- property4({ type: Number, attribute: false })
1718
+ property7({ type: Number, attribute: false })
899
1719
  ], DawPianoRollElement.prototype, "length", 2);
900
1720
  __decorateClass([
901
- property4({ type: Number, attribute: false })
1721
+ property7({ type: Number, attribute: false })
902
1722
  ], DawPianoRollElement.prototype, "waveHeight", 2);
903
1723
  __decorateClass([
904
- property4({ type: Number, attribute: "samples-per-pixel", noAccessor: true })
1724
+ property7({ type: Number, attribute: "samples-per-pixel", noAccessor: true })
905
1725
  ], DawPianoRollElement.prototype, "samplesPerPixel", 1);
906
1726
  __decorateClass([
907
- property4({ type: Number, attribute: "sample-rate", noAccessor: true })
1727
+ property7({ type: Number, attribute: "sample-rate", noAccessor: true })
908
1728
  ], DawPianoRollElement.prototype, "sampleRate", 1);
909
1729
  __decorateClass([
910
- property4({ type: Number, attribute: false })
1730
+ property7({ type: Number, attribute: false })
911
1731
  ], DawPianoRollElement.prototype, "clipOffsetSeconds", 2);
912
1732
  __decorateClass([
913
- property4({ type: Number, attribute: false })
1733
+ property7({ type: Number, attribute: false })
914
1734
  ], DawPianoRollElement.prototype, "visibleStart", 2);
915
1735
  __decorateClass([
916
- property4({ type: Number, attribute: false })
1736
+ property7({ type: Number, attribute: false })
917
1737
  ], DawPianoRollElement.prototype, "visibleEnd", 2);
918
1738
  __decorateClass([
919
- property4({ type: Number, attribute: false })
1739
+ property7({ type: Number, attribute: false })
920
1740
  ], DawPianoRollElement.prototype, "originX", 2);
921
1741
  __decorateClass([
922
- property4({ type: Boolean, reflect: true })
1742
+ property7({ type: Boolean, reflect: true })
923
1743
  ], DawPianoRollElement.prototype, "selected", 2);
924
1744
  DawPianoRollElement = __decorateClass([
925
- customElement4("daw-piano-roll")
1745
+ customElement7("daw-piano-roll")
926
1746
  ], DawPianoRollElement);
927
1747
 
928
1748
  // src/elements/daw-playhead.ts
929
- import { LitElement as LitElement5, html as html3, css as css3 } from "lit";
930
- import { customElement as customElement5 } from "lit/decorators.js";
931
- var DawPlayheadElement = class extends LitElement5 {
1749
+ import { LitElement as LitElement8, html as html4, css as css4 } from "lit";
1750
+ import { customElement as customElement8 } from "lit/decorators.js";
1751
+ var DawPlayheadElement = class extends LitElement8 {
932
1752
  constructor() {
933
1753
  super(...arguments);
934
1754
  this._line = null;
935
1755
  }
936
1756
  render() {
937
- return html3`<div></div>`;
1757
+ return html4`<div></div>`;
938
1758
  }
939
1759
  firstUpdated() {
940
1760
  this._line = this.shadowRoot.querySelector("div");
@@ -948,7 +1768,7 @@ var DawPlayheadElement = class extends LitElement5 {
948
1768
  }
949
1769
  }
950
1770
  };
951
- DawPlayheadElement.styles = css3`
1771
+ DawPlayheadElement.styles = css4`
952
1772
  :host {
953
1773
  position: absolute;
954
1774
  top: 0;
@@ -967,13 +1787,13 @@ DawPlayheadElement.styles = css3`
967
1787
  }
968
1788
  `;
969
1789
  DawPlayheadElement = __decorateClass([
970
- customElement5("daw-playhead")
1790
+ customElement8("daw-playhead")
971
1791
  ], DawPlayheadElement);
972
1792
 
973
1793
  // src/elements/daw-transport.ts
974
- import { LitElement as LitElement6 } from "lit";
975
- import { customElement as customElement6, property as property5 } from "lit/decorators.js";
976
- var DawTransportElement = class extends LitElement6 {
1794
+ import { LitElement as LitElement9 } from "lit";
1795
+ import { customElement as customElement9, property as property8 } from "lit/decorators.js";
1796
+ var DawTransportElement = class extends LitElement9 {
977
1797
  constructor() {
978
1798
  super(...arguments);
979
1799
  this.for = "";
@@ -988,18 +1808,18 @@ var DawTransportElement = class extends LitElement6 {
988
1808
  }
989
1809
  };
990
1810
  __decorateClass([
991
- property5()
1811
+ property8()
992
1812
  ], DawTransportElement.prototype, "for", 2);
993
1813
  DawTransportElement = __decorateClass([
994
- customElement6("daw-transport")
1814
+ customElement9("daw-transport")
995
1815
  ], DawTransportElement);
996
1816
 
997
1817
  // src/elements/daw-play-button.ts
998
- import { html as html4 } from "lit";
999
- import { customElement as customElement7, state } from "lit/decorators.js";
1818
+ import { html as html5 } from "lit";
1819
+ import { customElement as customElement10, state as state2 } from "lit/decorators.js";
1000
1820
 
1001
1821
  // src/elements/daw-transport-button.ts
1002
- import { LitElement as LitElement7, css as css4 } from "lit";
1822
+ import { LitElement as LitElement10, css as css5 } from "lit";
1003
1823
 
1004
1824
  // src/utils/transport-capability.ts
1005
1825
  function resolveTransportTarget(el) {
@@ -1040,7 +1860,7 @@ function warnUnsupportedOnce(element, methods) {
1040
1860
  }
1041
1861
 
1042
1862
  // src/elements/daw-transport-button.ts
1043
- var DawTransportButton = class extends LitElement7 {
1863
+ var DawTransportButton = class extends LitElement10 {
1044
1864
  constructor() {
1045
1865
  super(...arguments);
1046
1866
  this._onCapabilityPointerEnter = () => {
@@ -1096,7 +1916,7 @@ var DawTransportButton = class extends LitElement7 {
1096
1916
  /** Methods the transport target must implement for this control to be
1097
1917
  * enabled. Empty = works with any target. */
1098
1918
  DawTransportButton.requiredTargetMethods = [];
1099
- DawTransportButton.styles = css4`
1919
+ DawTransportButton.styles = css5`
1100
1920
  button {
1101
1921
  cursor: pointer;
1102
1922
  background: var(--daw-controls-background, #1a1a2e);
@@ -1130,16 +1950,31 @@ var DawPlayButtonElement = class extends DawTransportButton {
1130
1950
  connectedCallback() {
1131
1951
  super.connectedCallback();
1132
1952
  requestAnimationFrame(() => {
1133
- const target = this.target;
1134
- if (!target) return;
1135
- this._targetRef = target;
1136
- target.addEventListener("daw-recording-start", this._onRecStart);
1137
- target.addEventListener("daw-recording-complete", this._onRecEnd);
1138
- target.addEventListener("daw-recording-error", this._onRecEnd);
1953
+ if (!this.isConnected) return;
1954
+ this._ensureTargetListeners();
1139
1955
  });
1140
1956
  }
1141
1957
  disconnectedCallback() {
1142
1958
  super.disconnectedCallback();
1959
+ this._cleanupListeners();
1960
+ }
1961
+ updated() {
1962
+ this._ensureTargetListeners();
1963
+ }
1964
+ _ensureTargetListeners() {
1965
+ const target = this.target;
1966
+ if (target === this._targetRef) return;
1967
+ if (this._targetRef) {
1968
+ this._isRecording = false;
1969
+ }
1970
+ this._cleanupListeners();
1971
+ if (!target) return;
1972
+ this._targetRef = target;
1973
+ target.addEventListener("daw-recording-start", this._onRecStart);
1974
+ target.addEventListener("daw-recording-complete", this._onRecEnd);
1975
+ target.addEventListener("daw-recording-error", this._onRecEnd);
1976
+ }
1977
+ _cleanupListeners() {
1143
1978
  if (this._targetRef) {
1144
1979
  this._targetRef.removeEventListener("daw-recording-start", this._onRecStart);
1145
1980
  this._targetRef.removeEventListener("daw-recording-complete", this._onRecEnd);
@@ -1148,7 +1983,7 @@ var DawPlayButtonElement = class extends DawTransportButton {
1148
1983
  }
1149
1984
  }
1150
1985
  render() {
1151
- return html4`
1986
+ return html5`
1152
1987
  <button part="button" ?disabled=${this._isRecording} @click=${this._onClick}>
1153
1988
  <slot>Play</slot>
1154
1989
  </button>
@@ -1166,15 +2001,15 @@ var DawPlayButtonElement = class extends DawTransportButton {
1166
2001
  }
1167
2002
  };
1168
2003
  __decorateClass([
1169
- state()
2004
+ state2()
1170
2005
  ], DawPlayButtonElement.prototype, "_isRecording", 2);
1171
2006
  DawPlayButtonElement = __decorateClass([
1172
- customElement7("daw-play-button")
2007
+ customElement10("daw-play-button")
1173
2008
  ], DawPlayButtonElement);
1174
2009
 
1175
2010
  // src/elements/daw-pause-button.ts
1176
- import { html as html5, css as css5 } from "lit";
1177
- import { customElement as customElement8, state as state2 } from "lit/decorators.js";
2011
+ import { html as html6, css as css6 } from "lit";
2012
+ import { customElement as customElement11, state as state3 } from "lit/decorators.js";
1178
2013
  var DawPauseButtonElement = class extends DawTransportButton {
1179
2014
  constructor() {
1180
2015
  super(...arguments);
@@ -1198,18 +2033,34 @@ var DawPauseButtonElement = class extends DawTransportButton {
1198
2033
  connectedCallback() {
1199
2034
  super.connectedCallback();
1200
2035
  requestAnimationFrame(() => {
1201
- const target = this.target;
1202
- if (!target) return;
1203
- this._targetRef = target;
1204
- target.addEventListener("daw-recording-start", this._onRecStart);
1205
- target.addEventListener("daw-recording-complete", this._onRecEnd);
1206
- target.addEventListener("daw-recording-error", this._onRecEnd);
1207
- target.addEventListener("daw-recording-pause", this._onRecPause);
1208
- target.addEventListener("daw-recording-resume", this._onRecResume);
2036
+ if (!this.isConnected) return;
2037
+ this._ensureTargetListeners();
1209
2038
  });
1210
2039
  }
1211
2040
  disconnectedCallback() {
1212
2041
  super.disconnectedCallback();
2042
+ this._cleanupListeners();
2043
+ }
2044
+ updated() {
2045
+ this._ensureTargetListeners();
2046
+ }
2047
+ _ensureTargetListeners() {
2048
+ const target = this.target;
2049
+ if (target === this._targetRef) return;
2050
+ if (this._targetRef) {
2051
+ this._isRecording = false;
2052
+ this._isPaused = false;
2053
+ }
2054
+ this._cleanupListeners();
2055
+ if (!target) return;
2056
+ this._targetRef = target;
2057
+ target.addEventListener("daw-recording-start", this._onRecStart);
2058
+ target.addEventListener("daw-recording-complete", this._onRecEnd);
2059
+ target.addEventListener("daw-recording-error", this._onRecEnd);
2060
+ target.addEventListener("daw-recording-pause", this._onRecPause);
2061
+ target.addEventListener("daw-recording-resume", this._onRecResume);
2062
+ }
2063
+ _cleanupListeners() {
1213
2064
  if (this._targetRef) {
1214
2065
  this._targetRef.removeEventListener("daw-recording-start", this._onRecStart);
1215
2066
  this._targetRef.removeEventListener("daw-recording-complete", this._onRecEnd);
@@ -1220,7 +2071,7 @@ var DawPauseButtonElement = class extends DawTransportButton {
1220
2071
  }
1221
2072
  }
1222
2073
  render() {
1223
- return html5`
2074
+ return html6`
1224
2075
  <button part="button" ?data-paused=${this._isPaused} @click=${this._onClick}>
1225
2076
  <slot>Pause</slot>
1226
2077
  </button>
@@ -1243,7 +2094,7 @@ var DawPauseButtonElement = class extends DawTransportButton {
1243
2094
  };
1244
2095
  DawPauseButtonElement.styles = [
1245
2096
  DawTransportButton.styles,
1246
- css5`
2097
+ css6`
1247
2098
  button[data-paused] {
1248
2099
  background: rgba(255, 255, 255, 0.1);
1249
2100
  border-color: var(--daw-controls-text, #e0d4c8);
@@ -1251,21 +2102,21 @@ DawPauseButtonElement.styles = [
1251
2102
  `
1252
2103
  ];
1253
2104
  __decorateClass([
1254
- state2()
2105
+ state3()
1255
2106
  ], DawPauseButtonElement.prototype, "_isPaused", 2);
1256
2107
  __decorateClass([
1257
- state2()
2108
+ state3()
1258
2109
  ], DawPauseButtonElement.prototype, "_isRecording", 2);
1259
2110
  DawPauseButtonElement = __decorateClass([
1260
- customElement8("daw-pause-button")
2111
+ customElement11("daw-pause-button")
1261
2112
  ], DawPauseButtonElement);
1262
2113
 
1263
2114
  // src/elements/daw-stop-button.ts
1264
- import { html as html6 } from "lit";
1265
- import { customElement as customElement9 } from "lit/decorators.js";
2115
+ import { html as html7 } from "lit";
2116
+ import { customElement as customElement12 } from "lit/decorators.js";
1266
2117
  var DawStopButtonElement = class extends DawTransportButton {
1267
2118
  render() {
1268
- return html6`
2119
+ return html7`
1269
2120
  <button part="button" @click=${this._onClick}>
1270
2121
  <slot>Stop</slot>
1271
2122
  </button>
@@ -1299,12 +2150,12 @@ var DawStopButtonElement = class extends DawTransportButton {
1299
2150
  }
1300
2151
  };
1301
2152
  DawStopButtonElement = __decorateClass([
1302
- customElement9("daw-stop-button")
2153
+ customElement12("daw-stop-button")
1303
2154
  ], DawStopButtonElement);
1304
2155
 
1305
2156
  // src/elements/daw-editor.ts
1306
- import { LitElement as LitElement11, html as html10, css as css10 } from "lit";
1307
- import { customElement as customElement13, property as property9, state as state3 } from "lit/decorators.js";
2157
+ import { LitElement as LitElement14, html as html12, css as css11 } from "lit";
2158
+ import { customElement as customElement16, property as property12, state as state4 } from "lit/decorators.js";
1308
2159
 
1309
2160
  // src/types.ts
1310
2161
  function isDomClip(desc) {
@@ -1487,6 +2338,12 @@ function createPeaksWorker() {
1487
2338
  )
1488
2339
  );
1489
2340
  },
2341
+ // Reports NOT terminated: CSP blocking is permanent for the page, so
2342
+ // recreating on every call would just re-attempt (and re-warn about)
2343
+ // Worker construction each time.
2344
+ isTerminated() {
2345
+ return false;
2346
+ },
1490
2347
  terminate() {
1491
2348
  }
1492
2349
  };
@@ -1524,6 +2381,9 @@ function createPeaksWorker() {
1524
2381
  pending.clear();
1525
2382
  };
1526
2383
  return {
2384
+ isTerminated() {
2385
+ return terminated;
2386
+ },
1527
2387
  generate(params) {
1528
2388
  if (terminated) return Promise.reject(new Error("Worker terminated"));
1529
2389
  const messageId = String(++idCounter2);
@@ -1739,6 +2599,12 @@ var PeakPipeline = class {
1739
2599
  scale: cached.scale
1740
2600
  };
1741
2601
  }
2602
+ /** Scale of the cached WaveformData for this buffer — 0 when not cached.
2603
+ * Worker generation caches at baseScale; injected .dat data at its own
2604
+ * scale. This is the finest zoom the buffer's peaks can render at. */
2605
+ getCachedScale(audioBuffer) {
2606
+ return this._cache.get(audioBuffer)?.scale ?? 0;
2607
+ }
1742
2608
  /**
1743
2609
  * Return the coarsest (largest) scale among cached WaveformData entries
1744
2610
  * that correspond to the given clip buffers. Returns 0 if none are cached.
@@ -1760,7 +2626,7 @@ var PeakPipeline = class {
1760
2626
  if (cached) return cached;
1761
2627
  const inflight = this._inflight.get(audioBuffer);
1762
2628
  if (inflight) return inflight;
1763
- if (!this._worker) {
2629
+ if (!this._worker || this._worker.isTerminated()) {
1764
2630
  this._worker = createPeaksWorker();
1765
2631
  }
1766
2632
  const channels = [];
@@ -1789,8 +2655,8 @@ var PeakPipeline = class {
1789
2655
  };
1790
2656
 
1791
2657
  // src/elements/daw-ruler.ts
1792
- import { LitElement as LitElement8, html as html7, css as css6 } from "lit";
1793
- import { customElement as customElement10, property as property6 } from "lit/decorators.js";
2658
+ import { LitElement as LitElement11, html as html8, css as css7 } from "lit";
2659
+ import { customElement as customElement13, property as property9 } from "lit/decorators.js";
1794
2660
 
1795
2661
  // src/utils/time-format.ts
1796
2662
  function formatTime(milliseconds) {
@@ -1869,7 +2735,7 @@ function getCachedMusicalTicks(params) {
1869
2735
 
1870
2736
  // src/elements/daw-ruler.ts
1871
2737
  var MAX_CANVAS_WIDTH3 = 1e3;
1872
- var DawRulerElement = class extends LitElement8 {
2738
+ var DawRulerElement = class extends LitElement11 {
1873
2739
  constructor() {
1874
2740
  super(...arguments);
1875
2741
  this.samplesPerPixel = 1024;
@@ -1913,17 +2779,17 @@ var DawRulerElement = class extends LitElement8 {
1913
2779
  }
1914
2780
  render() {
1915
2781
  const widthX = this.scaleMode === "beats" ? this.totalWidth : this._tickData?.widthX ?? 0;
1916
- if (widthX <= 0) return html7``;
2782
+ if (widthX <= 0) return html8``;
1917
2783
  const totalChunks = Math.ceil(widthX / MAX_CANVAS_WIDTH3);
1918
2784
  const indices = Array.from({ length: totalChunks }, (_, i) => i);
1919
2785
  const dpr = typeof devicePixelRatio !== "undefined" ? devicePixelRatio : 1;
1920
2786
  const beatsLabels = this.scaleMode === "beats" ? this._musicalTickData?.ticks.filter((t) => t.label) ?? [] : [];
1921
2787
  const temporalLabels = this.scaleMode !== "beats" ? this._tickData?.labels ?? [] : [];
1922
- return html7`
2788
+ return html8`
1923
2789
  <div class="container" style="width: ${widthX}px; height: ${this.rulerHeight}px;">
1924
2790
  ${indices.map((i) => {
1925
2791
  const width = Math.min(MAX_CANVAS_WIDTH3, widthX - i * MAX_CANVAS_WIDTH3);
1926
- return html7`
2792
+ return html8`
1927
2793
  <canvas
1928
2794
  data-index=${i}
1929
2795
  width=${width * dpr}
@@ -1933,13 +2799,13 @@ var DawRulerElement = class extends LitElement8 {
1933
2799
  `;
1934
2800
  })}
1935
2801
  ${this.scaleMode === "beats" ? beatsLabels.map(
1936
- (t) => html7`<span
2802
+ (t) => html8`<span
1937
2803
  class="label ${t.pixel > 0 ? "centered" : ""}"
1938
2804
  style="left: ${t.pixel > 0 ? t.pixel : t.pixel + 4}px;"
1939
2805
  >${t.label}</span
1940
2806
  >`
1941
2807
  ) : temporalLabels.map(
1942
- ({ pix, text }) => html7`<span class="label" style="left: ${pix + 4}px;">${text}</span>`
2808
+ ({ pix, text }) => html8`<span class="label" style="left: ${pix + 4}px;">${text}</span>`
1943
2809
  )}
1944
2810
  </div>
1945
2811
  `;
@@ -1990,7 +2856,7 @@ var DawRulerElement = class extends LitElement8 {
1990
2856
  }
1991
2857
  }
1992
2858
  };
1993
- DawRulerElement.styles = css6`
2859
+ DawRulerElement.styles = css7`
1994
2860
  :host {
1995
2861
  display: block;
1996
2862
  position: relative;
@@ -2016,40 +2882,40 @@ DawRulerElement.styles = css6`
2016
2882
  }
2017
2883
  `;
2018
2884
  __decorateClass([
2019
- property6({ type: Number, attribute: false })
2885
+ property9({ type: Number, attribute: false })
2020
2886
  ], DawRulerElement.prototype, "samplesPerPixel", 2);
2021
2887
  __decorateClass([
2022
- property6({ type: Number, attribute: false })
2888
+ property9({ type: Number, attribute: false })
2023
2889
  ], DawRulerElement.prototype, "sampleRate", 2);
2024
2890
  __decorateClass([
2025
- property6({ type: Number, attribute: false })
2891
+ property9({ type: Number, attribute: false })
2026
2892
  ], DawRulerElement.prototype, "duration", 2);
2027
2893
  __decorateClass([
2028
- property6({ type: Number, attribute: false })
2894
+ property9({ type: Number, attribute: false })
2029
2895
  ], DawRulerElement.prototype, "rulerHeight", 2);
2030
2896
  __decorateClass([
2031
- property6({ type: String, attribute: false })
2897
+ property9({ type: String, attribute: false })
2032
2898
  ], DawRulerElement.prototype, "scaleMode", 2);
2033
2899
  __decorateClass([
2034
- property6({ type: Number, attribute: false })
2900
+ property9({ type: Number, attribute: false })
2035
2901
  ], DawRulerElement.prototype, "ticksPerPixel", 2);
2036
2902
  __decorateClass([
2037
- property6({ attribute: false })
2903
+ property9({ attribute: false })
2038
2904
  ], DawRulerElement.prototype, "meterEntries", 2);
2039
2905
  __decorateClass([
2040
- property6({ type: Number, attribute: false })
2906
+ property9({ type: Number, attribute: false })
2041
2907
  ], DawRulerElement.prototype, "ppqn", 2);
2042
2908
  __decorateClass([
2043
- property6({ type: Number, attribute: false })
2909
+ property9({ type: Number, attribute: false })
2044
2910
  ], DawRulerElement.prototype, "totalWidth", 2);
2045
2911
  DawRulerElement = __decorateClass([
2046
- customElement10("daw-ruler")
2912
+ customElement13("daw-ruler")
2047
2913
  ], DawRulerElement);
2048
2914
 
2049
2915
  // src/elements/daw-track-controls.ts
2050
- import { LitElement as LitElement9, html as html8, css as css7 } from "lit";
2051
- import { customElement as customElement11, property as property7 } from "lit/decorators.js";
2052
- var DawTrackControlsElement = class extends LitElement9 {
2916
+ import { LitElement as LitElement12, html as html9, css as css8 } from "lit";
2917
+ import { customElement as customElement14, property as property10 } from "lit/decorators.js";
2918
+ var DawTrackControlsElement = class extends LitElement12 {
2053
2919
  constructor() {
2054
2920
  super(...arguments);
2055
2921
  this.trackId = null;
@@ -2108,7 +2974,7 @@ var DawTrackControlsElement = class extends LitElement9 {
2108
2974
  const volPercent = Math.round(this.volume * 100);
2109
2975
  const panPercent = Math.round(Math.abs(this.pan) * 100);
2110
2976
  const panDisplay = this.pan === 0 ? "C" : (this.pan > 0 ? "R" : "L") + panPercent;
2111
- return html8`
2977
+ return html9`
2112
2978
  <div class="header">
2113
2979
  <span class="name" title=${this.trackName}>${this.trackName || "Untitled"}</span>
2114
2980
  <button class="remove-btn" @click=${this._onRemoveClick} title="Remove track">
@@ -2158,7 +3024,7 @@ var DawTrackControlsElement = class extends LitElement9 {
2158
3024
  `;
2159
3025
  }
2160
3026
  };
2161
- DawTrackControlsElement.styles = css7`
3027
+ DawTrackControlsElement.styles = css8`
2162
3028
  :host {
2163
3029
  display: flex;
2164
3030
  flex-direction: column;
@@ -2310,33 +3176,33 @@ DawTrackControlsElement.styles = css7`
2310
3176
  }
2311
3177
  `;
2312
3178
  __decorateClass([
2313
- property7({ attribute: false })
3179
+ property10({ attribute: false })
2314
3180
  ], DawTrackControlsElement.prototype, "trackId", 2);
2315
3181
  __decorateClass([
2316
- property7({ attribute: false })
3182
+ property10({ attribute: false })
2317
3183
  ], DawTrackControlsElement.prototype, "trackName", 2);
2318
3184
  __decorateClass([
2319
- property7({ type: Number, attribute: false })
3185
+ property10({ type: Number, attribute: false })
2320
3186
  ], DawTrackControlsElement.prototype, "volume", 2);
2321
3187
  __decorateClass([
2322
- property7({ type: Number, attribute: false })
3188
+ property10({ type: Number, attribute: false })
2323
3189
  ], DawTrackControlsElement.prototype, "pan", 2);
2324
3190
  __decorateClass([
2325
- property7({ type: Boolean, attribute: false })
3191
+ property10({ type: Boolean, attribute: false })
2326
3192
  ], DawTrackControlsElement.prototype, "muted", 2);
2327
3193
  __decorateClass([
2328
- property7({ type: Boolean, attribute: false })
3194
+ property10({ type: Boolean, attribute: false })
2329
3195
  ], DawTrackControlsElement.prototype, "soloed", 2);
2330
3196
  DawTrackControlsElement = __decorateClass([
2331
- customElement11("daw-track-controls")
3197
+ customElement14("daw-track-controls")
2332
3198
  ], DawTrackControlsElement);
2333
3199
 
2334
3200
  // src/elements/daw-grid.ts
2335
- import { LitElement as LitElement10, html as html9, css as css8 } from "lit";
2336
- import { customElement as customElement12, property as property8 } from "lit/decorators.js";
3201
+ import { LitElement as LitElement13, html as html10, css as css9 } from "lit";
3202
+ import { customElement as customElement15, property as property11 } from "lit/decorators.js";
2337
3203
  import { MIN_PIXELS_PER_UNIT } from "@waveform-playlist/core";
2338
3204
  var MAX_CANVAS_WIDTH4 = 1e3;
2339
- var DawGridElement = class extends LitElement10 {
3205
+ var DawGridElement = class extends LitElement13 {
2340
3206
  constructor() {
2341
3207
  super(...arguments);
2342
3208
  this.ticksPerPixel = 24;
@@ -2364,7 +3230,7 @@ var DawGridElement = class extends LitElement10 {
2364
3230
  }
2365
3231
  }
2366
3232
  render() {
2367
- if (!this._tickData) return html9``;
3233
+ if (!this._tickData) return html10``;
2368
3234
  const totalWidth = this.length;
2369
3235
  const dpr = typeof devicePixelRatio !== "undefined" ? devicePixelRatio : 1;
2370
3236
  const indices = getVisibleChunkIndices(
@@ -2373,11 +3239,11 @@ var DawGridElement = class extends LitElement10 {
2373
3239
  this.visibleStart,
2374
3240
  this.visibleEnd
2375
3241
  );
2376
- return html9`
3242
+ return html10`
2377
3243
  <div class="container" style="width: ${totalWidth}px; height: ${this.height}px;">
2378
3244
  ${indices.map((i) => {
2379
3245
  const width = Math.min(MAX_CANVAS_WIDTH4, totalWidth - i * MAX_CANVAS_WIDTH4);
2380
- return html9`
3246
+ return html10`
2381
3247
  <canvas
2382
3248
  data-index=${i}
2383
3249
  width=${width * dpr}
@@ -2438,7 +3304,7 @@ var DawGridElement = class extends LitElement10 {
2438
3304
  }
2439
3305
  }
2440
3306
  };
2441
- DawGridElement.styles = css8`
3307
+ DawGridElement.styles = css9`
2442
3308
  :host {
2443
3309
  display: block;
2444
3310
  position: absolute;
@@ -2456,33 +3322,33 @@ DawGridElement.styles = css8`
2456
3322
  }
2457
3323
  `;
2458
3324
  __decorateClass([
2459
- property8({ type: Number, attribute: false })
3325
+ property11({ type: Number, attribute: false })
2460
3326
  ], DawGridElement.prototype, "ticksPerPixel", 2);
2461
3327
  __decorateClass([
2462
- property8({ attribute: false })
3328
+ property11({ attribute: false })
2463
3329
  ], DawGridElement.prototype, "meterEntries", 2);
2464
3330
  __decorateClass([
2465
- property8({ type: Number, attribute: false })
3331
+ property11({ type: Number, attribute: false })
2466
3332
  ], DawGridElement.prototype, "ppqn", 2);
2467
3333
  __decorateClass([
2468
- property8({ type: Number, attribute: false })
3334
+ property11({ type: Number, attribute: false })
2469
3335
  ], DawGridElement.prototype, "visibleStart", 2);
2470
3336
  __decorateClass([
2471
- property8({ type: Number, attribute: false })
3337
+ property11({ type: Number, attribute: false })
2472
3338
  ], DawGridElement.prototype, "visibleEnd", 2);
2473
3339
  __decorateClass([
2474
- property8({ type: Number, attribute: false })
3340
+ property11({ type: Number, attribute: false })
2475
3341
  ], DawGridElement.prototype, "length", 2);
2476
3342
  __decorateClass([
2477
- property8({ type: Number, attribute: false })
3343
+ property11({ type: Number, attribute: false })
2478
3344
  ], DawGridElement.prototype, "height", 2);
2479
3345
  DawGridElement = __decorateClass([
2480
- customElement12("daw-grid")
3346
+ customElement15("daw-grid")
2481
3347
  ], DawGridElement);
2482
3348
 
2483
3349
  // src/styles/theme.ts
2484
- import { css as css9 } from "lit";
2485
- var hostStyles = css9`
3350
+ import { css as css10 } from "lit";
3351
+ var hostStyles = css10`
2486
3352
  :host {
2487
3353
  --daw-wave-color: #c49a6c;
2488
3354
  --daw-progress-color: #63c75f;
@@ -2498,7 +3364,7 @@ var hostStyles = css9`
2498
3364
  --daw-clip-header-text: #e0d4c8;
2499
3365
  }
2500
3366
  `;
2501
- var clipStyles = css9`
3367
+ var clipStyles = css10`
2502
3368
  .clip-container {
2503
3369
  position: absolute;
2504
3370
  overflow: hidden;
@@ -2751,7 +3617,11 @@ var RecordingController = class {
2751
3617
  * The session is only set after several awaits — without this, two rapid
2752
3618
  * start calls both pass the _sessions guard and build two capture
2753
3619
  * pipelines feeding one session (garbled audio + a leaked worklet). */
2754
- this._starting = /* @__PURE__ */ new Set();
3620
+ this._starting = /* @__PURE__ */ new Map();
3621
+ /** True between hostDisconnected and hostConnected. An in-flight
3622
+ * startRecording consults this after its awaits so a teardown mid-setup
3623
+ * doesn't leak a live capture session on a detached editor. */
3624
+ this._hostDisconnected = false;
2755
3625
  this._workletLoadedCtx = null;
2756
3626
  /** Tracks worklet pause state explicitly so external consumers (editor,
2757
3627
  * pause button, spacebar) can share one source of truth. */
@@ -2760,15 +3630,17 @@ var RecordingController = class {
2760
3630
  host.addController(this);
2761
3631
  }
2762
3632
  hostConnected() {
3633
+ this._hostDisconnected = false;
2763
3634
  }
2764
3635
  hostDisconnected() {
3636
+ this._hostDisconnected = true;
2765
3637
  for (const trackId of [...this._sessions.keys()]) {
2766
3638
  this._cleanupSession(trackId, true);
2767
3639
  }
2768
3640
  this._workletLoadedCtx = null;
2769
3641
  }
2770
3642
  get isRecording() {
2771
- return this._sessions.size > 0;
3643
+ return this._sessions.size > 0 || this._starting.size > 0;
2772
3644
  }
2773
3645
  get isPaused() {
2774
3646
  return this._isPaused && this._sessions.size > 0;
@@ -2786,7 +3658,14 @@ var RecordingController = class {
2786
3658
  console.warn('[dawcore] RecordingController: Already recording on track "' + trackId + '"');
2787
3659
  return;
2788
3660
  }
2789
- this._starting.add(trackId);
3661
+ let resolveStartSettled;
3662
+ const startEntry = {
3663
+ stopRequested: false,
3664
+ done: new Promise((resolve) => {
3665
+ resolveStartSettled = resolve;
3666
+ })
3667
+ };
3668
+ this._starting.set(trackId, startEntry);
2790
3669
  const bits = options.bits ?? 16;
2791
3670
  try {
2792
3671
  const rawCtx = this._host.audioContext;
@@ -2807,6 +3686,15 @@ var RecordingController = class {
2807
3686
  await addRecordingWorkletModule(addModule);
2808
3687
  this._workletLoadedCtx = rawCtx;
2809
3688
  }
3689
+ if (startEntry.stopRequested || this._hostDisconnected) {
3690
+ this._dispatchRecordingError(
3691
+ trackId,
3692
+ new Error(
3693
+ this._hostDisconnected ? "Recording start cancelled: editor was disconnected during setup" : "Recording start cancelled: stop requested before setup completed"
3694
+ )
3695
+ );
3696
+ return;
3697
+ }
2810
3698
  const detectedChannelCount = stream.getAudioTracks()[0]?.getSettings()?.channelCount;
2811
3699
  if (detectedChannelCount === void 0 && options.channelCount !== void 0) {
2812
3700
  console.warn(
@@ -2889,15 +3777,10 @@ var RecordingController = class {
2889
3777
  } catch (err) {
2890
3778
  this._cleanupSession(trackId);
2891
3779
  console.warn("[dawcore] RecordingController: Failed to start recording: " + String(err));
2892
- this._host.dispatchEvent(
2893
- new CustomEvent("daw-recording-error", {
2894
- bubbles: true,
2895
- composed: true,
2896
- detail: { trackId, error: err }
2897
- })
2898
- );
3780
+ this._dispatchRecordingError(trackId, err);
2899
3781
  } finally {
2900
3782
  this._starting.delete(trackId);
3783
+ resolveStartSettled();
2901
3784
  }
2902
3785
  }
2903
3786
  pauseRecording(trackId) {
@@ -2931,10 +3814,17 @@ var RecordingController = class {
2931
3814
  );
2932
3815
  }
2933
3816
  async stopRecording(trackId) {
2934
- const id = trackId ?? [...this._sessions.keys()][0];
3817
+ const id = trackId ?? [...this._sessions.keys()][0] ?? [...this._starting.keys()][0];
2935
3818
  if (!id) return;
2936
3819
  const session = this._sessions.get(id);
2937
- if (!session) return;
3820
+ if (!session) {
3821
+ const starting = this._starting.get(id);
3822
+ if (starting) {
3823
+ starting.stopRequested = true;
3824
+ return starting.done;
3825
+ }
3826
+ return;
3827
+ }
2938
3828
  if (session.stopping) {
2939
3829
  return session.stopPromise ?? void 0;
2940
3830
  }
@@ -2944,6 +3834,19 @@ var RecordingController = class {
2944
3834
  return stopPromise;
2945
3835
  }
2946
3836
  async _finishStopRecording(id, session) {
3837
+ try {
3838
+ await this._finalizeRecording(id, session);
3839
+ } catch (err) {
3840
+ const sessionWasActive = this._sessions.has(id);
3841
+ console.warn("[dawcore] RecordingController: Failed to finalize recording: " + String(err));
3842
+ this._cleanupSession(id);
3843
+ this._host.requestUpdate();
3844
+ if (sessionWasActive) {
3845
+ this._dispatchRecordingError(id, err);
3846
+ }
3847
+ }
3848
+ }
3849
+ async _finalizeRecording(id, session) {
2947
3850
  const wasPaused = this._isPaused;
2948
3851
  this._isPaused = false;
2949
3852
  if (session.wasOverdub && typeof this._host.stop === "function") {
@@ -2970,16 +3873,7 @@ var RecordingController = class {
2970
3873
  session.workletNode.disconnect();
2971
3874
  this._removeTrackEndedListener(session);
2972
3875
  if (session.totalSamples === 0) {
2973
- console.warn("[dawcore] RecordingController: No audio data captured");
2974
- this._sessions.delete(id);
2975
- this._host.requestUpdate();
2976
- this._host.dispatchEvent(
2977
- new CustomEvent("daw-recording-error", {
2978
- bubbles: true,
2979
- composed: true,
2980
- detail: { trackId: id, error: new Error("No audio data captured") }
2981
- })
2982
- );
3876
+ this._abandonFinalize(id, session, "No audio data captured");
2983
3877
  return;
2984
3878
  }
2985
3879
  const stopCtx = this._host.audioContext;
@@ -2993,16 +3887,11 @@ var RecordingController = class {
2993
3887
  const latencyOffsetSamples = session.latencySamples;
2994
3888
  const effectiveDuration = Math.max(0, audioBuffer.length - latencyOffsetSamples);
2995
3889
  if (effectiveDuration === 0) {
2996
- console.warn("[dawcore] RecordingController: Recording too short for latency compensation");
2997
- this._restoreArmedTrackMute(session);
2998
- this._sessions.delete(id);
2999
- this._host.requestUpdate();
3000
- this._host.dispatchEvent(
3001
- new CustomEvent("daw-recording-error", {
3002
- bubbles: true,
3003
- composed: true,
3004
- detail: { trackId: id, error: new Error("Recording too short to save") }
3005
- })
3890
+ this._abandonFinalize(
3891
+ id,
3892
+ session,
3893
+ "Recording too short for latency compensation",
3894
+ "Recording too short to save"
3006
3895
  );
3007
3896
  return;
3008
3897
  }
@@ -3137,6 +4026,26 @@ var RecordingController = class {
3137
4026
  session._audioTrack.removeEventListener("ended", session._onTrackEnded);
3138
4027
  }
3139
4028
  }
4029
+ _dispatchRecordingError(trackId, error) {
4030
+ this._host.dispatchEvent(
4031
+ new CustomEvent("daw-recording-error", {
4032
+ bubbles: true,
4033
+ composed: true,
4034
+ detail: { trackId, error }
4035
+ })
4036
+ );
4037
+ }
4038
+ /** Shared teardown for finalize paths that end without a take (no data
4039
+ * captured / too short after latency compensation): restore the armed-track
4040
+ * mute, drop the session, and notify via daw-recording-error so record
4041
+ * buttons reset their state. */
4042
+ _abandonFinalize(id, session, warnMessage, errorMessage = warnMessage) {
4043
+ console.warn("[dawcore] RecordingController: " + warnMessage);
4044
+ this._restoreArmedTrackMute(session);
4045
+ this._sessions.delete(id);
4046
+ this._host.requestUpdate();
4047
+ this._dispatchRecordingError(id, new Error(errorMessage));
4048
+ }
3140
4049
  /** Restore the armed track's pre-session mute state (idempotent — safe to
3141
4050
  * call from both the finalize path and _cleanupSession). */
3142
4051
  _restoreArmedTrackMute(session) {
@@ -3166,20 +4075,196 @@ var RecordingController = class {
3166
4075
  this._isPaused = false;
3167
4076
  }
3168
4077
  if (notifyError) {
3169
- this._host.dispatchEvent(
3170
- new CustomEvent("daw-recording-error", {
3171
- bubbles: true,
3172
- composed: true,
3173
- detail: {
3174
- trackId,
3175
- error: new Error("Recording cancelled: editor was disconnected mid-recording")
3176
- }
3177
- })
4078
+ this._dispatchRecordingError(
4079
+ trackId,
4080
+ new Error("Recording cancelled: editor was disconnected mid-recording")
3178
4081
  );
3179
4082
  }
3180
4083
  }
3181
4084
  };
3182
4085
 
4086
+ // src/controllers/annotation-controller.ts
4087
+ import { html as html11 } from "lit";
4088
+ var ANNOTATION_LANE_HEIGHT = 32;
4089
+ var AnnotationController = class {
4090
+ constructor(host) {
4091
+ this._tracks = [];
4092
+ this._removalObserver = null;
4093
+ /** Playback-following highlight per track, separate from each track's
4094
+ * `activeAnnotationId` (selection) so playback never disturbs selection.
4095
+ * Driven by daw-timeupdate, cleared on daw-stop, retained on pause.
4096
+ * Replaced immutably (a fresh Map) on every change. */
4097
+ this._playingIds = /* @__PURE__ */ new Map();
4098
+ this._onDataChange = () => {
4099
+ this.deriveSecondsCaches();
4100
+ this._host.requestUpdate();
4101
+ };
4102
+ /**
4103
+ * Update only on annotation-boundary crossings, not per animation frame.
4104
+ */
4105
+ this._onTimeUpdate = (e) => {
4106
+ const time = e.detail.time;
4107
+ let changed = false;
4108
+ const next = new Map(this._playingIds);
4109
+ for (const track of this._tracks) {
4110
+ const playingId = computePlayingAnnotationId(track.annotations, time);
4111
+ if (playingId !== (this._playingIds.get(track) ?? null)) {
4112
+ next.set(track, playingId);
4113
+ changed = true;
4114
+ }
4115
+ }
4116
+ if (!changed) return;
4117
+ this._playingIds = next;
4118
+ this._host.requestUpdate();
4119
+ };
4120
+ this._onStop = () => {
4121
+ if (this._playingIds.size === 0) return;
4122
+ this._playingIds = /* @__PURE__ */ new Map();
4123
+ this._host.requestUpdate();
4124
+ };
4125
+ this._host = host;
4126
+ host.addController(this);
4127
+ }
4128
+ get tracks() {
4129
+ return this._tracks;
4130
+ }
4131
+ /** Current playback-following highlight id for a track, or `null` when the
4132
+ * playhead isn't inside any of the track's annotations. */
4133
+ getPlayingAnnotationId(track) {
4134
+ return this._playingIds.get(track) ?? null;
4135
+ }
4136
+ get totalLaneHeight() {
4137
+ return this._tracks.length * ANNOTATION_LANE_HEIGHT;
4138
+ }
4139
+ /** Max annotation end (seconds) across registered tracks — 0 when none.
4140
+ * Lets the editor extend the timeline so annotations past the audio stay
4141
+ * reachable/scrollable. */
4142
+ get maxAnnotationEndSeconds() {
4143
+ return this._tracks.reduce(
4144
+ (max, track) => track.annotations.reduce((m, a) => Math.max(m, a.end), max),
4145
+ 0
4146
+ );
4147
+ }
4148
+ hostConnected() {
4149
+ this._host.addEventListener("daw-annotation-update", this._onDataChange);
4150
+ this._host.addEventListener("daw-annotation-select", this._onDataChange);
4151
+ this._host.addEventListener("daw-annotation-connected", this._onDataChange);
4152
+ this._host.addEventListener("daw-timeupdate", this._onTimeUpdate);
4153
+ this._host.addEventListener("daw-stop", this._onStop);
4154
+ this._removalObserver = new MutationObserver((mutations) => {
4155
+ let changed = false;
4156
+ for (const m of mutations) {
4157
+ for (const node of Array.from(m.removedNodes)) {
4158
+ if (!(node instanceof HTMLElement)) continue;
4159
+ if (node.tagName === "DAW-ANNOTATION-TRACK") {
4160
+ this._tracks = this._tracks.filter((t) => t !== node);
4161
+ changed = true;
4162
+ } else if (node.tagName === "DAW-ANNOTATION") {
4163
+ changed = true;
4164
+ }
4165
+ const nestedTracks = node.querySelectorAll?.("daw-annotation-track");
4166
+ if (nestedTracks) {
4167
+ for (const nested of nestedTracks) {
4168
+ this._tracks = this._tracks.filter((t) => t !== nested);
4169
+ changed = true;
4170
+ }
4171
+ }
4172
+ const nestedAnnotations = node.querySelectorAll?.("daw-annotation");
4173
+ if (nestedAnnotations && nestedAnnotations.length > 0) {
4174
+ changed = true;
4175
+ }
4176
+ }
4177
+ }
4178
+ if (changed) this._host.requestUpdate();
4179
+ });
4180
+ this._removalObserver.observe(this._host, { childList: true, subtree: true });
4181
+ }
4182
+ hostDisconnected() {
4183
+ this._host.removeEventListener("daw-annotation-update", this._onDataChange);
4184
+ this._host.removeEventListener("daw-annotation-select", this._onDataChange);
4185
+ this._host.removeEventListener("daw-annotation-connected", this._onDataChange);
4186
+ this._host.removeEventListener("daw-timeupdate", this._onTimeUpdate);
4187
+ this._host.removeEventListener("daw-stop", this._onStop);
4188
+ this._removalObserver?.disconnect();
4189
+ this._removalObserver = null;
4190
+ this._tracks = [];
4191
+ this._playingIds = /* @__PURE__ */ new Map();
4192
+ }
4193
+ handleTrackConnected(el) {
4194
+ if (this._tracks.includes(el)) return;
4195
+ this._tracks = [...this._tracks, el];
4196
+ this._host.requestUpdate();
4197
+ this.deriveSecondsCaches();
4198
+ }
4199
+ /**
4200
+ * Keep the seconds attributes (derived cache) of tick-based annotations in
4201
+ * sync with the host's tempo. Write-only-on-change: a write fires
4202
+ * daw-annotation-update → _onDataChange → this sweep again → values equal →
4203
+ * no write → the loop settles (idempotent).
4204
+ */
4205
+ deriveSecondsCaches() {
4206
+ for (const track of this._tracks) {
4207
+ for (const el of track.annotationElements) {
4208
+ if (!el.isTickBased) continue;
4209
+ const startSeconds = this._host._ticksToSeconds(el.startTick);
4210
+ const endSeconds = this._host._ticksToSeconds(el.endTick);
4211
+ if (el.start !== startSeconds) el.start = startSeconds;
4212
+ if (el.end !== endSeconds) el.end = endSeconds;
4213
+ }
4214
+ }
4215
+ }
4216
+ /** Pixel geometry for one annotation box. Tick-based annotations in beats
4217
+ * mode use CLIP-IDENTICAL tick math (round(tick / ticksPerPixel)) so they
4218
+ * align pixel-exactly with <daw-grid>; everything else uses the floor-based
4219
+ * seconds math (temporal mode reads the always-fresh seconds cache). */
4220
+ boxGeometry(a, spp, sampleRate, ticksPerPixel = null) {
4221
+ if (ticksPerPixel !== null && ticksPerPixel > 0 && a.startTick !== void 0 && a.endTick !== void 0) {
4222
+ const left2 = Math.round(a.startTick / ticksPerPixel);
4223
+ const width2 = Math.round(a.endTick / ticksPerPixel) - left2;
4224
+ return { left: left2, width: width2 };
4225
+ }
4226
+ const left = Math.floor(a.start * sampleRate / spp);
4227
+ const width = Math.floor(a.end * sampleRate / spp) - left;
4228
+ return { left, width };
4229
+ }
4230
+ /**
4231
+ * Lane templates for the editor's .timeline. onPointerDown is supplied by
4232
+ * the editor and dispatches into the drag interaction (Task 9).
4233
+ */
4234
+ renderLanes(spp, sampleRate, onPointerDown = () => {
4235
+ }, ticksPerPixel = null) {
4236
+ return this._tracks.map((track) => {
4237
+ const activeId = track.activeAnnotationId;
4238
+ const playingId = this._playingIds.get(track) ?? null;
4239
+ const elements = track.annotationElements;
4240
+ return html11`
4241
+ <div
4242
+ class="annotation-lane"
4243
+ style="height: ${ANNOTATION_LANE_HEIGHT}px;"
4244
+ @pointerdown=${(e) => onPointerDown(e, track)}
4245
+ >
4246
+ ${elements.map((el, i) => {
4247
+ const a = el.toAnnotationData();
4248
+ const geo = this.boxGeometry(a, spp, sampleRate, ticksPerPixel);
4249
+ const label = track.boxLabel === "none" ? "" : track.boxLabel === "id" ? el.id || String(i + 1) : a.lines.join(" ");
4250
+ return html11`
4251
+ <div
4252
+ class="annotation-box ${a.id === activeId ? "active" : ""} ${a.id === playingId ? "playing" : ""}"
4253
+ data-annotation-id=${a.id}
4254
+ style="left: ${geo.left}px; width: ${geo.width}px;"
4255
+ >
4256
+ ${track.editable ? html11`<div class="annotation-boundary" data-edge="start"></div>` : ""}
4257
+ <span class="annotation-box-text">${label}</span>
4258
+ ${track.editable ? html11`<div class="annotation-boundary" data-edge="end"></div>` : ""}
4259
+ </div>
4260
+ `;
4261
+ })}
4262
+ </div>
4263
+ `;
4264
+ });
4265
+ }
4266
+ };
4267
+
3183
4268
  // src/controllers/spectrogram-controller.ts
3184
4269
  import {
3185
4270
  SpectrogramOrchestrator
@@ -3240,8 +4325,8 @@ var SpectrogramController = class {
3240
4325
  unregisterCanvas(canvasId) {
3241
4326
  this.orchestrator?.unregisterCanvas(canvasId);
3242
4327
  }
3243
- setViewport(state8) {
3244
- this.orchestrator?.setViewport(state8);
4328
+ setViewport(state9) {
4329
+ this.orchestrator?.setViewport(state9);
3245
4330
  }
3246
4331
  dispose() {
3247
4332
  if (this.orchestrator) {
@@ -3321,6 +4406,14 @@ var PointerHandler = class {
3321
4406
  this._timeline = null;
3322
4407
  // Cached from onPointerDown to avoid forced layout reflows at 60fps during drag
3323
4408
  this._timelineRect = null;
4409
+ /** Pointer that started the current interaction — a pointercancel from any
4410
+ * OTHER pointer (palm rejection on touch) must not kill the active drag. */
4411
+ this._activePointerId = null;
4412
+ // Selection values at pointerdown — restored on cancel so an interrupted
4413
+ // drag doesn't destroy a previously committed selection (which the engine
4414
+ // still holds; zeroing only the host would desync the two).
4415
+ this._preDragSelectionStart = 0;
4416
+ this._preDragSelectionEnd = 0;
3324
4417
  this.onPointerDown = (e) => {
3325
4418
  const clipHandler = this._host._clipHandler;
3326
4419
  if (clipHandler) {
@@ -3335,12 +4428,12 @@ var PointerHandler = class {
3335
4428
  console.warn("[dawcore] setPointerCapture failed: " + String(err));
3336
4429
  }
3337
4430
  const onMove = (me) => clipHandler.onPointerMove(me);
3338
- const onUp = (ue) => {
3339
- clipHandler.onPointerUp(ue);
4431
+ const detach = (pe) => {
3340
4432
  this._timeline?.removeEventListener("pointermove", onMove);
3341
4433
  this._timeline?.removeEventListener("pointerup", onUp);
4434
+ this._timeline?.removeEventListener("pointercancel", onCancel);
3342
4435
  try {
3343
- this._timeline?.releasePointerCapture(ue.pointerId);
4436
+ this._timeline?.releasePointerCapture(pe.pointerId);
3344
4437
  } catch (err) {
3345
4438
  console.warn(
3346
4439
  "[dawcore] releasePointerCapture failed (may already be released): " + String(err)
@@ -3348,8 +4441,19 @@ var PointerHandler = class {
3348
4441
  }
3349
4442
  this._timeline = null;
3350
4443
  };
4444
+ const onUp = (ue) => {
4445
+ clipHandler.onPointerUp(ue);
4446
+ detach(ue);
4447
+ };
4448
+ const downPointerId = e.pointerId;
4449
+ const onCancel = (ce) => {
4450
+ if (ce.pointerId !== downPointerId) return;
4451
+ clipHandler.onPointerCancel(ce);
4452
+ detach(ce);
4453
+ };
3351
4454
  this._timeline.addEventListener("pointermove", onMove);
3352
4455
  this._timeline.addEventListener("pointerup", onUp);
4456
+ this._timeline.addEventListener("pointercancel", onCancel);
3353
4457
  }
3354
4458
  return;
3355
4459
  }
@@ -3364,6 +4468,9 @@ var PointerHandler = class {
3364
4468
  this._timelineRect = this._timeline.getBoundingClientRect();
3365
4469
  this._dragStartPx = this._pxFromPointer(e);
3366
4470
  this._isDragging = false;
4471
+ this._activePointerId = e.pointerId;
4472
+ this._preDragSelectionStart = this._host._selectionStartTime;
4473
+ this._preDragSelectionEnd = this._host._selectionEndTime;
3367
4474
  try {
3368
4475
  this._timeline.setPointerCapture(e.pointerId);
3369
4476
  } catch (err) {
@@ -3371,6 +4478,7 @@ var PointerHandler = class {
3371
4478
  }
3372
4479
  this._timeline.addEventListener("pointermove", this._onPointerMove);
3373
4480
  this._timeline.addEventListener("pointerup", this._onPointerUp);
4481
+ this._timeline.addEventListener("pointercancel", this._onPointerCancel);
3374
4482
  };
3375
4483
  this._onPointerMove = (e) => {
3376
4484
  if (!this._timeline) return;
@@ -3394,15 +4502,7 @@ var PointerHandler = class {
3394
4502
  };
3395
4503
  this._onPointerUp = (e) => {
3396
4504
  if (!this._timeline) return;
3397
- try {
3398
- this._timeline.releasePointerCapture(e.pointerId);
3399
- } catch (err) {
3400
- console.warn(
3401
- "[dawcore] releasePointerCapture failed (may already be released): " + String(err)
3402
- );
3403
- }
3404
- this._timeline.removeEventListener("pointermove", this._onPointerMove);
3405
- this._timeline.removeEventListener("pointerup", this._onPointerUp);
4505
+ this._detachTimeline(e);
3406
4506
  try {
3407
4507
  if (this._isDragging) {
3408
4508
  this._finalizeSelection();
@@ -3412,10 +4512,29 @@ var PointerHandler = class {
3412
4512
  } catch (err) {
3413
4513
  console.warn("[dawcore] Pointer interaction failed: " + String(err));
3414
4514
  } finally {
3415
- this._isDragging = false;
3416
- this._timeline = null;
3417
- this._timelineRect = null;
4515
+ this._resetInteractionState();
4516
+ }
4517
+ };
4518
+ /** pointercancel fires INSTEAD of pointerup on touch interruption / pen
4519
+ * leaving range / OS gestures — discard the interaction (no seek, no
4520
+ * selection finalize) and detach the drag listeners, or the still-attached
4521
+ * move handler keeps mutating the selection on hover with a stale rect. */
4522
+ this._onPointerCancel = (e) => {
4523
+ if (!this._timeline) return;
4524
+ if (e.pointerId !== this._activePointerId) return;
4525
+ this._detachTimeline(e);
4526
+ if (this._isDragging) {
4527
+ const h = this._host;
4528
+ h._selectionStartTime = this._preDragSelectionStart;
4529
+ h._selectionEndTime = this._preDragSelectionEnd;
4530
+ const sel = h.shadowRoot?.querySelector("daw-selection");
4531
+ if (sel) {
4532
+ sel.startPx = this._timeToPx(this._preDragSelectionStart);
4533
+ sel.endPx = this._timeToPx(this._preDragSelectionEnd);
4534
+ }
4535
+ h.requestUpdate();
3418
4536
  }
4537
+ this._resetInteractionState();
3419
4538
  };
3420
4539
  this._host = host;
3421
4540
  }
@@ -3443,6 +4562,28 @@ var PointerHandler = class {
3443
4562
  }
3444
4563
  return time * h.effectiveSampleRate / h.samplesPerPixel;
3445
4564
  }
4565
+ /** Detach the drag listeners and release capture — shared by the up and
4566
+ * cancel terminals so a new listener added to onPointerDown can't be
4567
+ * missed on one of them. */
4568
+ _detachTimeline(e) {
4569
+ if (!this._timeline) return;
4570
+ try {
4571
+ this._timeline.releasePointerCapture(e.pointerId);
4572
+ } catch (err) {
4573
+ console.warn(
4574
+ "[dawcore] releasePointerCapture failed (may already be released): " + String(err)
4575
+ );
4576
+ }
4577
+ this._timeline.removeEventListener("pointermove", this._onPointerMove);
4578
+ this._timeline.removeEventListener("pointerup", this._onPointerUp);
4579
+ this._timeline.removeEventListener("pointercancel", this._onPointerCancel);
4580
+ }
4581
+ _resetInteractionState() {
4582
+ this._isDragging = false;
4583
+ this._timeline = null;
4584
+ this._timelineRect = null;
4585
+ this._activePointerId = null;
4586
+ }
3446
4587
  _finalizeSelection() {
3447
4588
  const h = this._host;
3448
4589
  if (h._engine) {
@@ -3778,6 +4919,23 @@ var ClipPointerHandler = class {
3778
4919
  this._reset();
3779
4920
  }
3780
4921
  }
4922
+ /** Processes pointercancel — reverts the in-progress drag.
4923
+ *
4924
+ * pointercancel fires INSTEAD of pointerup on touch interruption, pen
4925
+ * leaving hover range, or OS gestures. Without this handler the drag stays
4926
+ * armed (hover keeps moving the clip), the engine transaction stays open
4927
+ * (every later edit becomes un-undoable until some drag commits), and the
4928
+ * per-frame skipAdapter moveClip mutations are never synced or rolled back
4929
+ * (waveform and audio permanently disagree). */
4930
+ onPointerCancel(_e) {
4931
+ if (this._mode === null) return;
4932
+ try {
4933
+ this._restoreTrimVisual();
4934
+ } finally {
4935
+ this._host.engine?.abortTransaction();
4936
+ this._reset();
4937
+ }
4938
+ }
3781
4939
  /** Re-extract peaks from cache and set on waveform elements during trim drag.
3782
4940
  * Returns true if peaks were successfully updated. */
3783
4941
  _updateWaveformPeaks(offsetSamples, durationSamples) {
@@ -3795,7 +4953,11 @@ var ClipPointerHandler = class {
3795
4953
  }
3796
4954
  return true;
3797
4955
  }
3798
- /** Restore clip container CSS to original values after trim visual preview. */
4956
+ /** Restore clip container CSS AND waveform peaks to original values after
4957
+ * a trim visual preview. Peaks matter: the drag wrote re-extracted peak
4958
+ * arrays imperatively onto the <daw-waveform> elements (bypassing Lit), and
4959
+ * a cancelled/zero-delta trim makes no engine mutation — so no statechange
4960
+ * re-render will ever repair them. */
3799
4961
  _restoreTrimVisual() {
3800
4962
  if (this._clipContainer) {
3801
4963
  this._clipContainer.style.left = this._originalLeft + "px";
@@ -3804,25 +4966,168 @@ var ClipPointerHandler = class {
3804
4966
  for (const wf of waveforms) {
3805
4967
  wf.style.left = "0px";
3806
4968
  }
3807
- }
4969
+ this._updateWaveformPeaks(this._originalOffsetSamples, this._originalDurationSamples);
4970
+ }
4971
+ }
4972
+ _reset() {
4973
+ if (this._boundaryEl) {
4974
+ this._boundaryEl.classList.remove("dragging");
4975
+ this._boundaryEl = null;
4976
+ }
4977
+ this._mode = null;
4978
+ this._clipId = "";
4979
+ this._trackId = "";
4980
+ this._startPx = 0;
4981
+ this._isDragging = false;
4982
+ this._cumulativeDeltaSamples = 0;
4983
+ this._clipContainer = null;
4984
+ this._originalLeft = 0;
4985
+ this._originalWidth = 0;
4986
+ this._originalOffsetSamples = 0;
4987
+ this._originalDurationSamples = 0;
4988
+ this._originalStartSample = 0;
4989
+ }
4990
+ };
4991
+
4992
+ // src/interactions/annotation-drag.ts
4993
+ import { updateAnnotationBoundaries as updateAnnotationBoundaries2, snapTickToGrid as snapTickToGrid3 } from "@waveform-playlist/core";
4994
+ import {
4995
+ ANNOTATION_LINK_THRESHOLD_TICKS as ANNOTATION_LINK_THRESHOLD_TICKS2,
4996
+ annotationMinDurationTicks as annotationMinDurationTicks2
4997
+ } from "@waveform-playlist/core";
4998
+ var AnnotationDragHandler = class {
4999
+ constructor(host) {
5000
+ this._drag = null;
5001
+ this.onPointerDown = (e, track) => {
5002
+ const target = e.target;
5003
+ const boundary = target.closest(".annotation-boundary");
5004
+ const box = target.closest(".annotation-box");
5005
+ if (!box) return;
5006
+ const annotationId = box.getAttribute("data-annotation-id") ?? "";
5007
+ const isBoundary = boundary !== null && track.editable;
5008
+ if (boundary !== null && !track.editable) {
5009
+ return;
5010
+ }
5011
+ e.stopPropagation();
5012
+ e.preventDefault();
5013
+ const elements = track.annotationElements;
5014
+ const el = elements.find((x) => x.annotationId === annotationId);
5015
+ if (!el) return;
5016
+ const mode = el.isTickBased ? "ticks" : "seconds";
5017
+ const snapshot = mode === "ticks" ? elements.map((x) => tickSpaceData(x, this._host)) : track.annotations;
5018
+ const index = snapshot.findIndex((a) => a.id === annotationId);
5019
+ if (index === -1) return;
5020
+ const edge = isBoundary ? boundary.getAttribute("data-edge") : null;
5021
+ const captureEl = isBoundary ? boundary : box;
5022
+ this._drag = {
5023
+ track,
5024
+ captureEl,
5025
+ pointerId: e.pointerId,
5026
+ startClientX: e.clientX,
5027
+ moved: false,
5028
+ edge,
5029
+ annotationId,
5030
+ mode,
5031
+ snapshot,
5032
+ // edgeTime holds ticks in 'ticks' mode, seconds in 'seconds' mode.
5033
+ edgeTime: edge === "start" ? snapshot[index].start : snapshot[index].end
5034
+ };
5035
+ try {
5036
+ captureEl.setPointerCapture(e.pointerId);
5037
+ } catch {
5038
+ }
5039
+ captureEl.addEventListener("pointermove", this._onPointerMove);
5040
+ captureEl.addEventListener("pointerup", this._onPointerUp);
5041
+ captureEl.addEventListener("pointercancel", this._onPointerCancel);
5042
+ };
5043
+ /** Non-private (underscore convention) so tests can drive moves directly. */
5044
+ this._onPointerMove = (e) => {
5045
+ const drag = this._drag;
5046
+ if (!drag || e.pointerId !== drag.pointerId) return;
5047
+ const deltaPx = e.clientX - drag.startClientX;
5048
+ if (Math.abs(deltaPx) >= DRAG_THRESHOLD) drag.moved = true;
5049
+ if (drag.edge === null || !drag.moved) return;
5050
+ const elements = drag.track.annotationElements;
5051
+ const index = drag.snapshot.findIndex((a) => a.id === drag.annotationId);
5052
+ if (index === -1) return;
5053
+ if (drag.mode === "ticks") {
5054
+ const deltaTicks = this._host.scaleMode === "beats" ? deltaPx * this._host.ticksPerPixel : this._host._secondsToTicks(
5055
+ this._host._ticksToSeconds(drag.edgeTime) + deltaPx * this._host._renderSpp / this._host.effectiveSampleRate
5056
+ ) - drag.edgeTime;
5057
+ let newTick = drag.edgeTime + deltaTicks;
5058
+ if (this._host.scaleMode === "beats" && this._host.snapTo !== "off") {
5059
+ newTick = snapTickToGrid3(
5060
+ newTick,
5061
+ this._host.snapTo,
5062
+ this._host._meterEntries,
5063
+ this._host.ppqn
5064
+ );
5065
+ }
5066
+ const clamp = this._host._annotationClampDuration;
5067
+ const updated2 = updateAnnotationBoundaries2(
5068
+ {
5069
+ annotationIndex: index,
5070
+ newTime: newTick,
5071
+ isDraggingStart: drag.edge === "start",
5072
+ annotations: drag.snapshot,
5073
+ duration: clamp === Infinity ? Infinity : this._host._secondsToTicks(clamp),
5074
+ linkEndpoints: drag.track.linkEndpoints
5075
+ },
5076
+ {
5077
+ linkThreshold: ANNOTATION_LINK_THRESHOLD_TICKS2,
5078
+ minDuration: annotationMinDurationTicks2(this._host.ppqn)
5079
+ }
5080
+ );
5081
+ applyTickBoundaryResults(elements, updated2, (t) => this._host._ticksToSeconds(t));
5082
+ return;
5083
+ }
5084
+ const deltaSeconds = deltaPx * this._host._renderSpp / this._host.effectiveSampleRate;
5085
+ const updated = updateAnnotationBoundaries2({
5086
+ annotationIndex: index,
5087
+ newTime: drag.edgeTime + deltaSeconds,
5088
+ isDraggingStart: drag.edge === "start",
5089
+ annotations: drag.snapshot,
5090
+ duration: this._host._annotationClampDuration,
5091
+ linkEndpoints: drag.track.linkEndpoints
5092
+ });
5093
+ applyBoundaryResults(elements, updated);
5094
+ };
5095
+ this._onPointerUp = (e) => {
5096
+ const drag = this._drag;
5097
+ if (!drag || e.pointerId !== drag.pointerId) return;
5098
+ if (!drag.moved && drag.edge === null) {
5099
+ const data = drag.track.annotations.find((a) => a.id === drag.annotationId);
5100
+ if (data) {
5101
+ drag.track.activeAnnotationId = drag.annotationId;
5102
+ this._host.seekTo(data.start);
5103
+ }
5104
+ }
5105
+ this._teardown();
5106
+ };
5107
+ this._onPointerCancel = (e) => {
5108
+ const drag = this._drag;
5109
+ if (!drag || e.pointerId !== drag.pointerId) return;
5110
+ const elements = drag.track.annotationElements;
5111
+ if (drag.mode === "ticks") {
5112
+ applyTickBoundaryResults(elements, drag.snapshot, (t) => this._host._ticksToSeconds(t));
5113
+ } else {
5114
+ applyBoundaryResults(elements, drag.snapshot);
5115
+ }
5116
+ this._teardown();
5117
+ };
5118
+ this._host = host;
3808
5119
  }
3809
- _reset() {
3810
- if (this._boundaryEl) {
3811
- this._boundaryEl.classList.remove("dragging");
3812
- this._boundaryEl = null;
5120
+ _teardown() {
5121
+ const drag = this._drag;
5122
+ if (!drag) return;
5123
+ try {
5124
+ drag.captureEl.releasePointerCapture(drag.pointerId);
5125
+ } catch {
3813
5126
  }
3814
- this._mode = null;
3815
- this._clipId = "";
3816
- this._trackId = "";
3817
- this._startPx = 0;
3818
- this._isDragging = false;
3819
- this._cumulativeDeltaSamples = 0;
3820
- this._clipContainer = null;
3821
- this._originalLeft = 0;
3822
- this._originalWidth = 0;
3823
- this._originalOffsetSamples = 0;
3824
- this._originalDurationSamples = 0;
3825
- this._originalStartSample = 0;
5127
+ drag.captureEl.removeEventListener("pointermove", this._onPointerMove);
5128
+ drag.captureEl.removeEventListener("pointerup", this._onPointerUp);
5129
+ drag.captureEl.removeEventListener("pointercancel", this._onPointerCancel);
5130
+ this._drag = null;
3826
5131
  }
3827
5132
  };
3828
5133
 
@@ -3889,8 +5194,18 @@ async function loadFiles(host, files) {
3889
5194
  const failed = [];
3890
5195
  for (const file of fileArray) {
3891
5196
  if (file.type && !file.type.startsWith("audio/")) {
3892
- failed.push({ file, error: new Error("Non-audio MIME type: " + file.type) });
5197
+ const error = new Error("Non-audio MIME type: " + file.type);
5198
+ failed.push({ file, error });
3893
5199
  console.warn("[dawcore] Skipping non-audio file: " + file.name + " (" + file.type + ")");
5200
+ if (host.isConnected) {
5201
+ host.dispatchEvent(
5202
+ new CustomEvent("daw-files-load-error", {
5203
+ bubbles: true,
5204
+ composed: true,
5205
+ detail: { file, error }
5206
+ })
5207
+ );
5208
+ }
3894
5209
  continue;
3895
5210
  }
3896
5211
  const blobUrl = URL.createObjectURL(file);
@@ -4111,15 +5426,18 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
4111
5426
  name: clipName ?? "Recording"
4112
5427
  });
4113
5428
  host._clipBuffers = new Map(host._clipBuffers).set(clip.id, trimmedBuf);
4114
- host._peakPipeline.generatePeaks(trimmedBuf, host.samplesPerPixel, host.mono).then((pd) => {
5429
+ host._clipOffsets.set(clip.id, { offsetSamples: 0, durationSamples: durSamples });
5430
+ host._peakPipeline.generatePeaks(trimmedBuf, host.renderSamplesPerPixel, host.mono).then((pd) => {
4115
5431
  const t = host._engineTracks.get(trackId);
4116
5432
  if (!t) {
4117
5433
  const next = new Map(host._clipBuffers);
4118
5434
  next.delete(clip.id);
4119
5435
  host._clipBuffers = next;
5436
+ host._clipOffsets.delete(clip.id);
4120
5437
  return;
4121
5438
  }
4122
5439
  host._peaksData = new Map(host._peaksData).set(clip.id, pd);
5440
+ host._raiseZoomFloor(host._peakPipeline.getCachedScale(trimmedBuf));
4123
5441
  host._engineTracks = new Map(host._engineTracks).set(trackId, {
4124
5442
  ...t,
4125
5443
  // Punch-in replace (#579): the recorded clip owns [startSample,
@@ -4163,6 +5481,7 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
4163
5481
  const next = new Map(host._clipBuffers);
4164
5482
  next.delete(clip.id);
4165
5483
  host._clipBuffers = next;
5484
+ host._clipOffsets.delete(clip.id);
4166
5485
  if (host.isConnected) {
4167
5486
  host.dispatchEvent(
4168
5487
  new CustomEvent("daw-error", {
@@ -4198,9 +5517,9 @@ function splitAtPlayhead(host) {
4198
5517
  function canSplitAtTime(host, time) {
4199
5518
  const { engine } = host;
4200
5519
  if (!engine) return false;
4201
- const state8 = engine.getState();
4202
- if (!state8.selectedTrackId) return false;
4203
- const track = state8.tracks.find((t) => t.id === state8.selectedTrackId);
5520
+ const state9 = engine.getState();
5521
+ if (!state9.selectedTrackId) return false;
5522
+ const track = state9.tracks.find((t) => t.id === state9.selectedTrackId);
4204
5523
  if (!track) return false;
4205
5524
  const atSample = Math.round(time * host.effectiveSampleRate);
4206
5525
  const clip = findClipAtSample(track.clips, atSample);
@@ -4387,12 +5706,15 @@ var EffectsChainController = class {
4387
5706
  kind: "wam",
4388
5707
  ...sourceFields,
4389
5708
  bypassed: entry.placeholder.bypassed,
4390
- ...entry.placeholder.state !== void 0 ? { state: entry.placeholder.state } : {}
5709
+ ...entry.placeholder.state !== void 0 ? { state: entry.placeholder.state } : {},
5710
+ // Lets offline export skip this entry (live playback silently
5711
+ // skips it too); restore ignores the flag and retries.
5712
+ placeholder: true
4391
5713
  };
4392
5714
  }
4393
- let state8;
5715
+ let state9;
4394
5716
  try {
4395
- state8 = await entry.instance.getState?.();
5717
+ state9 = await entry.instance.getState?.();
4396
5718
  } catch (err) {
4397
5719
  console.warn(
4398
5720
  '[waveform-playlist] serialize: plugin "' + (entry.url ?? entry.label ?? entry.type) + '" getState failed: ' + String(err)
@@ -4402,7 +5724,16 @@ var EffectsChainController = class {
4402
5724
  kind: "wam",
4403
5725
  ...sourceFields,
4404
5726
  bypassed: entry.bypassed,
4405
- ...state8 !== void 0 ? { state: state8 } : {}
5727
+ ...state9 !== void 0 ? { state: state9 } : {}
5728
+ };
5729
+ }
5730
+ if (entry.placeholder) {
5731
+ return {
5732
+ kind: "native",
5733
+ type: entry.type,
5734
+ params: { ...entry.params },
5735
+ bypassed: entry.placeholder.bypassed,
5736
+ placeholder: true
4406
5737
  };
4407
5738
  }
4408
5739
  return {
@@ -4443,13 +5774,17 @@ var EffectsChainController = class {
4443
5774
  entry.instance.dispose?.();
4444
5775
  this._rebuild();
4445
5776
  }
5777
+ /** Returns the index the entry actually landed at (the requested index is
5778
+ * clamped to the chain bounds), or -1 for an unknown effectId — event
5779
+ * dispatchers must report the actual index, not the raw request. */
4446
5780
  move(effectId, newIndex) {
4447
5781
  const entry = this._find("move", effectId);
4448
- if (!entry) return;
5782
+ if (!entry) return -1;
4449
5783
  const without = this._entries.filter((e) => e.id !== effectId);
4450
5784
  const at = Math.max(0, Math.min(newIndex, without.length));
4451
5785
  this._entries = [...without.slice(0, at), entry, ...without.slice(at)];
4452
5786
  this._rebuild();
5787
+ return at;
4453
5788
  }
4454
5789
  setParams(effectId, params) {
4455
5790
  const entry = this._find("setParams", effectId);
@@ -4673,10 +6008,11 @@ registerBuiltIns();
4673
6008
 
4674
6009
  // src/effects/effects-manager.ts
4675
6010
  var PREFIX2 = "[waveform-playlist] ";
4676
- function makeGuiRecord(element, destroyImpl) {
6011
+ function makeGuiRecord(element, destroyImpl, isFallback = false) {
4677
6012
  let destroyed = false;
4678
6013
  return {
4679
6014
  element,
6015
+ isFallback,
4680
6016
  destroy: () => {
4681
6017
  if (destroyed) return;
4682
6018
  destroyed = true;
@@ -4855,7 +6191,7 @@ var EffectsManager = class {
4855
6191
  );
4856
6192
  }
4857
6193
  const cached = this._guis.get(effectId);
4858
- if (cached) {
6194
+ if (cached && !cached.isFallback) {
4859
6195
  container.appendChild(cached.element);
4860
6196
  return cached.element;
4861
6197
  }
@@ -4866,7 +6202,22 @@ var EffectsManager = class {
4866
6202
  });
4867
6203
  this._guiPending.set(effectId, pending);
4868
6204
  }
4869
- const record = await pending;
6205
+ let record;
6206
+ try {
6207
+ record = await pending;
6208
+ } catch (err) {
6209
+ if (cached) {
6210
+ console.warn(
6211
+ PREFIX2 + 'openEffectGui: rebuilding the parameter panel for "' + effectId + '" failed \u2014 serving the cached panel (values may be stale): ' + String(err)
6212
+ );
6213
+ container.appendChild(cached.element);
6214
+ return cached.element;
6215
+ }
6216
+ throw err;
6217
+ }
6218
+ if (cached && cached !== record) {
6219
+ cached.element.remove();
6220
+ }
4870
6221
  if (chain.disposed || !chain.getEntry(effectId)) {
4871
6222
  this._guis.delete(effectId);
4872
6223
  record.element.remove();
@@ -4901,7 +6252,7 @@ var EffectsManager = class {
4901
6252
  }
4902
6253
  const element = await this._createFallbackPanel(chain, target, entry, effectId);
4903
6254
  return makeGuiRecord(element, () => {
4904
- });
6255
+ }, true);
4905
6256
  }
4906
6257
  /** The generic parameter panel — one code path for "no custom GUI":
4907
6258
  * native entries render from the registry's params metadata, WAM entries
@@ -5144,9 +6495,23 @@ var EffectsManager = class {
5144
6495
  for (const entry of entries) {
5145
6496
  if (superseded()) return;
5146
6497
  if (entry.kind === "native") {
5147
- const id = this._addToChain(chain, target, entry.type, entry.params);
5148
- if (entry.bypassed) {
5149
- this._runOp(chain, target, "setBypassed", id, true);
6498
+ try {
6499
+ const id = this._addToChain(chain, target, entry.type, entry.params);
6500
+ if (entry.bypassed) {
6501
+ this._runOp(chain, target, "setBypassed", id, true);
6502
+ }
6503
+ } catch (err) {
6504
+ if (superseded() || chain.disposed) return;
6505
+ const message = err instanceof Error ? err.message : String(err);
6506
+ console.warn(
6507
+ PREFIX2 + 'setEffectsState: native effect "' + entry.type + '" failed to restore: ' + message
6508
+ );
6509
+ const effectId = this._addNativePlaceholder(chain, entry, message);
6510
+ this._dispatch(target, "daw-effect-error", {
6511
+ effectId,
6512
+ type: entry.type,
6513
+ message
6514
+ });
5150
6515
  }
5151
6516
  continue;
5152
6517
  }
@@ -5163,7 +6528,7 @@ var EffectsManager = class {
5163
6528
  this._runOp(chain, target, "setBypassed", id, true);
5164
6529
  }
5165
6530
  } catch (err) {
5166
- if (superseded()) return;
6531
+ if (superseded() || chain.disposed) return;
5167
6532
  const message = err instanceof Error ? err.message : String(err);
5168
6533
  const sourceLabel = entry.url ?? entry.faustName ?? "Faust effect";
5169
6534
  console.warn(
@@ -5179,6 +6544,25 @@ var EffectsManager = class {
5179
6544
  }
5180
6545
  }
5181
6546
  }
6547
+ /** A silent passthrough occupying a failed NATIVE entry's chain position.
6548
+ * Carries the saved params/bypassed so the snapshot round-trips (serialize
6549
+ * re-emits them with `placeholder: true`). */
6550
+ _addNativePlaceholder(chain, entry, message) {
6551
+ const { audioContext } = this._requireWiring();
6552
+ const node = audioContext.createGain();
6553
+ const effectId = chain.add({
6554
+ kind: "native",
6555
+ type: entry.type,
6556
+ label: entry.type,
6557
+ error: message,
6558
+ placeholder: { bypassed: entry.bypassed },
6559
+ instance: { input: node, output: node, applyParams: () => {
6560
+ } },
6561
+ params: { ...entry.params }
6562
+ });
6563
+ chain.setBypassed(effectId, true);
6564
+ return effectId;
6565
+ }
5182
6566
  /** A silent passthrough occupying the failed plugin's chain position. */
5183
6567
  _addWamPlaceholder(chain, entry, message) {
5184
6568
  const { audioContext } = this._requireWiring();
@@ -5225,10 +6609,11 @@ var EffectsManager = class {
5225
6609
  chain.setBypassed(effectId, arg);
5226
6610
  this._dispatch(target, "daw-effect-bypass", { effectId, bypassed: arg });
5227
6611
  break;
5228
- case "move":
5229
- chain.move(effectId, arg);
5230
- this._dispatch(target, "daw-effect-reorder", { effectId, fromIndex, toIndex: arg });
6612
+ case "move": {
6613
+ const toIndex = chain.move(effectId, arg);
6614
+ this._dispatch(target, "daw-effect-reorder", { effectId, fromIndex, toIndex });
5231
6615
  break;
6616
+ }
5232
6617
  }
5233
6618
  }
5234
6619
  _dispatch(target, name, detail) {
@@ -5269,6 +6654,9 @@ function validateSerializedEntries(entries) {
5269
6654
  if (typeof e.bypassed !== "boolean") {
5270
6655
  throw new Error(PREFIX2 + "setEffectsState: entry requires a boolean bypassed flag" + at);
5271
6656
  }
6657
+ if (e.placeholder !== void 0 && e.placeholder !== true) {
6658
+ throw new Error(PREFIX2 + "setEffectsState: placeholder must be true when present" + at);
6659
+ }
5272
6660
  });
5273
6661
  }
5274
6662
  function toWamParameterMap(params) {
@@ -5301,6 +6689,9 @@ async function exportAudioImpl(host, options = {}) {
5301
6689
  try {
5302
6690
  const masterChain = await buildOfflineChain(ctx, await host.getMasterEffectsState());
5303
6691
  cleanups.push(masterChain.dispose);
6692
+ const masterVolume = ctx.createGain();
6693
+ masterVolume.gain.value = host.masterVolume ?? 1;
6694
+ masterVolume.connect(masterChain.input);
5304
6695
  masterChain.output.connect(ctx.destination);
5305
6696
  const anySoloed = host.tracks.some((t) => t.soloed);
5306
6697
  for (const track of host.tracks) {
@@ -5315,7 +6706,7 @@ async function exportAudioImpl(host, options = {}) {
5315
6706
  panner.pan.value = track.pan;
5316
6707
  volume.connect(panner);
5317
6708
  panner.connect(chain.input);
5318
- chain.output.connect(masterChain.input);
6709
+ chain.output.connect(masterVolume);
5319
6710
  for (const clip of track.clips) {
5320
6711
  scheduleClip(ctx, clip, startTime, duration, volume);
5321
6712
  }
@@ -5386,6 +6777,12 @@ async function buildOfflineChain(ctx, entries) {
5386
6777
  return { input, output, dispose };
5387
6778
  async function wireEntries() {
5388
6779
  for (const entry of entries) {
6780
+ if (entry.placeholder) {
6781
+ console.warn(
6782
+ PREFIX3 + 'exportAudio: skipping failed-plugin placeholder "' + (entry.kind === "native" ? entry.type : entry.url ?? "Faust effect") + '"'
6783
+ );
6784
+ continue;
6785
+ }
5389
6786
  if (entry.kind === "native") {
5390
6787
  const created = createEffectInstance(entry.type, ctx, entry.params);
5391
6788
  if (entry.bypassed) {
@@ -5627,6 +7024,7 @@ var PlaybackAnimationController = class {
5627
7024
  this._running = true;
5628
7025
  this._animation.start(() => {
5629
7026
  const time = getTime();
7027
+ if (!this._running) return;
5630
7028
  this._options.getPlayhead()?.setPosition(this._options.timeToPixels(time));
5631
7029
  this._dispatchTimeUpdate(time);
5632
7030
  });
@@ -5656,7 +7054,14 @@ var PlaybackAnimationController = class {
5656
7054
  // src/elements/daw-editor.ts
5657
7055
  var RULER_HEIGHT = 30;
5658
7056
  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();";
5659
- var DawEditorElement = class extends LitElement11 {
7057
+ var TrackLoadCancelledError = class extends Error {
7058
+ constructor(message, reason) {
7059
+ super(message);
7060
+ this.reason = reason;
7061
+ this.name = "TrackLoadCancelledError";
7062
+ }
7063
+ };
7064
+ var DawEditorElement = class extends LitElement14 {
5660
7065
  constructor() {
5661
7066
  super(...arguments);
5662
7067
  this._samplesPerPixel = 1024;
@@ -5694,7 +7099,17 @@ var DawEditorElement = class extends LitElement11 {
5694
7099
  this._selectionStartTime = 0;
5695
7100
  this._selectionEndTime = 0;
5696
7101
  this._currentTime = 0;
7102
+ // Bounded-playback watermark for the current play(start, end) call
7103
+ // (selection/annotation playback). The adapter's own auto-stop at
7104
+ // endTime (e.g. native Transport's internal timer) tears down audio but
7105
+ // never notifies isPlaying/daw-stop back up — the _startPlayhead rAF
7106
+ // loop below is the sole place that detects reaching it, same pattern
7107
+ // as the whole-track _duration check.
7108
+ this._activePlayEndTime = null;
5697
7109
  this._externalAdapter = null;
7110
+ /** True after a disconnect disposed the consumer's adapter via the engine
7111
+ * — rebuild attempts fail loudly until a fresh adapter is set. */
7112
+ this._adapterConsumedByDispose = false;
5698
7113
  // --- Effects (master chain; per-track chains delegated from <daw-track>) ---
5699
7114
  this._effectsManager = null;
5700
7115
  this._engine = null;
@@ -5709,9 +7124,18 @@ var DawEditorElement = class extends LitElement11 {
5709
7124
  /** Coarsest scale from pre-computed peaks — zoom cannot go finer than this. 0 = no limit. */
5710
7125
  this._minSamplesPerPixel = 0;
5711
7126
  this._trackElements = /* @__PURE__ */ new Map();
7127
+ /** Track ids with a _loadTrack in flight. Distinct from `_engineTracks`
7128
+ * membership: the peaks-first path inserts a render-only PREVIEW track
7129
+ * into _engineTracks mid-load, so `has()` alone cannot answer "is this
7130
+ * track still loading?". */
7131
+ this._loadingTracks = /* @__PURE__ */ new Set();
5712
7132
  this._childObserver = null;
5713
7133
  this._audioResume = new AudioResumeController(this);
5714
7134
  this._recordingController = new RecordingController(this);
7135
+ this._annotations = new AnnotationController(this);
7136
+ /** Last engine BPM seen by the statechange handler — re-derives tick
7137
+ * annotation seconds caches only when it actually changes. */
7138
+ this._lastAnnotationBpm = null;
5715
7139
  // Closures (not direct references) — _timeToPixels/_getPlayhead are
5716
7140
  // declared later in the class body; class-field init order would read
5717
7141
  // `undefined` for a direct reference here.
@@ -5726,8 +7150,17 @@ var DawEditorElement = class extends LitElement11 {
5726
7150
  * play-start position). Non-private: pointer-handler's seek path sets it.
5727
7151
  */
5728
7152
  this._inSeekTransition = false;
7153
+ /**
7154
+ * True while `stop()` (the public API) is actively calling `this._engine.stop()`.
7155
+ * Suppresses the engine 'stop' handler's own `daw-stop` dispatch — `stop()`
7156
+ * dispatches its own, and without this guard a consumer-initiated stop would
7157
+ * fire `daw-stop` twice. See the engine 'stop' handler for the counterpart
7158
+ * engine-initiated case this flag does NOT suppress.
7159
+ */
7160
+ this._inConsumerStop = false;
5729
7161
  this._spectrogramController = null;
5730
7162
  this._clipPointer = new ClipPointerHandler(this);
7163
+ this._annotationDrag = new AnnotationDragHandler(this);
5731
7164
  this._pointer = new PointerHandler(this);
5732
7165
  this._viewport = (() => {
5733
7166
  const v = new ViewportController(this);
@@ -5751,6 +7184,18 @@ var DawEditorElement = class extends LitElement11 {
5751
7184
  * update for properties unrelated to the viewport.
5752
7185
  */
5753
7186
  this._lastSpectrogramViewport = null;
7187
+ // --- Annotation Events ---
7188
+ this._onAnnotationTrackConnected = (e) => {
7189
+ this._annotations.handleTrackConnected(e.detail.element);
7190
+ };
7191
+ this._onAnnotationSelect = (e) => {
7192
+ const annotation = e.detail.annotation;
7193
+ if (!annotation) return;
7194
+ const scrollArea = this.shadowRoot?.querySelector(".scroll-area");
7195
+ if (!scrollArea) return;
7196
+ const px = Math.floor(annotation.start * this.effectiveSampleRate / this._renderSpp);
7197
+ scrollArea.scrollLeft = Math.max(0, px - scrollArea.clientWidth / 2);
7198
+ };
5754
7199
  // --- Track Events ---
5755
7200
  this._onTrackConnected = (e) => {
5756
7201
  const trackId = e.detail?.trackId;
@@ -5853,11 +7298,17 @@ var DawEditorElement = class extends LitElement11 {
5853
7298
  const trackEl = clipEl.closest("daw-track");
5854
7299
  if (!trackEl) return;
5855
7300
  const trackId = trackEl.trackId;
5856
- if (!this._engineTracks.has(trackId)) {
7301
+ if (!this._engineTracks.has(trackId) || this._loadingTracks.has(trackId)) {
5857
7302
  const desc = this._tracks.get(trackId);
5858
7303
  if (desc && !desc.clips.some((c) => isDomClip(c) && c.clipId === clipEl.clipId)) {
5859
- console.warn(
5860
- '[dawcore] daw-clip-connected fired while parent track "' + trackId + '" is still loading \u2014 late-appended clip may be missed. Wait for daw-track-ready before appending more <daw-clip> children, or use editor.addClip(trackId, config) after the track finishes loading.'
7304
+ 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.';
7305
+ console.warn("[dawcore] " + message);
7306
+ this.dispatchEvent(
7307
+ new CustomEvent("daw-clip-error", {
7308
+ bubbles: true,
7309
+ composed: true,
7310
+ detail: { trackId, clipId: clipEl.clipId, error: new Error(message) }
7311
+ })
5861
7312
  );
5862
7313
  }
5863
7314
  return;
@@ -5949,12 +7400,38 @@ var DawEditorElement = class extends LitElement11 {
5949
7400
  const clamped = this._minSamplesPerPixel > 0 && value < this._minSamplesPerPixel ? this._minSamplesPerPixel : value;
5950
7401
  if (clamped !== value) {
5951
7402
  console.warn(
5952
- "[dawcore] Zoom " + value + " spp rejected \u2014 pre-computed peaks limit is " + this._minSamplesPerPixel + " spp"
7403
+ "[dawcore] Zoom " + value + " spp clamped to the peak floor (" + this._minSamplesPerPixel + " spp) \u2014 peaks for the loaded audio (worker-generated or pre-computed) can only render at or above that scale"
5953
7404
  );
5954
7405
  }
5955
7406
  this._samplesPerPixel = clamped;
5956
7407
  this.requestUpdate("samplesPerPixel", old);
5957
7408
  }
7409
+ /** Raise the zoom floor and re-clamp the LIVE samplesPerPixel when it's
7410
+ * now below the floor. Peaks can only be extracted at >= the floor scale —
7411
+ * the setter alone clamps only FUTURE sets, so without the re-clamp an
7412
+ * already-finer spp keeps sizing clip containers while the waveforms
7413
+ * render at the coarser scale: half/quarter width, misaligned against the
7414
+ * ruler and playhead. */
7415
+ _raiseZoomFloor(scale) {
7416
+ if (!Number.isFinite(scale) || scale <= 0) return;
7417
+ if (scale > this._minSamplesPerPixel) {
7418
+ this._minSamplesPerPixel = scale;
7419
+ }
7420
+ if (this._samplesPerPixel < this._minSamplesPerPixel) {
7421
+ this.samplesPerPixel = this._minSamplesPerPixel;
7422
+ }
7423
+ }
7424
+ /** Recompute the floor from the surviving cached scales (track removal /
7425
+ * load cancellation / preview cleanup). Usually LOWERS the floor, freeing
7426
+ * finer zoom — but a buffer whose scale never raised the floor (or a mix
7427
+ * of scales) can raise it above the live spp, so re-clamp like
7428
+ * _raiseZoomFloor. Never mutate _minSamplesPerPixel directly. */
7429
+ _recomputeZoomFloor() {
7430
+ this._minSamplesPerPixel = this._peakPipeline.getMaxCachedScale(this._clipBuffers);
7431
+ if (this._minSamplesPerPixel > 0 && this._samplesPerPixel < this._minSamplesPerPixel) {
7432
+ this.samplesPerPixel = this._minSamplesPerPixel;
7433
+ }
7434
+ }
5958
7435
  get timeFormat() {
5959
7436
  return this._timeFormat;
5960
7437
  }
@@ -6100,6 +7577,7 @@ var DawEditorElement = class extends LitElement11 {
6100
7577
  console.warn("[dawcore] Adapter AudioContext is already closed. Ignoring.");
6101
7578
  return;
6102
7579
  }
7580
+ this._adapterConsumedByDispose = false;
6103
7581
  if (this._engine) {
6104
7582
  console.warn(
6105
7583
  "[dawcore] adapter set after engine is built. The engine will continue using the previous adapter."
@@ -6187,6 +7665,7 @@ var DawEditorElement = class extends LitElement11 {
6187
7665
  effectiveSampleRate: this.effectiveSampleRate,
6188
7666
  duration: this._duration,
6189
7667
  tracks: [...this._engineTracks.values()],
7668
+ masterVolume: this._engine?.getState().masterVolume ?? 1,
6190
7669
  getMasterEffectsState: () => this.getEffectsState(),
6191
7670
  getTrackEffectsState: (trackId) => this.getTrackEffectsState(trackId)
6192
7671
  },
@@ -6360,6 +7839,12 @@ var DawEditorElement = class extends LitElement11 {
6360
7839
  }
6361
7840
  return ticks * 60 / (this.bpm * this.ppqn);
6362
7841
  }
7842
+ /** Clamp limit for annotation boundary edits. indefinite-playback removes the
7843
+ * end-of-timeline bound — annotations may extend past the audio (DAW-style
7844
+ * unbounded timeline); the shared boundary math treats Infinity as "no end cap". */
7845
+ get _annotationClampDuration() {
7846
+ return this.indefinitePlayback ? Infinity : this._duration;
7847
+ }
6363
7848
  get _totalWidth() {
6364
7849
  if (this.scaleMode === "beats") {
6365
7850
  const contentTicks = this._secondsToTicks(this._duration);
@@ -6367,8 +7852,9 @@ var DawEditorElement = class extends LitElement11 {
6367
7852
  const minTicks = 32 * num * this.ppqn;
6368
7853
  return Math.ceil(Math.max(contentTicks, minTicks) / this.ticksPerPixel);
6369
7854
  }
7855
+ const naturalDuration = Math.max(this._duration, this._annotations.maxAnnotationEndSeconds);
6370
7856
  const naturalWidth = Math.ceil(
6371
- this._duration * this.effectiveSampleRate / this.samplesPerPixel
7857
+ naturalDuration * this.effectiveSampleRate / this.samplesPerPixel
6372
7858
  );
6373
7859
  if (this.indefinitePlayback || this.fillViewport) {
6374
7860
  return Math.max(naturalWidth, this._viewport.containerWidth);
@@ -6420,6 +7906,11 @@ var DawEditorElement = class extends LitElement11 {
6420
7906
  this.addEventListener("daw-track-remove", this._onTrackRemoveRequest);
6421
7907
  this.addEventListener("daw-clip-connected", this._onClipConnected);
6422
7908
  this.addEventListener("daw-clip-update", this._onClipUpdate);
7909
+ this.addEventListener(
7910
+ "daw-annotation-track-connected",
7911
+ this._onAnnotationTrackConnected
7912
+ );
7913
+ this.addEventListener("daw-annotation-select", this._onAnnotationSelect);
6423
7914
  this._childObserver = new MutationObserver((mutations) => {
6424
7915
  for (const mutation of mutations) {
6425
7916
  for (const node of mutation.removedNodes) {
@@ -6457,6 +7948,11 @@ var DawEditorElement = class extends LitElement11 {
6457
7948
  this.removeEventListener("daw-track-remove", this._onTrackRemoveRequest);
6458
7949
  this.removeEventListener("daw-clip-connected", this._onClipConnected);
6459
7950
  this.removeEventListener("daw-clip-update", this._onClipUpdate);
7951
+ this.removeEventListener(
7952
+ "daw-annotation-track-connected",
7953
+ this._onAnnotationTrackConnected
7954
+ );
7955
+ this.removeEventListener("daw-annotation-select", this._onAnnotationSelect);
6460
7956
  this._childObserver?.disconnect();
6461
7957
  this._childObserver = null;
6462
7958
  this._trackElements.clear();
@@ -6468,11 +7964,21 @@ var DawEditorElement = class extends LitElement11 {
6468
7964
  this._minSamplesPerPixel = 0;
6469
7965
  this._spectrogramController?.dispose();
6470
7966
  this._spectrogramController = null;
7967
+ this._lastSpectrogramViewport = null;
7968
+ const hadEngine = this._engine !== null;
6471
7969
  try {
6472
7970
  this._disposeEngine();
6473
7971
  } catch (err) {
6474
7972
  console.warn("[dawcore] Error disposing engine: " + String(err));
6475
7973
  }
7974
+ if (hadEngine) {
7975
+ this._adapterConsumedByDispose = true;
7976
+ }
7977
+ this._tracks = /* @__PURE__ */ new Map();
7978
+ this._engineTracks = /* @__PURE__ */ new Map();
7979
+ this._peaksData = /* @__PURE__ */ new Map();
7980
+ this._loadingTracks.clear();
7981
+ this._recomputeDuration();
6476
7982
  }
6477
7983
  willUpdate(changedProperties) {
6478
7984
  if (changedProperties.has("eagerResume")) {
@@ -6481,8 +7987,8 @@ var DawEditorElement = class extends LitElement11 {
6481
7987
  if ((changedProperties.has("samplesPerPixel") || changedProperties.has("ticksPerPixel") || changedProperties.has("bpm") || changedProperties.has("secondsToTicks")) && this._isPlaying) {
6482
7988
  this._startPlayhead();
6483
7989
  }
6484
- const zoomChanged = changedProperties.has("samplesPerPixel") || changedProperties.has("ticksPerPixel") || changedProperties.has("bpm") || changedProperties.has("scaleMode") || changedProperties.has("secondsToTicks");
6485
- if (zoomChanged && this._clipBuffers.size > 0) {
7990
+ const peaksInputChanged = changedProperties.has("samplesPerPixel") || changedProperties.has("ticksPerPixel") || changedProperties.has("bpm") || changedProperties.has("scaleMode") || changedProperties.has("secondsToTicks") || changedProperties.has("mono");
7991
+ if (peaksInputChanged && this._clipBuffers.size > 0) {
6486
7992
  const re = this._peakPipeline.reextractPeaks(
6487
7993
  this._clipBuffers,
6488
7994
  this._renderSpp,
@@ -6549,9 +8055,16 @@ var DawEditorElement = class extends LitElement11 {
6549
8055
  if (this._engine) {
6550
8056
  this._engine.removeTrack(trackId);
6551
8057
  }
6552
- this._minSamplesPerPixel = this._peakPipeline.getMaxCachedScale(this._clipBuffers);
8058
+ this._recomputeZoomFloor();
6553
8059
  this._disposeSpectrogramControllerIfEmpty();
6554
- if (nextEngine.size === 0) {
8060
+ if (existed && nextEngine.size === 0) {
8061
+ if (this._engine) {
8062
+ if (this._isPlaying) {
8063
+ this._withSeekSuppression(() => this._engine.stop());
8064
+ this.dispatchEvent(new CustomEvent("daw-stop", { bubbles: true, composed: true }));
8065
+ }
8066
+ this._engine.seek(0);
8067
+ }
6555
8068
  this._currentTime = 0;
6556
8069
  this._stopPlayhead();
6557
8070
  }
@@ -6574,6 +8087,45 @@ var DawEditorElement = class extends LitElement11 {
6574
8087
  if (!stillNeeded) {
6575
8088
  this._spectrogramController.dispose();
6576
8089
  this._spectrogramController = null;
8090
+ this._lastSpectrogramViewport = null;
8091
+ }
8092
+ }
8093
+ /** Reconcile `_tracks` descriptors with the engine's track list.
8094
+ *
8095
+ * ADD: engine.undo() restores removed tracks in ENGINE state only —
8096
+ * without a synthesized descriptor the track plays and renders but shows
8097
+ * "Untitled" controls and is missing from `editor.tracks`.
8098
+ * PRUNE (the symmetric half): redo removes the track from engine state
8099
+ * again — without pruning, the synthesized descriptor is a permanent
8100
+ * ghost that even removeTrack() can't clean (no element, no engine
8101
+ * entry). Never prunes tracks that are mid-load or element-backed —
8102
+ * their descriptors legitimately precede their engine entries. */
8103
+ _reconcileDescriptorsWithEngineTracks(tracks) {
8104
+ const engineIds = new Set(tracks.map((t) => t.id));
8105
+ let next = null;
8106
+ for (const track of tracks) {
8107
+ if (this._tracks.has(track.id)) continue;
8108
+ next ?? (next = new Map(this._tracks));
8109
+ next.set(track.id, {
8110
+ name: track.name ?? "",
8111
+ src: "",
8112
+ volume: track.volume ?? 1,
8113
+ pan: track.pan ?? 0,
8114
+ muted: track.muted ?? false,
8115
+ soloed: track.soloed ?? false,
8116
+ renderMode: track.clips.some((c) => c.midiNotes && c.midiNotes.length > 0) ? "piano-roll" : "waveform",
8117
+ clips: []
8118
+ });
8119
+ }
8120
+ for (const trackId of this._tracks.keys()) {
8121
+ if (engineIds.has(trackId) || this._loadingTracks.has(trackId) || this._trackElements.has(trackId)) {
8122
+ continue;
8123
+ }
8124
+ next ?? (next = new Map(this._tracks));
8125
+ next.delete(trackId);
8126
+ }
8127
+ if (next) {
8128
+ this._tracks = next;
6577
8129
  }
6578
8130
  }
6579
8131
  _onClipRemovedFromDom(clipEl) {
@@ -6719,9 +8271,8 @@ var DawEditorElement = class extends LitElement11 {
6719
8271
  throw err;
6720
8272
  }
6721
8273
  this._peaksData = new Map(this._peaksData).set(clip.id, peakData);
6722
- if (waveformData) {
6723
- this._minSamplesPerPixel = Math.max(this._minSamplesPerPixel, waveformData.scale);
6724
- }
8274
+ const cachedScale = waveformData?.scale ?? this._peakPipeline.getCachedScale(audioBuffer);
8275
+ this._raiseZoomFloor(cachedScale);
6725
8276
  return clip;
6726
8277
  }
6727
8278
  /**
@@ -6964,6 +8515,8 @@ var DawEditorElement = class extends LitElement11 {
6964
8515
  }
6965
8516
  // --- Audio Loading ---
6966
8517
  async _loadTrack(trackId, descriptor) {
8518
+ this._loadingTracks.add(trackId);
8519
+ const sppAtLoadStart = this._samplesPerPixel;
6967
8520
  try {
6968
8521
  const clips = [];
6969
8522
  for (const clipDesc of descriptor.clips) {
@@ -7001,18 +8554,20 @@ var DawEditorElement = class extends LitElement11 {
7001
8554
  durationSamples: clip2.durationSamples
7002
8555
  });
7003
8556
  this._peaksData = new Map(this._peaksData).set(clip2.id, peakData);
7004
- this._minSamplesPerPixel = Math.max(this._minSamplesPerPixel, waveformData.scale);
7005
- const previewTrack = createTrack2({
7006
- name: descriptor.name,
7007
- clips: [clip2],
7008
- volume: descriptor.volume,
7009
- pan: descriptor.pan,
7010
- muted: descriptor.muted,
7011
- soloed: descriptor.soloed
7012
- });
7013
- previewTrack.id = trackId;
7014
- this._engineTracks = new Map(this._engineTracks).set(trackId, previewTrack);
7015
- this._recomputeDuration();
8557
+ this._raiseZoomFloor(waveformData.scale);
8558
+ if (this._tracks.has(trackId)) {
8559
+ const previewTrack = createTrack2({
8560
+ name: descriptor.name,
8561
+ clips: [clip2],
8562
+ volume: descriptor.volume,
8563
+ pan: descriptor.pan,
8564
+ muted: descriptor.muted,
8565
+ soloed: descriptor.soloed
8566
+ });
8567
+ previewTrack.id = trackId;
8568
+ this._engineTracks = new Map(this._engineTracks).set(trackId, previewTrack);
8569
+ this._recomputeDuration();
8570
+ }
7016
8571
  let audioBuffer2;
7017
8572
  try {
7018
8573
  audioBuffer2 = await audioPromise;
@@ -7024,7 +8579,7 @@ var DawEditorElement = class extends LitElement11 {
7024
8579
  const nextEngine = new Map(this._engineTracks);
7025
8580
  nextEngine.delete(trackId);
7026
8581
  this._engineTracks = nextEngine;
7027
- this._minSamplesPerPixel = this._peakPipeline.getMaxCachedScale(this._clipBuffers);
8582
+ this._recomputeZoomFloor();
7028
8583
  this._recomputeDuration();
7029
8584
  throw audioErr;
7030
8585
  }
@@ -7058,6 +8613,26 @@ var DawEditorElement = class extends LitElement11 {
7058
8613
  }
7059
8614
  }
7060
8615
  }
8616
+ const trackWasRemoved = !this._tracks.has(trackId);
8617
+ if (trackWasRemoved || !this.isConnected) {
8618
+ for (const clip of clips) {
8619
+ this._purgeClipCaches(clip.id);
8620
+ }
8621
+ if (this._engineTracks.has(trackId)) {
8622
+ const nextEngine = new Map(this._engineTracks);
8623
+ nextEngine.delete(trackId);
8624
+ this._engineTracks = nextEngine;
8625
+ this._recomputeDuration();
8626
+ }
8627
+ this._recomputeZoomFloor();
8628
+ if (this._samplesPerPixel !== sppAtLoadStart && sppAtLoadStart >= this._minSamplesPerPixel) {
8629
+ this.samplesPerPixel = sppAtLoadStart;
8630
+ }
8631
+ throw new TrackLoadCancelledError(
8632
+ trackWasRemoved ? 'track "' + trackId + '" was removed while loading' : 'editor was disconnected while track "' + trackId + '" was loading',
8633
+ trackWasRemoved ? "removed" : "disconnected"
8634
+ );
8635
+ }
7061
8636
  const track = createTrack2({
7062
8637
  name: descriptor.name,
7063
8638
  clips,
@@ -7088,15 +8663,23 @@ var DawEditorElement = class extends LitElement11 {
7088
8663
  })
7089
8664
  );
7090
8665
  } catch (err) {
7091
- if (!this.isConnected) return;
7092
- console.warn('[dawcore] Failed to load track "' + trackId + '": ' + String(err));
8666
+ const cancelled = err instanceof TrackLoadCancelledError;
8667
+ console.warn(
8668
+ cancelled ? "[dawcore] Track load cancelled: " + err.message : '[dawcore] Failed to load track "' + trackId + '": ' + String(err)
8669
+ );
7093
8670
  this.dispatchEvent(
7094
8671
  new CustomEvent("daw-track-error", {
7095
8672
  bubbles: true,
7096
8673
  composed: true,
7097
- detail: { trackId, error: err }
8674
+ detail: {
8675
+ trackId,
8676
+ error: err,
8677
+ ...cancelled ? { reason: err.reason } : {}
8678
+ }
7098
8679
  })
7099
8680
  );
8681
+ } finally {
8682
+ this._loadingTracks.delete(trackId);
7100
8683
  }
7101
8684
  }
7102
8685
  async _fetchAndDecode(src) {
@@ -7155,6 +8738,11 @@ var DawEditorElement = class extends LitElement11 {
7155
8738
  if (!this._externalAdapter) {
7156
8739
  throw new Error(NO_ADAPTER_ERROR);
7157
8740
  }
8741
+ if (this._adapterConsumedByDispose) {
8742
+ throw new Error(
8743
+ "[dawcore] editor.adapter was disposed by a previous disconnect \u2014 set a fresh PlayoutAdapter after reparenting <daw-editor>."
8744
+ );
8745
+ }
7158
8746
  const { PlaylistEngine } = await import("@waveform-playlist/engine");
7159
8747
  const adapter = this._externalAdapter;
7160
8748
  if (!this._hasTickCallbacks) {
@@ -7191,6 +8779,7 @@ var DawEditorElement = class extends LitElement11 {
7191
8779
  nextTracks.set(track.id, track);
7192
8780
  }
7193
8781
  this._engineTracks = nextTracks;
8782
+ this._reconcileDescriptorsWithEngineTracks(engineState.tracks);
7194
8783
  }
7195
8784
  if (structuralChange) {
7196
8785
  this._effectsManager?.rewireTrackChains();
@@ -7200,6 +8789,10 @@ var DawEditorElement = class extends LitElement11 {
7200
8789
  });
7201
8790
  syncPeaksForChangedClips(this, audioTracks);
7202
8791
  }
8792
+ if (engineState.bpm !== this._lastAnnotationBpm) {
8793
+ this._lastAnnotationBpm = engineState.bpm;
8794
+ this._annotations.deriveSecondsCaches();
8795
+ }
7203
8796
  });
7204
8797
  engine.on("pause", () => {
7205
8798
  this._currentTime = engine.getCurrentTime();
@@ -7207,6 +8800,10 @@ var DawEditorElement = class extends LitElement11 {
7207
8800
  engine.on("stop", () => {
7208
8801
  this._currentTime = engine.getCurrentTime();
7209
8802
  this._stopPlayhead();
8803
+ this._activePlayEndTime = null;
8804
+ if (!this._inConsumerStop && !this._inSeekTransition && this.isConnected) {
8805
+ this.dispatchEvent(new CustomEvent("daw-stop", { bubbles: true, composed: true }));
8806
+ }
7210
8807
  });
7211
8808
  this._engine = engine;
7212
8809
  return engine;
@@ -7507,14 +9104,21 @@ var DawEditorElement = class extends LitElement11 {
7507
9104
  return clipEl;
7508
9105
  }
7509
9106
  // --- Playback ---
7510
- async play(startTime) {
9107
+ /**
9108
+ * Start playback, optionally seeking to `startTime` first. When `endTime`
9109
+ * is provided, playback stops at that time (selection/annotation playback).
9110
+ */
9111
+ async play(startTime, endTime) {
7511
9112
  try {
7512
9113
  const engine = await this._ensureEngine();
7513
9114
  await engine.init();
7514
- engine.play(startTime);
9115
+ this._activePlayEndTime = endTime ?? null;
7515
9116
  this._startPlayhead();
9117
+ engine.play(startTime, endTime);
7516
9118
  this.dispatchEvent(new CustomEvent("daw-play", { bubbles: true, composed: true }));
7517
9119
  } catch (err) {
9120
+ this._stopPlayhead();
9121
+ this._activePlayEndTime = null;
7518
9122
  console.warn("[dawcore] Playback failed: " + String(err));
7519
9123
  this.dispatchEvent(
7520
9124
  new CustomEvent("daw-error", {
@@ -7533,7 +9137,13 @@ var DawEditorElement = class extends LitElement11 {
7533
9137
  }
7534
9138
  stop() {
7535
9139
  if (!this._engine) return;
7536
- this._engine.stop();
9140
+ this._activePlayEndTime = null;
9141
+ this._inConsumerStop = true;
9142
+ try {
9143
+ this._engine.stop();
9144
+ } finally {
9145
+ this._inConsumerStop = false;
9146
+ }
7537
9147
  this._stopPlayhead();
7538
9148
  this.dispatchEvent(new CustomEvent("daw-stop", { bubbles: true, composed: true }));
7539
9149
  }
@@ -7547,24 +9157,61 @@ var DawEditorElement = class extends LitElement11 {
7547
9157
  this.play();
7548
9158
  }
7549
9159
  }
9160
+ /** Run `fn` with the stop-settle daw-timeupdate suppressed. Every
9161
+ * stop-adjacent code path that immediately re-positions (seek, split,
9162
+ * empty-timeline rewind) must use this — engine.stop() rewinds to the
9163
+ * play-start position and the settle would leak a backward-jumping
9164
+ * daw-timeupdate to consumers (CLAUDE.md seek-while-playing invariant).
9165
+ * The `finally` is load-bearing: a wedged true silently drops every
9166
+ * subsequent stop-settle dispatch. */
9167
+ _withSeekSuppression(fn) {
9168
+ this._inSeekTransition = true;
9169
+ try {
9170
+ fn();
9171
+ } finally {
9172
+ this._inSeekTransition = false;
9173
+ }
9174
+ }
7550
9175
  seekTo(time) {
7551
9176
  if (!this._engine) {
7552
9177
  console.warn("[dawcore] seekTo: engine not ready, call ignored");
7553
9178
  return;
7554
9179
  }
9180
+ if (!Number.isFinite(time)) {
9181
+ console.warn("[dawcore] seekTo: ignoring non-finite time " + String(time));
9182
+ return;
9183
+ }
9184
+ const target = Math.max(0, time);
7555
9185
  if (this._isPlaying) {
7556
- this._inSeekTransition = true;
7557
9186
  try {
7558
- this.stop();
7559
- } finally {
7560
- this._inSeekTransition = false;
9187
+ this._withSeekSuppression(() => this._engine.stop());
9188
+ this._engine.play(target);
9189
+ } catch (err) {
9190
+ console.warn("[dawcore] seekTo: engine reschedule failed: " + String(err));
9191
+ this.dispatchEvent(
9192
+ new CustomEvent("daw-error", {
9193
+ bubbles: true,
9194
+ composed: true,
9195
+ detail: { operation: "seek", error: err }
9196
+ })
9197
+ );
9198
+ return;
7561
9199
  }
7562
- this.play(time);
9200
+ this._activePlayEndTime = null;
9201
+ this._currentTime = target;
9202
+ this._startPlayhead();
7563
9203
  } else {
7564
- this._engine.seek(time);
7565
- this._currentTime = time;
9204
+ this._engine.seek(target);
9205
+ this._currentTime = target;
7566
9206
  this._stopPlayhead();
7567
9207
  }
9208
+ this.dispatchEvent(
9209
+ new CustomEvent("daw-seek", {
9210
+ bubbles: true,
9211
+ composed: true,
9212
+ detail: { time: target }
9213
+ })
9214
+ );
7568
9215
  }
7569
9216
  /** Undo the last structural edit. */
7570
9217
  undo() {
@@ -7599,8 +9246,10 @@ var DawEditorElement = class extends LitElement11 {
7599
9246
  engine: this._engine,
7600
9247
  dispatchEvent: (e) => this.dispatchEvent(e),
7601
9248
  stop: () => {
7602
- this._engine?.stop();
7603
- this._stopPlayhead();
9249
+ this._withSeekSuppression(() => {
9250
+ this._engine?.stop();
9251
+ this._stopPlayhead();
9252
+ });
7604
9253
  },
7605
9254
  // Call engine.play directly (synchronous) — not the async editor play()
7606
9255
  // which yields to microtask queue via await engine.init(). Engine is
@@ -7687,6 +9336,25 @@ var DawEditorElement = class extends LitElement11 {
7687
9336
  }
7688
9337
  await this._recordingController.startRecording(s, options);
7689
9338
  }
9339
+ /** Live-recording preview left/width. Beats mode uses the same tick-space
9340
+ * math as finalized clips — the sample÷renderSpp path is ceil-quantized,
9341
+ * so the take would visibly jump sideways on finalization (drift grows
9342
+ * with distance from t=0; CLAUDE.md live-preview parity invariant). */
9343
+ _previewPosition(startSample, audibleSamples) {
9344
+ if (this.scaleMode === "beats") {
9345
+ const sr = this.effectiveSampleRate;
9346
+ const startSec = startSample / sr;
9347
+ const startTick = this._secondsToTicks(startSec);
9348
+ const endTick = this._secondsToTicks(startSec + audibleSamples / sr);
9349
+ const left = Math.round(startTick / this.ticksPerPixel);
9350
+ return { left, width: Math.round(endTick / this.ticksPerPixel) - left };
9351
+ }
9352
+ const renderSpp = this._renderSpp;
9353
+ return {
9354
+ left: Math.floor(startSample / renderSpp),
9355
+ width: Math.floor(audibleSamples / renderSpp)
9356
+ };
9357
+ }
7690
9358
  _renderRecordingPreview(trackId, chH) {
7691
9359
  const rs = this._recordingController.getSession(trackId);
7692
9360
  if (!rs) return "";
@@ -7694,20 +9362,19 @@ var DawEditorElement = class extends LitElement11 {
7694
9362
  if (audibleSamples === 0) return "";
7695
9363
  const renderSpp = this._renderSpp;
7696
9364
  const latencyPixels = Math.floor(rs.latencySamples / renderSpp);
7697
- const left = Math.floor(rs.startSample / renderSpp);
7698
- const w = Math.floor(audibleSamples / renderSpp);
9365
+ const { left, width: w } = this._previewPosition(rs.startSample, audibleSamples);
7699
9366
  const hdrH = this.clipHeaders ? this.clipHeaderHeight : 0;
7700
9367
  const height = hdrH + chH * rs.peaks.length;
7701
- return html10`<div
9368
+ return html12`<div
7702
9369
  class="clip-container recording-preview"
7703
9370
  style="left:${left}px;top:0;width:${w}px;height:${height}px;"
7704
9371
  >
7705
- ${hdrH > 0 ? html10`<div class="clip-header" data-track-id=${trackId}>
9372
+ ${hdrH > 0 ? html12`<div class="clip-header" data-track-id=${trackId}>
7706
9373
  <span>${rs.clipName ?? "Recording\u2026"}</span>
7707
9374
  </div>` : ""}
7708
9375
  ${rs.peaks.map((chPeaks, ch) => {
7709
9376
  const slicedPeaks = latencyPixels > 0 ? chPeaks.slice(latencyPixels * 2) : chPeaks;
7710
- return html10`
9377
+ return html12`
7711
9378
  <daw-waveform
7712
9379
  data-recording-track=${trackId}
7713
9380
  data-recording-channel=${ch}
@@ -7730,6 +9397,11 @@ var DawEditorElement = class extends LitElement11 {
7730
9397
  if (!this._engine) return;
7731
9398
  const engine = this._engine;
7732
9399
  this._playbackAnimation.start(() => {
9400
+ if (this._activePlayEndTime !== null && !this.isRecording && engine.getCurrentTime() >= this._activePlayEndTime) {
9401
+ this.stop();
9402
+ const t = this._currentTime;
9403
+ return Number.isFinite(t) ? Math.max(0, t) : 0;
9404
+ }
7733
9405
  if (!this.indefinitePlayback && !this.isRecording && engine.getCurrentTime() >= this._duration) {
7734
9406
  this.stop();
7735
9407
  const t = this._currentTime;
@@ -7797,9 +9469,9 @@ var DawEditorElement = class extends LitElement11 {
7797
9469
  });
7798
9470
  const showControls = this._showControls;
7799
9471
  const showRuler = this._showRuler;
7800
- return html10`
7801
- ${showRuler ? html10`<div class="header-row" style="height: ${RULER_HEIGHT}px;">
7802
- ${showControls ? html10`<div class="ruler-gap"></div>` : ""}
9472
+ return html12`
9473
+ ${showRuler ? html12`<div class="header-row" style="height: ${RULER_HEIGHT}px;">
9474
+ ${showControls ? html12`<div class="ruler-gap"></div>` : ""}
7803
9475
  <div class="ruler-viewport" @pointerdown=${this._pointer.onPointerDown}>
7804
9476
  <div
7805
9477
  class="ruler-content"
@@ -7820,10 +9492,18 @@ var DawEditorElement = class extends LitElement11 {
7820
9492
  </div>
7821
9493
  </div>` : ""}
7822
9494
  <div class="body">
7823
- ${showControls ? html10`<div class="controls-viewport">
9495
+ ${showControls ? html12`<div class="controls-viewport">
7824
9496
  <div class="controls-column">
9497
+ ${this._annotations.tracks.map(
9498
+ (track) => html12`<div
9499
+ class="annotation-lane-spacer"
9500
+ style="height: ${ANNOTATION_LANE_HEIGHT}px;"
9501
+ >
9502
+ <span class="annotation-lane-name">${track.name}</span>
9503
+ </div>`
9504
+ )}
7825
9505
  ${orderedTracks.map(
7826
- (t) => html10`
9506
+ (t) => html12`
7827
9507
  <daw-track-controls
7828
9508
  style="height: ${t.trackHeight}px;"
7829
9509
  .trackId=${t.trackId}
@@ -7847,8 +9527,14 @@ var DawEditorElement = class extends LitElement11 {
7847
9527
  @dragleave=${this._onDragLeave}
7848
9528
  @drop=${this._onDrop}
7849
9529
  >
7850
- ${this.scaleMode === "beats" ? html10`<daw-grid
7851
- style="top: 0px;"
9530
+ ${this._annotations.renderLanes(
9531
+ spp,
9532
+ this.effectiveSampleRate,
9533
+ this._annotationDrag.onPointerDown,
9534
+ this.scaleMode === "beats" ? this.ticksPerPixel : null
9535
+ )}
9536
+ ${this.scaleMode === "beats" ? html12`<daw-grid
9537
+ style="top: ${this._annotations.totalLaneHeight}px;"
7852
9538
  .ticksPerPixel=${this.ticksPerPixel}
7853
9539
  .meterEntries=${this._meterEntries}
7854
9540
  .ppqn=${this.ppqn}
@@ -7857,11 +9543,11 @@ var DawEditorElement = class extends LitElement11 {
7857
9543
  .length=${this._totalWidth}
7858
9544
  .height=${orderedTracks.length > 0 ? orderedTracks.reduce((sum, t) => sum + t.trackHeight, 0) : this._emptyGridHeight}
7859
9545
  ></daw-grid>` : ""}
7860
- ${orderedTracks.length > 0 || this.scaleMode === "beats" || this.indefinitePlayback || this.fillViewport ? html10`<daw-selection .startPx=${selStartPx} .endPx=${selEndPx}></daw-selection>
9546
+ ${orderedTracks.length > 0 || this.scaleMode === "beats" || this.indefinitePlayback || this.fillViewport ? html12`<daw-selection .startPx=${selStartPx} .endPx=${selEndPx}></daw-selection>
7861
9547
  <daw-playhead></daw-playhead>` : ""}
7862
9548
  ${orderedTracks.map((t) => {
7863
9549
  const channelHeight = this.waveHeight;
7864
- return html10`
9550
+ return html12`
7865
9551
  <div
7866
9552
  class="track-row ${t.trackId === this._selectedTrackId ? "selected" : ""}"
7867
9553
  style="height: ${t.trackHeight}px;"
@@ -7927,12 +9613,12 @@ var DawEditorElement = class extends LitElement11 {
7927
9613
  const channels = segmentChannels ?? peakData?.data ?? [new Int16Array(0)];
7928
9614
  const hdrH = this.clipHeaders ? this.clipHeaderHeight : 0;
7929
9615
  const chH = this.waveHeight;
7930
- return html10` <div
9616
+ return html12` <div
7931
9617
  class="clip-container"
7932
9618
  style="left:${clipLeft}px;top:0;width:${width}px;height:${t.trackHeight}px;"
7933
9619
  data-clip-id=${clip.id}
7934
9620
  >
7935
- ${hdrH > 0 ? html10`<div
9621
+ ${hdrH > 0 ? html12`<div
7936
9622
  class="clip-header"
7937
9623
  data-clip-id=${clip.id}
7938
9624
  data-track-id=${t.trackId}
@@ -7940,7 +9626,7 @@ var DawEditorElement = class extends LitElement11 {
7940
9626
  >
7941
9627
  <span>${clip.name || t.descriptor?.name || ""}</span>
7942
9628
  </div>` : ""}
7943
- ${t.descriptor?.renderMode === "piano-roll" ? html10`<daw-piano-roll
9629
+ ${t.descriptor?.renderMode === "piano-roll" ? html12`<daw-piano-roll
7944
9630
  style="position:absolute;left:0;top:${hdrH}px;"
7945
9631
  .midiNotes=${clip.midiNotes ?? []}
7946
9632
  .length=${peakData?.length ?? width}
@@ -7953,7 +9639,7 @@ var DawEditorElement = class extends LitElement11 {
7953
9639
  .originX=${clipLeft}
7954
9640
  ?selected=${t.trackId === this._selectedTrackId}
7955
9641
  ></daw-piano-roll>` : t.descriptor?.renderMode === "spectrogram" ? channels.map(
7956
- (_chPeaks, chIdx) => html10`<daw-spectrogram
9642
+ (_chPeaks, chIdx) => html12`<daw-spectrogram
7957
9643
  style="position:absolute;left:0;top:${hdrH + chIdx * chH}px;height:${chH}px;width:${peakData?.length ?? width}px;"
7958
9644
  .clipId=${clip.id}
7959
9645
  .trackId=${t.trackId}
@@ -7968,7 +9654,7 @@ var DawEditorElement = class extends LitElement11 {
7968
9654
  .originX=${clipLeft}
7969
9655
  ></daw-spectrogram>`
7970
9656
  ) : channels.map(
7971
- (chPeaks, chIdx) => html10` <daw-waveform
9657
+ (chPeaks, chIdx) => html12` <daw-waveform
7972
9658
  style="position:absolute;left:0;top:${hdrH + chIdx * chH}px;"
7973
9659
  .peaks=${chPeaks}
7974
9660
  .length=${peakData?.length ?? width}
@@ -7982,7 +9668,7 @@ var DawEditorElement = class extends LitElement11 {
7982
9668
  .segments=${clipSegments}
7983
9669
  ></daw-waveform>`
7984
9670
  )}
7985
- ${this.interactiveClips ? html10` <div
9671
+ ${this.interactiveClips ? html12` <div
7986
9672
  class="clip-boundary"
7987
9673
  data-boundary-edge="left"
7988
9674
  data-clip-id=${clip.id}
@@ -8009,7 +9695,7 @@ var DawEditorElement = class extends LitElement11 {
8009
9695
  };
8010
9696
  DawEditorElement.styles = [
8011
9697
  hostStyles,
8012
- css10`
9698
+ css11`
8013
9699
  :host {
8014
9700
  display: flex;
8015
9701
  flex-direction: column;
@@ -8080,120 +9766,186 @@ DawEditorElement.styles = [
8080
9766
  outline: 2px dashed var(--daw-selection-color, rgba(99, 199, 95, 0.3));
8081
9767
  outline-offset: -2px;
8082
9768
  }
9769
+ .annotation-lane {
9770
+ position: relative;
9771
+ box-sizing: border-box;
9772
+ border-bottom: 1px solid var(--daw-annotation-lane-border, rgba(255, 255, 255, 0.08));
9773
+ background: var(--daw-annotation-lane-background, rgba(0, 0, 0, 0.15));
9774
+ user-select: none;
9775
+ -webkit-user-drag: none;
9776
+ }
9777
+ .annotation-lane-spacer {
9778
+ box-sizing: border-box;
9779
+ border-bottom: 1px solid var(--daw-annotation-lane-border, rgba(255, 255, 255, 0.08));
9780
+ display: flex;
9781
+ align-items: center;
9782
+ overflow: hidden;
9783
+ }
9784
+ .annotation-lane-name {
9785
+ padding: 0 10px;
9786
+ font-size: 11px;
9787
+ color: var(--daw-controls-text, #e0d4c8);
9788
+ opacity: 0.8;
9789
+ white-space: nowrap;
9790
+ overflow: hidden;
9791
+ text-overflow: ellipsis;
9792
+ }
9793
+ .annotation-box {
9794
+ position: absolute;
9795
+ top: 3px;
9796
+ bottom: 3px;
9797
+ overflow: hidden;
9798
+ display: flex;
9799
+ align-items: center;
9800
+ border: 1px solid var(--daw-annotation-box-border, #c49a6c);
9801
+ border-radius: 3px;
9802
+ background: var(--daw-annotation-box-background, rgba(196, 154, 108, 0.2));
9803
+ color: var(--daw-annotation-text-color, #e0d4c8);
9804
+ font-size: 11px;
9805
+ cursor: pointer;
9806
+ }
9807
+ .annotation-box.playing {
9808
+ box-shadow: inset 0 0 0 1px var(--daw-annotation-box-border, #c49a6c);
9809
+ background: var(--daw-annotation-playing-background, rgba(196, 154, 108, 0.32));
9810
+ }
9811
+ .annotation-box.active {
9812
+ background: var(--daw-annotation-active-background, rgba(196, 154, 108, 0.45));
9813
+ }
9814
+ .annotation-box-text {
9815
+ padding: 0 6px;
9816
+ white-space: nowrap;
9817
+ overflow: hidden;
9818
+ text-overflow: ellipsis;
9819
+ pointer-events: none;
9820
+ }
9821
+ .annotation-boundary {
9822
+ position: absolute;
9823
+ top: 0;
9824
+ bottom: 0;
9825
+ width: 6px;
9826
+ cursor: ew-resize;
9827
+ flex-shrink: 0;
9828
+ }
9829
+ .annotation-boundary[data-edge='start'] {
9830
+ left: 0;
9831
+ }
9832
+ .annotation-boundary[data-edge='end'] {
9833
+ right: 0;
9834
+ }
8083
9835
  `,
8084
9836
  clipStyles
8085
9837
  ];
8086
9838
  DawEditorElement._CONTROL_PROPS = /* @__PURE__ */ new Set(["volume", "pan", "muted", "soloed"]);
8087
9839
  __decorateClass([
8088
- property9({ type: Number, attribute: "samples-per-pixel", noAccessor: true })
9840
+ property12({ type: Number, attribute: "samples-per-pixel", noAccessor: true })
8089
9841
  ], DawEditorElement.prototype, "samplesPerPixel", 1);
8090
9842
  __decorateClass([
8091
- property9({ attribute: "time-format", reflect: true, noAccessor: true })
9843
+ property12({ attribute: "time-format", reflect: true, noAccessor: true })
8092
9844
  ], DawEditorElement.prototype, "timeFormat", 1);
8093
9845
  __decorateClass([
8094
- property9({ type: Number, attribute: "wave-height" })
9846
+ property12({ type: Number, attribute: "wave-height" })
8095
9847
  ], DawEditorElement.prototype, "waveHeight", 2);
8096
9848
  __decorateClass([
8097
- property9({ type: Boolean })
9849
+ property12({ type: Boolean })
8098
9850
  ], DawEditorElement.prototype, "timescale", 2);
8099
9851
  __decorateClass([
8100
- property9({ type: Boolean })
9852
+ property12({ type: Boolean })
8101
9853
  ], DawEditorElement.prototype, "mono", 2);
8102
9854
  __decorateClass([
8103
- property9({ type: Number, attribute: "bar-width" })
9855
+ property12({ type: Number, attribute: "bar-width" })
8104
9856
  ], DawEditorElement.prototype, "barWidth", 2);
8105
9857
  __decorateClass([
8106
- property9({ type: Number, attribute: "bar-gap" })
9858
+ property12({ type: Number, attribute: "bar-gap" })
8107
9859
  ], DawEditorElement.prototype, "barGap", 2);
8108
9860
  __decorateClass([
8109
- property9({ type: Boolean, attribute: "rounded-bars" })
9861
+ property12({ type: Boolean, attribute: "rounded-bars" })
8110
9862
  ], DawEditorElement.prototype, "roundedBars", 2);
8111
9863
  __decorateClass([
8112
- property9({ type: Boolean, attribute: "file-drop" })
9864
+ property12({ type: Boolean, attribute: "file-drop" })
8113
9865
  ], DawEditorElement.prototype, "fileDrop", 2);
8114
9866
  __decorateClass([
8115
- property9({ type: Boolean, attribute: "clip-headers" })
9867
+ property12({ type: Boolean, attribute: "clip-headers" })
8116
9868
  ], DawEditorElement.prototype, "clipHeaders", 2);
8117
9869
  __decorateClass([
8118
- property9({ type: Number, attribute: "clip-header-height" })
9870
+ property12({ type: Number, attribute: "clip-header-height" })
8119
9871
  ], DawEditorElement.prototype, "clipHeaderHeight", 2);
8120
9872
  __decorateClass([
8121
- property9({ type: Boolean, attribute: "interactive-clips" })
9873
+ property12({ type: Boolean, attribute: "interactive-clips" })
8122
9874
  ], DawEditorElement.prototype, "interactiveClips", 2);
8123
9875
  __decorateClass([
8124
- property9({ type: Boolean, attribute: "indefinite-playback" })
9876
+ property12({ type: Boolean, attribute: "indefinite-playback" })
8125
9877
  ], DawEditorElement.prototype, "indefinitePlayback", 2);
8126
9878
  __decorateClass([
8127
- property9({ type: Boolean, attribute: "fill-viewport" })
9879
+ property12({ type: Boolean, attribute: "fill-viewport" })
8128
9880
  ], DawEditorElement.prototype, "fillViewport", 2);
8129
9881
  __decorateClass([
8130
- property9({ attribute: false, noAccessor: true })
9882
+ property12({ attribute: false, noAccessor: true })
8131
9883
  ], DawEditorElement.prototype, "spectrogramConfig", 1);
8132
9884
  __decorateClass([
8133
- property9({ attribute: false, noAccessor: true })
9885
+ property12({ attribute: false, noAccessor: true })
8134
9886
  ], DawEditorElement.prototype, "spectrogramColorMap", 1);
8135
9887
  __decorateClass([
8136
- property9({ type: String, attribute: "scale-mode" })
9888
+ property12({ type: String, attribute: "scale-mode" })
8137
9889
  ], DawEditorElement.prototype, "scaleMode", 2);
8138
9890
  __decorateClass([
8139
- property9({ type: Number, attribute: "ticks-per-pixel", noAccessor: true })
9891
+ property12({ type: Number, attribute: "ticks-per-pixel", noAccessor: true })
8140
9892
  ], DawEditorElement.prototype, "ticksPerPixel", 1);
8141
9893
  __decorateClass([
8142
- property9({ type: Number, noAccessor: true })
9894
+ property12({ type: Number, noAccessor: true })
8143
9895
  ], DawEditorElement.prototype, "bpm", 1);
8144
9896
  __decorateClass([
8145
- property9({ attribute: false })
9897
+ property12({ attribute: false })
8146
9898
  ], DawEditorElement.prototype, "timeSignature", 2);
8147
9899
  __decorateClass([
8148
- property9({ attribute: false })
9900
+ property12({ attribute: false })
8149
9901
  ], DawEditorElement.prototype, "meterEntries", 2);
8150
9902
  __decorateClass([
8151
- property9({ type: Number, noAccessor: true })
9903
+ property12({ type: Number, noAccessor: true })
8152
9904
  ], DawEditorElement.prototype, "ppqn", 1);
8153
9905
  __decorateClass([
8154
- property9({ type: String, attribute: "snap-to" })
9906
+ property12({ type: String, attribute: "snap-to" })
8155
9907
  ], DawEditorElement.prototype, "snapTo", 2);
8156
9908
  __decorateClass([
8157
- property9({ attribute: false })
9909
+ property12({ attribute: false })
8158
9910
  ], DawEditorElement.prototype, "secondsToTicks", 2);
8159
9911
  __decorateClass([
8160
- property9({ attribute: false })
9912
+ property12({ attribute: false })
8161
9913
  ], DawEditorElement.prototype, "ticksToSeconds", 2);
8162
9914
  __decorateClass([
8163
- state3()
9915
+ state4()
8164
9916
  ], DawEditorElement.prototype, "_tracks", 2);
8165
9917
  __decorateClass([
8166
- state3()
9918
+ state4()
8167
9919
  ], DawEditorElement.prototype, "_engineTracks", 2);
8168
9920
  __decorateClass([
8169
- state3()
9921
+ state4()
8170
9922
  ], DawEditorElement.prototype, "_peaksData", 2);
8171
9923
  __decorateClass([
8172
- state3()
9924
+ state4()
8173
9925
  ], DawEditorElement.prototype, "_isPlaying", 2);
8174
9926
  __decorateClass([
8175
- state3()
9927
+ state4()
8176
9928
  ], DawEditorElement.prototype, "_duration", 2);
8177
9929
  __decorateClass([
8178
- state3()
9930
+ state4()
8179
9931
  ], DawEditorElement.prototype, "_selectedTrackId", 2);
8180
9932
  __decorateClass([
8181
- state3()
9933
+ state4()
8182
9934
  ], DawEditorElement.prototype, "_dragOver", 2);
8183
9935
  __decorateClass([
8184
- property9({ attribute: false })
9936
+ property12({ attribute: false })
8185
9937
  ], DawEditorElement.prototype, "adapter", 1);
8186
9938
  __decorateClass([
8187
- property9({ attribute: "eager-resume" })
9939
+ property12({ attribute: "eager-resume" })
8188
9940
  ], DawEditorElement.prototype, "eagerResume", 2);
8189
9941
  DawEditorElement = __decorateClass([
8190
- customElement13("daw-editor")
9942
+ customElement16("daw-editor")
8191
9943
  ], DawEditorElement);
8192
9944
 
8193
9945
  // src/elements/daw-selection.ts
8194
- import { LitElement as LitElement12, html as html11, css as css11 } from "lit";
8195
- import { customElement as customElement14, property as property10 } from "lit/decorators.js";
8196
- var DawSelectionElement = class extends LitElement12 {
9946
+ import { LitElement as LitElement15, html as html13, css as css12 } from "lit";
9947
+ import { customElement as customElement17, property as property13 } from "lit/decorators.js";
9948
+ var DawSelectionElement = class extends LitElement15 {
8197
9949
  constructor() {
8198
9950
  super(...arguments);
8199
9951
  this.startPx = 0;
@@ -8202,11 +9954,11 @@ var DawSelectionElement = class extends LitElement12 {
8202
9954
  render() {
8203
9955
  const left = Math.min(this.startPx, this.endPx);
8204
9956
  const width = Math.abs(this.endPx - this.startPx);
8205
- if (width === 0) return html11``;
8206
- return html11`<div style="left: ${left}px; width: ${width}px;"></div>`;
9957
+ if (width === 0) return html13``;
9958
+ return html13`<div style="left: ${left}px; width: ${width}px;"></div>`;
8207
9959
  }
8208
9960
  };
8209
- DawSelectionElement.styles = css11`
9961
+ DawSelectionElement.styles = css12`
8210
9962
  :host {
8211
9963
  position: absolute;
8212
9964
  top: 0;
@@ -8223,18 +9975,18 @@ DawSelectionElement.styles = css11`
8223
9975
  }
8224
9976
  `;
8225
9977
  __decorateClass([
8226
- property10({ type: Number, attribute: false })
9978
+ property13({ type: Number, attribute: false })
8227
9979
  ], DawSelectionElement.prototype, "startPx", 2);
8228
9980
  __decorateClass([
8229
- property10({ type: Number, attribute: false })
9981
+ property13({ type: Number, attribute: false })
8230
9982
  ], DawSelectionElement.prototype, "endPx", 2);
8231
9983
  DawSelectionElement = __decorateClass([
8232
- customElement14("daw-selection")
9984
+ customElement17("daw-selection")
8233
9985
  ], DawSelectionElement);
8234
9986
 
8235
9987
  // src/elements/daw-record-button.ts
8236
- import { html as html12, css as css12 } from "lit";
8237
- import { customElement as customElement15, state as state4 } from "lit/decorators.js";
9988
+ import { html as html14, css as css13 } from "lit";
9989
+ import { customElement as customElement18, state as state5 } from "lit/decorators.js";
8238
9990
  var DawRecordButtonElement = class extends DawTransportButton {
8239
9991
  constructor() {
8240
9992
  super(...arguments);
@@ -8283,7 +10035,7 @@ var DawRecordButtonElement = class extends DawTransportButton {
8283
10035
  }
8284
10036
  }
8285
10037
  render() {
8286
- return html12`
10038
+ return html14`
8287
10039
  <button
8288
10040
  part="button"
8289
10041
  ?disabled=${!this.targetSupported}
@@ -8311,7 +10063,7 @@ DawRecordButtonElement.requiredTargetMethods = [
8311
10063
  ];
8312
10064
  DawRecordButtonElement.styles = [
8313
10065
  DawTransportButton.styles,
8314
- css12`
10066
+ css13`
8315
10067
  button[data-recording] {
8316
10068
  color: #d08070;
8317
10069
  border-color: #d08070;
@@ -8320,28 +10072,33 @@ DawRecordButtonElement.styles = [
8320
10072
  `
8321
10073
  ];
8322
10074
  __decorateClass([
8323
- state4()
10075
+ state5()
8324
10076
  ], DawRecordButtonElement.prototype, "_isRecording", 2);
8325
10077
  DawRecordButtonElement = __decorateClass([
8326
- customElement15("daw-record-button")
10078
+ customElement18("daw-record-button")
8327
10079
  ], DawRecordButtonElement);
8328
10080
 
8329
10081
  // src/elements/daw-keyboard-shortcuts.ts
8330
- import { LitElement as LitElement13 } from "lit";
8331
- import { customElement as customElement16, property as property11 } from "lit/decorators.js";
10082
+ import { LitElement as LitElement16 } from "lit";
10083
+ import { customElement as customElement19, property as property14 } from "lit/decorators.js";
8332
10084
  import { handleKeyboardEvent } from "@waveform-playlist/core";
8333
- var DawKeyboardShortcutsElement = class extends LitElement13 {
10085
+ var DawKeyboardShortcutsElement = class extends LitElement16 {
8334
10086
  constructor() {
8335
10087
  super(...arguments);
8336
10088
  this.playback = false;
8337
10089
  this.splitting = false;
8338
10090
  this.undo = false;
8339
10091
  // --- JS properties for remapping ---
8340
- this.playbackShortcuts = null;
8341
- this.splittingShortcuts = null;
8342
- this.undoShortcuts = null;
10092
+ // Accessors, not plain fields: assigning a remap after any keydown has
10093
+ // warmed _cachedShortcuts must invalidate it, or the documented remapping
10094
+ // API is silently ignored until an unrelated boolean attribute toggles.
10095
+ // (connectedCallback runs the standard upgrade-property dance so values
10096
+ // assigned BEFORE the element was defined don't shadow these accessors.)
10097
+ this._playbackShortcuts = null;
10098
+ this._splittingShortcuts = null;
10099
+ this._undoShortcuts = null;
8343
10100
  /** Additional custom shortcuts. */
8344
- this.customShortcuts = [];
10101
+ this._customShortcuts = [];
8345
10102
  this._editor = null;
8346
10103
  this._cachedShortcuts = null;
8347
10104
  // --- Event handler ---
@@ -8363,6 +10120,34 @@ var DawKeyboardShortcutsElement = class extends LitElement13 {
8363
10120
  }
8364
10121
  };
8365
10122
  }
10123
+ get playbackShortcuts() {
10124
+ return this._playbackShortcuts;
10125
+ }
10126
+ set playbackShortcuts(value) {
10127
+ this._playbackShortcuts = value;
10128
+ this._cachedShortcuts = null;
10129
+ }
10130
+ get splittingShortcuts() {
10131
+ return this._splittingShortcuts;
10132
+ }
10133
+ set splittingShortcuts(value) {
10134
+ this._splittingShortcuts = value;
10135
+ this._cachedShortcuts = null;
10136
+ }
10137
+ get undoShortcuts() {
10138
+ return this._undoShortcuts;
10139
+ }
10140
+ set undoShortcuts(value) {
10141
+ this._undoShortcuts = value;
10142
+ this._cachedShortcuts = null;
10143
+ }
10144
+ get customShortcuts() {
10145
+ return this._customShortcuts;
10146
+ }
10147
+ set customShortcuts(value) {
10148
+ this._customShortcuts = value;
10149
+ this._cachedShortcuts = null;
10150
+ }
8366
10151
  /** All active shortcuts (read-only, cached). */
8367
10152
  get shortcuts() {
8368
10153
  if (!this._cachedShortcuts) {
@@ -8377,6 +10162,18 @@ var DawKeyboardShortcutsElement = class extends LitElement13 {
8377
10162
  // --- Lifecycle ---
8378
10163
  connectedCallback() {
8379
10164
  super.connectedCallback();
10165
+ for (const prop of [
10166
+ "playbackShortcuts",
10167
+ "splittingShortcuts",
10168
+ "undoShortcuts",
10169
+ "customShortcuts"
10170
+ ]) {
10171
+ if (Object.prototype.hasOwnProperty.call(this, prop)) {
10172
+ const value = this[prop];
10173
+ delete this[prop];
10174
+ this[prop] = value;
10175
+ }
10176
+ }
8380
10177
  this._editor = this.closest("daw-editor");
8381
10178
  if (!this._editor) {
8382
10179
  console.warn(
@@ -8484,23 +10281,23 @@ var DawKeyboardShortcutsElement = class extends LitElement13 {
8484
10281
  }
8485
10282
  };
8486
10283
  __decorateClass([
8487
- property11({ type: Boolean })
10284
+ property14({ type: Boolean })
8488
10285
  ], DawKeyboardShortcutsElement.prototype, "playback", 2);
8489
10286
  __decorateClass([
8490
- property11({ type: Boolean })
10287
+ property14({ type: Boolean })
8491
10288
  ], DawKeyboardShortcutsElement.prototype, "splitting", 2);
8492
10289
  __decorateClass([
8493
- property11({ type: Boolean })
10290
+ property14({ type: Boolean })
8494
10291
  ], DawKeyboardShortcutsElement.prototype, "undo", 2);
8495
10292
  DawKeyboardShortcutsElement = __decorateClass([
8496
- customElement16("daw-keyboard-shortcuts")
10293
+ customElement19("daw-keyboard-shortcuts")
8497
10294
  ], DawKeyboardShortcutsElement);
8498
10295
 
8499
10296
  // src/elements/daw-spectrogram.ts
8500
- import { LitElement as LitElement14, html as html13, css as css13 } from "lit";
8501
- import { customElement as customElement17, property as property12 } from "lit/decorators.js";
10297
+ import { LitElement as LitElement17, html as html15, css as css14 } from "lit";
10298
+ import { customElement as customElement20, property as property15 } from "lit/decorators.js";
8502
10299
  import { MAX_CANVAS_WIDTH as MAX_CANVAS_WIDTH5, buildSpectrogramCanvasId } from "@waveform-playlist/core";
8503
- var DawSpectrogramElement = class extends LitElement14 {
10300
+ var DawSpectrogramElement = class extends LitElement17 {
8504
10301
  constructor() {
8505
10302
  super(...arguments);
8506
10303
  this.clipId = "";
@@ -8636,10 +10433,10 @@ var DawSpectrogramElement = class extends LitElement14 {
8636
10433
  this._unregisterAllCanvases();
8637
10434
  }
8638
10435
  render() {
8639
- return html13`${this._canvases.map((c) => c)}`;
10436
+ return html15`${this._canvases.map((c) => c)}`;
8640
10437
  }
8641
10438
  };
8642
- DawSpectrogramElement.styles = css13`
10439
+ DawSpectrogramElement.styles = css14`
8643
10440
  :host {
8644
10441
  display: block;
8645
10442
  position: relative;
@@ -8654,46 +10451,46 @@ DawSpectrogramElement.styles = css13`
8654
10451
  }
8655
10452
  `;
8656
10453
  __decorateClass([
8657
- property12({ attribute: false })
10454
+ property15({ attribute: false })
8658
10455
  ], DawSpectrogramElement.prototype, "clipId", 2);
8659
10456
  __decorateClass([
8660
- property12({ attribute: false })
10457
+ property15({ attribute: false })
8661
10458
  ], DawSpectrogramElement.prototype, "trackId", 2);
8662
10459
  __decorateClass([
8663
- property12({ type: Number, attribute: false })
10460
+ property15({ type: Number, attribute: false })
8664
10461
  ], DawSpectrogramElement.prototype, "channelIndex", 2);
8665
10462
  __decorateClass([
8666
- property12({ type: Number, attribute: false })
10463
+ property15({ type: Number, attribute: false })
8667
10464
  ], DawSpectrogramElement.prototype, "length", 2);
8668
10465
  __decorateClass([
8669
- property12({ type: Number, attribute: false })
10466
+ property15({ type: Number, attribute: false })
8670
10467
  ], DawSpectrogramElement.prototype, "waveHeight", 2);
8671
10468
  __decorateClass([
8672
- property12({ type: Number, attribute: false, noAccessor: true })
10469
+ property15({ type: Number, attribute: false, noAccessor: true })
8673
10470
  ], DawSpectrogramElement.prototype, "samplesPerPixel", 1);
8674
10471
  __decorateClass([
8675
- property12({ type: Number, attribute: false, noAccessor: true })
10472
+ property15({ type: Number, attribute: false, noAccessor: true })
8676
10473
  ], DawSpectrogramElement.prototype, "sampleRate", 1);
8677
10474
  __decorateClass([
8678
- property12({ type: Number, attribute: false })
10475
+ property15({ type: Number, attribute: false })
8679
10476
  ], DawSpectrogramElement.prototype, "clipOffsetSeconds", 2);
8680
10477
  __decorateClass([
8681
- property12({ type: Number, attribute: false })
10478
+ property15({ type: Number, attribute: false })
8682
10479
  ], DawSpectrogramElement.prototype, "visibleStart", 2);
8683
10480
  __decorateClass([
8684
- property12({ type: Number, attribute: false })
10481
+ property15({ type: Number, attribute: false })
8685
10482
  ], DawSpectrogramElement.prototype, "visibleEnd", 2);
8686
10483
  __decorateClass([
8687
- property12({ type: Number, attribute: false })
10484
+ property15({ type: Number, attribute: false })
8688
10485
  ], DawSpectrogramElement.prototype, "originX", 2);
8689
10486
  DawSpectrogramElement = __decorateClass([
8690
- customElement17("daw-spectrogram")
10487
+ customElement20("daw-spectrogram")
8691
10488
  ], DawSpectrogramElement);
8692
10489
 
8693
10490
  // src/elements/daw-time-display.ts
8694
- import { LitElement as LitElement15, html as html14, css as css14 } from "lit";
8695
- import { customElement as customElement18, state as state5 } from "lit/decorators.js";
8696
- var DawTimeDisplayElement = class extends LitElement15 {
10491
+ import { LitElement as LitElement18, html as html16, css as css15 } from "lit";
10492
+ import { customElement as customElement21, state as state6 } from "lit/decorators.js";
10493
+ var DawTimeDisplayElement = class extends LitElement18 {
8697
10494
  constructor() {
8698
10495
  super(...arguments);
8699
10496
  this._time = null;
@@ -8746,10 +10543,10 @@ var DawTimeDisplayElement = class extends LitElement15 {
8746
10543
  }
8747
10544
  render() {
8748
10545
  const text = this._time === null ? "--:--:--" : formatDisplayTime(this._time, this._format);
8749
- return html14`<span role="status" aria-label="Playback time" aria-live="off">${text}</span>`;
10546
+ return html16`<span role="status" aria-label="Playback time" aria-live="off">${text}</span>`;
8750
10547
  }
8751
10548
  };
8752
- DawTimeDisplayElement.styles = css14`
10549
+ DawTimeDisplayElement.styles = css15`
8753
10550
  span {
8754
10551
  display: inline-block;
8755
10552
  font-family: ui-monospace, 'SF Mono', Menlo, Consolas, monospace;
@@ -8761,19 +10558,19 @@ DawTimeDisplayElement.styles = css14`
8761
10558
  }
8762
10559
  `;
8763
10560
  __decorateClass([
8764
- state5()
10561
+ state6()
8765
10562
  ], DawTimeDisplayElement.prototype, "_time", 2);
8766
10563
  __decorateClass([
8767
- state5()
10564
+ state6()
8768
10565
  ], DawTimeDisplayElement.prototype, "_format", 2);
8769
10566
  DawTimeDisplayElement = __decorateClass([
8770
- customElement18("daw-time-display")
10567
+ customElement21("daw-time-display")
8771
10568
  ], DawTimeDisplayElement);
8772
10569
 
8773
10570
  // src/elements/daw-time-format.ts
8774
- import { LitElement as LitElement16, html as html15, css as css15 } from "lit";
8775
- import { customElement as customElement19, state as state6 } from "lit/decorators.js";
8776
- var DawTimeFormatElement = class extends LitElement16 {
10571
+ import { LitElement as LitElement19, html as html17, css as css16 } from "lit";
10572
+ import { customElement as customElement22, state as state7 } from "lit/decorators.js";
10573
+ var DawTimeFormatElement = class extends LitElement19 {
8777
10574
  constructor() {
8778
10575
  super(...arguments);
8779
10576
  this._format = "hh:mm:ss.sss";
@@ -8848,20 +10645,20 @@ var DawTimeFormatElement = class extends LitElement16 {
8848
10645
  target.setTimeFormat?.(value);
8849
10646
  }
8850
10647
  render() {
8851
- return html15`
10648
+ return html17`
8852
10649
  <select
8853
10650
  aria-label="Time format"
8854
10651
  ?disabled=${!this._targetSupported}
8855
10652
  @change=${this._onSelectChange}
8856
10653
  >
8857
10654
  ${TIME_DISPLAY_FORMATS.map(
8858
- (f) => html15`<option value=${f} ?selected=${f === this._format}>${f}</option>`
10655
+ (f) => html17`<option value=${f} ?selected=${f === this._format}>${f}</option>`
8859
10656
  )}
8860
10657
  </select>
8861
10658
  `;
8862
10659
  }
8863
10660
  };
8864
- DawTimeFormatElement.styles = css15`
10661
+ DawTimeFormatElement.styles = css16`
8865
10662
  select {
8866
10663
  cursor: pointer;
8867
10664
  background: var(--daw-controls-background, #1a1a2e);
@@ -8876,20 +10673,20 @@ DawTimeFormatElement.styles = css15`
8876
10673
  }
8877
10674
  `;
8878
10675
  __decorateClass([
8879
- state6()
10676
+ state7()
8880
10677
  ], DawTimeFormatElement.prototype, "_format", 2);
8881
10678
  DawTimeFormatElement = __decorateClass([
8882
- customElement19("daw-time-format")
10679
+ customElement22("daw-time-format")
8883
10680
  ], DawTimeFormatElement);
8884
10681
 
8885
10682
  // src/elements/daw-player.ts
8886
- import { LitElement as LitElement17, html as html16, css as css16 } from "lit";
8887
- import { customElement as customElement20, property as property13, state as state7 } from "lit/decorators.js";
10683
+ import { LitElement as LitElement20, html as html18, css as css17 } from "lit";
10684
+ import { customElement as customElement23, property as property16, state as state8 } from "lit/decorators.js";
8888
10685
  import { repeat } from "lit/directives/repeat.js";
8889
10686
  import { MediaElementPlayout } from "@waveform-playlist/media-element-playout";
8890
10687
  var MIN_RATE = 0.25;
8891
10688
  var MAX_RATE = 4;
8892
- var DawPlayerElement = class extends LitElement17 {
10689
+ var DawPlayerElement = class extends LitElement20 {
8893
10690
  constructor() {
8894
10691
  super(...arguments);
8895
10692
  this.src = "";
@@ -8902,6 +10699,9 @@ var DawPlayerElement = class extends LitElement17 {
8902
10699
  this.roundedBars = false;
8903
10700
  this._playbackRate = 1;
8904
10701
  this._engine = new MediaElementPlayout();
10702
+ /** Set by disconnectedCallback — a reconnect (DOM reparent, framework
10703
+ * re-render) must rebuild the engine + track or the player is dead. */
10704
+ this._engineDisposed = false;
8905
10705
  this._trackId = null;
8906
10706
  this._anim = new AnimationController(this);
8907
10707
  this._metadataLoaded = false;
@@ -8919,7 +10719,6 @@ var DawPlayerElement = class extends LitElement17 {
8919
10719
  if (width <= 0 || d <= 0) return;
8920
10720
  const ratio = Math.max(0, Math.min(1, e.offsetX / width));
8921
10721
  this.seekTo(ratio * d);
8922
- this._updatePlayhead();
8923
10722
  };
8924
10723
  this._onLoadedMetadata = () => {
8925
10724
  this._metadataLoaded = true;
@@ -8967,6 +10766,15 @@ var DawPlayerElement = class extends LitElement17 {
8967
10766
  }
8968
10767
  connectedCallback() {
8969
10768
  super.connectedCallback();
10769
+ let rebuilt = false;
10770
+ if (this._engineDisposed) {
10771
+ const volume = this._engine.masterVolume;
10772
+ this._engine = new MediaElementPlayout();
10773
+ this._engine.setMasterVolume(volume);
10774
+ this._engineDisposed = false;
10775
+ this._trackId = null;
10776
+ rebuilt = true;
10777
+ }
8970
10778
  this._engine.on("loadedmetadata", this._onLoadedMetadata);
8971
10779
  this._engine.on("play", this._onPlay);
8972
10780
  this._engine.on("pause", this._onPause);
@@ -8977,13 +10785,17 @@ var DawPlayerElement = class extends LitElement17 {
8977
10785
  const area = this.shadowRoot?.querySelector(".waveform-area");
8978
10786
  if (area) this._resizeObserver?.observe(area);
8979
10787
  });
10788
+ if (rebuilt && this.src) {
10789
+ this._loadSource();
10790
+ this._playhead?.setPosition(0);
10791
+ }
8980
10792
  }
8981
10793
  render() {
8982
10794
  const width = this._timelineWidth;
8983
10795
  const channels = this._channelPeaks.length;
8984
10796
  const channelHeight = channels > 0 ? this.waveHeight / channels : this.waveHeight;
8985
- return html16`
8986
- ${this.timescale ? html16`<daw-ruler
10797
+ return html18`
10798
+ ${this.timescale ? html18`<daw-ruler
8987
10799
  .samplesPerPixel=${this._channelSpp(width)}
8988
10800
  .sampleRate=${this._sampleRate}
8989
10801
  .duration=${this._engine.duration}
@@ -8997,7 +10809,7 @@ var DawPlayerElement = class extends LitElement17 {
8997
10809
  ${repeat(
8998
10810
  this._channelPeaks,
8999
10811
  (_p, i) => i,
9000
- (peaks) => html16`<daw-waveform
10812
+ (peaks) => html18`<daw-waveform
9001
10813
  .peaks=${peaks}
9002
10814
  .length=${width}
9003
10815
  .waveHeight=${channelHeight}
@@ -9036,6 +10848,7 @@ var DawPlayerElement = class extends LitElement17 {
9036
10848
  this._renderWaveform();
9037
10849
  this._maybeDispatchReady();
9038
10850
  } catch (err) {
10851
+ if (this.peaksSrc !== requested) return;
9039
10852
  console.warn("[dawcore] <daw-player> failed to load peaks-src: " + String(err));
9040
10853
  this._peaksSettled = true;
9041
10854
  this._renderWaveform();
@@ -9076,7 +10889,7 @@ var DawPlayerElement = class extends LitElement17 {
9076
10889
  }
9077
10890
  // --- Transport methods ---
9078
10891
  play() {
9079
- this._engine.play();
10892
+ this._engine.resume();
9080
10893
  }
9081
10894
  pause() {
9082
10895
  this._engine.pause();
@@ -9089,6 +10902,10 @@ var DawPlayerElement = class extends LitElement17 {
9089
10902
  }
9090
10903
  seekTo(time) {
9091
10904
  this._engine.seekTo(time);
10905
+ if (!this._engine.isPlaying) {
10906
+ this._updatePlayhead();
10907
+ this._dispatch("daw-timeupdate", { time: this._engine.getCurrentTime() });
10908
+ }
9092
10909
  }
9093
10910
  setPlaybackRate(rate) {
9094
10911
  this.playbackRate = rate;
@@ -9107,7 +10924,7 @@ var DawPlayerElement = class extends LitElement17 {
9107
10924
  return this._engine.getCurrentTime();
9108
10925
  }
9109
10926
  set currentTime(time) {
9110
- this._engine.seekTo(time);
10927
+ this.seekTo(time);
9111
10928
  }
9112
10929
  get volume() {
9113
10930
  return this._engine.masterVolume;
@@ -9129,6 +10946,7 @@ var DawPlayerElement = class extends LitElement17 {
9129
10946
  this._engine.off("ended", this._onEnded);
9130
10947
  this._engine.off("error", this._onError);
9131
10948
  this._engine.dispose();
10949
+ this._engineDisposed = true;
9132
10950
  }
9133
10951
  // --- Private event handlers (arrow fields for stable identity) ---
9134
10952
  _dispatch(name, detail) {
@@ -9154,7 +10972,7 @@ var DawPlayerElement = class extends LitElement17 {
9154
10972
  return this.shadowRoot?.querySelector(".waveform-area")?.clientWidth ?? 0;
9155
10973
  }
9156
10974
  };
9157
- DawPlayerElement.styles = css16`
10975
+ DawPlayerElement.styles = css17`
9158
10976
  :host {
9159
10977
  display: block;
9160
10978
  position: relative;
@@ -9167,41 +10985,45 @@ DawPlayerElement.styles = css16`
9167
10985
  }
9168
10986
  `;
9169
10987
  __decorateClass([
9170
- property13({ type: String })
10988
+ property16({ type: String })
9171
10989
  ], DawPlayerElement.prototype, "src", 2);
9172
10990
  __decorateClass([
9173
- property13({ type: String, attribute: "peaks-src" })
10991
+ property16({ type: String, attribute: "peaks-src" })
9174
10992
  ], DawPlayerElement.prototype, "peaksSrc", 2);
9175
10993
  __decorateClass([
9176
- property13({ type: Number, attribute: "wave-height" })
10994
+ property16({ type: Number, attribute: "wave-height" })
9177
10995
  ], DawPlayerElement.prototype, "waveHeight", 2);
9178
10996
  __decorateClass([
9179
- property13({ type: Boolean })
10997
+ property16({ type: Boolean })
9180
10998
  ], DawPlayerElement.prototype, "timescale", 2);
9181
10999
  __decorateClass([
9182
- property13({ type: Boolean })
11000
+ property16({ type: Boolean })
9183
11001
  ], DawPlayerElement.prototype, "mono", 2);
9184
11002
  __decorateClass([
9185
- property13({ type: Number, attribute: "bar-width" })
11003
+ property16({ type: Number, attribute: "bar-width" })
9186
11004
  ], DawPlayerElement.prototype, "barWidth", 2);
9187
11005
  __decorateClass([
9188
- property13({ type: Number, attribute: "bar-gap" })
11006
+ property16({ type: Number, attribute: "bar-gap" })
9189
11007
  ], DawPlayerElement.prototype, "barGap", 2);
9190
11008
  __decorateClass([
9191
- property13({ type: Boolean, attribute: "rounded-bars" })
11009
+ property16({ type: Boolean, attribute: "rounded-bars" })
9192
11010
  ], DawPlayerElement.prototype, "roundedBars", 2);
9193
11011
  __decorateClass([
9194
- property13({ type: Number, attribute: "playback-rate", noAccessor: true })
11012
+ property16({ type: Number, attribute: "playback-rate", noAccessor: true })
9195
11013
  ], DawPlayerElement.prototype, "playbackRate", 1);
9196
11014
  __decorateClass([
9197
- state7()
11015
+ state8()
9198
11016
  ], DawPlayerElement.prototype, "_channelPeaks", 2);
9199
11017
  DawPlayerElement = __decorateClass([
9200
- customElement20("daw-player")
11018
+ customElement23("daw-player")
9201
11019
  ], DawPlayerElement);
9202
11020
  export {
11021
+ ANNOTATION_LANE_HEIGHT,
9203
11022
  AudioResumeController,
9204
11023
  ClipPointerHandler,
11024
+ DawAnnotationElement,
11025
+ DawAnnotationListElement,
11026
+ DawAnnotationTrackElement,
9205
11027
  DawClipElement,
9206
11028
  DawEditorElement,
9207
11029
  DawGridElement,