@dawcore/components 0.0.35 → 0.0.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2232,7 +2232,7 @@ function isDomClip(desc) {
2232
2232
  }
2233
2233
 
2234
2234
  // src/elements/daw-editor.ts
2235
- var import_core13 = require("@waveform-playlist/core");
2235
+ var import_core12 = require("@waveform-playlist/core");
2236
2236
 
2237
2237
  // src/workers/peaksWorker.ts
2238
2238
  var import_waveform_data = __toESM(require("waveform-data"));
@@ -2988,6 +2988,9 @@ var DawTrackControlsElement = class extends import_lit15.LitElement {
2988
2988
  this.pan = 0;
2989
2989
  this.muted = false;
2990
2990
  this.soloed = false;
2991
+ this.reorderable = false;
2992
+ this.trackIndex = 0;
2993
+ this.trackCount = 1;
2991
2994
  this._onVolumeInput = (e) => {
2992
2995
  const value = Number(e.target.value);
2993
2996
  if (Number.isFinite(value)) this._dispatchControl("volume", value);
@@ -3012,6 +3015,23 @@ var DawTrackControlsElement = class extends import_lit15.LitElement {
3012
3015
  })
3013
3016
  );
3014
3017
  };
3018
+ this._onMoveUp = () => this._dispatchReorder(this.trackIndex - 1);
3019
+ this._onMoveDown = () => this._dispatchReorder(this.trackIndex + 1);
3020
+ this._onGripPointerDown = (e) => {
3021
+ if (!this.trackId) return;
3022
+ e.preventDefault();
3023
+ this.dispatchEvent(
3024
+ new CustomEvent("daw-track-reorder-grab", {
3025
+ bubbles: true,
3026
+ composed: true,
3027
+ detail: {
3028
+ trackId: this.trackId,
3029
+ pointerEvent: e,
3030
+ gripElement: e.currentTarget
3031
+ }
3032
+ })
3033
+ );
3034
+ };
3015
3035
  }
3016
3036
  firstUpdated() {
3017
3037
  requestAnimationFrame(() => {
@@ -3034,12 +3054,30 @@ var DawTrackControlsElement = class extends import_lit15.LitElement {
3034
3054
  })
3035
3055
  );
3036
3056
  }
3057
+ _dispatchReorder(toIndex) {
3058
+ if (!this.trackId) return;
3059
+ this.dispatchEvent(
3060
+ new CustomEvent("daw-track-reorder", {
3061
+ bubbles: true,
3062
+ composed: true,
3063
+ detail: { trackId: this.trackId, fromIndex: this.trackIndex, toIndex }
3064
+ })
3065
+ );
3066
+ }
3037
3067
  render() {
3038
3068
  const volPercent = Math.round(this.volume * 100);
3039
3069
  const panPercent = Math.round(Math.abs(this.pan) * 100);
3040
3070
  const panDisplay = this.pan === 0 ? "C" : (this.pan > 0 ? "R" : "L") + panPercent;
3041
3071
  return import_lit15.html`
3042
3072
  <div class="header">
3073
+ ${this.reorderable ? import_lit15.html`<button
3074
+ class="grip"
3075
+ title="Drag to reorder track"
3076
+ aria-label="Drag to reorder track"
3077
+ @pointerdown=${this._onGripPointerDown}
3078
+ >
3079
+ ⠿
3080
+ </button>` : ""}
3043
3081
  <span class="name" title=${this.trackName}>${this.trackName || "Untitled"}</span>
3044
3082
  <button class="remove-btn" @click=${this._onRemoveClick} title="Remove track">
3045
3083
  &times;
@@ -3056,6 +3094,24 @@ var DawTrackControlsElement = class extends import_lit15.LitElement {
3056
3094
  <button class="btn ${this.soloed ? "active" : ""}" @click=${this._onSoloClick} title="Solo">
3057
3095
  S
3058
3096
  </button>
3097
+ ${this.reorderable ? import_lit15.html`<button
3098
+ class="btn reorder-up"
3099
+ title="Move track up"
3100
+ aria-label="Move track up"
3101
+ ?disabled=${this.trackIndex <= 0}
3102
+ @click=${this._onMoveUp}
3103
+ >
3104
+ ▲
3105
+ </button>
3106
+ <button
3107
+ class="btn reorder-down"
3108
+ title="Move track down"
3109
+ aria-label="Move track down"
3110
+ ?disabled=${this.trackIndex >= this.trackCount - 1}
3111
+ @click=${this._onMoveDown}
3112
+ >
3113
+ ▼
3114
+ </button>` : ""}
3059
3115
  </div>
3060
3116
  <div class="slider-row vol-row">
3061
3117
  <span class="slider-label">
@@ -3132,6 +3188,20 @@ DawTrackControlsElement.styles = import_lit15.css`
3132
3188
  opacity: 1;
3133
3189
  color: #d08070;
3134
3190
  }
