@hyperframes/studio 0.9.41 → 0.9.42

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.
Files changed (54) hide show
  1. package/dist/assets/{codec-B_mpbc4w.js → codec-CKqLGYc6.js} +1 -1
  2. package/dist/assets/{hyperframes-player-Dvi3I_mv.js → hyperframes-player-DoEYqOIa.js} +1 -1
  3. package/dist/assets/{index-B5ExwsOp.js → index-DLyQ91Ek.js} +160 -160
  4. package/dist/assets/{index-BrFm9Y5k.js → index-s9iqoWnr.js} +1 -1
  5. package/dist/assets/{pausedVideoDecoder-MHQ57yZ6.js → pausedVideoDecoder-B-ReRg6i.js} +1 -1
  6. package/dist/index.d.ts +9 -1
  7. package/dist/index.html +1 -1
  8. package/dist/index.js +1057 -721
  9. package/package.json +10 -10
  10. package/src/components/editor/LayersPanel.opaque.test.ts +176 -0
  11. package/src/components/editor/LayersPanel.tsx +41 -10
  12. package/src/components/editor/domEditInlineText.ts +1 -16
  13. package/src/components/editor/domEditingTypes.ts +7 -1
  14. package/src/components/editor/gestureUndoRevert.ts +18 -1
  15. package/src/components/editor/inlineTextStyleRange.fill.test.ts +129 -0
  16. package/src/components/editor/inlineTextStyleRange.test.ts +0 -82
  17. package/src/components/editor/layerKind.ts +2 -19
  18. package/src/components/editor/layersPanelSort.ts +2 -2
  19. package/src/components/editor/manualEdits.ts +1 -0
  20. package/src/components/editor/manualEditsSnapshot.ts +10 -0
  21. package/src/components/editor/manualOffsetDrag.test.ts +1 -1
  22. package/src/components/editor/manualOffsetDrag.ts +7 -1
  23. package/src/components/editor/marqueeCommit.ts +47 -4
  24. package/src/components/editor/plainTranslate.ts +35 -16
  25. package/src/components/editor/previewDrafts.test.ts +263 -0
  26. package/src/components/editor/previewDrafts.ts +73 -0
  27. package/src/components/editor/previewLayers.test.ts +308 -0
  28. package/src/components/editor/previewLayers.ts +164 -0
  29. package/src/components/editor/previewOverlayRects.ts +27 -0
  30. package/src/components/editor/previewPointerTargets.test.ts +68 -1
  31. package/src/components/editor/previewSelection.ts +55 -11
  32. package/src/components/editor/resizeDraft.ts +38 -0
  33. package/src/components/editor/useDomEditOverlayGestures.ts +2 -2
  34. package/src/components/editor/useLayerDrag.ts +1 -1
  35. package/src/components/nle/NLEPreview.slowBoot.test.ts +0 -1
  36. package/src/hooks/domEditDeleteMembers.test.ts +7 -0
  37. package/src/hooks/domSelectionTimelineMirror.ts +3 -1
  38. package/src/hooks/timelineTimingSync.ts +4 -1
  39. package/src/hooks/useDomSelection.ts +2 -0
  40. package/src/hooks/useEditorSave.test.tsx +22 -1
  41. package/src/hooks/useEditorSave.ts +3 -1
  42. package/src/hooks/usePreviewInteraction.ts +4 -1
  43. package/src/hooks/useProjectFileWriter.ts +7 -3
  44. package/src/hooks/useTimelineSelectionPreviewSync.test.tsx +30 -0
  45. package/src/hooks/useTimelineSelectionPreviewSync.ts +7 -2
  46. package/src/player/lib/layerOrdering.ts +2 -11
  47. package/src/player/lib/previewElements.ts +31 -0
  48. package/src/test-setup.ts +2 -0
  49. package/src/utils/gsapSoftReload.ts +1 -1
  50. package/src/utils/studioFileHistory.ts +1 -1
  51. package/src/utils/studioHelpers.ts +27 -4
  52. package/src/utils/studioSaveDiagnostics.test.ts +34 -0
  53. package/src/utils/studioSaveDiagnostics.ts +35 -6
  54. package/src/utils/timelineCompositionInsert.ts +3 -1
package/dist/index.js CHANGED
@@ -2863,21 +2863,12 @@ function getTimelinePlayheadTransform(time, pixelsPerSecond, contentOrigin, atRe
2863
2863
  }
2864
2864
 
2865
2865
  // src/player/lib/layerOrdering.ts
