@dawcore/components 0.0.35 → 0.0.37

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
@@ -2164,9 +2164,9 @@ function isDomClip(desc) {
2164
2164
 
2165
2165
  // src/elements/daw-editor.ts
2166
2166
  import {
2167
- createClip as createClip3,
2167
+ createClip as createClip2,
2168
2168
  createClipFromSeconds,
2169
- createTrack as createTrack2,
2169
+ createTrack,
2170
2170
  clipPixelWidth
2171
2171
  } from "@waveform-playlist/core";
2172
2172
 
@@ -2924,6 +2924,9 @@ var DawTrackControlsElement = class extends LitElement12 {
2924
2924
  this.pan = 0;
2925
2925
  this.muted = false;
2926
2926
  this.soloed = false;
2927
+ this.reorderable = false;
2928
+ this.trackIndex = 0;
2929
+ this.trackCount = 1;
2927
2930
  this._onVolumeInput = (e) => {
2928
2931
  const value = Number(e.target.value);
2929
2932
  if (Number.isFinite(value)) this._dispatchControl("volume", value);
@@ -2948,6 +2951,23 @@ var DawTrackControlsElement = class extends LitElement12 {
2948
2951
  })
2949
2952
  );
2950
2953
  };
2954
+ this._onMoveUp = () => this._dispatchReorder(this.trackIndex - 1);
2955
+ this._onMoveDown = () => this._dispatchReorder(this.trackIndex + 1);
2956
+ this._onGripPointerDown = (e) => {
2957
+ if (!this.trackId) return;
2958
+ e.preventDefault();
2959
+ this.dispatchEvent(
2960
+ new CustomEvent("daw-track-reorder-grab", {
2961
+ bubbles: true,
2962
+ composed: true,
2963
+ detail: {
2964
+ trackId: this.trackId,
2965
+ pointerEvent: e,
2966
+ gripElement: e.currentTarget
2967
+ }
2968
+ })
2969
+ );
2970
+ };
2951
2971
  }
2952
2972
  firstUpdated() {
2953
2973
  requestAnimationFrame(() => {
@@ -2970,12 +2990,30 @@ var DawTrackControlsElement = class extends LitElement12 {
2970
2990
  })
2971
2991
  );
2972
2992
  }
2993
+ _dispatchReorder(toIndex) {
2994
+ if (!this.trackId) return;
2995
+ this.dispatchEvent(
2996
+ new CustomEvent("daw-track-reorder", {
2997
+ bubbles: true,
2998
+ composed: true,
2999
+ detail: { trackId: this.trackId, fromIndex: this.trackIndex, toIndex }
3000
+ })
3001
+ );
3002
+ }
2973
3003
  render() {
2974
3004
  const volPercent = Math.round(this.volume * 100);
2975
3005
  const panPercent = Math.round(Math.abs(this.pan) * 100);
2976
3006
  const panDisplay = this.pan === 0 ? "C" : (this.pan > 0 ? "R" : "L") + panPercent;
2977
3007
  return html9`
2978
3008
  <div class="header">
3009
+ ${this.reorderable ? html9`<button
3010
+ class="grip"
3011
+ title="Drag to reorder track"
3012
+ aria-label="Drag to reorder track"
3013
+ @pointerdown=${this._onGripPointerDown}
3014
+ >
3015
+ ⠿
3016
+ </button>` : ""}
2979
3017
  <span class="name" title=${this.trackName}>${this.trackName || "Untitled"}</span>
2980
3018
  <button class="remove-btn" @click=${this._onRemoveClick} title="Remove track">
2981
3019
  &times;
@@ -2992,6 +3030,24 @@ var DawTrackControlsElement = class extends LitElement12 {
2992
3030
  <button class="btn ${this.soloed ? "active" : ""}" @click=${this._onSoloClick} title="Solo">
2993
3031
  S
2994
3032
  </button>
3033
+ ${this.reorderable ? html9`<button
3034
+ class="btn reorder-up"
3035
+ title="Move track up"
3036
+ aria-label="Move track up"
3037
+ ?disabled=${this.trackIndex <= 0}
3038
+ @click=${this._onMoveUp}
3039
+ >
3040
+ ▲
3041
+ </button>
3042
+ <button
3043
+ class="btn reorder-down"
3044
+ title="Move track down"
3045
+ aria-label="Move track down"
3046
+ ?disabled=${this.trackIndex >= this.trackCount - 1}
3047
+ @click=${this._onMoveDown}
3048
+ >
3049
+ ▼
3050
+ </button>` : ""}
2995
3051
  </div>
2996
3052
  <div class="slider-row vol-row">
2997
3053
  <span class="slider-label">
@@ -3068,6 +3124,20 @@ DawTrackControlsElement.styles = css8`
3068
3124
  opacity: 1;
3069
3125
  color: #d08070;
3070
3126
  }