3191
+ .grip {
3192
+ background: none;
3193
+ border: none;
3194
+ color: var(--daw-controls-text, #c49a6c);
3195
+ cursor: grab;
3196
+ padding: 0 2px;
3197
+ font-size: 12px;
3198
+ line-height: 1;
3199
+ opacity: 0.4;
3200
+ touch-action: none;
3201
+ }
3202
+ .grip:hover {
3203
+ opacity: 1;
3204
+ }
3135
3205
  .buttons {
3136
3206
  display: flex;
3137
3207
  gap: 3px;
@@ -3161,6 +3231,10 @@ DawTrackControlsElement.styles = import_lit15.css`
3161
3231
  border-color: rgba(208, 128, 112, 0.5);
3162
3232
  color: #d08070;
3163
3233
  }
3234
+ .btn:disabled {
3235
+ opacity: 0.3;
3236
+ cursor: default;
3237
+ }
3164
3238
  .slider-row {
3165
3239
  display: flex;
3166
3240
  align-items: center;
@@ -3257,6 +3331,15 @@ __decorateClass([
3257
3331
  __decorateClass([
3258
3332
  (0, import_decorators14.property)({ type: Boolean, attribute: false })
3259
3333
  ], DawTrackControlsElement.prototype, "soloed", 2);
3334
+ __decorateClass([
3335
+ (0, import_decorators14.property)({ type: Boolean, attribute: false })
3336
+ ], DawTrackControlsElement.prototype, "reorderable", 2);
3337
+ __decorateClass([
3338
+ (0, import_decorators14.property)({ type: Number, attribute: false })
3339
+ ], DawTrackControlsElement.prototype, "trackIndex", 2);
3340
+ __decorateClass([
3341
+ (0, import_decorators14.property)({ type: Number, attribute: false })
3342
+ ], DawTrackControlsElement.prototype, "trackCount", 2);
3260
3343
  DawTrackControlsElement = __decorateClass([
3261
3344
  (0, import_decorators14.customElement)("daw-track-controls")
3262
3345
  ], DawTrackControlsElement);
@@ -5182,6 +5265,179 @@ var AnnotationDragHandler = class {
5182
5265
  }
5183
5266
  };
5184
5267
 
5268
+ // src/interactions/track-reorder-handler.ts
5269
+ var TrackReorderHandler = class _TrackReorderHandler {
5270
+ constructor(host) {
5271
+ this._trackId = null;
5272
+ this._pointerId = -1;
5273
+ this._startY = 0;
5274
+ this._rows = [];
5275
+ this._lanes = [];
5276
+ // aligned with _rows indices; null = lane not found
5277
+ this._fromIndex = 0;
5278
+ this._targetIndex = 0;
5279
+ this._gripEl = null;
5280
+ this.onGrab = (trackId, e, gripEl) => {
5281
+ if (this._trackId !== null) return;
5282
+ const column = this._host.shadowRoot?.querySelector(".controls-column");
5283
+ if (!column) return;
5284
+ const rows = [...column.querySelectorAll("daw-track-controls")];
5285
+ this._rows = rows.map((el) => {
5286
+ const rect = el.getBoundingClientRect();
5287
+ return {
5288
+ el,
5289
+ top: rect.top,
5290
+ height: rect.height,
5291
+ trackId: el.trackId ?? ""
5292
+ };
5293
+ });
5294
+ this._fromIndex = this._rows.findIndex((r) => r.trackId === trackId);
5295
+ if (this._fromIndex === -1) {
5296
+ this._rows = [];
5297
+ return;
5298
+ }
5299
+ this._trackId = trackId;
5300
+ this._targetIndex = this._fromIndex;
5301
+ this._pointerId = e.pointerId;
5302
+ this._startY = e.clientY;
5303
+ this._gripEl = gripEl;
5304
+ const timeline = this._host.shadowRoot?.querySelector(".timeline");
5305
+ const laneEls = timeline ? [...timeline.querySelectorAll(".track-row")] : [];
5306
+ this._lanes = this._rows.map((r) => {
5307
+ const el = laneEls.find((l) => l.getAttribute("data-track-id") === r.trackId) ?? null;
5308
+ if (!el) return null;
5309
+ const rect = el.getBoundingClientRect();
5310
+ return { el, top: rect.top, height: rect.height, trackId: r.trackId };
5311
+ });
5312
+ const draggedLane = this._lanes[this._fromIndex];
5313
+ if (draggedLane) {
5314
+ draggedLane.el.setAttribute("data-track-drag-source", "");
5315
+ draggedLane.el.style.zIndex = "10";
5316
+ draggedLane.el.style.position = "relative";
5317
+ }
5318
+ if (!_TrackReorderHandler._reducedMotion()) {
5319
+ for (let i = 0; i < this._rows.length; i++) {
5320
+ if (i !== this._fromIndex) this._rows[i].el.style.transition = "transform 150ms ease";
5321
+ const lane = this._lanes[i];
5322
+ if (lane) lane.el.style.transition = "transform 150ms ease";
5323
+ }
5324
+ }
5325
+ try {
5326
+ gripEl.setPointerCapture(e.pointerId);
5327
+ } catch {
5328
+ }
5329
+ gripEl.addEventListener("pointermove", this._onPointerMove);
5330
+ gripEl.addEventListener("pointerup", this._onPointerUp);
5331
+ gripEl.addEventListener("pointercancel", this._onPointerCancel);
5332
+ };
5333
+ this._onPointerMove = (e) => {
5334
+ if (e.pointerId !== this._pointerId || this._trackId === null) return;
5335
+ const dragged = this._rows[this._fromIndex];
5336
+ const dy = e.clientY - this._startY;
5337
+ dragged.el.style.transform = "translateY(" + dy + "px)";
5338
+ dragged.el.style.zIndex = "10";
5339
+ dragged.el.style.position = "relative";
5340
+ let target = this._fromIndex;
5341
+ for (let i = 0; i < this._rows.length; i++) {
5342
+ if (i === this._fromIndex) continue;
5343
+ const mid = this._rows[i].top + this._rows[i].height / 2;
5344
+ if (i < this._fromIndex && e.clientY < mid) {
5345
+ target = i;
5346
+ break;
5347
+ }
5348
+ if (i > this._fromIndex && e.clientY > mid) {
5349
+ target = i;
5350
+ }
5351
+ }
5352
+ this._targetIndex = target;
5353
+ for (let i = 0; i < this._rows.length; i++) {
5354
+ if (i === this._fromIndex) continue;
5355
+ const row = this._rows[i];
5356
+ let shift = 0;
5357
+ if (i > this._fromIndex && i <= target) shift = -dragged.height;
5358
+ else if (i < this._fromIndex && i >= target) shift = dragged.height;
5359
+ row.el.style.transform = shift === 0 ? "" : "translateY(" + shift + "px)";
5360
+ }
5361
+ const draggedLaneInfo = this._lanes[this._fromIndex];
5362
+ for (let i = 0; i < this._lanes.length; i++) {
5363
+ const lane = this._lanes[i];
5364
+ if (!lane || !draggedLaneInfo) continue;
5365
+ if (i === this._fromIndex) {
5366
+ let offset = 0;
5367
+ const targetLane = this._lanes[target];
5368
+ if (targetLane && target > this._fromIndex) {
5369
+ offset = targetLane.top + targetLane.height - (draggedLaneInfo.top + draggedLaneInfo.height);
5370
+ } else if (targetLane && target < this._fromIndex) {
5371
+ offset = targetLane.top - draggedLaneInfo.top;
5372
+ }
5373
+ lane.el.style.transform = offset === 0 ? "" : "translateY(" + offset + "px)";
5374
+ continue;
5375
+ }
5376
+ let laneShift = 0;
5377
+ if (i > this._fromIndex && i <= target) laneShift = -draggedLaneInfo.height;
5378
+ else if (i < this._fromIndex && i >= target) laneShift = draggedLaneInfo.height;
5379
+ lane.el.style.transform = laneShift === 0 ? "" : "translateY(" + laneShift + "px)";
5380
+ }
5381
+ };
5382
+ this._onPointerUp = (e) => {
5383
+ if (e.pointerId !== this._pointerId || this._trackId === null) return;
5384
+ const trackId = this._trackId;
5385
+ const target = this._targetIndex;
5386
+ const from = this._fromIndex;
5387
+ this._cleanup();
5388
+ if (target !== from) {
5389
+ this._host.reorderTrack(trackId, target);
5390
+ }
5391
+ };
5392
+ this._onPointerCancel = (e) => {
5393
+ if (e.pointerId !== this._pointerId) return;
5394
+ this._cleanup();
5395
+ };
5396
+ this._host = host;
5397
+ }
5398
+ static _reducedMotion() {
5399
+ return typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
5400
+ }
5401
+ /** Abort any in-progress drag and reset state. Called by the editor on
5402
+ * disconnect — without this, a drag interrupted by editor removal (with no
5403
+ * pointercancel delivered) would leave the handler wedged and silently
5404
+ * block every future grab. */
5405
+ cancel() {
5406
+ this._cleanup();
5407
+ }
5408
+ _cleanup() {
5409
+ for (const row of this._rows) {
5410
+ row.el.style.transform = "";
5411
+ row.el.style.zIndex = "";
5412
+ row.el.style.position = "";
5413
+ row.el.style.transition = "";
5414
+ }
5415
+ for (const lane of this._lanes) {
5416
+ if (!lane) continue;
5417
+ lane.el.style.transform = "";
5418
+ lane.el.style.transition = "";
5419
+ lane.el.style.zIndex = "";
5420
+ lane.el.style.position = "";
5421
+ lane.el.removeAttribute("data-track-drag-source");
5422
+ }
5423
+ this._lanes = [];
5424
+ const grip = this._gripEl;
5425
+ if (grip) {
5426
+ grip.removeEventListener("pointermove", this._onPointerMove);
5427
+ grip.removeEventListener("pointerup", this._onPointerUp);
5428
+ grip.removeEventListener("pointercancel", this._onPointerCancel);
5429
+ try {
5430
+ grip.releasePointerCapture(this._pointerId);
5431
+ } catch {
5432
+ }
5433
+ }
5434
+ this._gripEl = null;
5435
+ this._trackId = null;
5436
+ this._pointerId = -1;
5437
+ this._rows = [];
5438
+ }
5439
+ };
5440
+
5185
5441
  // src/utils/time-display-format.ts
5186
5442
  var TIME_DISPLAY_FORMATS = [
5187
5443
  "hh:mm:ss.sss",
@@ -5234,7 +5490,6 @@ function parseDisplayTime(value, format) {
5234
5490
  }
5235
5491
 
5236
5492
  // src/interactions/file-loader.ts
5237
- var import_core11 = require("@waveform-playlist/core");
5238
5493
  async function loadFiles(host, files) {
5239
5494
  if (!files) {
5240
5495
  console.warn("[dawcore] loadFiles called with null/undefined");
@@ -5243,107 +5498,36 @@ async function loadFiles(host, files) {
5243
5498
  const fileArray = Array.from(files);
5244
5499
  const loaded = [];
5245
5500
  const failed = [];
5501
+ const dispatchLoadError = (file, error) => {
5502
+ failed.push({ file, error });
5503
+ if (host.isConnected) {
5504
+ host.dispatchEvent(
5505
+ new CustomEvent("daw-files-load-error", {
5506
+ bubbles: true,
5507
+ composed: true,
5508
+ detail: { file, error }
5509
+ })
5510
+ );
5511
+ }
5512
+ };
5246
5513
  for (const file of fileArray) {
5247
5514
  if (file.type && !file.type.startsWith("audio/")) {
5248
5515
  const error = new Error("Non-audio MIME type: " + file.type);
5249
- failed.push({ file, error });
5250
5516
  console.warn("[dawcore] Skipping non-audio file: " + file.name + " (" + file.type + ")");
5251
- if (host.isConnected) {
5252
- host.dispatchEvent(
5253
- new CustomEvent("daw-files-load-error", {
5254
- bubbles: true,
5255
- composed: true,
5256
- detail: { file, error }
5257
- })
5258
- );
5259
- }
5517
+ dispatchLoadError(file, error);
5260
5518
  continue;
5261
5519
  }
5262
5520
  const blobUrl = URL.createObjectURL(file);
5521
+ const name = file.name.replace(/\.\w+$/, "");
5263
5522
  try {
5264
- const audioBuffer = await host._fetchAndDecode(blobUrl);
5265
- URL.revokeObjectURL(blobUrl);
5266
- host._audioCache.delete(blobUrl);
5267
- host._resolvedSampleRate = audioBuffer.sampleRate;
5268
- const name = file.name.replace(/\.\w+$/, "");
5269
- const clip = (0, import_core11.createClip)({
5270
- audioBuffer,
5271
- startSample: 0,
5272
- durationSamples: audioBuffer.length,
5273
- offsetSamples: 0,
5274
- gain: 1,
5275
- name,
5276
- sampleRate: audioBuffer.sampleRate,
5277
- sourceDurationSamples: audioBuffer.length
5278
- });
5279
- host._clipBuffers = new Map(host._clipBuffers).set(clip.id, audioBuffer);
5280
- host._clipOffsets = new Map(host._clipOffsets).set(clip.id, {
5281
- offsetSamples: clip.offsetSamples,
5282
- durationSamples: clip.durationSamples
5283
- });
5284
- const peakData = await host._peakPipeline.generatePeaks(
5285
- audioBuffer,
5286
- host.renderSamplesPerPixel,
5287
- host.mono,
5288
- clip.offsetSamples,
5289
- clip.durationSamples
5290
- );
5291
- host._peaksData = new Map(host._peaksData).set(clip.id, peakData);
5292
- const trackId = crypto.randomUUID();
5293
- const track = (0, import_core11.createTrack)({ name, clips: [clip] });
5294
- track.id = trackId;
5295
- host._tracks = new Map(host._tracks).set(trackId, {
5296
- name,
5297
- src: "",
5298
- volume: 1,
5299
- pan: 0,
5300
- muted: false,
5301
- soloed: false,
5302
- renderMode: "waveform",
5303
- clips: [
5304
- {
5305
- kind: "drop",
5306
- src: "",
5307
- peaksSrc: "",
5308
- start: 0,
5309
- duration: audioBuffer.duration,
5310
- offset: 0,
5311
- gain: 1,
5312
- name,
5313
- fadeIn: 0,
5314
- fadeOut: 0,
5315
- fadeType: "linear",
5316
- midiNotes: null,
5317
- midiChannel: null,
5318
- midiProgram: null
5319
- }
5320
- ]
5321
- });
5322
- host._engineTracks = new Map(host._engineTracks).set(trackId, track);
5323
- host._recomputeDuration();
5324
- const engine = await host._ensureEngine();
5325
- engine.setTracks([...host._engineTracks.values()]);
5326
- loaded.push(trackId);
5327
- host.dispatchEvent(
5328
- new CustomEvent("daw-track-ready", {
5329
- bubbles: true,
5330
- composed: true,
5331
- detail: { trackId }
5332
- })
5333
- );
5523
+ const trackEl = await host.addTrack({ name, clips: [{ src: blobUrl, name }] });
5524
+ loaded.push(trackEl.trackId);
5334
5525
  } catch (err) {
5335
- URL.revokeObjectURL(blobUrl);
5336
5526
  console.warn("[dawcore] Failed to load file: " + file.name + " \u2014 " + String(err));
5337
- failed.push({ file, error: err });
5338
- if (host.isConnected) {
5339
- host.dispatchEvent(
5340
- new CustomEvent("daw-files-load-error", {
5341
- bubbles: true,
5342
- composed: true,
5343
- detail: { file, error: err }
5344
- })
5345
- );
5346
- }
5527
+ dispatchLoadError(file, err);
5528
+ } finally {
5529
+ URL.revokeObjectURL(blobUrl);
5530
+ host._audioCache.delete(blobUrl);
5347
5531
  }
5348
5532
  }
5349
5533
  return { loaded, failed };
@@ -5452,7 +5636,7 @@ function stringifyReason(reason) {
5452
5636
  }
5453
5637
 
5454
5638
  // src/interactions/recording-clip.ts
5455
- var import_core12 = require("@waveform-playlist/core");
5639
+ var import_core11 = require("@waveform-playlist/core");
5456
5640
  function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamples = 0, clipName) {
5457
5641
  let trimmedBuf = buf;
5458
5642
  if (offsetSamples > 0 && offsetSamples < buf.length) {
@@ -5467,7 +5651,7 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
5467
5651
  }
5468
5652
  trimmedBuf = trimmed;
5469
5653
  }
5470
- const clip = (0, import_core12.createClip)({
5654
+ const clip = (0, import_core11.createClip)({
5471
5655
  audioBuffer: trimmedBuf,
5472
5656
  startSample,
5473
5657
  durationSamples: durSamples,
@@ -5494,7 +5678,7 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
5494
5678
  // Punch-in replace (#579): the recorded clip owns [startSample,
5495
5679
  // startSample + durSamples) — carve overlapped content out of the
5496
5680
  // existing clips before inserting (parity with the React provider).
5497
- clips: [...(0, import_core12.carveClipRange)(t.clips, startSample, startSample + durSamples), clip]
5681
+ clips: [...(0, import_core11.carveClipRange)(t.clips, startSample, startSample + durSamples), clip]
5498
5682
  });
5499
5683
  const desc = host._tracks.get(trackId);
5500
5684
  if (desc) {
@@ -7130,6 +7314,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
7130
7314
  this.interactiveClips = false;
7131
7315
  this.indefinitePlayback = false;
7132
7316
  this.fillViewport = false;
7317
+ this.trackReordering = false;
7133
7318
  this._spectrogramConfig = null;
7134
7319
  this._spectrogramColorMap = null;
7135
7320
  this.scaleMode = "temporal";
@@ -7213,6 +7398,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
7213
7398
  this._spectrogramController = null;
7214
7399
  this._clipPointer = new ClipPointerHandler(this);
7215
7400
  this._annotationDrag = new AnnotationDragHandler(this);
7401
+ this._trackReorderDrag = new TrackReorderHandler(this);
7216
7402
  this._pointer = new PointerHandler(this);
7217
7403
  this._viewport = (() => {
7218
7404
  const v = new ViewportController(this);
@@ -7256,6 +7442,10 @@ var DawEditorElement = class extends import_lit19.LitElement {
7256
7442
  console.warn("[dawcore] Invalid daw-track-connected event detail: " + String(e.detail));
7257
7443
  return;
7258
7444
  }
7445
+ if (this._tracks.has(trackId)) {
7446
+ this._trackElements.set(trackId, trackEl);
7447
+ return;
7448
+ }
7259
7449
  const descriptor = this._readTrackDescriptor(trackEl);
7260
7450
  this._tracks = new Map(this._tracks).set(trackId, descriptor);
7261
7451
  this._trackElements.set(trackId, trackEl);
@@ -7365,6 +7555,10 @@ var DawEditorElement = class extends import_lit19.LitElement {
7365
7555
  }
7366
7556
  return;
7367
7557
  }
7558
+ const loadedDesc = this._tracks.get(trackId);
7559
+ if (loadedDesc && loadedDesc.clips.some((c) => isDomClip(c) && c.clipId === clipEl.clipId)) {
7560
+ return;
7561
+ }
7368
7562
  const clipDesc = {
7369
7563
  kind: "dom",
7370
7564
  clipId: clipEl.clipId,
@@ -7429,6 +7623,13 @@ var DawEditorElement = class extends import_lit19.LitElement {
7429
7623
  );
7430
7624
  }
7431
7625
  };
7626
+ this._onTrackReorder = (e) => {
7627
+ this.reorderTrack(e.detail.trackId, e.detail.toIndex);
7628
+ };
7629
+ this._onTrackReorderGrab = (e) => {
7630
+ if (!this.trackReordering) return;
7631
+ this._trackReorderDrag.onGrab(e.detail.trackId, e.detail.pointerEvent, e.detail.gripElement);
7632
+ };
7432
7633
  // --- Recording ---
7433
7634
  this.recordingStream = null;
7434
7635
  /** Set in togglePauseRecording when Transport is paused alongside the
@@ -7442,6 +7643,11 @@ var DawEditorElement = class extends import_lit19.LitElement {
7442
7643
  }
7443
7644
  return time * this.effectiveSampleRate / this.samplesPerPixel;
7444
7645
  };
7646
+ /** Guards the statechange handler's engine→DOM sync (Task: reorder #612)
7647
+ * while the observer is pushing DOM order INTO the engine — the intermediate
7648
+ * statechange emissions during the transaction would otherwise bounce
7649
+ * half-applied orders back into the DOM. */
7650
+ this._inOrderSync = false;
7445
7651
  }
7446
7652
  get samplesPerPixel() {
7447
7653
  return this._samplesPerPixel;
@@ -7963,30 +8169,50 @@ var DawEditorElement = class extends import_lit19.LitElement {
7963
8169
  this._onAnnotationTrackConnected
7964
8170
  );
7965
8171
  this.addEventListener("daw-annotation-select", this._onAnnotationSelect);
8172
+ this.addEventListener("daw-track-reorder", this._onTrackReorder);
8173
+ this.addEventListener("daw-track-reorder-grab", this._onTrackReorderGrab);
7966
8174
  this._childObserver = new MutationObserver((mutations) => {
8175
+ const removedTracks = /* @__PURE__ */ new Map();
8176
+ const removedClips = /* @__PURE__ */ new Set();
8177
+ const addedTrackIds = /* @__PURE__ */ new Set();
7967
8178
  for (const mutation of mutations) {
8179
+ for (const node of mutation.addedNodes) {
8180
+ if (!(node instanceof HTMLElement)) continue;
8181
+ if (node.tagName === "DAW-TRACK") {
8182
+ addedTrackIds.add(node.trackId);
8183
+ }
8184
+ node.querySelectorAll?.("daw-track").forEach((t) => {
8185
+ addedTrackIds.add(t.trackId);
8186
+ });
8187
+ }
7968
8188
  for (const node of mutation.removedNodes) {
7969
- if (node instanceof HTMLElement) {
7970
- if (node.tagName === "DAW-TRACK") {
7971
- this._onTrackRemoved(node.trackId);
7972
- } else if (node.tagName === "DAW-CLIP") {
7973
- this._onClipRemovedFromDom(node);
7974
- }
7975
- const nestedTracks = node.querySelectorAll?.("daw-track");
7976
- if (nestedTracks) {
7977
- for (const track of nestedTracks) {
7978
- this._onTrackRemoved(track.trackId);
7979
- }
7980
- }
7981
- const nestedClips = node.querySelectorAll?.("daw-clip");
7982
- if (nestedClips) {
7983
- for (const clip of nestedClips) {
7984
- this._onClipRemovedFromDom(clip);
7985
- }
7986
- }
8189
+ if (!(node instanceof HTMLElement)) continue;
8190
+ if (node.tagName === "DAW-TRACK") {
8191
+ removedTracks.set(node.trackId, node);
8192
+ } else if (node.tagName === "DAW-CLIP") {
8193
+ removedClips.add(node);
7987
8194
  }
8195
+ node.querySelectorAll?.("daw-track").forEach((t) => {
8196
+ removedTracks.set(t.trackId, t);
8197
+ });
8198
+ node.querySelectorAll?.("daw-clip").forEach((c) => {
8199
+ removedClips.add(c);
8200
+ });
8201
+ }
8202
+ }
8203
+ let orderMayHaveChanged = addedTrackIds.size > 0;
8204
+ for (const [trackId] of removedTracks) {
8205
+ if (addedTrackIds.has(trackId)) {
8206
+ orderMayHaveChanged = true;
8207
+ continue;
7988
8208
  }
8209
+ this._onTrackRemoved(trackId);
7989
8210
  }
8211
+ for (const clip of removedClips) {
8212
+ if (clip.isConnected) continue;
8213
+ this._onClipRemovedFromDom(clip);
8214
+ }
8215
+ if (orderMayHaveChanged) this._syncEngineOrderToDom();
7990
8216
  });
7991
8217
  this._childObserver.observe(this, { childList: true, subtree: true });
7992
8218
  }
@@ -8005,6 +8231,9 @@ var DawEditorElement = class extends import_lit19.LitElement {
8005
8231
  this._onAnnotationTrackConnected
8006
8232
  );
8007
8233
  this.removeEventListener("daw-annotation-select", this._onAnnotationSelect);
8234
+ this.removeEventListener("daw-track-reorder", this._onTrackReorder);
8235
+ this.removeEventListener("daw-track-reorder-grab", this._onTrackReorderGrab);
8236
+ this._trackReorderDrag.cancel();
8008
8237
  this._childObserver?.disconnect();
8009
8238
  this._childObserver = null;
8010
8239
  this._trackElements.clear();
@@ -8279,7 +8508,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
8279
8508
  let clip;
8280
8509
  if (waveformData) {
8281
8510
  const wdRate = waveformData.sample_rate;
8282
- clip = (0, import_core13.createClip)({
8511
+ clip = (0, import_core12.createClip)({
8283
8512
  audioBuffer,
8284
8513
  waveformData,
8285
8514
  startSample: Math.round(clipDesc.start * wdRate),
@@ -8292,7 +8521,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
8292
8521
  });
8293
8522
  this._peakPipeline.cacheWaveformData(audioBuffer, waveformData);
8294
8523
  } else {
8295
- clip = (0, import_core13.createClipFromSeconds)({
8524
+ clip = (0, import_core12.createClipFromSeconds)({
8296
8525
  audioBuffer,
8297
8526
  startTime: clipDesc.start,
8298
8527
  duration: clipDesc.duration || audioBuffer.duration,
@@ -8371,7 +8600,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
8371
8600
  const noteSpanSeconds = notes.length ? notes.reduce((max, n) => Math.max(max, n.time + n.duration), 0) : 0;
8372
8601
  const sourceDurationSamples = Math.ceil(Math.max(noteSpanSeconds, clipDesc.duration, 1) * sr);
8373
8602
  const requestedDurationSamples = clipDesc.duration > 0 ? Math.round(clipDesc.duration * sr) : sourceDurationSamples;
8374
- const clip = (0, import_core13.createClip)({
8603
+ const clip = (0, import_core12.createClip)({
8375
8604
  startSample: Math.round(clipDesc.start * sr),
8376
8605
  durationSamples: requestedDurationSamples,
8377
8606
  offsetSamples: Math.round(clipDesc.offset * sr),
@@ -8407,7 +8636,8 @@ var DawEditorElement = class extends import_lit19.LitElement {
8407
8636
  _commitTrackChange(trackId, updatedTrack) {
8408
8637
  this._recomputeDuration();
8409
8638
  if (this._engine?.updateTrack) this._engine.updateTrack(trackId, updatedTrack);
8410
- else if (this._engine) this._engine.setTracks([...this._engineTracks.values()]);
8639
+ else if (this._engine)
8640
+ this._engine.setTracks(this._getOrderedTracks().map(([, track]) => track));
8411
8641
  }
8412
8642
  _applyClipUpdate(trackId, clipId, clipEl) {
8413
8643
  const t = this._engineTracks.get(trackId);
@@ -8582,7 +8812,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
8582
8812
  const waveformData = await waveformDataPromise;
8583
8813
  if (waveformData) {
8584
8814
  const wdRate = waveformData.sample_rate;
8585
- const clip2 = (0, import_core13.createClip)({
8815
+ const clip2 = (0, import_core12.createClip)({
8586
8816
  waveformData,
8587
8817
  startSample: Math.round(clipDesc.start * wdRate),
8588
8818
  durationSamples: Math.round((clipDesc.duration || waveformData.duration) * wdRate),
@@ -8608,7 +8838,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
8608
8838
  this._peaksData = new Map(this._peaksData).set(clip2.id, peakData);
8609
8839
  this._raiseZoomFloor(waveformData.scale);
8610
8840
  if (this._tracks.has(trackId)) {
8611
- const previewTrack = (0, import_core13.createTrack)({
8841
+ const previewTrack = (0, import_core12.createTrack)({
8612
8842
  name: descriptor.name,
8613
8843
  clips: [clip2],
8614
8844
  volume: descriptor.volume,
@@ -8685,7 +8915,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
8685
8915
  trackWasRemoved ? "removed" : "disconnected"
8686
8916
  );
8687
8917
  }
8688
- const track = (0, import_core13.createTrack)({
8918
+ const track = (0, import_core12.createTrack)({
8689
8919
  name: descriptor.name,
8690
8920
  clips,
8691
8921
  volume: descriptor.volume,
@@ -8706,7 +8936,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
8706
8936
  this._maybeRegisterSpectrogramClipAudio(trackId, c);
8707
8937
  }
8708
8938
  const engine = await this._ensureEngine();
8709
- engine.setTracks([...this._engineTracks.values()]);
8939
+ engine.setTracks(this._getOrderedTracks().map(([, track2]) => track2));
8710
8940
  this.dispatchEvent(
8711
8941
  new CustomEvent("daw-track-ready", {
8712
8942
  bubbles: true,
@@ -8834,6 +9064,9 @@ var DawEditorElement = class extends import_lit19.LitElement {
8834
9064
  this._reconcileDescriptorsWithEngineTracks(engineState.tracks);
8835
9065
  }
8836
9066
  if (structuralChange) {
9067
+ if (!this._inOrderSync) {
9068
+ this._syncDomToEngineOrder(engineState.tracks);
9069
+ }
8837
9070
  this._effectsManager?.rewireTrackChains();
8838
9071
  const audioTracks = engineState.tracks.filter((t) => {
8839
9072
  const desc = this._tracks.get(t.id);
@@ -8974,6 +9207,34 @@ var DawEditorElement = class extends import_lit19.LitElement {
8974
9207
  console.warn('[dawcore] removeTrack: no track found for id "' + trackId + '"');
8975
9208
  }
8976
9209
  }
9210
+ /**
9211
+ * Move a track to a new position in the vertical order (0-based index among
9212
+ * `<daw-track>` elements). Element-backed tracks move their DOM element —
9213
+ * the MutationObserver syncs the engine (single write path). Element-less
9214
+ * tracks (undo-resurrected) reorder the engine directly.
9215
+ */
9216
+ reorderTrack(trackId, toIndex) {
9217
+ if (!Number.isFinite(toIndex)) {
9218
+ console.warn("[dawcore] reorderTrack: invalid toIndex " + String(toIndex));
9219
+ return;
9220
+ }
9221
+ const el = this._trackElements.get(trackId);
9222
+ if (el) {
9223
+ const els = [...this.querySelectorAll("daw-track")];
9224
+ const from = els.indexOf(el);
9225
+ if (from === -1) return;
9226
+ const clamped = Math.max(0, Math.min(toIndex, els.length - 1));
9227
+ if (from === clamped) return;
9228
+ const anchor = els[clamped];
9229
+ if (clamped > from) anchor.after(el);
9230
+ else anchor.before(el);
9231
+ } else if (this._engineTracks.has(trackId)) {
9232
+ this._engine.reorderTrack(trackId, toIndex);
9233
+ this.requestUpdate();
9234
+ } else {
9235
+ console.warn('[dawcore] reorderTrack: no track found for id "' + trackId + '"');
9236
+ }
9237
+ }
8977
9238
  /**
8978
9239
  * Update reflected attributes on a track. For DOM-element tracks the changes
8979
9240
  * are written to the `<daw-track>` element (which fires `daw-track-update`);
@@ -9478,6 +9739,64 @@ var DawEditorElement = class extends import_lit19.LitElement {
9478
9739
  get _showRuler() {
9479
9740
  return (this._getOrderedTracks().length > 0 || this.scaleMode === "beats" || this.indefinitePlayback || this.fillViewport) && this.timescale;
9480
9741
  }
9742
+ /**
9743
+ * DOM → engine: make the engine's track order match the light-DOM
9744
+ * `<daw-track>` order. Single write path for reorders — editor-initiated
9745
+ * (buttons/drag move the element) and consumer-initiated (insertBefore)
9746
+ * mutations both land here via the MutationObserver. Element-less tracks
9747
+ * (undo-resurrected) keep their engine positions (stable sort).
9748
+ * Write-only-on-change: a no-op when orders already match, so the
9749
+ * engine→DOM direction (statechange handler) converges in one pass.
9750
+ */
9751
+ _syncEngineOrderToDom() {
9752
+ const engine = this._engine;
9753
+ if (!engine) return;
9754
+ const domOrder = [...this.querySelectorAll("daw-track")].map(
9755
+ (el) => el.trackId
9756
+ );
9757
+ const engineIds = engine.getState().tracks.map((t) => t.id);
9758
+ const target = [...engineIds].sort((a, b) => {
9759
+ const ai = domOrder.indexOf(a);
9760
+ const bi = domOrder.indexOf(b);
9761
+ if (ai === -1 || bi === -1) return 0;
9762
+ return ai - bi;
9763
+ });
9764
+ if (target.every((id, i) => id === engineIds[i])) return;
9765
+ this._inOrderSync = true;
9766
+ try {
9767
+ engine.beginTransaction();
9768
+ const current = [...engineIds];
9769
+ for (let i = 0; i < target.length; i++) {
9770
+ if (current[i] === target[i]) continue;
9771
+ engine.reorderTrack(target[i], i);
9772
+ const from = current.indexOf(target[i]);
9773
+ current.splice(from, 1);
9774
+ current.splice(i, 0, target[i]);
9775
+ }
9776
+ engine.commitTransaction();
9777
+ } finally {
9778
+ this._inOrderSync = false;
9779
+ }
9780
+ this.requestUpdate();
9781
+ }
9782
+ /**
9783
+ * Engine → DOM: after an engine-initiated order change (undo/redo), move
9784
+ * `<daw-track>` elements to match engine order. The resulting mutations fire
9785
+ * the observer's _syncEngineOrderToDom, which finds the orders equal and
9786
+ * no-ops — converges in one pass (write-only-on-change).
9787
+ */
9788
+ _syncDomToEngineOrder(tracks) {
9789
+ const els = [...this.querySelectorAll("daw-track")];
9790
+ if (els.length < 2) return;
9791
+ const byId = new Map(els.map((el) => [el.trackId, el]));
9792
+ const desired = tracks.map((t) => byId.get(t.id)).filter((el) => el != null);
9793
+ if (desired.length === 0) return;
9794
+ if (desired.every((el, i) => el === els[i])) return;
9795
+ if (els[0] !== desired[0]) els[0].before(desired[0]);
9796
+ for (let i = 1; i < desired.length; i++) {
9797
+ if (desired[i - 1].nextElementSibling !== desired[i]) desired[i - 1].after(desired[i]);
9798
+ }
9799
+ }
9481
9800
  _getOrderedTracks() {
9482
9801
  const domOrder = [...this.querySelectorAll("daw-track")].map(
9483
9802
  (el) => el.trackId
@@ -9555,7 +9874,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9555
9874
  </div>`
9556
9875
  )}