2866
+ import { elementZIndex } from "@hyperframes/core/runtime/editing-port";
2866
2867
  function getElementZIndex(element) {
2867
2868
  try {
2868
2869
  const prior = readLayerRevealPriorZ(element);
2869
2870
  if (prior != null) return prior;
2870
- const inline = element.style?.zIndex;
2871
- if (inline && inline !== "auto") {
2872
- const parsed2 = parseInt(inline, 10);
2873
- if (Number.isFinite(parsed2)) return parsed2;
2874
- }
2875
- const win = element.ownerDocument?.defaultView;
2876
- if (!win) return 0;
2877
- const value = win.getComputedStyle(element).zIndex;
2878
- if (value === "auto" || value === "") return 0;
2879
- const parsed = parseInt(value, 10);
2880
- return Number.isFinite(parsed) ? parsed : 0;
2871
+ return elementZIndex(element);
2881
2872
  } catch {
2882
2873
  return 0;
2883
2874
  }
@@ -9831,11 +9822,13 @@ var STUDIO_SAVE_ATTEMPT_PROPERTY = "__studioSaveAttempt";
9831
9822
  var StudioSaveHttpError = class extends Error {
9832
9823
  statusCode;
9833
9824
  alreadyToasted;
9825
+ heldFile;
9834
9826
  constructor(message, statusCode, options = {}) {
9835
9827
  super(message);
9836
9828
  this.name = "StudioSaveHttpError";
9837
9829
  this.statusCode = statusCode;
9838
9830
  this.alreadyToasted = options.alreadyToasted ?? false;
9831
+ this.heldFile = options.heldFile ?? false;
9839
9832
  }
9840
9833
  };
9841
9834
  var StudioSaveNetworkError = class extends Error {
@@ -9956,6 +9949,20 @@ function trackStudioSaveFailure(input) {
9956
9949
  function trackStudioEditBlocked(input) {
9957
9950
  trackStudioEvent("edit_blocked", buildStudioSaveFailureProperties(input));
9958
9951
  }
9952
+ var HELD_FILE_WORDS = {
9953
+ busy: (file) => `${file} is open in another program. Close it there, then try again.`,
9954
+ permission: (file) => `${file} can't be changed: it is read-only or protected. Check its permissions, then try again.`
9955
+ };
9956
+ function heldFileMessage(body, path) {
9957
+ if (!path) return null;
9958
+ try {
9959
+ const why = JSON.parse(body).why;
9960
+ if (why !== "busy" && why !== "permission") return null;
9961
+ return HELD_FILE_WORDS[why](path.split(/[\\/]/).pop() ?? path);
9962
+ } catch {
9963
+ return null;
9964
+ }
9965
+ }
9959
9966
  async function createStudioSaveHttpError(response, fallbackMessage, options = {}) {
9960
9967
  let body = "";
9961
9968
  try {
@@ -9964,9 +9971,11 @@ async function createStudioSaveHttpError(response, fallbackMessage, options = {}
9964
9971
  body = "";
9965
9972
  }
9966
9973
  const detail = body.trim().slice(0, 300);
9967
- const message = detail ? `${fallbackMessage} (${response.status}): ${detail}` : `${fallbackMessage} (${response.status})`;
9968
- return new StudioSaveHttpError(message, response.status, options);
9974
+ const held = heldFileMessage(body, options.path);
9975
+ const message = held ?? (detail ? `${fallbackMessage} (${response.status}): ${detail}` : `${fallbackMessage} (${response.status})`);
9976
+ return new StudioSaveHttpError(message, response.status, { ...options, heldFile: held !== null });
9969
9977
  }
9978
+ var heldFileWords = (error) => error instanceof StudioSaveHttpError && error.heldFile ? error.message : null;
9970
9979
  async function retryStudioSave(operation, options = {}) {
9971
9980
  const retries = options.retries ?? 3;
9972
9981
  const baseDelayMs = options.baseDelayMs ?? 500;
@@ -17280,20 +17289,20 @@ function applyPatchByTarget(html2, target, op) {
17280
17289
  // src/utils/studioFileMutationCoordinator.ts
17281
17290
  var mutationQueues = /* @__PURE__ */ new WeakMap();
17282
17291
  function serializeStudioFileMutation(writer, targetPath, task) {
17283
- let queues = mutationQueues.get(writer);
17284
- if (!queues) {
17285
- queues = /* @__PURE__ */ new Map();
17286
- mutationQueues.set(writer, queues);
17292
+ let queues2 = mutationQueues.get(writer);
17293
+ if (!queues2) {
17294
+ queues2 = /* @__PURE__ */ new Map();
17295
+ mutationQueues.set(writer, queues2);
17287
17296
  }
17288
- const prior = queues.get(targetPath) ?? Promise.resolve();
17297
+ const prior = queues2.get(targetPath) ?? Promise.resolve();
17289
17298
  const next = prior.then(task, task);
17290
- queues.set(targetPath, next);
17299
+ queues2.set(targetPath, next);
17291
17300
  void next.then(
17292
17301
  () => {
17293
- if (queues?.get(targetPath) === next) queues.delete(targetPath);
17302
+ if (queues2?.get(targetPath) === next) queues2.delete(targetPath);
17294
17303
  },
17295
17304
  () => {
17296
- if (queues?.get(targetPath) === next) queues.delete(targetPath);
17305
+ if (queues2?.get(targetPath) === next) queues2.delete(targetPath);
17297
17306
  }
17298
17307
  );
17299
17308
  return next;
@@ -17324,7 +17333,7 @@ async function readProjectFileContent(pid, path) {
17324
17333
  buildProjectApiPath(pid, `/files/${encodeURIComponent(path)}`)
17325
17334
  );
17326
17335
  if (!response.ok) {
17327
- throw await createStudioSaveHttpError(response, `Failed to read ${path}`);
17336
+ throw await createStudioSaveHttpError(response, `Failed to read ${path}`, { path });
17328
17337
  }
17329
17338
  const data = await response.json();
17330
17339
  if (typeof data.content !== "string") {
@@ -17776,8 +17785,8 @@ function finalizeSoftReload(win, currentTime) {
17776
17785
  }
17777
17786
  function applySoftReloadFinalization(iframe, currentTime) {
17778
17787
  const win = iframe?.contentWindow;
17779
- if (!win?.__hfForceTimelineRebind) return false;
17780
17788
  try {
17789
+ if (!win?.__hfForceTimelineRebind) return false;
17781
17790
  if (win.__hfSuppressSceneMutations) {
17782
17791
  win.__hfSuppressSceneMutations(() => finalizeSoftReload(win, currentTime));
17783
17792
  } else {
@@ -18234,7 +18243,9 @@ async function readFileContent(projectId, targetPath) {
18234
18243
  `/api/projects/${encodeURIComponent(projectId)}/files/${encodeURIComponent(targetPath)}`
18235
18244
  );
18236
18245
  if (!response.ok) {
18237
- throw new Error(`Failed to read ${targetPath}`);
18246
+ throw await createStudioSaveHttpError(response, `Failed to read ${targetPath}`, {
18247
+ path: targetPath
18248
+ });
18238
18249
  }
18239
18250
  const data = await response.json();
18240
18251
  if (typeof data.content !== "string") {
@@ -21679,12 +21690,21 @@ function historyTooltipLabel(action, lastAction) {
21679
21690
  const verb = action === "undo" ? "Undo" : "Redo";
21680
21691
  return lastAction ? `${verb} ${lastAction} (${shortcut})` : `${verb} (${shortcut})`;
21681
21692
  }
21682
- function matchesByDomId(selection, element, selectionSourceFile) {
21693
+ function matchesByClipId(selection, element, file, value, clipIdScope) {
21694
+ if (!clipIdScope || !selection.handle) return false;
21695
+ if (element.domId || element.hfId || element.selector) return false;
21696
+ return element.id === value && (element.sourceFile || clipIdScope) === file;
21697
+ }
21698
+ function matchesByDomId(selection, element, selectionSourceFile, clipIdScope) {
21683
21699
  if (!selection.id) return false;
21700
+ if (matchesByClipId(selection, element, selectionSourceFile, selection.id, clipIdScope))
21701
+ return true;
21684
21702
  return element.domId === selection.id && (element.sourceFile || "index.html") === selectionSourceFile;
21685
21703
  }
21686
- function matchesByHfId(selection, element, selectionSourceFile) {
21704
+ function matchesByHfId(selection, element, selectionSourceFile, clipIdScope) {
21687
21705
  if (!selection.hfId) return false;
21706
+ if (matchesByClipId(selection, element, selectionSourceFile, selection.hfId, clipIdScope))
21707
+ return true;
21688
21708
  return element.hfId === selection.hfId && (element.sourceFile || "index.html") === selectionSourceFile;
21689
21709
  }
21690
21710
  function matchesByCompositionHost(selection, element) {
@@ -21695,11 +21715,11 @@ function matchesBySelector(selection, element) {
21695
21715
  if (!selection.selector) return false;
21696
21716
  return element.selector === selection.selector && (element.selectorIndex ?? 0) === (selection.selectorIndex ?? 0) && (element.sourceFile ?? "index.html") === selection.sourceFile;
21697
21717
  }
21698
- function findMatchingTimelineElementId(selection, elements) {
21718
+ function findMatchingTimelineElementId(selection, elements, clipIdScope) {
21699
21719
  const selectionSourceFile = selection.sourceFile || "index.html";
21700
- const byId = selection.id ? elements.find((el) => matchesByDomId(selection, el, selectionSourceFile)) : void 0;
21720
+ const byId = selection.id ? elements.find((el) => matchesByDomId(selection, el, selectionSourceFile, clipIdScope)) : void 0;
21701
21721
  if (byId) return byId.key ?? byId.id;
21702
- const byHfId = selection.hfId ? elements.find((el) => matchesByHfId(selection, el, selectionSourceFile)) : void 0;
21722
+ const byHfId = selection.hfId ? elements.find((el) => matchesByHfId(selection, el, selectionSourceFile, clipIdScope)) : void 0;
21703
21723
  if (byHfId) return byHfId.key ?? byHfId.id;
21704
21724
  const bySelector = selection.selector ? elements.find((el) => matchesBySelector(selection, el)) : void 0;
21705
21725
  if (bySelector) return bySelector.key ?? bySelector.id;
@@ -21729,8 +21749,9 @@ function findTimelineIdByAncestor(element, elements, sourceFile) {
21729
21749
  }
21730
21750
  return null;
21731
21751
  }
21732
- function resolveTimelineIdForSelection(selection, elements, activeCompPath) {
21733
- return findMatchingTimelineElementId(selection, elements) ?? findTimelineIdByAncestor(
21752
+ function resolveTimelineIdForSelection(selection, elements, activeCompPath, byClipId = false) {
21753
+ const clipIdScope = byClipId ? activeCompPath || "index.html" : void 0;
21754
+ return findMatchingTimelineElementId(selection, elements, clipIdScope) ?? findTimelineIdByAncestor(
21734
21755
  selection.element,
21735
21756
  elements,
21736
21757
  selection.sourceFile || activeCompPath || "index.html"
@@ -38349,6 +38370,869 @@ function isDomEditGestureTap(g, e) {
38349
38370
  return !g.travelled && Math.hypot(e.clientX - g.startX, e.clientY - g.startY) < BLOCKED_MOVE_THRESHOLD_PX;
38350
38371
  }
38351
38372
 
38373
+ // src/components/editor/previewLayers.ts
38374
+ import { MAX_DESCRIBE_HANDLES as MAX_DESCRIBE_HANDLES4 } from "@hyperframes/core/runtime/editing-port";
38375
+
38376
+ // src/player/lib/previewElements.ts
38377
+ import {
38378
+ EDITING_ELEMENT_HANDLE,
38379
+ MAX_DESCRIBE_HANDLES,
38380
+ MAX_ELEMENT_ENTRIES,
38381
+ MAX_ELEMENT_VALUE,
38382
+ MAX_GEOMETRY_CHILDREN
38383
+ } from "@hyperframes/core/runtime/editing-port";
38384
+ var isFields = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
38385
+ var isHandle = (value) => typeof value === "string" && EDITING_ELEMENT_HANDLE.test(value);
38386
+ var isText = (value) => typeof value === "string";
38387
+ var isTextOrNull = (value) => value === null || typeof value === "string";
38388
+ var isCount = (value) => Number.isSafeInteger(value) && value >= 0;
38389
+ var isSource = (value) => isFields(value) && isTextOrNull(value.file) && isTextOrNull(value.compositionId) && isTextOrNull(value.originalCompositionId);
38390
+ var isTextRecord = (value) => isFields(value) && Object.values(value).every(isText);
38391
+ function hasPlainFields(value) {
38392
+ const { matchesBefore, attributes, children } = value;
38393
+ const groupsOk = matchesBefore === null || Array.isArray(matchesBefore) && matchesBefore.every((g) => isFields(g) && isSource(g.source) && isCount(g.count));
38394
+ const attributesOk = Array.isArray(attributes) && attributes.every((a) => Array.isArray(a) && a.length === 2 && a.every(isText));
38395
+ const childrenOk = Array.isArray(children) && children.every((c) => isFields(c) && (isHandle(c.handle) || isText(c.text)));
38396
+ return groupsOk && attributesOk && childrenOk && typeof value.truncated === "boolean";
38397
+ }
38398
+ var isRect = (value) => isFields(value) && [value.x, value.y, value.width, value.height].every(Number.isFinite);
38399
+ function readHit(value) {
38400
+ if (!isFields(value) || !isHandle(value.handle) || !isText(value.tag)) return null;
38401
+ return isRect(value.rect) ? value : null;
38402
+ }
38403
+ function readPreviewElement(value) {
38404
+ if (!readHit(value) || !isFields(value)) return null;
38405
+ if (value.parent !== null && !isHandle(value.parent)) return null;
38406
+ if (!isTextOrNull(value.id) || !isTextOrNull(value.selector)) return null;
38407
+ if (!isSource(value.source) || typeof value.locked !== "boolean") return null;
38408
+ if (!isTextRecord(value.inlineStyles) || !isText(value.text)) return null;
38409
+ return hasPlainFields(value) ? value : null;
38410
+ }
38411
+ async function previewPointerTargets(iframe, rootFractionX, rootFractionY) {
38412
+ const params = { x: rootFractionX, y: rootFractionY };
38413
+ const reply = await previewRequest(iframe, "pointer-targets", params);
38414
+ const stack = reply?.stack;
38415
+ if (!reply || !Array.isArray(stack)) return null;
38416
+ return { target: readHit(reply.target), stack: stack.map(readHit).filter((hit) => hit !== null) };
38417
+ }
38418
+ async function describePreviewElements(iframe, handles) {
38419
+ if (!handles.length || handles.length > MAX_DESCRIBE_HANDLES) return null;
38420
+ const reply = await previewRequest(iframe, "describe", { handles: [...handles] });
38421
+ const elements = reply?.elements;
38422
+ if (!Array.isArray(elements) || elements.length !== handles.length) return null;
38423
+ return elements.map((entry3, index2) => {
38424
+ const element = readPreviewElement(entry3);
38425
+ return element?.handle === handles[index2] ? element : null;
38426
+ });
38427
+ }
38428
+ async function previewAncestors(iframe, handles) {
38429
+ if (!handles.length || handles.length > MAX_DESCRIBE_HANDLES) return null;
38430
+ const reply = await previewRequest(iframe, "ancestors", { handles: [...handles] });
38431
+ const chains = reply?.ancestors;
38432
+ if (!Array.isArray(chains) || chains.length !== handles.length) return null;
38433
+ return chains.map(
38434
+ (chain) => Array.isArray(chain) && chain.every(isHandle) ? chain : null
38435
+ );
38436
+ }
38437
+ async function queryPreviewElements(iframe, selector) {
38438
+ const reply = await previewRequest(iframe, "query", { selector });
38439
+ const matches = reply?.matches;
38440
+ if (!Array.isArray(matches) || typeof reply?.truncated !== "boolean") return null;
38441
+ const ok = matches.every((m) => isFields(m) && isHandle(m.handle) && isSource(m.source));
38442
+ return ok ? { matches, truncated: reply.truncated } : null;
38443
+ }
38444
+ function previewElementSourceFile(element, activeCompositionPath) {
38445
+ return resolveElementSourceFile(element.source, activeCompositionPath);
38446
+ }
38447
+ function previewElementSelectorIndex(element, activeCompositionPath) {
38448
+ if (!element.selector?.startsWith(".") || !element.matchesBefore) return void 0;
38449
+ const file = previewElementSourceFile(element, activeCompositionPath);
38450
+ return element.matchesBefore.filter((group) => resolveElementSourceFile(group.source, activeCompositionPath) === file).reduce((sum, group) => sum + group.count, 0);
38451
+ }
38452
+ var isPoint = (value) => isFields(value) && Number.isFinite(value.x) && Number.isFinite(value.y);
38453
+ var isSizeOrNull = (value) => value === null || Number.isFinite(value) && value > 0;
38454
+ var CORNERS = ["nw", "ne", "se", "sw"];
38455
+ var isCorners = (value) => value === null || isFields(value) && CORNERS.every((corner) => isPoint(value[corner]));
38456
+ var isSourceBox = (value) => value === null || isFields(value) && Number.isFinite(value.width) && Number.isFinite(value.height) && isSizeOrNull(value.declaredWidth) && isSizeOrNull(value.declaredHeight);
38457
+ var isClipPath = (value) => value === null || isText(value) && value.length <= MAX_ELEMENT_VALUE;
38458
+ var isBox = (value) => isFields(value) && isRect(value.rect) && Number.isFinite(value.angle) && isCorners(value.corners) && isSourceBox(value.source) && isClipPath(value.clipPath);
38459
+ var readGeometry = (value) => {
38460
+ if (!isBox(value) || !isFields(value) || typeof value.visible !== "boolean") return null;
38461
+ const { members } = value;
38462
+ const membersOk = members === null || Array.isArray(members) && members.length <= MAX_ELEMENT_ENTRIES && members.every(isRect);
38463
+ return membersOk ? value : null;
38464
+ };
38465
+ async function previewGeometry(iframe, handles, children) {
38466
+ if (!handles.length || handles.length > MAX_DESCRIBE_HANDLES) return null;
38467
+ const params = { handles: [...handles], ...children ? { children } : {} };
38468
+ const reply = await previewRequest(iframe, "geometry", params);
38469
+ const elements = reply?.elements;
38470
+ if (!Array.isArray(elements) || elements.length !== handles.length) return null;
38471
+ const boxes = reply?.children;
38472
+ const childrenOk = Array.isArray(boxes) && boxes.length <= MAX_GEOMETRY_CHILDREN && boxes.every(isBox);
38473
+ return {
38474
+ elements: elements.map(readGeometry),
38475
+ children: children && childrenOk ? boxes : null
38476
+ };
38477
+ }
38478
+ var LAYER_KINDS = /* @__PURE__ */ new Set(["image", "video", "audio", "vector", "group", "text", "shape"]);
38479
+ var isLayer = (value) => isFields(value) && isHandle(value.handle) && isCount(value.depth) && isCount(value.childCount) && Number.isFinite(value.zIndex) && LAYER_KINDS.has(value.kind);
38480
+ async function previewLayers(iframe, group, offset = 0) {
38481
+ const params = { ...group ? { group } : {}, ...offset ? { offset } : {} };
38482
+ const reply = await previewRequest(iframe, "layers", params);
38483
+ const layers = reply?.layers;
38484
+ const { truncated, missingGroup } = reply ?? {};
38485
+ if (!Array.isArray(layers) || typeof truncated !== "boolean") return null;
38486
+ if (typeof missingGroup !== "boolean") return null;
38487
+ return layers.every(isLayer) ? { layers, truncated, missingGroup } : null;
38488
+ }
38489
+
38490
+ // src/components/editor/previewOverlayRects.ts
38491
+ import {
38492
+ MAX_DESCRIBE_HANDLES as MAX_DESCRIBE_HANDLES2,
38493
+ ROTATION_GATE_EPSILON_DEG as ROTATION_GATE_EPSILON_DEG2
38494
+ } from "@hyperframes/core/runtime/editing-port";
38495
+ var clientRect = ({ x, y, width, height }) => ({ left: x, top: y, width, height });
38496
+ var baseRect = (scale, box) => frameRectToOverlay(scale, clientRect(box.rect), box.source);
38497
+ function orientedRect(scale, box) {
38498
+ const base2 = baseRect(scale, box);
38499
+ if (Math.abs(box.angle) < ROTATION_GATE_EPSILON_DEG2) return base2;
38500
+ return orientOverlayRect(
38501
+ base2,
38502
+ box.angle,
38503
+ box.corners && frameCornersToOverlay(scale, box.corners)
38504
+ );
38505
+ }
38506
+ function groupAwareRect(scale, geometry, oriented) {
38507
+ if (!geometry.members)
38508
+ return oriented ? orientedRect(scale, geometry) : baseRect(scale, geometry);
38509
+ const rect = baseRect(scale, geometry);
38510
+ const members = geometry.members.map(
38511
+ (member) => frameRectToOverlay(scale, clientRect(member), null)
38512
+ );
38513
+ const union = resolveDomEditGroupOverlayRect(members);
38514
+ return union ? { ...union, editScaleX: rect.editScaleX, editScaleY: rect.editScaleY } : rect;
38515
+ }
38516
+ function visibleRect(scale, box) {
38517
+ const rect = orientedRect(scale, box);
38518
+ return { ...rect, ...hugRectForClipPath(rect, box.clipPath) };
38519
+ }
38520
+ async function measurePreviewOverlay(iframe, overlayEl, targets) {
38521
+ const handles = [.../* @__PURE__ */ new Set([targets.selection, targets.hover, ...targets.group])].filter(
38522
+ (handle) => Boolean(handle)
38523
+ );
38524
+ const reply = handles.length ? await previewGeometry(iframe, handles, targets.selection ?? void 0) : { elements: [], children: null };
38525
+ const scale = reply && computeOverlayRootScale(overlayEl, iframe, null);
38526
+ if (!reply || !scale) return null;
38527
+ const read2 = (handle) => handle ? reply.elements[handles.indexOf(handle)] ?? null : null;
38528
+ const selected = read2(targets.selection);
38529
+ const shown3 = selected?.visible ? selected : null;
38530
+ const hovered = read2(targets.hover);
38531
+ return {
38532
+ selection: shown3 && groupAwareRect(scale, shown3, true),
38533
+ children: shown3 ? (reply.children ?? []).map((box) => visibleRect(scale, box)).filter((rect) => rect.width > 2 && rect.height > 2) : [],
38534
+ group: targets.group.map((handle) => {
38535
+ const member = read2(handle);
38536
+ const rect = member && groupAwareRect(scale, member, false);
38537
+ return rect && { ...rect, ...hugRectForClipPath(rect, member.clipPath) };
38538
+ }),
38539
+ hover: hovered && groupAwareRect(scale, hovered, true)
38540
+ };
38541
+ }
38542
+ async function measurePreviewRects(iframe, overlayEl, handles) {
38543
+ const reply = await previewGeometry(iframe, handles);
38544
+ const scale = reply && computeOverlayRootScale(overlayEl, iframe, null);
38545
+ if (!reply || !scale) return null;
38546
+ return reply.elements.map((geometry) => geometry && groupAwareRect(scale, geometry, true));
38547
+ }
38548
+ async function measurePreviewVisibleRects(iframe, overlayEl, handles) {
38549
+ const measured = [];
38550
+ for (let at = 0; at < handles.length; at += MAX_DESCRIBE_HANDLES2) {
38551
+ const reply = await previewGeometry(iframe, handles.slice(at, at + MAX_DESCRIBE_HANDLES2));
38552
+ const scale = reply && computeOverlayRootScale(overlayEl, iframe, null);
38553
+ if (!reply || !scale) return null;
38554
+ for (const box of reply.elements) {
38555
+ const rect = box && baseRect(scale, box);
38556
+ measured.push(
38557
+ box && rect && {
38558
+ rect: { ...rect, ...hugRectForClipPath(rect, box.clipPath) },
38559
+ frame: box.rect,
38560
+ visible: box.visible
38561
+ }
38562
+ );
38563
+ }
38564
+ }
38565
+ return measured;
38566
+ }
38567
+
38568
+ // src/components/editor/previewSelection.ts
38569
+ import { resolveEditingAffordances } from "@hyperframes/core/editing";
38570
+ import {
38571
+ MAX_ELEMENT_ENTRIES as MAX_ELEMENT_ENTRIES2,
38572
+ MAX_ELEMENT_VALUE as MAX_ELEMENT_VALUE2
38573
+ } from "@hyperframes/core/runtime/editing-port";
38574
+
38575
+ // src/components/editor/previewDrafts.ts
38576
+ import { MAX_DESCRIBE_HANDLES as MAX_DESCRIBE_HANDLES3 } from "@hyperframes/core/runtime/editing-port";
38577
+ var standIns = /* @__PURE__ */ new WeakMap();
38578
+ var queues = /* @__PURE__ */ new WeakMap();
38579
+ function registerPreviewStandIn(standIn, iframe, handle) {
38580
+ standIns.set(standIn, { iframe, handle });
38581
+ }
38582
+ function queueFor(iframe) {
38583
+ let queue2 = queues.get(iframe);
38584
+ if (!queue2) {
38585
+ queue2 = { ops: [], drawn: /* @__PURE__ */ new Map(), sending: false };
38586
+ queues.set(iframe, queue2);
38587
+ }
38588
+ return queue2;
38589
+ }
38590
+ function send2(iframe, queue2) {
38591
+ if (queue2.sending || !queue2.ops.length) return;
38592
+ const drafts = queue2.ops.splice(0, MAX_DESCRIBE_HANDLES3);
38593
+ queue2.sending = true;
38594
+ void previewRequest(iframe, "draft", { drafts }).finally(() => {
38595
+ queue2.sending = false;
38596
+ send2(iframe, queue2);
38597
+ });
38598
+ }
38599
+ function drawPreviewDraft(element, part) {
38600
+ const target = standIns.get(element);
38601
+ if (!target) return;
38602
+ const queue2 = queueFor(target.iframe);
38603
+ const drawn = { translate: null, size: null, ...queue2.drawn.get(target.handle), ...part };
38604
+ queue2.drawn.set(target.handle, drawn);
38605
+ const op = { handle: target.handle, ...drawn };
38606
+ const last = queue2.ops.map((queued) => queued.handle).lastIndexOf(target.handle);
38607
+ const waiting = queue2.ops[last];
38608
+ if (waiting && !("end" in waiting)) queue2.ops[last] = op;
38609
+ else queue2.ops.push(op);
38610
+ send2(target.iframe, queue2);
38611
+ }
38612
+ function endPreviewDraft(element, end) {
38613
+ const target = standIns.get(element);
38614
+ if (!target) return;
38615
+ const queue2 = queueFor(target.iframe);
38616
+ if (!queue2.drawn.delete(target.handle)) return;
38617
+ queue2.ops.push({ handle: target.handle, end });
38618
+ send2(target.iframe, queue2);
38619
+ }
38620
+
38621
+ // src/hooks/draggedGsapPosition.ts
38622
+ var cssValue = (style, prop) => {
38623
+ const value = style.getPropertyValue(prop).trim();
38624
+ return value === "none" ? "" : value;
38625
+ };
38626
+ function readCssRotation(element, withRotate = true) {
38627
+ const view = element.ownerDocument.defaultView;
38628
+ if (!view) return 0;
38629
+ const style = view.getComputedStyle(element);
38630
+ const rotate2 = withRotate ? cssValue(style, "rotate") : "";
38631
+ const scale = cssValue(style, "scale");
38632
+ const transform = cssValue(style, "transform");
38633
+ const angle = (list) => {
38634
+ if (!list) return 0;
38635
+ const m = new view.DOMMatrix(list);
38636
+ return Math.atan2(m.b, m.a) * 180 / Math.PI;
38637
+ };
38638
+ const folded = [rotate2 && `rotate(${rotate2})`, scale && `scale(${scale.split(/\s+/).join(",")})`];
38639
+ try {
38640
+ return angle([...folded, transform].join(" ").trim());
38641
+ } catch {
38642
+ return angle(transform);
38643
+ }
38644
+ }
38645
+ function readDragStamp(element) {
38646
+ const read2 = (name) => Number.parseFloat(element.getAttribute(name) ?? "");
38647
+ return {
38648
+ origX: read2("data-hf-drag-initial-offset-x") || 0,
38649
+ origY: read2("data-hf-drag-initial-offset-y") || 0,
38650
+ baseX: read2("data-hf-drag-gsap-base-x"),
38651
+ baseY: read2("data-hf-drag-gsap-base-y"),
38652
+ at: readEditMoment(element)
38653
+ };
38654
+ }
38655
+ function readEditMoment(element) {
38656
+ const raw = element.getAttribute(STUDIO_EDIT_MOMENT_ATTR);
38657
+ return raw ? JSON.parse(raw) : void 0;
38658
+ }
38659
+ var freezeDragStamp = (element) => ({
38660
+ ...readDragStamp(element),
38661
+ frozen: true
38662
+ });
38663
+ function computeDraggedGsapPosition(element, studioOffset, fallbackBase, stamp = readDragStamp(element)) {
38664
+ const rotStyle = element.style.getPropertyValue("--hf-studio-rotation");
38665
+ const rotDeg = Number.parseFloat(rotStyle) || 0;
38666
+ const rad = -rotDeg * Math.PI / 180;
38667
+ const cos = Math.cos(rad);
38668
+ const sin = Math.sin(rad);
38669
+ const deltaX = studioOffset.x - stamp.origX;
38670
+ const deltaY = studioOffset.y - stamp.origY;
38671
+ const adjX = deltaX * cos - deltaY * sin;
38672
+ const adjY = deltaX * sin + deltaY * cos;
38673
+ const baseGsapX = Number.isFinite(stamp.baseX) ? stamp.baseX : fallbackBase.x;
38674
+ const baseGsapY = Number.isFinite(stamp.baseY) ? stamp.baseY : fallbackBase.y;
38675
+ return {
38676
+ newX: roundTo3(baseGsapX + adjX),
38677
+ newY: roundTo3(baseGsapY + adjY),
38678
+ baseGsapX,
38679
+ baseGsapY
38680
+ };
38681
+ }
38682
+ function restoreDragOffset(element, stamp = readDragStamp(element)) {
38683
+ if (stamp.frozen) return;
38684
+ element.style.setProperty("--hf-studio-offset-x", `${stamp.origX}px`);
38685
+ element.style.setProperty("--hf-studio-offset-y", `${stamp.origY}px`);
38686
+ element.removeAttribute("data-hf-drag-initial-offset-x");
38687
+ element.removeAttribute("data-hf-drag-initial-offset-y");
38688
+ }
38689
+
38690
+ // src/components/editor/plainTranslate.ts
38691
+ var TOKEN = /\s*(?:(\d*\.?\d+(?:e[-+]?\d+)?)(px|%)?|([a-z]+)\(|([-+*/(),]))/giy;
38692
+ var FUNCTIONS = {
38693
+ "(": ([a = Number.NaN]) => a,
38694
+ "calc(": ([a = Number.NaN]) => a,
38695
+ "min(": (args) => Math.min(...args),
38696
+ "max(": (args) => Math.max(...args),
38697
+ "clamp(": ([lo = Number.NaN, v = Number.NaN, hi = Number.NaN]) => Math.max(lo, Math.min(v, hi))
38698
+ };
38699
+ function tokenize(value, side) {
38700
+ const tokens = [];
38701
+ const end = value.trimEnd().length;
38702
+ TOKEN.lastIndex = 0;
38703
+ for (let m = TOKEN.exec(value); m; m = TOKEN.lastIndex < end ? TOKEN.exec(value) : null) {
38704
+ if (m[1]) tokens.push(Number(m[1]) * (m[2] === "%" ? side / 100 : 1));
38705
+ else tokens.push(m[3] ? `${m[3].toLowerCase()}(` : m[4] ?? "");
38706
+ }
38707
+ return TOKEN.lastIndex < end ? [] : tokens;
38708
+ }
38709
+ function evaluateLength(value, side) {
38710
+ const tokens = tokenize(value, side);
38711
+ let i = 0;
38712
+ const next = () => tokens[i++];
38713
+ const take = (...ops) => ops.includes(tokens[i]) && next();
38714
+ function sum() {
38715
+ let total2 = product();
38716
+ for (let op = take("+", "-"); op; op = take("+", "-"))
38717
+ total2 += (op === "+" ? 1 : -1) * product();
38718
+ return total2;
38719
+ }
38720
+ function product() {
38721
+ let total2 = unary();
38722
+ for (let op = take("*", "/"); op; op = take("*", "/"))
38723
+ total2 = op === "*" ? total2 * unary() : total2 / unary();
38724
+ return total2;
38725
+ }
38726
+ function unary() {
38727
+ return take("-") ? -unary() : atom();
38728
+ }
38729
+ function atom() {
38730
+ const token = next();
38731
+ if (typeof token === "number") return token;
38732
+ const fn = FUNCTIONS[token ?? ""];
38733
+ if (!fn) return Number.NaN;
38734
+ const args = [sum()];
38735
+ while (take(",")) args.push(sum());
38736
+ return take(")") ? fn(args) : Number.NaN;
38737
+ }
38738
+ const total = tokens.length ? sum() : Number.NaN;
38739
+ return i === tokens.length ? total : Number.NaN;
38740
+ }
38741
+ var CONTENT_BOXES = /* @__PURE__ */ new Set(["content-box", "fill-box"]);
38742
+ var TRANSLATE_PX_PROPERTIES = [
38743
+ "translate",
38744
+ "width",
38745
+ "height",
38746
+ "box-sizing",
38747
+ "transform-box",
38748
+ ...["left", "right", "top", "bottom"].flatMap((s) => [`padding-${s}`, `border-${s}-width`])
38749
+ ];
38750
+ function referenceBox(read2, size, a, b) {
38751
+ const n = (prop) => Number.parseFloat(read2(prop)) || 0;
38752
+ const pad2 = n(`padding-${a}`) + n(`padding-${b}`) + n(`border-${a}-width`) + n(`border-${b}-width`);
38753
+ const content = n(size) - (read2("box-sizing") === "border-box" ? pad2 : 0);
38754
+ return CONTENT_BOXES.has(read2("transform-box")) ? content : content + pad2;
38755
+ }
38756
+ function translatePx(value, read2) {
38757
+ if (value === "none") return { x: 0, y: 0 };
38758
+ const [x = "0px", y = "0px"] = splitTopLevelWhitespace(value);
38759
+ const side = (size, a, b) => read2 ? referenceBox(read2, size, a, b) : Number.NaN;
38760
+ return {
38761
+ x: evaluateLength(x, side("width", "left", "right")),
38762
+ y: evaluateLength(y, side("height", "top", "bottom"))
38763
+ };
38764
+ }
38765
+ var frameTranslates = /* @__PURE__ */ new WeakMap();
38766
+ function rememberFrameTranslate(el, px) {
38767
+ frameTranslates.set(el, { inline: el.style.getPropertyValue("translate"), px });
38768
+ }
38769
+ function readTranslatePx(el) {
38770
+ const cs = el.ownerDocument.defaultView?.getComputedStyle(el);
38771
+ const inline = el.style.getPropertyValue("translate");
38772
+ const frame3 = cs ? void 0 : frameTranslates.get(el);
38773
+ if (frame3?.inline === inline) return frame3.px;
38774
+ return translatePx(cs?.translate || inline || "none", cs && ((p) => cs.getPropertyValue(p)));
38775
+ }
38776
+ function readTranslatePxLeavingPercent(el) {
38777
+ const value = el.ownerDocument.defaultView?.getComputedStyle(el).translate || "none";
38778
+ const [x = "0px", y = "0px"] = value === "none" ? [] : splitTopLevelWhitespace(value);
38779
+ const px = (part) => roundTo3(evaluateLength(part, 0)) || 0;
38780
+ return { x: px(x), y: px(y) };
38781
+ }
38782
+ var UNREADABLE_TRANSLATE = "Studio can't read this layer's translate. Move it in the Code tab.";
38783
+ function formatTranslatePx(p) {
38784
+ return `${roundTo3(p.x)}px ${roundTo3(p.y)}px`;
38785
+ }
38786
+ var LEGACY_OFFSET_VARS = [STUDIO_OFFSET_X_PROP, STUDIO_OFFSET_Y_PROP];
38787
+ function writePlainMove(el, p) {
38788
+ writeTranslatePx(el, p);
38789
+ const patches = [
38790
+ { type: "inline-style", property: "translate", value: formatTranslatePx(p) },
38791
+ {
38792
+ type: "attribute",
38793
+ property: STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR,
38794
+ value: el.getAttribute(STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR)
38795
+ }
38796
+ ];
38797
+ for (const prop of LEGACY_OFFSET_VARS.filter((v) => el.style.getPropertyValue(v))) {
38798
+ el.style.removeProperty(prop);
38799
+ patches.push({ type: "inline-style", property: prop, value: null });
38800
+ }
38801
+ if (el.hasAttribute(STUDIO_PATH_OFFSET_ATTR)) {
38802
+ el.removeAttribute(STUDIO_PATH_OFFSET_ATTR);
38803
+ patches.push({ type: "attribute", property: STUDIO_PATH_OFFSET_ATTR, value: null });
38804
+ }
38805
+ return patches;
38806
+ }
38807
+ function writeTranslatePx(el, p) {
38808
+ if (!el.hasAttribute(STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR)) {
38809
+ const own = el.style.getPropertyValue("translate");
38810
+ el.setAttribute(STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR, styleUsesStudioOffset(own) ? "" : own);
38811
+ }
38812
+ el.style.setProperty("translate", formatTranslatePx(p));
38813
+ }
38814
+ function readMoveOffset(el, plainTranslate = editsPlainCss(el, "move")) {
38815
+ return plainTranslate ? readTranslatePx(el) : readStudioPathOffset(el);
38816
+ }
38817
+ function readShownRotation(el) {
38818
+ return editsPlainCss(el, "rotate") ? { angle: roundTo3(readCssRotation(el)) } : readStudioRotation(el);
38819
+ }
38820
+
38821
+ // src/components/editor/previewSelection.ts
38822
+ var inertDocument;
38823
+ var inert = () => inertDocument ??= document.implementation.createHTMLDocument("");
38824
+ function inertElement(tag) {
38825
+ try {
38826
+ return inert().createElement(tag);
38827
+ } catch {
38828
+ return inert().createElement("div");
38829
+ }
38830
+ }
38831
+ var GESTURE_START_STYLES = [
38832
+ "translate",
38833
+ STUDIO_OFFSET_X_PROP,
38834
+ STUDIO_OFFSET_Y_PROP,
38835
+ STUDIO_WIDTH_PROP,
38836
+ STUDIO_HEIGHT_PROP
38837
+ ];
38838
+ var GESTURE_START_ATTRS = [
38839
+ STUDIO_PATH_OFFSET_ATTR,
38840
+ STUDIO_ORIGINAL_TRANSLATE_ATTR,
38841
+ STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR
38842
+ ];
38843
+ var standIns2 = /* @__PURE__ */ new WeakMap();
38844
+ var standInHandles = /* @__PURE__ */ new WeakMap();
38845
+ var standInAncestors = /* @__PURE__ */ new WeakMap();
38846
+ function standInFor(iframe, element) {
38847
+ const client = previewEditingClient(iframe);
38848
+ const byHandle = standIns2.get(client) ?? /* @__PURE__ */ new Map();
38849
+ standIns2.set(client, byHandle);
38850
+ let standIn = byHandle.get(element.handle);
38851
+ if (!standIn) {
38852
+ standIn = inertElement(element.tag);
38853
+ for (const name of GESTURE_START_STYLES) {
38854
+ const value = element.inlineStyles[name];
38855
+ if (value && !mayBeCut(value)) standIn.style.setProperty(name, value);
38856
+ }
38857
+ for (const name of GESTURE_START_ATTRS) {
38858
+ const value = attr(element, name);
38859
+ if (value !== null && !mayBeCut(value)) standIn.setAttribute(name, value);
38860
+ }
38861
+ byHandle.set(element.handle, standIn);
38862
+ standInHandles.set(standIn, element.handle);
38863
+ registerPreviewStandIn(standIn, iframe, element.handle);
38864
+ }
38865
+ return standIn;
38866
+ }
38867
+ function readable(element) {
38868
+ const probe2 = inertElement(element.tag);
38869
+ for (const [name, value] of element.attributes) {
38870
+ if (name !== "id" && name !== "class" && !name.startsWith("data-")) continue;
38871
+ try {
38872
+ probe2.setAttribute(name, value);
38873
+ } catch {
38874
+ }
38875
+ }
38876
+ for (const [name, value] of Object.entries(element.inlineStyles)) {
38877
+ probe2.style.setProperty(name, value);
38878
+ }
38879
+ probe2.textContent = element.text;
38880
+ return probe2;
38881
+ }
38882
+ var attr = (element, name) => element.attributes.find(([key2]) => key2 === name)?.[1] ?? null;
38883
+ var mayBeCut = (value) => value.length >= MAX_ELEMENT_VALUE2 || value.startsWith("data:") && value.endsWith(",");
38884
+ function valuesWhole(element) {
38885
+ if (!element.truncated) return true;
38886
+ const styles = Object.values(element.inlineStyles);
38887
+ if (element.attributes.length >= MAX_ELEMENT_ENTRIES2 || styles.length >= MAX_ELEMENT_ENTRIES2)
38888
+ return false;
38889
+ return ![...element.attributes.map(([, value]) => value), ...styles].some(mayBeCut);
38890
+ }
38891
+ var hasAudio = (element) => element.tag === "video" && attr(element, "muted") === null && isVideoAudible({ tag: "video", hasAudioAttr: attr(element, "data-has-audio"), muted: false });
38892
+ var validSelector = (selector) => {
38893
+ try {
38894
+ inert().querySelector(selector);
38895
+ return true;
38896
+ } catch {
38897
+ return false;
38898
+ }
38899
+ };
38900
+ async function findPreviewElementForSelection(iframe, selection, activeCompositionPath) {
38901
+ for (const { selector, index: index2 } of selectionLookups(selection)) {
38902
+ if (!validSelector(selector)) continue;
38903
+ const reply = await queryPreviewElements(iframe, selector);
38904
+ if (!reply) return void 0;
38905
+ const fromFile = reply.matches.filter(
38906
+ ({ source }) => !selection.sourceFile || resolveElementSourceFile(source, activeCompositionPath) === selection.sourceFile
38907
+ );
38908
+ const match = fromFile[index2];
38909
+ if (!match) {
38910
+ if (reply.truncated) return void 0;
38911
+ continue;
38912
+ }
38913
+ const [element] = await describePreviewElements(iframe, [match.handle]) ?? [];
38914
+ return element ?? void 0;
38915
+ }
38916
+ return null;
38917
+ }
38918
+ async function findByClipId(iframe, element, sourceFile, path) {
38919
+ if (!element.id || element.domId || element.selector || element.compositionSrc) return null;
38920
+ const byId = await findPreviewElementForSelection(iframe, { id: element.id, sourceFile }, path);
38921
+ if (byId !== null) return byId;
38922
+ return findPreviewElementForSelection(iframe, { hfId: element.id, sourceFile }, path);
38923
+ }
38924
+ async function findPreviewElementForTimelineElement(iframe, element, options) {
38925
+ const { target, sourceFile, rootFallback } = timelineElementLookup(element, options);
38926
+ const path = options.activeCompositionPath;
38927
+ const found = target && await findPreviewElementForSelection(iframe, target, path);
38928
+ if (found !== null) return found;
38929
+ const byClipId = await findByClipId(iframe, element, sourceFile, path);
38930
+ if (byClipId !== null) return byClipId;
38931
+ if (!rootFallback) return null;
38932
+ const reply = await queryPreviewElements(iframe, "[data-composition-id]");
38933
+ if (!reply) return void 0;
38934
+ const root = reply.matches[0];
38935
+ if (!root || resolveElementSourceFile(root.source, path) !== sourceFile) return null;
38936
+ const [described] = await describePreviewElements(iframe, [root.handle]) ?? [];
38937
+ return described ?? void 0;
38938
+ }
38939
+ async function previewChain(iframe, target) {
38940
+ const [lineage] = await previewAncestors(iframe, [target.handle]) ?? [];
38941
+ if (!lineage) return null;
38942
+ const ancestors = lineage.length ? await describePreviewElements(iframe, lineage) : [];
38943
+ if (!ancestors || ancestors.some((entry3) => entry3 === null)) return null;
38944
+ const chain = [target, ...ancestors];
38945
+ const linked = chain.every((node, i) => node.parent === (chain[i + 1]?.handle ?? null));
38946
+ return linked ? chain : null;
38947
+ }
38948
+ function chainReader(chain) {
38949
+ const root = chain.at(-1);
38950
+ const body = chain.at(-2);
38951
+ return {
38952
+ attr,
38953
+ selector: (node) => node.selector ?? void 0,
38954
+ isDocumentRoot: (node) => node === root || node === body && node.tag === "body"
38955
+ };
38956
+ }
38957
+ async function compositionRoot2(iframe, documentElement) {
38958
+ const reply = await queryPreviewElements(iframe, "[data-composition-id]");
38959
+ if (!reply) return null;
38960
+ const first = reply.matches[0];
38961
+ const [root] = first ? await describePreviewElements(iframe, [first.handle]) ?? [null] : [];
38962
+ if (root === null) return null;
38963
+ const element = root ?? documentElement;
38964
+ const { x, y, width, height } = element.rect;
38965
+ return {
38966
+ rect: { left: x, top: y, width, height },
38967
+ width: attr(element, "data-width"),
38968
+ height: attr(element, "data-height")
38969
+ };
38970
+ }
38971
+ function chainIndex(chain, read2, options) {
38972
+ const active = options.activeGroupElement;
38973
+ const activeHandle = active ? standInHandles.get(active) : void 0;
38974
+ return selectionTargetIndex(chain, read2, {
38975
+ exactTarget: options.exactTarget,
38976
+ preferClipAncestor: options.preferClipAncestor,
38977
+ activeGroupIndex: active ? chain.findIndex((node) => node.handle === activeHandle) : null
38978
+ });
38979
+ }
38980
+ function previewIdentity(current2, path) {
38981
+ const selector = current2.selector ?? void 0;
38982
+ return {
38983
+ id: current2.id || void 0,
38984
+ hfId: attr(current2, "data-hf-id")?.trim() || void 0,
38985
+ selector,
38986
+ selectorIndex: selector ? previewElementSelectorIndex(current2, path) : void 0,
38987
+ sourceFile: previewElementSourceFile(current2, path)
38988
+ };
38989
+ }
38990
+ async function isPreviewCompositionRoot(iframe, chain, index2, computedStyles) {
38991
+ const current2 = chain[index2];
38992
+ if (attr(current2, "data-composition-id") !== null && !compositionSourceOf(current2)) return true;
38993
+ const parent = chain[index2 + 1];
38994
+ const underBody = parent?.tag === "body" && chainReader(chain).isDocumentRoot(parent);
38995
+ if (!underBody || attr(current2, "data-hf-allow-root-edit") !== null) return false;
38996
+ const { x, y, width, height } = current2.rect;
38997
+ const rect = { left: x, top: y, width, height };
38998
+ const root = await compositionRoot2(iframe, chain.at(-1));
38999
+ return root && coversCompositionRoot({ rect, computedStyles }, root);
39000
+ }
39001
+ var compositionSourceOf = (element) => attr(element, "data-composition-src") ?? attr(element, "data-composition-file") ?? void 0;
39002
+ async function resolvePreviewSelection(iframe, target, options) {
39003
+ const chain = await previewChain(iframe, target);
39004
+ const index2 = chain && chainIndex(chain, chainReader(chain), options);
39005
+ if (!chain || index2 === null) return null;
39006
+ const current2 = chain[index2];
39007
+ if (!valuesWhole(current2)) return null;
39008
+ const element = standInFor(iframe, current2);
39009
+ standInAncestors.set(
39010
+ element,
39011
+ chain.slice(index2 + 1).map((node) => node.handle)
39012
+ );
39013
+ const identity = previewIdentity(current2, options.activeCompositionPath);
39014
+ const compositionSrc = compositionSourceOf(current2);
39015
+ const probe2 = readable(current2);
39016
+ const inlineStyles = getInlineStyles(probe2);
39017
+ const styles = await previewComputedStyles(iframe, current2, [
39018
+ .../* @__PURE__ */ new Set([...CURATED_STYLE_PROPERTIES, ...TRANSLATE_PX_PROPERTIES])
39019
+ ]);
39020
+ if (!styles) return null;
39021
+ rememberFrameTranslate(
39022
+ element,
39023
+ translatePx(styles.translate ?? "none", (p) => styles[p] ?? "")
39024
+ );
39025
+ const computedStyles = Object.fromEntries(
39026
+ CURATED_STYLE_PROPERTIES.flatMap((p) => p in styles ? [[p, styles[p]]] : [])
39027
+ );
39028
+ const isCompositionRoot = await isPreviewCompositionRoot(iframe, chain, index2, computedStyles);
39029
+ if (isCompositionRoot === null) return null;
39030
+ const isInsideLocked = chainLocked(chain, chainReader(chain), index2);
39031
+ const { sourceFile } = identity;
39032
+ const existsInSource = await existsInSourceFile(
39033
+ options.previous,
39034
+ element,
39035
+ sourceFile,
39036
+ identity,
39037
+ options
39038
+ );
39039
+ const capabilities = resolveEditingAffordances(
39040
+ capabilityFacts({
39041
+ hasStableTarget: Boolean(identity.selector || identity.hfId),
39042
+ tag: current2.tag,
39043
+ inlineStyles,
39044
+ computedStyles,
39045
+ isCompositionHost: Boolean(compositionSrc),
39046
+ isCompositionRoot,
39047
+ isInsideLockedComposition: isInsideLocked,
39048
+ isMasterView: options.isMasterView,
39049
+ existsInSource: existsInSource ?? true
39050
+ })
39051
+ ).capabilities;
39052
+ const { x, y, width, height } = current2.rect;
39053
+ return {
39054
+ element,
39055
+ handle: current2.handle,
39056
+ hasAudio: hasAudio(current2),
39057
+ src: attr(current2, "src"),
39058
+ ...identity,
39059
+ compositionPath: sourceFile,
39060
+ compositionSrc,
39061
+ isCompositionHost: Boolean(compositionSrc),
39062
+ isInsideLockedComposition: isInsideLocked,
39063
+ label: buildElementLabel(probe2),
39064
+ tagName: current2.tag,
39065
+ boundingBox: { x, y, width, height },
39066
+ textContent: current2.text.trim() || null,
39067
+ dataAttributes: getDataAttributes(probe2),
39068
+ inlineStyles,
39069
+ computedStyles,
39070
+ textFields: [],
39071
+ capabilities,
39072
+ existsInSource
39073
+ };
39074
+ }
39075
+ function liveElementForSelection(iframe, selection, activeCompositionPath) {
39076
+ let doc = null;
39077
+ try {
39078
+ doc = iframe?.contentDocument ?? null;
39079
+ } catch {
39080
+ return void 0;
39081
+ }
39082
+ return doc ? findElementForSelection(doc, selection, activeCompositionPath) : void 0;
39083
+ }
39084
+ async function findSelectionElement(iframe, selection, activeCompositionPath) {
39085
+ return iframe && previewFrameOpaque(iframe) ? findPreviewElementForSelection(iframe, selection, activeCompositionPath) : liveElementForSelection(iframe, selection, activeCompositionPath);
39086
+ }
39087
+ async function resolveFoundSelection(iframe, found, options) {
39088
+ if (isHtmlElement(found)) return resolveDomEditSelection(found, options);
39089
+ return iframe ? resolvePreviewSelection(iframe, found, options) : null;
39090
+ }
39091
+ async function findOpaqueTimelineElement(iframe, element, lookup2) {
39092
+ if (!iframe || !previewFrameOpaque(iframe)) return null;
39093
+ return await findPreviewElementForTimelineElement(iframe, element, lookup2) ?? null;
39094
+ }
39095
+ var standInHandle = (element) => standInHandles.get(element);
39096
+ function elementWithin(container, element) {
39097
+ const handle = standInHandles.get(container);
39098
+ if (handle === void 0) return container.contains(element);
39099
+ return element === container || (standInAncestors.get(element)?.includes(handle) ?? false);
39100
+ }
39101
+ function selectionDataAttribute(selection, name) {
39102
+ if (!selection.handle) return selection.element.getAttribute(name);
39103
+ return selection.dataAttributes[name.slice("data-".length)] ?? null;
39104
+ }
39105
+ var pointerAnswers = /* @__PURE__ */ new WeakMap();
39106
+ async function previewPointerTarget(iframe, clientX, clientY) {
39107
+ const { x, y } = framePointFraction(iframe, clientX, clientY);
39108
+ const reply = await previewPointerTargets(iframe, x, y);
39109
+ if (reply) pointerAnswers.set(iframe, { x: clientX, y: clientY, found: reply.target !== null });
39110
+ return reply;
39111
+ }
39112
+ function pointerMayHitElement(iframe, clientX, clientY) {
39113
+ if (!previewFrameOpaque(iframe))
39114
+ return Boolean(getPreviewTargetFromPointer(iframe, clientX, clientY));
39115
+ const answer = pointerAnswers.get(iframe);
39116
+ const near4 = answer && Math.hypot(answer.x - clientX, answer.y - clientY) <= 2;
39117
+ return near4 ? answer.found : true;
39118
+ }
39119
+ async function findPointerTarget(iframe, clientX, clientY) {
39120
+ if (!previewFrameOpaque(iframe)) return getPreviewTargetFromPointer(iframe, clientX, clientY);
39121
+ const reply = await previewPointerTarget(iframe, clientX, clientY);
39122
+ if (!reply?.target) return reply ? null : void 0;
39123
+ const [described] = await describePreviewElements(iframe, [reply.target.handle]) ?? [];
39124
+ return described ?? void 0;
39125
+ }
39126
+ async function findPointerTargets(iframe, clientX, clientY) {
39127
+ if (!previewFrameOpaque(iframe)) return getAllPreviewTargetsFromPointer(iframe, clientX, clientY);
39128
+ const reply = await previewPointerTarget(iframe, clientX, clientY);
39129
+ const handles = reply?.stack.map((hit) => hit.handle) ?? [];
39130
+ const described = handles.length ? await describePreviewElements(iframe, handles) : [];
39131
+ return (described ?? []).filter((element) => element !== null);
39132
+ }
39133
+ var selectionElementLive = (selection) => selection.handle !== void 0 || selection.element.isConnected;
39134
+
39135
+ // src/components/editor/previewLayers.ts
39136
+ async function describeAll(iframe, handles) {
39137
+ const described = [];
39138
+ for (let at = 0; at < handles.length; at += MAX_DESCRIBE_HANDLES4) {
39139
+ const part = await describePreviewElements(
39140
+ iframe,
39141
+ handles.slice(at, at + MAX_DESCRIBE_HANDLES4)
39142
+ );
39143
+ if (!part) return null;
39144
+ described.push(...part);
39145
+ }
39146
+ return described;
39147
+ }
39148
+ function layerItem(iframe, layer, element, path) {
39149
+ const probe2 = readable(element);
39150
+ const identity = previewIdentity(element, path);
39151
+ return {
39152
+ ...identity,
39153
+ key: getDomEditLayerKey(identity),
39154
+ element: standInFor(iframe, element),
39155
+ label: buildElementLabel(probe2),
39156
+ tagName: element.tag,
39157
+ depth: layer.depth,
39158
+ childCount: layer.childCount,
39159
+ preview: {
39160
+ handle: layer.handle,
39161
+ zIndex: layer.zIndex,
39162
+ kind: layer.kind,
39163
+ dataAttributes: getDataAttributes(probe2)
39164
+ }
39165
+ };
39166
+ }
39167
+ async function collectPreviewLayerItems(iframe, options, maxItems = Number.POSITIVE_INFINITY) {
39168
+ const group = options.activeGroupElement && standInHandle(options.activeGroupElement);
39169
+ const reply = await previewLayers(iframe, group ?? void 0);
39170
+ const layers = reply?.layers.slice(0, maxItems) ?? [];
39171
+ const described = reply && await describeAll(
39172
+ iframe,
39173
+ layers.map((layer) => layer.handle)
39174
+ );
39175
+ if (!reply || !described) return null;
39176
+ const items = layers.flatMap((layer, index2) => {
39177
+ const element = described[index2];
39178
+ return element ? [layerItem(iframe, layer, element, options.activeCompositionPath)] : [];
39179
+ });
39180
+ return { items, missingGroup: reply.missingGroup };
39181
+ }
39182
+ var MAX_LAYER_PAGES = 64;
39183
+ async function allPreviewLayers(iframe) {
39184
+ const layers = [];
39185
+ for (let page = 0; page < MAX_LAYER_PAGES; page += 1) {
39186
+ const reply = await previewLayers(iframe, void 0, layers.length);
39187
+ if (!reply) return null;
39188
+ layers.push(...reply.layers);
39189
+ if (!reply.truncated || !reply.layers.length) break;
39190
+ }
39191
+ return layers;
39192
+ }
39193
+ function layerDataAttribute(layer, name) {
39194
+ if (!layer.preview) return layer.element.getAttribute(name);
39195
+ return layer.preview.dataAttributes[name.slice("data-".length)] ?? null;
39196
+ }
39197
+ async function compositionViewport(iframe) {
39198
+ const roots = await queryPreviewElements(iframe, "[data-composition-id]");
39199
+ const root = roots?.matches[0] ?? (await queryPreviewElements(iframe, "html"))?.matches[0];
39200
+ const [described] = root && await describePreviewElements(iframe, [root.handle]) || [];
39201
+ if (!described) return null;
39202
+ const declared = (name) => Number.parseFloat(described.attributes.find(([key2]) => key2 === name)?.[1] ?? "");
39203
+ const [width, height] = [declared("data-width"), declared("data-height")];
39204
+ return {
39205
+ width: width > 0 ? width : described.rect.width || 1,
39206
+ height: height > 0 ? height : described.rect.height || 1
39207
+ };
39208
+ }
39209
+ async function collectPreviewMarqueeCandidates(iframe, overlayEl) {
39210
+ const layers = await allPreviewLayers(iframe);
39211
+ const handles = layers?.map((layer) => layer.handle) ?? [];
39212
+ const viewport2 = handles.length ? await compositionViewport(iframe) : null;
39213
+ const described = viewport2 && await describeAll(iframe, handles);
39214
+ const measured = described && await measurePreviewVisibleRects(iframe, overlayEl, handles);
39215
+ if (!described || !measured || !viewport2) return [];
39216
+ return handles.flatMap((_, index2) => {
39217
+ const description = described[index2];
39218
+ const box = measured[index2];
39219
+ if (!description || !box?.visible || coversComposition(box.frame, viewport2)) return [];
39220
+ const { left, top, width, height } = box.rect;
39221
+ const element = standInFor(iframe, description);
39222
+ return [{ element, rect: { left, top, width, height }, description }];
39223
+ });
39224
+ }
39225
+ async function resolvePreviewMarqueeHits(iframe, hits, activeCompositionPath) {
39226
+ const isMasterView = !activeCompositionPath || activeCompositionPath === "index.html";
39227
+ const options = { activeCompositionPath, isMasterView, skipSourceProbe: true };
39228
+ const picks = [];
39229
+ for (const hit of hits) {
39230
+ const selection = await resolvePreviewSelection(iframe, hit.description, options);
39231
+ if (selection) picks.push(selection);
39232
+ }
39233
+ return picks;
39234
+ }
39235
+
38352
39236
  // src/components/editor/marqueeCommit.ts
38353
39237
  function currentMarqueeCandidates(cached5, iframe, overlay, path) {
38354
39238
  if (cached5?.every((hit) => hit.element.ownerDocument === iframe.contentDocument)) return cached5;
@@ -38403,6 +39287,16 @@ async function resolveDomEditSelections(elements, activeCompositionPath) {
38403
39287
  }
38404
39288
  return hits;
38405
39289
  }
39290
+ function bandCandidates(iframe, overlay, acp, measured) {
39291
+ if (!previewFrameOpaque(iframe))
39292
+ return currentMarqueeCandidates(measured.cached, iframe, overlay, acp);
39293
+ return measured.measuring ?? collectPreviewMarqueeCandidates(iframe, overlay);
39294
+ }
39295
+ function resolveMarqueeHits(iframe, hits, acp) {
39296
+ const elements = hits.map((hit) => hit.element);
39297
+ if (!previewFrameOpaque(iframe)) return resolveDomEditSelections(elements, acp);
39298
+ return resolvePreviewMarqueeHits(iframe, hits, acp);
39299
+ }
38406
39300
  function trackMarqueeSelection(result) {
38407
39301
  if (result?.changed && result.count > 1) trackPreviewFeatureUsed("multi_select", "drag");
38408
39302
  }
@@ -38417,16 +39311,18 @@ function useMarqueeGestures(deps) {
38417
39311
  const [marqueeRect, setMarqueeRect] = useState50(null);
38418
39312
  const [candidateRects, setCandidateRects] = useState50([]);
38419
39313
  const candidatesRef = useRef67(null);
39314
+ const opaqueCandidatesRef = useRef67(null);
39315
+ const bandRef = useRef67(null);
38420
39316
  const commitMarquee = useCallback58(
38421
39317
  async (rect, mode) => {
38422
39318
  const iframe = deps.iframeRef.current;
38423
39319
  const overlay = deps.overlayRef.current;
38424
39320
  if (!iframe || !overlay || !deps.onMarqueeSelectRef.current) return;
38425
39321
  const acp = deps.activeCompositionPathRef.current ?? "index.html";
38426
- const candidates = currentMarqueeCandidates(candidatesRef.current, iframe, overlay, acp);
38427
- const elements = hitsWithin(rect, candidates).map((hit) => hit.element);
39322
+ const measured = { cached: candidatesRef.current, measuring: opaqueCandidatesRef.current };
39323
+ const hits = hitsWithin(rect, await bandCandidates(iframe, overlay, acp, measured));
38428
39324
  const resolveHits = deps.resolveHits;
38429
- const picks = resolveHits ? await resolveHits(elements) : await resolveDomEditSelections(elements, acp);
39325
+ const picks = resolveHits ? await resolveHits(hits.map((hit) => hit.element)) : await resolveMarqueeHits(iframe, hits, acp);
38430
39326
  const applySelection = deps.onMarqueeSelectRef.current;
38431
39327
  if (!applySelection) return;
38432
39328
  const result = applySelection(picks, mode);
@@ -38445,6 +39341,8 @@ function useMarqueeGestures(deps) {
38445
39341
  setMarqueeRect(null);
38446
39342
  setCandidateRects([]);
38447
39343
  candidatesRef.current = null;
39344
+ opaqueCandidatesRef.current = null;
39345
+ bandRef.current = null;
38448
39346
  }, []);
38449
39347
  const begin = useCallback58(
38450
39348
  (event) => {
@@ -38490,6 +39388,18 @@ function useMarqueeGestures(deps) {
38490
39388
  const overlay = deps.overlayRef.current;
38491
39389
  if (!iframe || !overlay) return;
38492
39390
  const acp = deps.activeCompositionPathRef.current ?? "index.html";
39391
+ bandRef.current = { rect, mode };
39392
+ if (!candidatesRef.current && previewFrameOpaque(iframe)) {
39393
+ if (opaqueCandidatesRef.current) return;
39394
+ const measuring = collectPreviewMarqueeCandidates(iframe, overlay);
39395
+ opaqueCandidatesRef.current = measuring;
39396
+ void measuring.then((hits2) => {
39397
+ if (opaqueCandidatesRef.current !== measuring || !bandRef.current) return;
39398
+ candidatesRef.current = hits2;
39399
+ showCandidates(bandRef.current.rect, bandRef.current.mode);
39400
+ });
39401
+ return;
39402
+ }
38493
39403
  candidatesRef.current ??= collectMarqueeCandidates(iframe, overlay, acp);
38494
39404
  let hits = hitsWithin(rect, candidatesRef.current);
38495
39405
  if (mode === "subtract") hits = hits.filter((h) => isSelectedElement(h.element));
@@ -38512,6 +39422,7 @@ function useMarqueeGestures(deps) {
38512
39422
  if (Math.hypot(dx, dy) < MARQUEE_THRESHOLD_PX) return;
38513
39423
  m.pastThreshold = true;
38514
39424
  candidatesRef.current = null;
39425
+ opaqueCandidatesRef.current = null;
38515
39426
  }
38516
39427
  const rect = {
38517
39428
  left: Math.min(m.startX, m.currentX),
@@ -38690,171 +39601,6 @@ function useCanvasContextMenuState({
38690
39601
 
38691
39602
  // src/components/editor/useDomEditOverlayRects.ts
38692
39603
  import { useRef as useRef69, useState as useState53 } from "react";
38693
-
38694
- // src/components/editor/previewOverlayRects.ts
38695
- import {
38696
- ROTATION_GATE_EPSILON_DEG as ROTATION_GATE_EPSILON_DEG2
38697
- } from "@hyperframes/core/runtime/editing-port";
38698
-
38699
- // src/player/lib/previewElements.ts
38700
- import {
38701
- EDITING_ELEMENT_HANDLE,
38702
- MAX_DESCRIBE_HANDLES,
38703
- MAX_ELEMENT_ENTRIES,
38704
- MAX_ELEMENT_VALUE,
38705
- MAX_GEOMETRY_CHILDREN
38706
- } from "@hyperframes/core/runtime/editing-port";
38707
- var isFields = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
38708
- var isHandle = (value) => typeof value === "string" && EDITING_ELEMENT_HANDLE.test(value);
38709
- var isText = (value) => typeof value === "string";
38710
- var isTextOrNull = (value) => value === null || typeof value === "string";
38711
- var isCount = (value) => Number.isSafeInteger(value) && value >= 0;
38712
- var isSource = (value) => isFields(value) && isTextOrNull(value.file) && isTextOrNull(value.compositionId) && isTextOrNull(value.originalCompositionId);
38713
- var isTextRecord = (value) => isFields(value) && Object.values(value).every(isText);
38714
- function hasPlainFields(value) {
38715
- const { matchesBefore, attributes, children } = value;
38716
- const groupsOk = matchesBefore === null || Array.isArray(matchesBefore) && matchesBefore.every((g) => isFields(g) && isSource(g.source) && isCount(g.count));
38717
- const attributesOk = Array.isArray(attributes) && attributes.every((a) => Array.isArray(a) && a.length === 2 && a.every(isText));
38718
- const childrenOk = Array.isArray(children) && children.every((c) => isFields(c) && (isHandle(c.handle) || isText(c.text)));
38719
- return groupsOk && attributesOk && childrenOk && typeof value.truncated === "boolean";
38720
- }
38721
- var isRect = (value) => isFields(value) && [value.x, value.y, value.width, value.height].every(Number.isFinite);
38722
- function readHit(value) {
38723
- if (!isFields(value) || !isHandle(value.handle) || !isText(value.tag)) return null;
38724
- return isRect(value.rect) ? value : null;
38725
- }
38726
- function readPreviewElement(value) {
38727
- if (!readHit(value) || !isFields(value)) return null;
38728
- if (value.parent !== null && !isHandle(value.parent)) return null;
38729
- if (!isTextOrNull(value.id) || !isTextOrNull(value.selector)) return null;
38730
- if (!isSource(value.source) || typeof value.locked !== "boolean") return null;
38731
- if (!isTextRecord(value.inlineStyles) || !isText(value.text)) return null;
38732
- return hasPlainFields(value) ? value : null;
38733
- }
38734
- async function previewPointerTargets(iframe, rootFractionX, rootFractionY) {
38735
- const params = { x: rootFractionX, y: rootFractionY };
38736
- const reply = await previewRequest(iframe, "pointer-targets", params);
38737
- const stack = reply?.stack;
38738
- if (!reply || !Array.isArray(stack)) return null;
38739
- return { target: readHit(reply.target), stack: stack.map(readHit).filter((hit) => hit !== null) };
38740
- }
38741
- async function describePreviewElements(iframe, handles) {
38742
- if (!handles.length || handles.length > MAX_DESCRIBE_HANDLES) return null;
38743
- const reply = await previewRequest(iframe, "describe", { handles: [...handles] });
38744
- const elements = reply?.elements;
38745
- if (!Array.isArray(elements) || elements.length !== handles.length) return null;
38746
- return elements.map((entry3, index2) => {
38747
- const element = readPreviewElement(entry3);
38748
- return element?.handle === handles[index2] ? element : null;
38749
- });
38750
- }
38751
- async function previewAncestors(iframe, handles) {
38752
- if (!handles.length || handles.length > MAX_DESCRIBE_HANDLES) return null;
38753
- const reply = await previewRequest(iframe, "ancestors", { handles: [...handles] });
38754
- const chains = reply?.ancestors;
38755
- if (!Array.isArray(chains) || chains.length !== handles.length) return null;
38756
- return chains.map(
38757
- (chain) => Array.isArray(chain) && chain.every(isHandle) ? chain : null
38758
- );
38759
- }
38760
- async function queryPreviewElements(iframe, selector) {
38761
- const reply = await previewRequest(iframe, "query", { selector });
38762
- const matches = reply?.matches;
38763
- if (!Array.isArray(matches) || typeof reply?.truncated !== "boolean") return null;
38764
- const ok = matches.every((m) => isFields(m) && isHandle(m.handle) && isSource(m.source));
38765
- return ok ? { matches, truncated: reply.truncated } : null;
38766
- }
38767
- function previewElementSourceFile(element, activeCompositionPath) {
38768
- return resolveElementSourceFile(element.source, activeCompositionPath);
38769
- }
38770
- function previewElementSelectorIndex(element, activeCompositionPath) {
38771
- if (!element.selector?.startsWith(".") || !element.matchesBefore) return void 0;
38772
- const file = previewElementSourceFile(element, activeCompositionPath);
38773
- return element.matchesBefore.filter((group) => resolveElementSourceFile(group.source, activeCompositionPath) === file).reduce((sum, group) => sum + group.count, 0);
38774
- }
38775
- var isPoint = (value) => isFields(value) && Number.isFinite(value.x) && Number.isFinite(value.y);
38776
- var isSizeOrNull = (value) => value === null || Number.isFinite(value) && value > 0;
38777
- var CORNERS = ["nw", "ne", "se", "sw"];
38778
- var isCorners = (value) => value === null || isFields(value) && CORNERS.every((corner) => isPoint(value[corner]));
38779
- var isSourceBox = (value) => value === null || isFields(value) && Number.isFinite(value.width) && Number.isFinite(value.height) && isSizeOrNull(value.declaredWidth) && isSizeOrNull(value.declaredHeight);
38780
- var isClipPath = (value) => value === null || isText(value) && value.length <= MAX_ELEMENT_VALUE;
38781
- var isBox = (value) => isFields(value) && isRect(value.rect) && Number.isFinite(value.angle) && isCorners(value.corners) && isSourceBox(value.source) && isClipPath(value.clipPath);
38782
- var readGeometry = (value) => {
38783
- if (!isBox(value) || !isFields(value) || typeof value.visible !== "boolean") return null;
38784
- const { members } = value;
38785
- const membersOk = members === null || Array.isArray(members) && members.length <= MAX_ELEMENT_ENTRIES && members.every(isRect);
38786
- return membersOk ? value : null;
38787
- };
38788
- async function previewGeometry(iframe, handles, children) {
38789
- if (!handles.length || handles.length > MAX_DESCRIBE_HANDLES) return null;
38790
- const params = { handles: [...handles], ...children ? { children } : {} };
38791
- const reply = await previewRequest(iframe, "geometry", params);
38792
- const elements = reply?.elements;
38793
- if (!Array.isArray(elements) || elements.length !== handles.length) return null;
38794
- const boxes = reply?.children;
38795
- const childrenOk = Array.isArray(boxes) && boxes.length <= MAX_GEOMETRY_CHILDREN && boxes.every(isBox);
38796
- return {
38797
- elements: elements.map(readGeometry),
38798
- children: children && childrenOk ? boxes : null
38799
- };
38800
- }
38801
-
38802
- // src/components/editor/previewOverlayRects.ts
38803
- var clientRect = ({ x, y, width, height }) => ({ left: x, top: y, width, height });
38804
- var baseRect = (scale, box) => frameRectToOverlay(scale, clientRect(box.rect), box.source);
38805
- function orientedRect(scale, box) {
38806
- const base2 = baseRect(scale, box);
38807
- if (Math.abs(box.angle) < ROTATION_GATE_EPSILON_DEG2) return base2;
38808
- return orientOverlayRect(
38809
- base2,
38810
- box.angle,
38811
- box.corners && frameCornersToOverlay(scale, box.corners)
38812
- );
38813
- }
38814
- function groupAwareRect(scale, geometry, oriented) {
38815
- if (!geometry.members)
38816
- return oriented ? orientedRect(scale, geometry) : baseRect(scale, geometry);
38817
- const rect = baseRect(scale, geometry);
38818
- const members = geometry.members.map(
38819
- (member) => frameRectToOverlay(scale, clientRect(member), null)
38820
- );
38821
- const union = resolveDomEditGroupOverlayRect(members);
38822
- return union ? { ...union, editScaleX: rect.editScaleX, editScaleY: rect.editScaleY } : rect;
38823
- }
38824
- function visibleRect(scale, box) {
38825
- const rect = orientedRect(scale, box);
38826
- return { ...rect, ...hugRectForClipPath(rect, box.clipPath) };
38827
- }
38828
- async function measurePreviewOverlay(iframe, overlayEl, targets) {
38829
- const handles = [.../* @__PURE__ */ new Set([targets.selection, targets.hover, ...targets.group])].filter(
38830
- (handle) => Boolean(handle)
38831
- );
38832
- const reply = handles.length ? await previewGeometry(iframe, handles, targets.selection ?? void 0) : { elements: [], children: null };
38833
- const scale = reply && computeOverlayRootScale(overlayEl, iframe, null);
38834
- if (!reply || !scale) return null;
38835
- const read2 = (handle) => handle ? reply.elements[handles.indexOf(handle)] ?? null : null;
38836
- const selected = read2(targets.selection);
38837
- const shown3 = selected?.visible ? selected : null;
38838
- const hovered = read2(targets.hover);
38839
- return {
38840
- selection: shown3 && groupAwareRect(scale, shown3, true),
38841
- children: shown3 ? (reply.children ?? []).map((box) => visibleRect(scale, box)).filter((rect) => rect.width > 2 && rect.height > 2) : [],
38842
- group: targets.group.map((handle) => {
38843
- const member = read2(handle);
38844
- const rect = member && groupAwareRect(scale, member, false);
38845
- return rect && { ...rect, ...hugRectForClipPath(rect, member.clipPath) };
38846
- }),
38847
- hover: hovered && groupAwareRect(scale, hovered, true)
38848
- };
38849
- }
38850
- async function measurePreviewRects(iframe, overlayEl, handles) {
38851
- const reply = await previewGeometry(iframe, handles);
38852
- const scale = reply && computeOverlayRootScale(overlayEl, iframe, null);
38853
- if (!reply || !scale) return null;
38854
- return reply.elements.map((geometry) => geometry && groupAwareRect(scale, geometry, true));
38855
- }
38856
-
38857
- // src/components/editor/useDomEditOverlayRects.ts
38858
39604
  function childRectsEqual(a, b) {
38859
39605
  if (a.length !== b.length) return false;
38860
39606
  for (let i = 0; i < a.length; i++) {
@@ -39539,6 +40285,7 @@ function restoreStyleProperty(element, property, value) {
39539
40285
  else element.style.removeProperty(property);
39540
40286
  }
39541
40287
  function restoreStudioBoxSize(element, previous) {
40288
+ endPreviewDraft(element, "restore");
39542
40289
  forgetStudioBoxSizeDraftBase(element);
39543
40290
  restoreStyleProperty(element, "width", previous.width);
39544
40291
  restoreStyleProperty(element, "height", previous.height);
@@ -39591,6 +40338,10 @@ function restoreStudioRotation(element, previous) {
39591
40338
  );
39592
40339
  }
39593
40340
  function restoreStudioPathOffset(element, previous) {
40341
+ endPreviewDraft(element, "restore");
40342
+ restoreStudioPathOffsetStyles(element, previous);
40343
+ }
40344
+ function restoreStudioPathOffsetStyles(element, previous) {
39594
40345
  if (previous.translate) element.style.setProperty("translate", previous.translate);
39595
40346
  else element.style.removeProperty("translate");
39596
40347
  if (previous.x) element.style.setProperty(STUDIO_OFFSET_X_PROP, previous.x);
@@ -39905,189 +40656,6 @@ function installStudioManualEditSeekReapply(win, apply) {
39905
40656
  return wrappedHfSeek || wrappedPlayerSeek || wrappedPlayerRenderSeek || wrappedTimelineSeek || wrappedPlayerPlay || wrappedTimelinePlay || wrappedPlayerPause || wrappedTimelinePause || wrappedNamedTimelineSeek || wrappedNamedTimelinePlay || wrappedNamedTimelinePause;
39906
40657
  }
39907
40658
 
39908
- // src/hooks/draggedGsapPosition.ts
39909
- var cssValue = (style, prop) => {
39910
- const value = style.getPropertyValue(prop).trim();
39911
- return value === "none" ? "" : value;
39912
- };
39913
- function readCssRotation(element, withRotate = true) {
39914
- const view = element.ownerDocument.defaultView;
39915
- if (!view) return 0;
39916
- const style = view.getComputedStyle(element);
39917
- const rotate2 = withRotate ? cssValue(style, "rotate") : "";
39918
- const scale = cssValue(style, "scale");
39919
- const transform = cssValue(style, "transform");
39920
- const angle = (list) => {
39921
- if (!list) return 0;
39922
- const m = new view.DOMMatrix(list);
39923
- return Math.atan2(m.b, m.a) * 180 / Math.PI;
39924
- };
39925
- const folded = [rotate2 && `rotate(${rotate2})`, scale && `scale(${scale.split(/\s+/).join(",")})`];
39926
- try {
39927
- return angle([...folded, transform].join(" ").trim());
39928
- } catch {
39929
- return angle(transform);
39930
- }
39931
- }
39932
- function readDragStamp(element) {
39933
- const read2 = (name) => Number.parseFloat(element.getAttribute(name) ?? "");
39934
- return {
39935
- origX: read2("data-hf-drag-initial-offset-x") || 0,
39936
- origY: read2("data-hf-drag-initial-offset-y") || 0,
39937
- baseX: read2("data-hf-drag-gsap-base-x"),
39938
- baseY: read2("data-hf-drag-gsap-base-y"),
39939
- at: readEditMoment(element)
39940
- };
39941
- }
39942
- function readEditMoment(element) {
39943
- const raw = element.getAttribute(STUDIO_EDIT_MOMENT_ATTR);
39944
- return raw ? JSON.parse(raw) : void 0;
39945
- }
39946
- var freezeDragStamp = (element) => ({
39947
- ...readDragStamp(element),
39948
- frozen: true
39949
- });
39950
- function computeDraggedGsapPosition(element, studioOffset, fallbackBase, stamp = readDragStamp(element)) {
39951
- const rotStyle = element.style.getPropertyValue("--hf-studio-rotation");
39952
- const rotDeg = Number.parseFloat(rotStyle) || 0;
39953
- const rad = -rotDeg * Math.PI / 180;
39954
- const cos = Math.cos(rad);
39955
- const sin = Math.sin(rad);
39956
- const deltaX = studioOffset.x - stamp.origX;
39957
- const deltaY = studioOffset.y - stamp.origY;
39958
- const adjX = deltaX * cos - deltaY * sin;
39959
- const adjY = deltaX * sin + deltaY * cos;
39960
- const baseGsapX = Number.isFinite(stamp.baseX) ? stamp.baseX : fallbackBase.x;
39961
- const baseGsapY = Number.isFinite(stamp.baseY) ? stamp.baseY : fallbackBase.y;
39962
- return {
39963
- newX: roundTo3(baseGsapX + adjX),
39964
- newY: roundTo3(baseGsapY + adjY),
39965
- baseGsapX,
39966
- baseGsapY
39967
- };
39968
- }
39969
- function restoreDragOffset(element, stamp = readDragStamp(element)) {
39970
- if (stamp.frozen) return;
39971
- element.style.setProperty("--hf-studio-offset-x", `${stamp.origX}px`);
39972
- element.style.setProperty("--hf-studio-offset-y", `${stamp.origY}px`);
39973
- element.removeAttribute("data-hf-drag-initial-offset-x");
39974
- element.removeAttribute("data-hf-drag-initial-offset-y");
39975
- }
39976
-
39977
- // src/components/editor/plainTranslate.ts
39978
- var TOKEN = /\s*(?:(\d*\.?\d+(?:e[-+]?\d+)?)(px|%)?|([a-z]+)\(|([-+*/(),]))/giy;
39979
- var FUNCTIONS = {
39980
- "(": ([a = Number.NaN]) => a,
39981
- "calc(": ([a = Number.NaN]) => a,
39982
- "min(": (args) => Math.min(...args),
39983
- "max(": (args) => Math.max(...args),
39984
- "clamp(": ([lo = Number.NaN, v = Number.NaN, hi = Number.NaN]) => Math.max(lo, Math.min(v, hi))
39985
- };
39986
- function tokenize(value, side) {
39987
- const tokens = [];
39988
- const end = value.trimEnd().length;
39989
- TOKEN.lastIndex = 0;
39990
- for (let m = TOKEN.exec(value); m; m = TOKEN.lastIndex < end ? TOKEN.exec(value) : null) {
39991
- if (m[1]) tokens.push(Number(m[1]) * (m[2] === "%" ? side / 100 : 1));
39992
- else tokens.push(m[3] ? `${m[3].toLowerCase()}(` : m[4] ?? "");
39993
- }
39994
- return TOKEN.lastIndex < end ? [] : tokens;
39995
- }
39996
- function evaluateLength(value, side) {
39997
- const tokens = tokenize(value, side);
39998
- let i = 0;
39999
- const next = () => tokens[i++];
40000
- const take = (...ops) => ops.includes(tokens[i]) && next();
40001
- function sum() {
40002
- let total2 = product();
40003
- for (let op = take("+", "-"); op; op = take("+", "-"))
40004
- total2 += (op === "+" ? 1 : -1) * product();
40005
- return total2;
40006
- }
40007
- function product() {
40008
- let total2 = unary();
40009
- for (let op = take("*", "/"); op; op = take("*", "/"))
40010
- total2 = op === "*" ? total2 * unary() : total2 / unary();
40011
- return total2;
40012
- }
40013
- function unary() {
40014
- return take("-") ? -unary() : atom();
40015
- }
40016
- function atom() {
40017
- const token = next();
40018
- if (typeof token === "number") return token;
40019
- const fn = FUNCTIONS[token ?? ""];
40020
- if (!fn) return Number.NaN;
40021
- const args = [sum()];
40022
- while (take(",")) args.push(sum());
40023
- return take(")") ? fn(args) : Number.NaN;
40024
- }
40025
- const total = tokens.length ? sum() : Number.NaN;
40026
- return i === tokens.length ? total : Number.NaN;
40027
- }
40028
- var CONTENT_BOXES = /* @__PURE__ */ new Set(["content-box", "fill-box"]);
40029
- function referenceBox(cs, size, a, b) {
40030
- const n = (prop) => Number.parseFloat(cs.getPropertyValue(prop)) || 0;
40031
- const pad2 = n(`padding-${a}`) + n(`padding-${b}`) + n(`border-${a}-width`) + n(`border-${b}-width`);
40032
- const content = n(size) - (cs.boxSizing === "border-box" ? pad2 : 0);
40033
- return CONTENT_BOXES.has(cs.getPropertyValue("transform-box")) ? content : content + pad2;
40034
- }
40035
- function readTranslatePx(el) {
40036
- const cs = el.ownerDocument.defaultView?.getComputedStyle(el);
40037
- const value = cs?.translate || el.style.getPropertyValue("translate") || "none";
40038
- if (value === "none") return { x: 0, y: 0 };
40039
- const [x = "0px", y = "0px"] = splitTopLevelWhitespace(value);
40040
- const side = (size, a, b) => cs ? referenceBox(cs, size, a, b) : 0;
40041
- return {
40042
- x: evaluateLength(x, side("width", "left", "right")),
40043
- y: evaluateLength(y, side("height", "top", "bottom"))
40044
- };
40045
- }
40046
- function readTranslatePxLeavingPercent(el) {
40047
- const value = el.ownerDocument.defaultView?.getComputedStyle(el).translate || "none";
40048
- const [x = "0px", y = "0px"] = value === "none" ? [] : splitTopLevelWhitespace(value);
40049
- const px = (part) => roundTo3(evaluateLength(part, 0)) || 0;
40050
- return { x: px(x), y: px(y) };
40051
- }
40052
- var UNREADABLE_TRANSLATE = "Studio can't read this layer's translate. Move it in the Code tab.";
40053
- function formatTranslatePx(p) {
40054
- return `${roundTo3(p.x)}px ${roundTo3(p.y)}px`;
40055
- }
40056
- var LEGACY_OFFSET_VARS = [STUDIO_OFFSET_X_PROP, STUDIO_OFFSET_Y_PROP];
40057
- function writePlainMove(el, p) {
40058
- writeTranslatePx(el, p);
40059
- const patches = [
40060
- { type: "inline-style", property: "translate", value: formatTranslatePx(p) },
40061
- {
40062
- type: "attribute",
40063
- property: STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR,
40064
- value: el.getAttribute(STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR)
40065
- }
40066
- ];
40067
- for (const prop of LEGACY_OFFSET_VARS.filter((v) => el.style.getPropertyValue(v))) {
40068
- el.style.removeProperty(prop);
40069
- patches.push({ type: "inline-style", property: prop, value: null });
40070
- }
40071
- if (el.hasAttribute(STUDIO_PATH_OFFSET_ATTR)) {
40072
- el.removeAttribute(STUDIO_PATH_OFFSET_ATTR);
40073
- patches.push({ type: "attribute", property: STUDIO_PATH_OFFSET_ATTR, value: null });
40074
- }
40075
- return patches;
40076
- }
40077
- function writeTranslatePx(el, p) {
40078
- if (!el.hasAttribute(STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR)) {
40079
- const own = el.style.getPropertyValue("translate");
40080
- el.setAttribute(STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR, styleUsesStudioOffset(own) ? "" : own);
40081
- }
40082
- el.style.setProperty("translate", formatTranslatePx(p));
40083
- }
40084
- function readMoveOffset(el, plainTranslate = editsPlainCss(el, "move")) {
40085
- return plainTranslate ? readTranslatePx(el) : readStudioPathOffset(el);
40086
- }
40087
- function readShownRotation(el) {
40088
- return editsPlainCss(el, "rotate") ? { angle: roundTo3(readCssRotation(el)) } : readStudioRotation(el);
40089
- }
40090
-
40091
40659
  // src/components/editor/manualOffsetDrag.ts
40092
40660
  function getOffsetDragGsap(element) {
40093
40661
  const win = element.ownerDocument.defaultView;
@@ -40233,7 +40801,7 @@ function measureManualOffsetDragScreenToOffsetMatrix(element, initialOffset, opt
40233
40801
  }
40234
40802
  return { ok: true, matrix: screenToOffset };
40235
40803
  } finally {
40236
- restoreStudioPathOffset(element, snapshot3);
40804
+ restoreStudioPathOffsetStyles(element, snapshot3);
40237
40805
  }
40238
40806
  }
40239
40807
  function resolveManualOffsetForPointerDelta(input) {
@@ -40282,6 +40850,7 @@ function createManualOffsetDragMember(input) {
40282
40850
  scaleY: input.rect.editScaleY,
40283
40851
  plainTranslate
40284
40852
  });
40853
+ endPreviewDraft(input.element, "keep");
40285
40854
  if (!measured.ok) {
40286
40855
  const scaleX = input.rect.editScaleX || 1;
40287
40856
  const scaleY = input.rect.editScaleY || 1;
@@ -40327,6 +40896,8 @@ function resolveManualOffsetDragMemberOffset(member, dx, dy) {
40327
40896
  });
40328
40897
  }
40329
40898
  function drawMemberOffset(member, offset, commit2) {
40899
+ const { x, y } = member.initialOffset;
40900
+ drawPreviewDraft(member.element, { translate: { x: offset.x - x, y: offset.y - y } });
40330
40901
  if (member.plainTranslate) writeTranslatePx(member.element, offset);
40331
40902
  else if (applyOffsetDragDraftViaGsap(member.element, offset, member.baseGsap)) return;
40332
40903
  else if (commit2) applyStudioPathOffset(member.element, offset);
@@ -40392,6 +40963,7 @@ function endManualOffsetDragMembers(members) {
40392
40963
  for (const member of members) {
40393
40964
  if (!isStudioManualEditGestureCurrent(member.element, member.gestureToken)) continue;
40394
40965
  endStudioManualEditGesture(member.element, member.gestureToken);
40966
+ endPreviewDraft(member.element, "keep");
40395
40967
  member.element.removeAttribute("data-hf-drag-initial-offset-x");
40396
40968
  member.element.removeAttribute("data-hf-drag-initial-offset-y");
40397
40969
  member.element.removeAttribute("data-hf-drag-gsap-base-x");
@@ -40445,6 +41017,13 @@ function showMemberPosition(member, position) {
40445
41017
  if (!member.plainTranslate)
40446
41018
  stampGestureBase(member.element, member.initialOffset, member.baseGsap);
40447
41019
  }
41020
+ function redrawMemberOnFrame(member) {
41021
+ const { element, initialOffset } = member;
41022
+ const offset = member.plainTranslate ? readTranslatePx(element) : readAppliedStudioPathOffset(element);
41023
+ const translate = { x: offset.x - initialOffset.x, y: offset.y - initialOffset.y };
41024
+ if (Number.isFinite(translate.x) && Number.isFinite(translate.y) && (translate.x || translate.y))
41025
+ drawPreviewDraft(element, { translate });
41026
+ }
40448
41027
  function manualOffsetMoveRevert(members) {
40449
41028
  const startPlacement = members.map((member) => placementOf(member.element));
40450
41029
  return () => {
@@ -40456,7 +41035,10 @@ function manualOffsetMoveRevert(members) {
40456
41035
  placement: startPlacement[i]
40457
41036
  })
40458
41037
  );
40459
- return () => members.forEach((member, i) => showMemberPosition(member, shown3[i]));
41038
+ return () => members.forEach((member, i) => {
41039
+ showMemberPosition(member, shown3[i]);
41040
+ redrawMemberOnFrame(member);
41041
+ });
40460
41042
  };
40461
41043
  }
40462
41044
  var GSAP_LOOK_PROPS = ["x", "y", "rotation", "scaleX", "scaleY"];
@@ -41291,295 +41873,6 @@ function editMoment(stamp) {
41291
41873
  return stamp?.at ?? playheadMoment();
41292
41874
  }
41293
41875
 
41294
- // src/components/editor/previewSelection.ts
41295
- import { resolveEditingAffordances } from "@hyperframes/core/editing";
41296
- import {
41297
- MAX_ELEMENT_ENTRIES as MAX_ELEMENT_ENTRIES2,
41298
- MAX_ELEMENT_VALUE as MAX_ELEMENT_VALUE2
41299
- } from "@hyperframes/core/runtime/editing-port";
41300
- var inertDocument;
41301
- var inert = () => inertDocument ??= document.implementation.createHTMLDocument("");
41302
- function inertElement(tag) {
41303
- try {
41304
- return inert().createElement(tag);
41305
- } catch {
41306
- return inert().createElement("div");
41307
- }
41308
- }
41309
- var standIns = /* @__PURE__ */ new WeakMap();
41310
- var standInHandles = /* @__PURE__ */ new WeakMap();
41311
- var standInAncestors = /* @__PURE__ */ new WeakMap();
41312
- function standInFor(iframe, element) {
41313
- const client = previewEditingClient(iframe);
41314
- const byHandle = standIns.get(client) ?? /* @__PURE__ */ new Map();
41315
- standIns.set(client, byHandle);
41316
- let standIn = byHandle.get(element.handle);
41317
- if (!standIn) {
41318
- standIn = inertElement(element.tag);
41319
- byHandle.set(element.handle, standIn);
41320
- standInHandles.set(standIn, element.handle);
41321
- }
41322
- return standIn;
41323
- }
41324
- function readable(element) {
41325
- const probe2 = inertElement(element.tag);
41326
- for (const [name, value] of element.attributes) {
41327
- if (name !== "id" && name !== "class" && !name.startsWith("data-")) continue;
41328
- try {
41329
- probe2.setAttribute(name, value);
41330
- } catch {
41331
- }
41332
- }
41333
- for (const [name, value] of Object.entries(element.inlineStyles)) {
41334
- probe2.style.setProperty(name, value);
41335
- }
41336
- probe2.textContent = element.text;
41337
- return probe2;
41338
- }
41339
- var attr = (element, name) => element.attributes.find(([key2]) => key2 === name)?.[1] ?? null;
41340
- var mayBeCut = (value) => value.length >= MAX_ELEMENT_VALUE2 || value.startsWith("data:") && value.endsWith(",");
41341
- function valuesWhole(element) {
41342
- if (!element.truncated) return true;
41343
- const styles = Object.values(element.inlineStyles);
41344
- if (element.attributes.length >= MAX_ELEMENT_ENTRIES2 || styles.length >= MAX_ELEMENT_ENTRIES2)
41345
- return false;
41346
- return ![...element.attributes.map(([, value]) => value), ...styles].some(mayBeCut);
41347
- }
41348
- var hasAudio = (element) => element.tag === "video" && attr(element, "muted") === null && isVideoAudible({ tag: "video", hasAudioAttr: attr(element, "data-has-audio"), muted: false });
41349
- var validSelector = (selector) => {
41350
- try {
41351
- inert().querySelector(selector);
41352
- return true;
41353
- } catch {
41354
- return false;
41355
- }
41356
- };
41357
- async function findPreviewElementForSelection(iframe, selection, activeCompositionPath) {
41358
- for (const { selector, index: index2 } of selectionLookups(selection)) {
41359
- if (!validSelector(selector)) continue;
41360
- const reply = await queryPreviewElements(iframe, selector);
41361
- if (!reply) return void 0;
41362
- const fromFile = reply.matches.filter(
41363
- ({ source }) => !selection.sourceFile || resolveElementSourceFile(source, activeCompositionPath) === selection.sourceFile
41364
- );
41365
- const match = fromFile[index2];
41366
- if (!match) {
41367
- if (reply.truncated) return void 0;
41368
- continue;
41369
- }
41370
- const [element] = await describePreviewElements(iframe, [match.handle]) ?? [];
41371
- return element ?? void 0;
41372
- }
41373
- return null;
41374
- }
41375
- async function findByClipId(iframe, element, sourceFile, path) {
41376
- if (!element.id || element.domId || element.selector || element.compositionSrc) return null;
41377
- const byId = await findPreviewElementForSelection(iframe, { id: element.id, sourceFile }, path);
41378
- if (byId !== null) return byId;
41379
- return findPreviewElementForSelection(iframe, { hfId: element.id, sourceFile }, path);
41380
- }
41381
- async function findPreviewElementForTimelineElement(iframe, element, options) {
41382
- const { target, sourceFile, rootFallback } = timelineElementLookup(element, options);
41383
- const path = options.activeCompositionPath;
41384
- const found = target && await findPreviewElementForSelection(iframe, target, path);
41385
- if (found !== null) return found;
41386
- const byClipId = await findByClipId(iframe, element, sourceFile, path);
41387
- if (byClipId !== null) return byClipId;
41388
- if (!rootFallback) return null;
41389
- const reply = await queryPreviewElements(iframe, "[data-composition-id]");
41390
- if (!reply) return void 0;
41391
- const root = reply.matches[0];
41392
- if (!root || resolveElementSourceFile(root.source, path) !== sourceFile) return null;
41393
- const [described] = await describePreviewElements(iframe, [root.handle]) ?? [];
41394
- return described ?? void 0;
41395
- }
41396
- async function previewChain(iframe, target) {
41397
- const [lineage] = await previewAncestors(iframe, [target.handle]) ?? [];
41398
- if (!lineage) return null;
41399
- const ancestors = lineage.length ? await describePreviewElements(iframe, lineage) : [];
41400
- if (!ancestors || ancestors.some((entry3) => entry3 === null)) return null;
41401
- const chain = [target, ...ancestors];
41402
- const linked = chain.every((node, i) => node.parent === (chain[i + 1]?.handle ?? null));
41403
- return linked ? chain : null;
41404
- }
41405
- function chainReader(chain) {
41406
- const root = chain.at(-1);
41407
- const body = chain.at(-2);
41408
- return {
41409
- attr,
41410
- selector: (node) => node.selector ?? void 0,
41411
- isDocumentRoot: (node) => node === root || node === body && node.tag === "body"
41412
- };
41413
- }
41414
- async function compositionRoot2(iframe, documentElement) {
41415
- const reply = await queryPreviewElements(iframe, "[data-composition-id]");
41416
- if (!reply) return null;
41417
- const first = reply.matches[0];
41418
- const [root] = first ? await describePreviewElements(iframe, [first.handle]) ?? [null] : [];
41419
- if (root === null) return null;
41420
- const element = root ?? documentElement;
41421
- const { x, y, width, height } = element.rect;
41422
- return {
41423
- rect: { left: x, top: y, width, height },
41424
- width: attr(element, "data-width"),
41425
- height: attr(element, "data-height")
41426
- };
41427
- }
41428
- function chainIndex(chain, read2, options) {
41429
- const active = options.activeGroupElement;
41430
- const activeHandle = active ? standInHandles.get(active) : void 0;
41431
- return selectionTargetIndex(chain, read2, {
41432
- exactTarget: options.exactTarget,
41433
- preferClipAncestor: options.preferClipAncestor,
41434
- activeGroupIndex: active ? chain.findIndex((node) => node.handle === activeHandle) : null
41435
- });
41436
- }
41437
- function previewIdentity(current2, path) {
41438
- const selector = current2.selector ?? void 0;
41439
- return {
41440
- id: current2.id || void 0,
41441
- hfId: attr(current2, "data-hf-id")?.trim() || void 0,
41442
- selector,
41443
- selectorIndex: selector ? previewElementSelectorIndex(current2, path) : void 0,
41444
- sourceFile: previewElementSourceFile(current2, path)
41445
- };
41446
- }
41447
- async function isPreviewCompositionRoot(iframe, chain, index2, computedStyles) {
41448
- const current2 = chain[index2];
41449
- if (attr(current2, "data-composition-id") !== null && !compositionSourceOf(current2)) return true;
41450
- const parent = chain[index2 + 1];
41451
- const underBody = parent?.tag === "body" && chainReader(chain).isDocumentRoot(parent);
41452
- if (!underBody || attr(current2, "data-hf-allow-root-edit") !== null) return false;
41453
- const { x, y, width, height } = current2.rect;
41454
- const rect = { left: x, top: y, width, height };
41455
- const root = await compositionRoot2(iframe, chain.at(-1));
41456
- return root && coversCompositionRoot({ rect, computedStyles }, root);
41457
- }
41458
- var compositionSourceOf = (element) => attr(element, "data-composition-src") ?? attr(element, "data-composition-file") ?? void 0;
41459
- async function resolvePreviewSelection(iframe, target, options) {
41460
- const chain = await previewChain(iframe, target);
41461
- const index2 = chain && chainIndex(chain, chainReader(chain), options);
41462
- if (!chain || index2 === null) return null;
41463
- const current2 = chain[index2];
41464
- if (!valuesWhole(current2)) return null;
41465
- const element = standInFor(iframe, current2);
41466
- standInAncestors.set(
41467
- element,
41468
- chain.slice(index2 + 1).map((node) => node.handle)
41469
- );
41470
- const identity = previewIdentity(current2, options.activeCompositionPath);
41471
- const compositionSrc = compositionSourceOf(current2);
41472
- const probe2 = readable(current2);
41473
- const inlineStyles = getInlineStyles(probe2);
41474
- const computedStyles = await previewComputedStyles(iframe, current2, [
41475
- ...CURATED_STYLE_PROPERTIES
41476
- ]);
41477
- if (!computedStyles) return null;
41478
- const isCompositionRoot = await isPreviewCompositionRoot(iframe, chain, index2, computedStyles);
41479
- if (isCompositionRoot === null) return null;
41480
- const isInsideLocked = chainLocked(chain, chainReader(chain), index2);
41481
- const { sourceFile } = identity;
41482
- const existsInSource = await existsInSourceFile(
41483
- options.previous,
41484
- element,
41485
- sourceFile,
41486
- identity,
41487
- options
41488
- );
41489
- const capabilities = resolveEditingAffordances(
41490
- capabilityFacts({
41491
- hasStableTarget: Boolean(identity.selector || identity.hfId),
41492
- tag: current2.tag,
41493
- inlineStyles,
41494
- computedStyles,
41495
- isCompositionHost: Boolean(compositionSrc),
41496
- isCompositionRoot,
41497
- isInsideLockedComposition: isInsideLocked,
41498
- isMasterView: options.isMasterView,
41499
- existsInSource: existsInSource ?? true
41500
- })
41501
- ).capabilities;
41502
- const { x, y, width, height } = current2.rect;
41503
- return {
41504
- element,
41505
- handle: current2.handle,
41506
- hasAudio: hasAudio(current2),
41507
- src: attr(current2, "src"),
41508
- ...identity,
41509
- compositionPath: sourceFile,
41510
- compositionSrc,
41511
- isCompositionHost: Boolean(compositionSrc),
41512
- isInsideLockedComposition: isInsideLocked,
41513
- label: buildElementLabel(probe2),
41514
- tagName: current2.tag,
41515
- boundingBox: { x, y, width, height },
41516
- textContent: current2.text.trim() || null,
41517
- dataAttributes: getDataAttributes(probe2),
41518
- inlineStyles,
41519
- computedStyles,
41520
- textFields: [],
41521
- capabilities,
41522
- existsInSource
41523
- };
41524
- }
41525
- function liveElementForSelection(iframe, selection, activeCompositionPath) {
41526
- let doc = null;
41527
- try {
41528
- doc = iframe?.contentDocument ?? null;
41529
- } catch {
41530
- return void 0;
41531
- }
41532
- return doc ? findElementForSelection(doc, selection, activeCompositionPath) : void 0;
41533
- }
41534
- async function findSelectionElement(iframe, selection, activeCompositionPath) {
41535
- return iframe && previewFrameOpaque(iframe) ? findPreviewElementForSelection(iframe, selection, activeCompositionPath) : liveElementForSelection(iframe, selection, activeCompositionPath);
41536
- }
41537
- async function resolveFoundSelection(iframe, found, options) {
41538
- if (isHtmlElement(found)) return resolveDomEditSelection(found, options);
41539
- return iframe ? resolvePreviewSelection(iframe, found, options) : null;
41540
- }
41541
- async function findOpaqueTimelineElement(iframe, element, lookup2) {
41542
- if (!iframe || !previewFrameOpaque(iframe)) return null;
41543
- return await findPreviewElementForTimelineElement(iframe, element, lookup2) ?? null;
41544
- }
41545
- function elementWithin(container, element) {
41546
- const handle = standInHandles.get(container);
41547
- if (handle === void 0) return container.contains(element);
41548
- return element === container || (standInAncestors.get(element)?.includes(handle) ?? false);
41549
- }
41550
- function selectionDataAttribute(selection, name) {
41551
- if (!selection.handle) return selection.element.getAttribute(name);
41552
- return selection.dataAttributes[name.slice("data-".length)] ?? null;
41553
- }
41554
- var pointerAnswers = /* @__PURE__ */ new WeakMap();
41555
- async function previewPointerTarget(iframe, clientX, clientY) {
41556
- const { x, y } = framePointFraction(iframe, clientX, clientY);
41557
- const reply = await previewPointerTargets(iframe, x, y);
41558
- if (reply) pointerAnswers.set(iframe, { x: clientX, y: clientY, found: reply.target !== null });
41559
- return reply;
41560
- }
41561
- function pointerMayHitElement(iframe, clientX, clientY) {
41562
- if (!previewFrameOpaque(iframe))
41563
- return Boolean(getPreviewTargetFromPointer(iframe, clientX, clientY));
41564
- const answer = pointerAnswers.get(iframe);
41565
- return answer?.x === clientX && answer.y === clientY ? answer.found : true;
41566
- }
41567
- async function findPointerTarget(iframe, clientX, clientY) {
41568
- if (!previewFrameOpaque(iframe)) return getPreviewTargetFromPointer(iframe, clientX, clientY);
41569
- const reply = await previewPointerTarget(iframe, clientX, clientY);
41570
- if (!reply?.target) return reply ? null : void 0;
41571
- const [described] = await describePreviewElements(iframe, [reply.target.handle]) ?? [];
41572
- return described ?? void 0;
41573
- }
41574
- async function findPointerTargets(iframe, clientX, clientY) {
41575
- if (!previewFrameOpaque(iframe)) return getAllPreviewTargetsFromPointer(iframe, clientX, clientY);
41576
- const reply = await previewPointerTarget(iframe, clientX, clientY);
41577
- const handles = reply?.stack.map((hit) => hit.handle) ?? [];
41578
- const described = handles.length ? await describePreviewElements(iframe, handles) : [];
41579
- return (described ?? []).filter((element) => element !== null);
41580
- }
41581
- var selectionElementLive = (selection) => selection.handle !== void 0 || selection.element.isConnected;
41582
-
41583
41876
  // src/components/editor/previewGestureStarts.ts
41584
41877
  var MAX_SETTLED_WAIT_FRAMES = 60;
41585
41878
  var PRESS_WAIT_MAX_MS = 1e4;
@@ -41874,7 +42167,34 @@ function resolveAnchoredResizeDraft(g, member, element, overlayEl, iframe, measu
41874
42167
  angle: g.actualRotation
41875
42168
  };
41876
42169
  }
42170
+ function resolveUnmeasuredResizeDraft(g, element, { written }) {
42171
+ const width = g.originWidth * written.width / g.actualWidth;
42172
+ const height = g.originHeight * written.height / g.actualHeight;
42173
+ if (g.pathOffsetMember) {
42174
+ const anchor2 = {
42175
+ dx: (g.actualWidth - written.width) / 2 * g.editScaleX,
42176
+ dy: (g.actualHeight - written.height) / 2 * g.editScaleY
42177
+ };
42178
+ g.lastResizeAnchor = anchor2;
42179
+ applyManualOffsetDragDraft(g.pathOffsetMember, anchor2.dx, anchor2.dy);
42180
+ }
42181
+ drawPreviewDraft(element, { size: written });
42182
+ return {
42183
+ left: g.originLeft + (g.originWidth - width) / 2,
42184
+ top: g.originTop + (g.originHeight - height) / 2,
42185
+ width,
42186
+ height,
42187
+ editScaleX: g.editScaleX,
42188
+ editScaleY: g.editScaleY,
42189
+ angle: g.actualRotation
42190
+ };
42191
+ }
42192
+ function endResizeWithoutMember(element, token) {
42193
+ if (!token || isStudioManualEditGestureCurrent(element, token)) endPreviewDraft(element, "keep");
42194
+ endStudioManualEditGesture(element, token);
42195
+ }
41877
42196
  function resolveResizeDraftRect(g, element, overlayEl, iframe, measureOrientedRect, sizes) {
42197
+ if (iframe && previewFrameOpaque(iframe)) return resolveUnmeasuredResizeDraft(g, element, sizes);
41878
42198
  if (g.pathOffsetMember) {
41879
42199
  return resolveAnchoredResizeDraft(
41880
42200
  g,
@@ -42445,7 +42765,7 @@ function createDomEditOverlayGestureHandlers(opts) {
42445
42765
  logGestureCommitFailure("resize commit failed", error);
42446
42766
  }).finally(() => {
42447
42767
  if (member) endManualOffsetDragMembers([member]);
42448
- else endStudioManualEditGesture(sel.element, g.manualEditDragToken);
42768
+ else endResizeWithoutMember(sel.element, g.manualEditDragToken);
42449
42769
  });
42450
42770
  edit.settle(saved2);
42451
42771
  logResizeSettle(sel.element, "post-release");
@@ -44603,7 +44923,7 @@ function placeCaretAtEnd(element) {
44603
44923
  }
44604
44924
 
44605
44925
  // src/components/editor/domEditInlineText.ts
44606
- import { isRichTextFormattingTag as isRichTextFormattingTag2 } from "@hyperframes/core/rich-text-sanitize";
44926
+ import { hasOnlyFormattingChildren } from "@hyperframes/core/runtime/editing-port";
44607
44927
  function canEditTextInline(selection) {
44608
44928
  if (!selection) return false;
44609
44929
  if (!isTextEditableSelection(selection)) return false;
@@ -44620,17 +44940,6 @@ function canEditElementTextInline(element) {
44620
44940
  if (element.isContentEditable) return false;
44621
44941
  return (element.textContent ?? "").trim().length > 0;
44622
44942
  }
44623
- function hasOnlyFormattingChildren(element) {
44624
- for (const child of Array.from(element.children)) {
44625
- if (!isRichTextFormattingTag2(child.tagName)) return false;
44626
- if (!isHtmlFromAnyWindow(child)) return false;
44627
- if (!hasOnlyFormattingChildren(child)) return false;
44628
- }
44629
- return true;
44630
- }
44631
- function isHtmlFromAnyWindow(node) {
44632
- return node.namespaceURI === "http://www.w3.org/1999/xhtml";
44633
- }
44634
44943
  var DOUBLE_PRESS_MS = 450;
44635
44944
  var DOUBLE_PRESS_SLOP_PX = 6;
44636
44945
  function isDoublePress(previous, next) {
@@ -52282,9 +52591,14 @@ function useTimelineSelectionPreviewSync({
52282
52591
  const currentDomEditGroupSelections = domEditGroupSelectionsRef.current;
52283
52592
  const currentSelections = currentDomEditGroupSelections.length > 1 ? currentDomEditGroupSelections : currentDomEditSelection ? [currentDomEditSelection] : [];
52284
52593
  const currentIds = currentSelections.map(
52285
- (selection) => resolveTimelineIdForSelection(selection, timelineElements, activeCompPath)
52594
+ (selection) => resolveTimelineIdForSelection(selection, timelineElements, activeCompPath, true)
52286
52595
  ).filter((id) => Boolean(id));
52287
- const currentAnchor = currentDomEditSelection ? resolveTimelineIdForSelection(currentDomEditSelection, timelineElements, activeCompPath) : null;
52596
+ const currentAnchor = currentDomEditSelection ? resolveTimelineIdForSelection(
52597
+ currentDomEditSelection,
52598
+ timelineElements,
52599
+ activeCompPath,
52600
+ true
52601
+ ) : null;
52288
52602
  if (selectedIds.length === 0) {
52289
52603
  missingSelectionKeyRef.current = "";
52290
52604
  unresolvedAttemptsRef.current = { id: "", count: 0 };
@@ -77419,7 +77733,7 @@ function useEditorSave({
77419
77733
  if (lastFailureToastAtRef.current === null || now2 - lastFailureToastAtRef.current >= FAILURE_BURST_MS) {
77420
77734
  lastFailureToastAtRef.current = now2;
77421
77735
  showToast(
77422
- `Couldn't save ${path}. Your latest edits are NOT persisted. Check the preview server; editing again retries the save.`,
77736
+ heldFileWords(error) ?? `Couldn't save ${path}. Your latest edits are NOT persisted. Check the preview server; editing again retries the save.`,
77423
77737
  "error"
77424
77738
  );
77425
77739
  }
@@ -77508,7 +77822,8 @@ async function fetchProjectFile(projectId, path, query) {
77508
77822
  const response = await studioApiFetch(
77509
77823
  `/api/projects/${encodeURIComponent(projectId)}/files/${encodeURIComponent(path)}${query}`
77510
77824
  );
77511
- if (!response.ok) throw new Error(`Failed to read ${path}`);
77825
+ if (!response.ok)
77826
+ throw await createStudioSaveHttpError(response, `Failed to read ${path}`, { path });
77512
77827
  const data = await response.json();
77513
77828
  return { content: data.content, version: data.version ?? response.headers.get("etag") };
77514
77829
  }
@@ -77561,7 +77876,9 @@ function useProjectFileWriter({ projectId }) {
77561
77876
  } else if (preflight.status === 404) {
77562
77877
  expectedVersion = null;
77563
77878
  } else {
77564
- throw await createStudioSaveHttpError(preflight, `Failed to read ${path} before save`);
77879
+ throw await createStudioSaveHttpError(preflight, `Failed to read ${path} before save`, {
77880
+ path
77881
+ });
77565
77882
  }
77566
77883
  }
77567
77884
  await retryStudioSave(async () => {
@@ -77598,7 +77915,8 @@ function useProjectFileWriter({ projectId }) {
77598
77915
  attemptedContent: content
77599
77916
  });
77600
77917
  }
77601
- if (!response.ok) throw await createStudioSaveHttpError(response, `Failed to save ${path}`);
77918
+ if (!response.ok)
77919
+ throw await createStudioSaveHttpError(response, `Failed to save ${path}`, { path });
77602
77920
  const result = await response.json();
77603
77921
  const version = result.version ?? response.headers.get("etag");
77604
77922
  if (!version)
@@ -78950,7 +79268,9 @@ async function insertTimelineComposition(input) {
78950
79268
  buildProjectApiPath(input.projectId, `/files/${encodeURIComponent(input.targetPath)}`)
78951
79269
  );
78952
79270
  if (!current2.ok) {
78953
- throw await createStudioSaveHttpError(current2, `Failed to read ${input.targetPath}`);
79271
+ throw await createStudioSaveHttpError(current2, `Failed to read ${input.targetPath}`, {
79272
+ path: input.targetPath
79273
+ });
78954
79274
  }
78955
79275
  const snapshot3 = await current2.json();
78956
79276
  if (typeof snapshot3.version !== "string") throw new Error("Missing composition file version");
@@ -81883,6 +82203,7 @@ import { HF_AUDIO_GROUP_TAG as HF_AUDIO_GROUP_TAG7 } from "@hyperframes/core/aud
81883
82203
  function announceTimelineSelection(deps, group, primary, replaceSet = false) {
81884
82204
  const {
81885
82205
  timelineElements,
82206
+ activeCompPath,
81886
82207
  getTimelineSelectionSet: getTimelineSelectionSet2,
81887
82208
  setSelectedTimelineElementId,
81888
82209
  setTimelineSelectionSet
@@ -81892,7 +82213,7 @@ function announceTimelineSelection(deps, group, primary, replaceSet = false) {
81892
82213
  setSelectedTimelineElementId(null);
81893
82214
  return;
81894
82215
  }
81895
- const timelineIdFor = (selection) => findMatchingTimelineElementId(selection, timelineElements) ?? findTimelineIdByAncestor(
82216
+ const timelineIdFor = (selection) => findMatchingTimelineElementId(selection, timelineElements, activeCompPath || "index.html") ?? findTimelineIdByAncestor(
81896
82217
  selection.element,
81897
82218
  timelineElements,
81898
82219
  selection.sourceFile || "index.html"
@@ -81962,6 +82283,7 @@ function useDomSelection({
81962
82283
  (group, primary, replaceSet) => announceTimelineSelection(
81963
82284
  {
81964
82285
  timelineElements,
82286
+ activeCompPath,
81965
82287
  getTimelineSelectionSet: getTimelineSelectionSet2,
81966
82288
  setSelectedTimelineElementId,
81967
82289
  setTimelineSelectionSet
@@ -81971,6 +82293,7 @@ function useDomSelection({
81971
82293
  replaceSet
81972
82294
  ),
81973
82295
  [
82296
+ activeCompPath,
81974
82297
  getTimelineSelectionSet2,
81975
82298
  setSelectedTimelineElementId,
81976
82299
  setTimelineSelectionSet,
@@ -82342,6 +82665,7 @@ function usePreviewInteraction({
82342
82665
  }) {
82343
82666
  const cycleRef = useRef149(null);
82344
82667
  const lastDownRef = useRef149(null);
82668
+ const hoverSeqRef = useRef149(0);
82345
82669
  const pausePreviewPlayback = useCallback130(() => {
82346
82670
  const pausedTime = pauseStudioPreviewPlayback(previewIframeRef.current);
82347
82671
  const playerStore = usePlayerStore.getState();
@@ -82457,6 +82781,7 @@ function usePreviewInteraction({
82457
82781
  const handlePreviewCanvasPointerMove = useCallback130(
82458
82782
  // fallow-ignore-next-line complexity
82459
82783
  async (e, options) => {
82784
+ const seq = ++hoverSeqRef.current;
82460
82785
  if (captionEditMode || compositionLoading) {
82461
82786
  updateDomEditHoverSelection(null);
82462
82787
  return null;
@@ -82465,7 +82790,7 @@ function usePreviewInteraction({
82465
82790
  preferClipAncestor: options?.preferClipAncestor ?? false,
82466
82791
  skipSourceProbe: true
82467
82792
  });
82468
- updateDomEditHoverSelection(nextSelection);
82793
+ if (seq === hoverSeqRef.current) updateDomEditHoverSelection(nextSelection);
82469
82794
  return nextSelection;
82470
82795
  },
82471
82796
  [
@@ -82476,6 +82801,7 @@ function usePreviewInteraction({
82476
82801
  ]
82477
82802
  );
82478
82803
  const handlePreviewCanvasPointerLeave = useCallback130(() => {
82804
+ hoverSeqRef.current += 1;
82479
82805
  updateDomEditHoverSelection(null);
82480
82806
  }, [updateDomEditHoverSelection]);
82481
82807
  const handleBlockedDomMove = useCallback130(
@@ -96784,25 +97110,13 @@ import { memo as memo62, useCallback as useCallback192 } from "react";
96784
97110
  import { memo as memo52, useState as useState153, useCallback as useCallback176, useEffect as useEffect151, useRef as useRef184 } from "react";
96785
97111
 
96786
97112
  // src/components/editor/layerKind.ts
96787
- function isCompositionHost(el) {
96788
- return el.hasAttribute("data-composition-src") || el.hasAttribute("data-composition-file");
96789
- }
96790
- function layerKindOf(el, hasChildren) {
96791
- const tag = el.tagName.toLowerCase();
96792
- if (tag === "img" || tag === "picture") return "image";
96793
- if (tag === "video") return "video";
96794
- if (tag === "audio") return "audio";
96795
- if (tag === "svg") return "vector";
96796
- if (el.hasAttribute("data-hf-group") || isCompositionHost(el)) return "group";
96797
- if (hasOnlyFormattingChildren(el) && el.textContent?.trim()) return "text";
96798
- return hasChildren ? "group" : "shape";
96799
- }
97113
+ import { isCompositionHost, layerKindOf } from "@hyperframes/core/runtime/editing-port";
96800
97114
 
96801
97115
  // src/components/editor/useLayerDrag.ts
96802
97116
  import { useRef as useRef183, useState as useState152, useCallback as useCallback175 } from "react";
96803
97117
  var DRAG_THRESHOLD_PX4 = 4;
96804
97118
  function isLayerDraggable(layer) {
96805
- if (!(layer.selector || layer.id)) return false;
97119
+ if (!(layer.selector || layer.id) || layer.preview) return false;
96806
97120
  let el = layer.element;
96807
97121
  while (el) {
96808
97122
  if (el.hasAttribute("data-timeline-locked")) return false;
@@ -96977,8 +97291,8 @@ function sortLayersByZIndex(layers) {
96977
97291
  return layers;
96978
97292
  }
96979
97293
  chunks.sort((a, b) => {
96980
- const zA = getElementZIndex(a.root.element);
96981
- const zB = getElementZIndex(b.root.element);
97294
+ const zA = a.root.preview?.zIndex ?? getElementZIndex(a.root.element);
97295
+ const zB = b.root.preview?.zIndex ?? getElementZIndex(b.root.element);
96982
97296
  if (zA !== zB) return zB - zA;
96983
97297
  return b.domIndex - a.domIndex;
96984
97298
  });
@@ -97078,9 +97392,24 @@ var LayersPanel = memo52(function LayersPanel2({ host }) {
97078
97392
  });
97079
97393
  const isMasterView = !activeCompPath || activeCompPath === "index.html";
97080
97394
  const livePreviewIframe = useLivePreviewIframe();
97395
+ const opaqueRead = useRef184(null);
97081
97396
  const collectLayers = useCallback176(() => {
97082
97397
  const iframe = previewIframeRef.current;
97083
97398
  if (!iframe) return;
97399
+ if (previewFrameOpaque(iframe)) {
97400
+ if (opaqueRead.current) return void (opaqueRead.current.again = true);
97401
+ const read2 = { again: false };
97402
+ opaqueRead.current = read2;
97403
+ const scope = { activeCompositionPath: activeCompPath, activeGroupElement };
97404
+ void collectPreviewLayerItems(iframe, scope, LAYERS_PANEL_MAX_ROWS).then((reply) => {
97405
+ if (opaqueRead.current !== read2) return;
97406
+ opaqueRead.current = null;
97407
+ if (reply?.missingGroup) return setActiveGroupElement(null);
97408
+ if (reply) setLayers(sortLayersByZIndex(reply.items));
97409
+ if (read2.again) collectLayers();
97410
+ });
97411
+ return;
97412
+ }
97084
97413
  let doc = null;
97085
97414
  try {
97086
97415
  doc = iframe.contentDocument;
@@ -97101,6 +97430,7 @@ var LayersPanel = memo52(function LayersPanel2({ host }) {
97101
97430
  setLayers(sortLayersByZIndex(items));
97102
97431
  }, [previewIframeRef, activeCompPath, isMasterView, activeGroupElement, setActiveGroupElement]);
97103
97432
  useEffect151(() => {
97433
+ opaqueRead.current = null;
97104
97434
  collectLayers();
97105
97435
  }, [collectLayers, refreshKey, zEditVersion, livePreviewIframe]);
97106
97436
  useEffect151(() => {
@@ -97127,15 +97457,20 @@ var LayersPanel = memo52(function LayersPanel2({ host }) {
97127
97457
  };
97128
97458
  }, [collectLayers]);
97129
97459
  const resolveSelection = useCallback176(
97130
- (layer) => {
97131
- const doc = previewIframeRef.current?.contentDocument;
97132
- const el = liveLayerElement(layer, doc, activeCompPath);
97133
- return resolveDomEditSelection(el, {
97460
+ async (layer) => {
97461
+ const iframe = previewIframeRef.current;
97462
+ const options = {
97134
97463
  activeCompositionPath: activeCompPath,
97135
97464
  isMasterView,
97136
97465
  preferClipAncestor: false,
97137
97466
  activeGroupElement
97138
- });
97467
+ };
97468
+ if (layer.preview && iframe) {
97469
+ const [described] = await describePreviewElements(iframe, [layer.preview.handle]) ?? [];
97470
+ return described ? resolvePreviewSelection(iframe, described, options) : null;
97471
+ }
97472
+ const el = liveLayerElement(layer, iframe?.contentDocument, activeCompPath);
97473
+ return resolveDomEditSelection(el, options);
97139
97474
  },
97140
97475
  [activeCompPath, isMasterView, previewIframeRef, activeGroupElement]
97141
97476
  );
@@ -97143,7 +97478,8 @@ var LayersPanel = memo52(function LayersPanel2({ host }) {
97143
97478
  async (layer) => {
97144
97479
  const selection = await resolveSelection(layer);
97145
97480
  if (!selection) return;
97146
- let matchedId = findMatchingTimelineElementId(selection, timelineElements);
97481
+ const scope = activeCompPath || "index.html";
97482
+ let matchedId = findMatchingTimelineElementId(selection, timelineElements, scope);
97147
97483
  if (!matchedId) {
97148
97484
  const sourceFile = selection.sourceFile ?? "index.html";
97149
97485
  let ancestor = layer.element.parentElement;
@@ -97166,7 +97502,7 @@ var LayersPanel = memo52(function LayersPanel2({ host }) {
97166
97502
  }
97167
97503
  }
97168
97504
  },
97169
- [currentTime, resolveSelection, timelineElements]
97505
+ [activeCompPath, currentTime, resolveSelection, timelineElements]
97170
97506
  );
97171
97507
  const handleSelectLayer = useCallback176(
97172
97508
  async (layer) => {
@@ -97181,7 +97517,7 @@ var LayersPanel = memo52(function LayersPanel2({ host }) {
97181
97517
  const handleLayerDoubleClick = useCallback176(
97182
97518
  async (layer) => {
97183
97519
  const selection = await resolveSelection(layer);
97184
- if (selection?.element.hasAttribute("data-hf-group")) {
97520
+ if (selection && selectionDataAttribute(selection, "data-hf-group") !== null) {
97185
97521
  setActiveGroupElement(selection.element);
97186
97522
  } else {
97187
97523
  await handleSelectLayer(layer);
@@ -97327,8 +97663,8 @@ var LayersPanel = memo52(function LayersPanel2({ host }) {
97327
97663
  const draggable = isLayerDraggable(layer);
97328
97664
  const isCollapsed = collapsed[layer.key] ?? false;
97329
97665
  const hasChildren = layer.childCount > 0;
97330
- const isCompHost = isCompositionHost(layer.element);
97331
- const kind = layerKindOf(layer.element, hasChildren);
97666
+ const isCompHost = layer.preview ? layerDataAttribute(layer, "data-composition-src") !== null || layerDataAttribute(layer, "data-composition-file") !== null : isCompositionHost(layer.element);
97667
+ const kind = layer.preview?.kind ?? layerKindOf(layer.element, hasChildren);
97332
97668
  const KindIcon = KIND_ICON[kind];
97333
97669
  const kindName = kind[0].toUpperCase() + kind.slice(1);
97334
97670
  const hint = draggable ? layer.element.hasAttribute("data-hf-group") ? "Double-click to enter group" : void 0 : "This layer can't be reordered";