3127
+ .grip {
3128
+ background: none;
3129
+ border: none;
3130
+ color: var(--daw-controls-text, #c49a6c);
3131
+ cursor: grab;
3132
+ padding: 0 2px;
3133
+ font-size: 12px;
3134
+ line-height: 1;
3135
+ opacity: 0.4;
3136
+ touch-action: none;
3137
+ }
3138
+ .grip:hover {
3139
+ opacity: 1;
3140
+ }
3071
3141
  .buttons {
3072
3142
  display: flex;
3073
3143
  gap: 3px;
@@ -3097,6 +3167,10 @@ DawTrackControlsElement.styles = css8`
3097
3167
  border-color: rgba(208, 128, 112, 0.5);
3098
3168
  color: #d08070;
3099
3169
  }
3170
+ .btn:disabled {
3171
+ opacity: 0.3;
3172
+ cursor: default;
3173
+ }
3100
3174
  .slider-row {
3101
3175
  display: flex;
3102
3176
  align-items: center;
@@ -3193,6 +3267,15 @@ __decorateClass([
3193
3267
  __decorateClass([
3194
3268
  property10({ type: Boolean, attribute: false })
3195
3269
  ], DawTrackControlsElement.prototype, "soloed", 2);
3270
+ __decorateClass([
3271
+ property10({ type: Boolean, attribute: false })
3272
+ ], DawTrackControlsElement.prototype, "reorderable", 2);
3273
+ __decorateClass([
3274
+ property10({ type: Number, attribute: false })
3275
+ ], DawTrackControlsElement.prototype, "trackIndex", 2);
3276
+ __decorateClass([
3277
+ property10({ type: Number, attribute: false })
3278
+ ], DawTrackControlsElement.prototype, "trackCount", 2);
3196
3279
  DawTrackControlsElement = __decorateClass([
3197
3280
  customElement14("daw-track-controls")
3198
3281
  ], DawTrackControlsElement);
@@ -5131,6 +5214,179 @@ var AnnotationDragHandler = class {
5131
5214
  }
5132
5215
  };
5133
5216
 
5217
+ // src/interactions/track-reorder-handler.ts
5218
+ var TrackReorderHandler = class _TrackReorderHandler {
5219
+ constructor(host) {
5220
+ this._trackId = null;
5221
+ this._pointerId = -1;
5222
+ this._startY = 0;
5223
+ this._rows = [];
5224
+ this._lanes = [];
5225
+ // aligned with _rows indices; null = lane not found
5226
+ this._fromIndex = 0;
5227
+ this._targetIndex = 0;
5228
+ this._gripEl = null;
5229
+ this.onGrab = (trackId, e, gripEl) => {
5230
+ if (this._trackId !== null) return;
5231
+ const column = this._host.shadowRoot?.querySelector(".controls-column");
5232
+ if (!column) return;
5233
+ const rows = [...column.querySelectorAll("daw-track-controls")];
5234
+ this._rows = rows.map((el) => {
5235
+ const rect = el.getBoundingClientRect();
5236
+ return {
5237
+ el,
5238
+ top: rect.top,
5239
+ height: rect.height,
5240
+ trackId: el.trackId ?? ""
5241
+ };
5242
+ });
5243
+ this._fromIndex = this._rows.findIndex((r) => r.trackId === trackId);
5244
+ if (this._fromIndex === -1) {
5245
+ this._rows = [];
5246
+ return;
5247
+ }
5248
+ this._trackId = trackId;
5249
+ this._targetIndex = this._fromIndex;
5250
+ this._pointerId = e.pointerId;
5251
+ this._startY = e.clientY;
5252
+ this._gripEl = gripEl;
5253
+ const timeline = this._host.shadowRoot?.querySelector(".timeline");
5254
+ const laneEls = timeline ? [...timeline.querySelectorAll(".track-row")] : [];
5255
+ this._lanes = this._rows.map((r) => {
5256
+ const el = laneEls.find((l) => l.getAttribute("data-track-id") === r.trackId) ?? null;
5257
+ if (!el) return null;
5258
+ const rect = el.getBoundingClientRect();
5259
+ return { el, top: rect.top, height: rect.height, trackId: r.trackId };
5260
+ });
5261
+ const draggedLane = this._lanes[this._fromIndex];
5262
+ if (draggedLane) {
5263
+ draggedLane.el.setAttribute("data-track-drag-source", "");
5264
+ draggedLane.el.style.zIndex = "10";
5265
+ draggedLane.el.style.position = "relative";
5266
+ }
5267
+ if (!_TrackReorderHandler._reducedMotion()) {
5268
+ for (let i = 0; i < this._rows.length; i++) {
5269
+ if (i !== this._fromIndex) this._rows[i].el.style.transition = "transform 150ms ease";
5270
+ const lane = this._lanes[i];
5271
+ if (lane) lane.el.style.transition = "transform 150ms ease";
5272
+ }
5273
+ }
5274
+ try {
5275
+ gripEl.setPointerCapture(e.pointerId);
5276
+ } catch {
5277
+ }
5278
+ gripEl.addEventListener("pointermove", this._onPointerMove);
5279
+ gripEl.addEventListener("pointerup", this._onPointerUp);
5280
+ gripEl.addEventListener("pointercancel", this._onPointerCancel);
5281
+ };
5282
+ this._onPointerMove = (e) => {
5283
+ if (e.pointerId !== this._pointerId || this._trackId === null) return;
5284
+ const dragged = this._rows[this._fromIndex];
5285
+ const dy = e.clientY - this._startY;
5286
+ dragged.el.style.transform = "translateY(" + dy + "px)";
5287
+ dragged.el.style.zIndex = "10";
5288
+ dragged.el.style.position = "relative";
5289
+ let target = this._fromIndex;
5290
+ for (let i = 0; i < this._rows.length; i++) {
5291
+ if (i === this._fromIndex) continue;
5292
+ const mid = this._rows[i].top + this._rows[i].height / 2;
5293
+ if (i < this._fromIndex && e.clientY < mid) {
5294
+ target = i;
5295
+ break;
5296
+ }
5297
+ if (i > this._fromIndex && e.clientY > mid) {
5298
+ target = i;
5299
+ }
5300
+ }
5301
+ this._targetIndex = target;
5302
+ for (let i = 0; i < this._rows.length; i++) {
5303
+ if (i === this._fromIndex) continue;
5304
+ const row = this._rows[i];
5305
+ let shift = 0;
5306
+ if (i > this._fromIndex && i <= target) shift = -dragged.height;
5307
+ else if (i < this._fromIndex && i >= target) shift = dragged.height;
5308
+ row.el.style.transform = shift === 0 ? "" : "translateY(" + shift + "px)";
5309
+ }
5310
+ const draggedLaneInfo = this._lanes[this._fromIndex];
5311
+ for (let i = 0; i < this._lanes.length; i++) {
5312
+ const lane = this._lanes[i];
5313
+ if (!lane || !draggedLaneInfo) continue;
5314
+ if (i === this._fromIndex) {
5315
+ let offset = 0;
5316
+ const targetLane = this._lanes[target];
5317
+ if (targetLane && target > this._fromIndex) {
5318
+ offset = targetLane.top + targetLane.height - (draggedLaneInfo.top + draggedLaneInfo.height);
5319
+ } else if (targetLane && target < this._fromIndex) {
5320
+ offset = targetLane.top - draggedLaneInfo.top;
5321
+ }
5322
+ lane.el.style.transform = offset === 0 ? "" : "translateY(" + offset + "px)";
5323
+ continue;
5324
+ }
5325
+ let laneShift = 0;
5326
+ if (i > this._fromIndex && i <= target) laneShift = -draggedLaneInfo.height;
5327
+ else if (i < this._fromIndex && i >= target) laneShift = draggedLaneInfo.height;
5328
+ lane.el.style.transform = laneShift === 0 ? "" : "translateY(" + laneShift + "px)";
5329
+ }
5330
+ };
5331
+ this._onPointerUp = (e) => {
5332
+ if (e.pointerId !== this._pointerId || this._trackId === null) return;
5333
+ const trackId = this._trackId;
5334
+ const target = this._targetIndex;
5335
+ const from = this._fromIndex;
5336
+ this._cleanup();
5337
+ if (target !== from) {
5338
+ this._host.reorderTrack(trackId, target);
5339
+ }
5340
+ };
5341
+ this._onPointerCancel = (e) => {
5342
+ if (e.pointerId !== this._pointerId) return;
5343
+ this._cleanup();
5344
+ };
5345
+ this._host = host;
5346
+ }
5347
+ static _reducedMotion() {
5348
+ return typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
5349
+ }
5350
+ /** Abort any in-progress drag and reset state. Called by the editor on
5351
+ * disconnect — without this, a drag interrupted by editor removal (with no
5352
+ * pointercancel delivered) would leave the handler wedged and silently
5353
+ * block every future grab. */
5354
+ cancel() {
5355
+ this._cleanup();
5356
+ }
5357
+ _cleanup() {
5358
+ for (const row of this._rows) {
5359
+ row.el.style.transform = "";
5360
+ row.el.style.zIndex = "";
5361
+ row.el.style.position = "";
5362
+ row.el.style.transition = "";
5363
+ }
5364
+ for (const lane of this._lanes) {
5365
+ if (!lane) continue;
5366
+ lane.el.style.transform = "";
5367
+ lane.el.style.transition = "";
5368
+ lane.el.style.zIndex = "";
5369
+ lane.el.style.position = "";
5370
+ lane.el.removeAttribute("data-track-drag-source");
5371
+ }
5372
+ this._lanes = [];
5373
+ const grip = this._gripEl;
5374
+ if (grip) {
5375
+ grip.removeEventListener("pointermove", this._onPointerMove);
5376
+ grip.removeEventListener("pointerup", this._onPointerUp);
5377
+ grip.removeEventListener("pointercancel", this._onPointerCancel);
5378
+ try {
5379
+ grip.releasePointerCapture(this._pointerId);
5380
+ } catch {
5381
+ }
5382
+ }
5383
+ this._gripEl = null;
5384
+ this._trackId = null;
5385
+ this._pointerId = -1;
5386
+ this._rows = [];
5387
+ }
5388
+ };
5389
+
5134
5390
  // src/utils/time-display-format.ts
5135
5391
  var TIME_DISPLAY_FORMATS = [
5136
5392
  "hh:mm:ss.sss",
@@ -5183,7 +5439,6 @@ function parseDisplayTime(value, format) {
5183
5439
  }
5184
5440
 
5185
5441
  // src/interactions/file-loader.ts
5186
- import { createClip, createTrack } from "@waveform-playlist/core";
5187
5442
  async function loadFiles(host, files) {
5188
5443
  if (!files) {
5189
5444
  console.warn("[dawcore] loadFiles called with null/undefined");
@@ -5192,107 +5447,36 @@ async function loadFiles(host, files) {
5192
5447
  const fileArray = Array.from(files);
5193
5448
  const loaded = [];
5194
5449
  const failed = [];
5450
+ const dispatchLoadError = (file, error) => {
5451
+ failed.push({ file, error });
5452
+ if (host.isConnected) {
5453
+ host.dispatchEvent(
5454
+ new CustomEvent("daw-files-load-error", {
5455
+ bubbles: true,
5456
+ composed: true,
5457
+ detail: { file, error }
5458
+ })
5459
+ );
5460
+ }
5461
+ };
5195
5462
  for (const file of fileArray) {
5196
5463
  if (file.type && !file.type.startsWith("audio/")) {
5197
5464
  const error = new Error("Non-audio MIME type: " + file.type);
5198
- failed.push({ file, error });
5199
5465
  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
- }
5466
+ dispatchLoadError(file, error);
5209
5467
  continue;
5210
5468
  }
5211
5469
  const blobUrl = URL.createObjectURL(file);
5470
+ const name = file.name.replace(/\.\w+$/, "");
5212
5471
  try {
5213
- const audioBuffer = await host._fetchAndDecode(blobUrl);
5214
- URL.revokeObjectURL(blobUrl);
5215
- host._audioCache.delete(blobUrl);
5216
- host._resolvedSampleRate = audioBuffer.sampleRate;
5217
- const name = file.name.replace(/\.\w+$/, "");
5218
- const clip = createClip({
5219
- audioBuffer,
5220
- startSample: 0,
5221
- durationSamples: audioBuffer.length,
5222
- offsetSamples: 0,
5223
- gain: 1,
5224
- name,
5225
- sampleRate: audioBuffer.sampleRate,
5226
- sourceDurationSamples: audioBuffer.length
5227
- });
5228
- host._clipBuffers = new Map(host._clipBuffers).set(clip.id, audioBuffer);
5229
- host._clipOffsets = new Map(host._clipOffsets).set(clip.id, {
5230
- offsetSamples: clip.offsetSamples,
5231
- durationSamples: clip.durationSamples
5232
- });
5233
- const peakData = await host._peakPipeline.generatePeaks(
5234
- audioBuffer,
5235
- host.renderSamplesPerPixel,
5236
- host.mono,
5237
- clip.offsetSamples,
5238
- clip.durationSamples
5239
- );
5240
- host._peaksData = new Map(host._peaksData).set(clip.id, peakData);
5241
- const trackId = crypto.randomUUID();
5242
- const track = createTrack({ name, clips: [clip] });
5243
- track.id = trackId;
5244
- host._tracks = new Map(host._tracks).set(trackId, {
5245
- name,
5246
- src: "",
5247
- volume: 1,
5248
- pan: 0,
5249
- muted: false,
5250
- soloed: false,
5251
- renderMode: "waveform",
5252
- clips: [
5253
- {
5254
- kind: "drop",
5255
- src: "",
5256
- peaksSrc: "",
5257
- start: 0,
5258
- duration: audioBuffer.duration,
5259
- offset: 0,
5260
- gain: 1,
5261
- name,
5262
- fadeIn: 0,
5263
- fadeOut: 0,
5264
- fadeType: "linear",
5265
- midiNotes: null,
5266
- midiChannel: null,
5267
- midiProgram: null
5268
- }
5269
- ]
5270
- });
5271
- host._engineTracks = new Map(host._engineTracks).set(trackId, track);
5272
- host._recomputeDuration();
5273
- const engine = await host._ensureEngine();
5274
- engine.setTracks([...host._engineTracks.values()]);
5275
- loaded.push(trackId);
5276
- host.dispatchEvent(
5277
- new CustomEvent("daw-track-ready", {
5278
- bubbles: true,
5279
- composed: true,
5280
- detail: { trackId }
5281
- })
5282
- );
5472
+ const trackEl = await host.addTrack({ name, clips: [{ src: blobUrl, name }] });
5473
+ loaded.push(trackEl.trackId);
5283
5474
  } catch (err) {
5284
- URL.revokeObjectURL(blobUrl);
5285
5475
  console.warn("[dawcore] Failed to load file: " + file.name + " \u2014 " + String(err));
5286
- failed.push({ file, error: err });
5287
- if (host.isConnected) {
5288
- host.dispatchEvent(
5289
- new CustomEvent("daw-files-load-error", {
5290
- bubbles: true,
5291
- composed: true,
5292
- detail: { file, error: err }
5293
- })
5294
- );
5295
- }
5476
+ dispatchLoadError(file, err);
5477
+ } finally {
5478
+ URL.revokeObjectURL(blobUrl);
5479
+ host._audioCache.delete(blobUrl);
5296
5480
  }
5297
5481
  }
5298
5482
  return { loaded, failed };
@@ -5401,7 +5585,7 @@ function stringifyReason(reason) {
5401
5585
  }
5402
5586
 
5403
5587
  // src/interactions/recording-clip.ts
5404
- import { carveClipRange, createClip as createClip2 } from "@waveform-playlist/core";
5588
+ import { carveClipRange, createClip } from "@waveform-playlist/core";
5405
5589
  function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamples = 0, clipName) {
5406
5590
  let trimmedBuf = buf;
5407
5591
  if (offsetSamples > 0 && offsetSamples < buf.length) {
@@ -5416,7 +5600,7 @@ function addRecordedClip(host, trackId, buf, startSample, durSamples, offsetSamp
5416
5600
  }
5417
5601
  trimmedBuf = trimmed;
5418
5602
  }
5419
- const clip = createClip2({
5603
+ const clip = createClip({
5420
5604
  audioBuffer: trimmedBuf,
5421
5605
  startSample,
5422
5606
  durationSamples: durSamples,
@@ -7078,6 +7262,7 @@ var DawEditorElement = class extends LitElement14 {
7078
7262
  this.interactiveClips = false;
7079
7263
  this.indefinitePlayback = false;
7080
7264
  this.fillViewport = false;
7265
+ this.trackReordering = false;
7081
7266
  this._spectrogramConfig = null;
7082
7267
  this._spectrogramColorMap = null;
7083
7268
  this.scaleMode = "temporal";
@@ -7161,6 +7346,7 @@ var DawEditorElement = class extends LitElement14 {
7161
7346
  this._spectrogramController = null;
7162
7347
  this._clipPointer = new ClipPointerHandler(this);
7163
7348
  this._annotationDrag = new AnnotationDragHandler(this);
7349
+ this._trackReorderDrag = new TrackReorderHandler(this);
7164
7350
  this._pointer = new PointerHandler(this);
7165
7351
  this._viewport = (() => {
7166
7352
  const v = new ViewportController(this);
@@ -7204,6 +7390,10 @@ var DawEditorElement = class extends LitElement14 {
7204
7390
  console.warn("[dawcore] Invalid daw-track-connected event detail: " + String(e.detail));
7205
7391
  return;
7206
7392
  }
7393
+ if (this._tracks.has(trackId)) {
7394
+ this._trackElements.set(trackId, trackEl);
7395
+ return;
7396
+ }
7207
7397
  const descriptor = this._readTrackDescriptor(trackEl);
7208
7398
  this._tracks = new Map(this._tracks).set(trackId, descriptor);
7209
7399
  this._trackElements.set(trackId, trackEl);
@@ -7313,6 +7503,10 @@ var DawEditorElement = class extends LitElement14 {
7313
7503
  }
7314
7504
  return;
7315
7505
  }
7506
+ const loadedDesc = this._tracks.get(trackId);
7507
+ if (loadedDesc && loadedDesc.clips.some((c) => isDomClip(c) && c.clipId === clipEl.clipId)) {
7508
+ return;
7509
+ }
7316
7510
  const clipDesc = {
7317
7511
  kind: "dom",
7318
7512
  clipId: clipEl.clipId,
@@ -7377,6 +7571,13 @@ var DawEditorElement = class extends LitElement14 {
7377
7571
  );
7378
7572
  }
7379
7573
  };
7574
+ this._onTrackReorder = (e) => {
7575
+ this.reorderTrack(e.detail.trackId, e.detail.toIndex);
7576
+ };
7577
+ this._onTrackReorderGrab = (e) => {
7578
+ if (!this.trackReordering) return;
7579
+ this._trackReorderDrag.onGrab(e.detail.trackId, e.detail.pointerEvent, e.detail.gripElement);
7580
+ };
7380
7581
  // --- Recording ---
7381
7582
  this.recordingStream = null;
7382
7583
  /** Set in togglePauseRecording when Transport is paused alongside the
@@ -7390,6 +7591,11 @@ var DawEditorElement = class extends LitElement14 {
7390
7591
  }
7391
7592
  return time * this.effectiveSampleRate / this.samplesPerPixel;
7392
7593
  };
7594
+ /** Guards the statechange handler's engine→DOM sync (Task: reorder #612)
7595
+ * while the observer is pushing DOM order INTO the engine — the intermediate
7596
+ * statechange emissions during the transaction would otherwise bounce
7597
+ * half-applied orders back into the DOM. */
7598
+ this._inOrderSync = false;
7393
7599
  }
7394
7600
  get samplesPerPixel() {
7395
7601
  return this._samplesPerPixel;
@@ -7911,30 +8117,50 @@ var DawEditorElement = class extends LitElement14 {
7911
8117
  this._onAnnotationTrackConnected
7912
8118
  );
7913
8119
  this.addEventListener("daw-annotation-select", this._onAnnotationSelect);
8120
+ this.addEventListener("daw-track-reorder", this._onTrackReorder);
8121
+ this.addEventListener("daw-track-reorder-grab", this._onTrackReorderGrab);
7914
8122
  this._childObserver = new MutationObserver((mutations) => {
8123
+ const removedTracks = /* @__PURE__ */ new Map();
8124
+ const removedClips = /* @__PURE__ */ new Set();
8125
+ const addedTrackIds = /* @__PURE__ */ new Set();
7915
8126
  for (const mutation of mutations) {
8127
+ for (const node of mutation.addedNodes) {
8128
+ if (!(node instanceof HTMLElement)) continue;
8129
+ if (node.tagName === "DAW-TRACK") {
8130
+ addedTrackIds.add(node.trackId);
8131
+ }
8132
+ node.querySelectorAll?.("daw-track").forEach((t) => {
8133
+ addedTrackIds.add(t.trackId);
8134
+ });
8135
+ }
7916
8136
  for (const node of mutation.removedNodes) {
7917
- if (node instanceof HTMLElement) {
7918
- if (node.tagName === "DAW-TRACK") {
7919
- this._onTrackRemoved(node.trackId);
7920
- } else if (node.tagName === "DAW-CLIP") {
7921
- this._onClipRemovedFromDom(node);
7922
- }
7923
- const nestedTracks = node.querySelectorAll?.("daw-track");
7924
- if (nestedTracks) {
7925
- for (const track of nestedTracks) {
7926
- this._onTrackRemoved(track.trackId);
7927
- }
7928
- }
7929
- const nestedClips = node.querySelectorAll?.("daw-clip");
7930
- if (nestedClips) {
7931
- for (const clip of nestedClips) {
7932
- this._onClipRemovedFromDom(clip);
7933
- }
7934
- }
8137
+ if (!(node instanceof HTMLElement)) continue;
8138
+ if (node.tagName === "DAW-TRACK") {
8139
+ removedTracks.set(node.trackId, node);
8140
+ } else if (node.tagName === "DAW-CLIP") {
8141
+ removedClips.add(node);
7935
8142
  }
8143
+ node.querySelectorAll?.("daw-track").forEach((t) => {
8144
+ removedTracks.set(t.trackId, t);
8145
+ });
8146
+ node.querySelectorAll?.("daw-clip").forEach((c) => {
8147
+ removedClips.add(c);
8148
+ });
7936
8149
  }
7937
8150
  }
8151
+ let orderMayHaveChanged = addedTrackIds.size > 0;
8152
+ for (const [trackId] of removedTracks) {
8153
+ if (addedTrackIds.has(trackId)) {
8154
+ orderMayHaveChanged = true;
8155
+ continue;
8156
+ }
8157
+ this._onTrackRemoved(trackId);
8158
+ }
8159
+ for (const clip of removedClips) {
8160
+ if (clip.isConnected) continue;
8161
+ this._onClipRemovedFromDom(clip);
8162
+ }
8163
+ if (orderMayHaveChanged) this._syncEngineOrderToDom();
7938
8164
  });
7939
8165
  this._childObserver.observe(this, { childList: true, subtree: true });
7940
8166
  }
@@ -7953,6 +8179,9 @@ var DawEditorElement = class extends LitElement14 {
7953
8179
  this._onAnnotationTrackConnected
7954
8180
  );
7955
8181
  this.removeEventListener("daw-annotation-select", this._onAnnotationSelect);
8182
+ this.removeEventListener("daw-track-reorder", this._onTrackReorder);
8183
+ this.removeEventListener("daw-track-reorder-grab", this._onTrackReorderGrab);
8184
+ this._trackReorderDrag.cancel();
7956
8185
  this._childObserver?.disconnect();
7957
8186
  this._childObserver = null;
7958
8187
  this._trackElements.clear();
@@ -8227,7 +8456,7 @@ var DawEditorElement = class extends LitElement14 {
8227
8456
  let clip;
8228
8457
  if (waveformData) {
8229
8458
  const wdRate = waveformData.sample_rate;
8230
- clip = createClip3({
8459
+ clip = createClip2({
8231
8460
  audioBuffer,
8232
8461
  waveformData,
8233
8462
  startSample: Math.round(clipDesc.start * wdRate),
@@ -8319,7 +8548,7 @@ var DawEditorElement = class extends LitElement14 {
8319
8548
  const noteSpanSeconds = notes.length ? notes.reduce((max, n) => Math.max(max, n.time + n.duration), 0) : 0;
8320
8549
  const sourceDurationSamples = Math.ceil(Math.max(noteSpanSeconds, clipDesc.duration, 1) * sr);
8321
8550
  const requestedDurationSamples = clipDesc.duration > 0 ? Math.round(clipDesc.duration * sr) : sourceDurationSamples;
8322
- const clip = createClip3({
8551
+ const clip = createClip2({
8323
8552
  startSample: Math.round(clipDesc.start * sr),
8324
8553
  durationSamples: requestedDurationSamples,
8325
8554
  offsetSamples: Math.round(clipDesc.offset * sr),
@@ -8355,7 +8584,8 @@ var DawEditorElement = class extends LitElement14 {
8355
8584
  _commitTrackChange(trackId, updatedTrack) {
8356
8585
  this._recomputeDuration();
8357
8586
  if (this._engine?.updateTrack) this._engine.updateTrack(trackId, updatedTrack);
8358
- else if (this._engine) this._engine.setTracks([...this._engineTracks.values()]);
8587
+ else if (this._engine)
8588
+ this._engine.setTracks(this._getOrderedTracks().map(([, track]) => track));
8359
8589
  }
8360
8590
  _applyClipUpdate(trackId, clipId, clipEl) {
8361
8591
  const t = this._engineTracks.get(trackId);
@@ -8530,7 +8760,7 @@ var DawEditorElement = class extends LitElement14 {
8530
8760
  const waveformData = await waveformDataPromise;
8531
8761
  if (waveformData) {
8532
8762
  const wdRate = waveformData.sample_rate;
8533
- const clip2 = createClip3({
8763
+ const clip2 = createClip2({
8534
8764
  waveformData,
8535
8765
  startSample: Math.round(clipDesc.start * wdRate),
8536
8766
  durationSamples: Math.round((clipDesc.duration || waveformData.duration) * wdRate),
@@ -8556,7 +8786,7 @@ var DawEditorElement = class extends LitElement14 {
8556
8786
  this._peaksData = new Map(this._peaksData).set(clip2.id, peakData);
8557
8787
  this._raiseZoomFloor(waveformData.scale);
8558
8788
  if (this._tracks.has(trackId)) {
8559
- const previewTrack = createTrack2({
8789
+ const previewTrack = createTrack({
8560
8790
  name: descriptor.name,
8561
8791
  clips: [clip2],
8562
8792
  volume: descriptor.volume,
@@ -8633,7 +8863,7 @@ var DawEditorElement = class extends LitElement14 {
8633
8863
  trackWasRemoved ? "removed" : "disconnected"
8634
8864
  );
8635
8865
  }
8636
- const track = createTrack2({
8866
+ const track = createTrack({
8637
8867
  name: descriptor.name,
8638
8868
  clips,
8639
8869
  volume: descriptor.volume,
@@ -8654,7 +8884,7 @@ var DawEditorElement = class extends LitElement14 {
8654
8884
  this._maybeRegisterSpectrogramClipAudio(trackId, c);
8655
8885
  }
8656
8886
  const engine = await this._ensureEngine();
8657
- engine.setTracks([...this._engineTracks.values()]);
8887
+ engine.setTracks(this._getOrderedTracks().map(([, track2]) => track2));
8658
8888
  this.dispatchEvent(
8659
8889
  new CustomEvent("daw-track-ready", {
8660
8890
  bubbles: true,
@@ -8782,6 +9012,9 @@ var DawEditorElement = class extends LitElement14 {
8782
9012
  this._reconcileDescriptorsWithEngineTracks(engineState.tracks);
8783
9013
  }
8784
9014
  if (structuralChange) {
9015
+ if (!this._inOrderSync) {
9016
+ this._syncDomToEngineOrder(engineState.tracks);
9017
+ }
8785
9018
  this._effectsManager?.rewireTrackChains();
8786
9019
  const audioTracks = engineState.tracks.filter((t) => {
8787
9020
  const desc = this._tracks.get(t.id);
@@ -8922,6 +9155,34 @@ var DawEditorElement = class extends LitElement14 {
8922
9155
  console.warn('[dawcore] removeTrack: no track found for id "' + trackId + '"');
8923
9156
  }
8924
9157
  }
9158
+ /**
9159
+ * Move a track to a new position in the vertical order (0-based index among
9160
+ * `<daw-track>` elements). Element-backed tracks move their DOM element —
9161
+ * the MutationObserver syncs the engine (single write path). Element-less
9162
+ * tracks (undo-resurrected) reorder the engine directly.
9163
+ */
9164
+ reorderTrack(trackId, toIndex) {
9165
+ if (!Number.isFinite(toIndex)) {
9166
+ console.warn("[dawcore] reorderTrack: invalid toIndex " + String(toIndex));
9167
+ return;
9168
+ }
9169
+ const el = this._trackElements.get(trackId);
9170
+ if (el) {
9171
+ const els = [...this.querySelectorAll("daw-track")];
9172
+ const from = els.indexOf(el);
9173
+ if (from === -1) return;
9174
+ const clamped = Math.max(0, Math.min(toIndex, els.length - 1));
9175
+ if (from === clamped) return;
9176
+ const anchor = els[clamped];
9177
+ if (clamped > from) anchor.after(el);
9178
+ else anchor.before(el);
9179
+ } else if (this._engineTracks.has(trackId)) {
9180
+ this._engine.reorderTrack(trackId, toIndex);
9181
+ this.requestUpdate();
9182
+ } else {
9183
+ console.warn('[dawcore] reorderTrack: no track found for id "' + trackId + '"');
9184
+ }
9185
+ }
8925
9186
  /**
8926
9187
  * Update reflected attributes on a track. For DOM-element tracks the changes
8927
9188
  * are written to the `<daw-track>` element (which fires `daw-track-update`);
@@ -9426,6 +9687,69 @@ var DawEditorElement = class extends LitElement14 {
9426
9687
  get _showRuler() {
9427
9688
  return (this._getOrderedTracks().length > 0 || this.scaleMode === "beats" || this.indefinitePlayback || this.fillViewport) && this.timescale;
9428
9689
  }
9690
+ /**
9691
+ * DOM → engine: make the engine's track order match the light-DOM
9692
+ * `<daw-track>` order. Single write path for reorders — editor-initiated
9693
+ * (buttons/drag move the element) and consumer-initiated (insertBefore)
9694
+ * mutations both land here via the MutationObserver. Element-less tracks
9695
+ * (undo-resurrected) keep their engine positions (stable sort).
9696
+ * Write-only-on-change: a no-op when orders already match, so the
9697
+ * engine→DOM direction (statechange handler) converges in one pass.
9698
+ */
9699
+ _syncEngineOrderToDom() {
9700
+ const engine = this._engine;
9701
+ if (!engine) return;
9702
+ const domOrder = [...this.querySelectorAll("daw-track")].map(
9703
+ (el) => el.trackId
9704
+ );
9705
+ const engineIds = engine.getState().tracks.map((t) => t.id);
9706
+ const target = [...engineIds].sort((a, b) => {
9707
+ const ai = domOrder.indexOf(a);
9708
+ const bi = domOrder.indexOf(b);
9709
+ if (ai === -1 || bi === -1) return 0;
9710
+ return ai - bi;
9711
+ });
9712
+ if (target.every((id, i) => id === engineIds[i])) return;
9713
+ this._inOrderSync = true;
9714
+ try {
9715
+ engine.beginTransaction();
9716
+ const current = [...engineIds];
9717
+ for (let i = 0; i < target.length; i++) {
9718
+ if (current[i] === target[i]) continue;
9719
+ engine.reorderTrack(target[i], i);
9720
+ const from = current.indexOf(target[i]);
9721
+ current.splice(from, 1);
9722
+ current.splice(i, 0, target[i]);
9723
+ }
9724
+ engine.commitTransaction();
9725
+ } finally {
9726
+ this._inOrderSync = false;
9727
+ }
9728
+ this.requestUpdate();
9729
+ }
9730
+ /**
9731
+ * Engine → DOM: after an engine-initiated order change (undo/redo), move
9732
+ * `<daw-track>` elements to match engine order. The resulting mutations fire
9733
+ * the observer's _syncEngineOrderToDom, which finds the orders equal and
9734
+ * no-ops — converges in one pass (write-only-on-change).
9735
+ */
9736
+ _syncDomToEngineOrder(tracks) {
9737
+ const els = [...this.querySelectorAll("daw-track")];
9738
+ if (els.length < 2) return;
9739
+ const byId = new Map(els.map((el) => [el.trackId, el]));
9740
+ const desired = tracks.map((t) => byId.get(t.id)).filter((el) => el != null);
9741
+ if (desired.length < 2) return;
9742
+ const desiredSet = new Set(desired);
9743
+ const slots = els.filter((el) => desiredSet.has(el));
9744
+ if (desired.every((el, i) => el === slots[i])) return;
9745
+ for (let i = 0; i < desired.length; i++) {
9746
+ if (slots[i] === desired[i]) continue;
9747
+ slots[i].before(desired[i]);
9748
+ const from = slots.indexOf(desired[i]);
9749
+ slots.splice(from, 1);
9750
+ slots.splice(i, 0, desired[i]);
9751
+ }
9752
+ }
9429
9753
  _getOrderedTracks() {
9430
9754
  const domOrder = [...this.querySelectorAll("daw-track")].map(
9431
9755
  (el) => el.trackId
@@ -9503,7 +9827,7 @@ var DawEditorElement = class extends LitElement14 {
9503
9827
  </div>`
9504
9828
  )}