9557
9876
  ${orderedTracks.map(
9558
- (t) => import_lit19.html`
9877
+ (t, i) => import_lit19.html`
9559
9878
  <daw-track-controls
9560
9879
  style="height: ${t.trackHeight}px;"
9561
9880
  .trackId=${t.trackId}
@@ -9564,6 +9883,9 @@ var DawEditorElement = class extends import_lit19.LitElement {
9564
9883
  .pan=${t.descriptor?.pan ?? 0}
9565
9884
  .muted=${t.descriptor?.muted ?? false}
9566
9885
  .soloed=${t.descriptor?.soloed ?? false}
9886
+ .reorderable=${this.trackReordering}
9887
+ .trackIndex=${i}
9888
+ .trackCount=${orderedTracks.length}
9567
9889
  ></daw-track-controls>
9568
9890
  `
9569
9891
  )}
@@ -9618,7 +9940,7 @@ var DawEditorElement = class extends import_lit19.LitElement {
9618
9940
  width = Math.round(endTick / this.ticksPerPixel) - clipLeft;
9619
9941
  } else {
9620
9942
  clipLeft = Math.floor(clip.startSample / spp);
9621
- width = (0, import_core13.clipPixelWidth)(clip.startSample, clip.durationSamples, spp);
9943
+ width = (0, import_core12.clipPixelWidth)(clip.startSample, clip.durationSamples, spp);
9622
9944
  }
9623
9945
  let clipSegments;
9624
9946
  let segmentChannels;
@@ -9805,6 +10127,9 @@ DawEditorElement.styles = [
9805
10127
  .track-row.selected {
9806
10128
  background: rgba(99, 199, 95, 0.08);
9807
10129
  }
10130
+ .track-row[data-track-drag-source] {
10131
+ background: rgba(99, 199, 95, 0.08);
10132
+ }
9808
10133
  :host([scale-mode='beats']) .track-row {
9809
10134
  background: transparent;
9810
10135
  }
@@ -9930,6 +10255,9 @@ __decorateClass([
9930
10255
  __decorateClass([
9931
10256
  (0, import_decorators16.property)({ type: Boolean, attribute: "fill-viewport" })
9932
10257
  ], DawEditorElement.prototype, "fillViewport", 2);
10258
+ __decorateClass([
10259
+ (0, import_decorators16.property)({ type: Boolean, attribute: "track-reordering" })
10260
+ ], DawEditorElement.prototype, "trackReordering", 2);
9933
10261
  __decorateClass([
9934
10262
  (0, import_decorators16.property)({ attribute: false, noAccessor: true })
9935
10263
  ], DawEditorElement.prototype, "spectrogramConfig", 1);
@@ -10133,7 +10461,7 @@ DawRecordButtonElement = __decorateClass([
10133
10461
  // src/elements/daw-keyboard-shortcuts.ts
10134
10462
  var import_lit22 = require("lit");
10135
10463
  var import_decorators19 = require("lit/decorators.js");
10136
- var import_core14 = require("@waveform-playlist/core");
10464
+ var import_core13 = require("@waveform-playlist/core");
10137
10465
  var DawKeyboardShortcutsElement = class extends import_lit22.LitElement {
10138
10466
  constructor() {
10139
10467
  super(...arguments);
@@ -10158,7 +10486,7 @@ var DawKeyboardShortcutsElement = class extends import_lit22.LitElement {
10158
10486
  const shortcuts = this.shortcuts;
10159
10487
  if (shortcuts.length === 0) return;
10160
10488
  try {
10161
- (0, import_core14.handleKeyboardEvent)(e, shortcuts, true);
10489
+ (0, import_core13.handleKeyboardEvent)(e, shortcuts, true);
10162
10490
  } catch (err) {
10163
10491
  console.warn("[dawcore] Keyboard shortcut failed (key=" + e.key + "): " + String(err));
10164
10492
  const target = this._editor ?? this;
@@ -10348,7 +10676,7 @@ DawKeyboardShortcutsElement = __decorateClass([
10348
10676
  // src/elements/daw-spectrogram.ts
10349
10677
  var import_lit23 = require("lit");
10350
10678
  var import_decorators20 = require("lit/decorators.js");
10351
- var import_core15 = require("@waveform-playlist/core");
10679
+ var import_core14 = require("@waveform-playlist/core");
10352
10680
  var DawSpectrogramElement = class extends import_lit23.LitElement {
10353
10681
  constructor() {
10354
10682
  super(...arguments);
@@ -10413,11 +10741,11 @@ var DawSpectrogramElement = class extends import_lit23.LitElement {
10413
10741
  this._unregisterAllCanvases();
10414
10742
  this._canvases = [];
10415
10743
  if (this.length <= 0) return;
10416
- const chunkCount = Math.ceil(this.length / import_core15.MAX_CANVAS_WIDTH);
10744
+ const chunkCount = Math.ceil(this.length / import_core14.MAX_CANVAS_WIDTH);
10417
10745
  for (let i = 0; i < chunkCount; i++) {
10418
- const widthPx = Math.min(import_core15.MAX_CANVAS_WIDTH, this.length - i * import_core15.MAX_CANVAS_WIDTH);
10746
+ const widthPx = Math.min(import_core14.MAX_CANVAS_WIDTH, this.length - i * import_core14.MAX_CANVAS_WIDTH);
10419
10747
  const canvas = document.createElement("canvas");
10420
- canvas.style.left = i * import_core15.MAX_CANVAS_WIDTH + "px";
10748
+ canvas.style.left = i * import_core14.MAX_CANVAS_WIDTH + "px";
10421
10749
  canvas.style.width = widthPx + "px";
10422
10750
  const dpr = window.devicePixelRatio || 1;
10423
10751
  canvas.width = widthPx * dpr;
@@ -10443,7 +10771,7 @@ var DawSpectrogramElement = class extends import_lit23.LitElement {
10443
10771
  }
10444
10772
  for (let i = 0; i < this._canvases.length; i++) {
10445
10773
  const canvas = this._canvases[i];
10446
- const canvasId = (0, import_core15.buildSpectrogramCanvasId)({
10774
+ const canvasId = (0, import_core14.buildSpectrogramCanvasId)({
10447
10775
  clipId: this.clipId,
10448
10776
  channelIndex: this.channelIndex,
10449
10777
  chunkIndex: i
@@ -10464,7 +10792,7 @@ var DawSpectrogramElement = class extends import_lit23.LitElement {
10464
10792
  trackId: this.trackId,
10465
10793
  channelIndex: this.channelIndex,
10466
10794
  chunkIndex: i,
10467
- globalPixelOffset: this.originX + i * import_core15.MAX_CANVAS_WIDTH,
10795
+ globalPixelOffset: this.originX + i * import_core14.MAX_CANVAS_WIDTH,
10468
10796
  widthPx: parseFloat(canvas.style.width),
10469
10797
  heightPx: this.waveHeight
10470
10798
  });