9505
9829
  ${orderedTracks.map(
9506
- (t) => html12`
9830
+ (t, i) => html12`
9507
9831
  <daw-track-controls
9508
9832
  style="height: ${t.trackHeight}px;"
9509
9833
  .trackId=${t.trackId}
@@ -9512,6 +9836,9 @@ var DawEditorElement = class extends LitElement14 {
9512
9836
  .pan=${t.descriptor?.pan ?? 0}
9513
9837
  .muted=${t.descriptor?.muted ?? false}
9514
9838
  .soloed=${t.descriptor?.soloed ?? false}
9839
+ .reorderable=${this.trackReordering}
9840
+ .trackIndex=${i}
9841
+ .trackCount=${orderedTracks.length}
9515
9842
  ></daw-track-controls>
9516
9843
  `
9517
9844
  )}
@@ -9753,6 +10080,9 @@ DawEditorElement.styles = [
9753
10080
  .track-row.selected {
9754
10081
  background: rgba(99, 199, 95, 0.08);
9755
10082
  }
10083
+ .track-row[data-track-drag-source] {
10084
+ background: rgba(99, 199, 95, 0.08);
10085
+ }
9756
10086
  :host([scale-mode='beats']) .track-row {
9757
10087
  background: transparent;
9758
10088
  }
@@ -9878,6 +10208,9 @@ __decorateClass([
9878
10208
  __decorateClass([
9879
10209
  property12({ type: Boolean, attribute: "fill-viewport" })
9880
10210
  ], DawEditorElement.prototype, "fillViewport", 2);
10211
+ __decorateClass([
10212
+ property12({ type: Boolean, attribute: "track-reordering" })
10213
+ ], DawEditorElement.prototype, "trackReordering", 2);
9881
10214
  __decorateClass([
9882
10215
  property12({ attribute: false, noAccessor: true })
9883
10216
  ], DawEditorElement.prototype, "spectrogramConfig", 1);