@hyperframes/studio 0.9.41 → 0.9.43

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 (61) hide show
  1. package/dist/assets/{codec-B_mpbc4w.js → codec-DHChmhF2.js} +1 -1
  2. package/dist/assets/{hyperframes-player-Dvi3I_mv.js → hyperframes-player-CdbweVDs.js} +1 -1
  3. package/dist/assets/{index-B5ExwsOp.js → index-CjWDrWWG.js} +166 -166
  4. package/dist/assets/{index-BrFm9Y5k.js → index-l-ti2dV8.js} +1 -1
  5. package/dist/assets/{pausedVideoDecoder-MHQ57yZ6.js → pausedVideoDecoder-xqOQ0ciK.js} +1 -1
  6. package/dist/index.d.ts +9 -1
  7. package/dist/index.html +1 -1
  8. package/dist/index.js +1380 -989
  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/domEditOverlayGeometry.ts +2 -0
  14. package/src/components/editor/domEditOverlayStartGesture.ts +31 -7
  15. package/src/components/editor/domEditingTypes.ts +7 -1
  16. package/src/components/editor/gestureUndoRevert.ts +18 -1
  17. package/src/components/editor/inlineTextStyleRange.fill.test.ts +129 -0
  18. package/src/components/editor/inlineTextStyleRange.test.ts +0 -82
  19. package/src/components/editor/layerKind.ts +2 -19
  20. package/src/components/editor/layersPanelSort.ts +2 -2
  21. package/src/components/editor/manualEdits.ts +1 -0
  22. package/src/components/editor/manualEditsSnapshot.ts +10 -0
  23. package/src/components/editor/manualOffsetDrag.test.ts +1 -1
  24. package/src/components/editor/manualOffsetDrag.ts +17 -6
  25. package/src/components/editor/marqueeCommit.ts +47 -4
  26. package/src/components/editor/plainTranslate.ts +37 -16
  27. package/src/components/editor/previewDrafts.test.ts +263 -0
  28. package/src/components/editor/previewDrafts.ts +73 -0
  29. package/src/components/editor/previewGestureStartRead.test.ts +279 -0
  30. package/src/components/editor/previewGestureStartRead.ts +67 -0
  31. package/src/components/editor/previewGestureStarts.ts +21 -15
  32. package/src/components/editor/previewLayers.test.ts +308 -0
  33. package/src/components/editor/previewLayers.ts +164 -0
  34. package/src/components/editor/previewOverlayRects.test.ts +62 -0
  35. package/src/components/editor/previewOverlayRects.ts +23 -8
  36. package/src/components/editor/previewPointerTargets.test.ts +68 -1
  37. package/src/components/editor/previewSelection.ts +55 -11
  38. package/src/components/editor/resizeDraft.ts +38 -0
  39. package/src/components/editor/snapTargetCollection.ts +26 -62
  40. package/src/components/editor/useDomEditOverlayGestures.ts +2 -2
  41. package/src/components/editor/useLayerDrag.ts +1 -1
  42. package/src/components/nle/NLEPreview.slowBoot.test.ts +0 -1
  43. package/src/hooks/domEditDeleteMembers.test.ts +7 -0
  44. package/src/hooks/domSelectionTimelineMirror.ts +3 -1
  45. package/src/hooks/timelineTimingSync.ts +4 -1
  46. package/src/hooks/useDomSelection.ts +2 -0
  47. package/src/hooks/useEditorSave.test.tsx +22 -1
  48. package/src/hooks/useEditorSave.ts +3 -1
  49. package/src/hooks/usePreviewInteraction.ts +4 -1
  50. package/src/hooks/useProjectFileWriter.ts +7 -3
  51. package/src/hooks/useTimelineSelectionPreviewSync.test.tsx +30 -0
  52. package/src/hooks/useTimelineSelectionPreviewSync.ts +7 -2
  53. package/src/player/lib/layerOrdering.ts +2 -11
  54. package/src/player/lib/previewElements.ts +68 -0
  55. package/src/test-setup.ts +2 -0
  56. package/src/utils/gsapSoftReload.ts +1 -1
  57. package/src/utils/studioFileHistory.ts +1 -1
  58. package/src/utils/studioHelpers.ts +27 -4
  59. package/src/utils/studioSaveDiagnostics.test.ts +34 -0
  60. package/src/utils/studioSaveDiagnostics.ts +35 -6
  61. 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,352 +38370,8 @@ 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
 
38352
- // src/components/editor/marqueeCommit.ts
38353
- function currentMarqueeCandidates(cached5, iframe, overlay, path) {
38354
- if (cached5?.every((hit) => hit.element.ownerDocument === iframe.contentDocument)) return cached5;
38355
- return collectMarqueeCandidates(iframe, overlay, path);
38356
- }
38357
- var MARQUEE_THRESHOLD_PX = 4;
38358
- function collectMarqueeCandidates(iframe, overlayEl, activeCompositionPath) {
38359
- const doc = iframe.contentDocument;
38360
- if (!doc) return [];
38361
- const root = doc.querySelector("[data-composition-id]") ?? doc.body;
38362
- const isMasterView = !activeCompositionPath || activeCompositionPath === "index.html";
38363
- const items = collectDomEditLayerItems(root, { activeCompositionPath, isMasterView });
38364
- const rootEl = doc.querySelector("[data-composition-id]") ?? doc.documentElement;
38365
- const declW = Number.parseFloat(rootEl?.getAttribute("data-width") ?? "");
38366
- const declH = Number.parseFloat(rootEl?.getAttribute("data-height") ?? "");
38367
- const viewport2 = {
38368
- width: declW > 0 ? declW : rootEl.getBoundingClientRect().width || 1,
38369
- height: declH > 0 ? declH : rootEl.getBoundingClientRect().height || 1
38370
- };
38371
- const candidates = [];
38372
- for (const item of items) {
38373
- const el = item.element;
38374
- if (!isElementComputedVisible(el)) continue;
38375
- if (coversComposition(el.getBoundingClientRect(), viewport2)) continue;
38376
- const overlayRect = toVisibleOverlayRect(overlayEl, iframe, el);
38377
- if (!overlayRect) continue;
38378
- candidates.push({
38379
- element: el,
38380
- rect: {
38381
- left: overlayRect.left,
38382
- top: overlayRect.top,
38383
- width: overlayRect.width,
38384
- height: overlayRect.height
38385
- }
38386
- });
38387
- }
38388
- return candidates;
38389
- }
38390
- function hitsWithin(rect, candidates) {
38391
- return candidates.filter((candidate) => rectsOverlap(rect, candidate.rect));
38392
- }
38393
- async function resolveDomEditSelections(elements, activeCompositionPath) {
38394
- const isMasterView = !activeCompositionPath || activeCompositionPath === "index.html";
38395
- const hits = [];
38396
- for (const element of elements) {
38397
- const sel = await resolveDomEditSelection(element, {
38398
- activeCompositionPath,
38399
- isMasterView,
38400
- skipSourceProbe: true
38401
- });
38402
- if (sel) hits.push(sel);
38403
- }
38404
- return hits;
38405
- }
38406
- function trackMarqueeSelection(result) {
38407
- if (result?.changed && result.count > 1) trackPreviewFeatureUsed("multi_select", "drag");
38408
- }
38409
- function releaseCapture(m) {
38410
- try {
38411
- m.target.releasePointerCapture(m.pointerId);
38412
- } catch {
38413
- }
38414
- }
38415
- function useMarqueeGestures(deps) {
38416
- const marqueeRef = useRef67(null);
38417
- const [marqueeRect, setMarqueeRect] = useState50(null);
38418
- const [candidateRects, setCandidateRects] = useState50([]);
38419
- const candidatesRef = useRef67(null);
38420
- const commitMarquee = useCallback58(
38421
- async (rect, mode) => {
38422
- const iframe = deps.iframeRef.current;
38423
- const overlay = deps.overlayRef.current;
38424
- if (!iframe || !overlay || !deps.onMarqueeSelectRef.current) return;
38425
- 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);
38428
- const resolveHits = deps.resolveHits;
38429
- const picks = resolveHits ? await resolveHits(elements) : await resolveDomEditSelections(elements, acp);
38430
- const applySelection = deps.onMarqueeSelectRef.current;
38431
- if (!applySelection) return;
38432
- const result = applySelection(picks, mode);
38433
- trackMarqueeSelection(result);
38434
- },
38435
- [
38436
- deps.iframeRef,
38437
- deps.overlayRef,
38438
- deps.onMarqueeSelectRef,
38439
- deps.activeCompositionPathRef,
38440
- deps.resolveHits
38441
- ]
38442
- );
38443
- const reset = useCallback58(() => {
38444
- marqueeRef.current = null;
38445
- setMarqueeRect(null);
38446
- setCandidateRects([]);
38447
- candidatesRef.current = null;
38448
- }, []);
38449
- const begin = useCallback58(
38450
- (event) => {
38451
- const oRect = deps.overlayRef.current?.getBoundingClientRect();
38452
- if (!oRect) return;
38453
- event.currentTarget.setPointerCapture(event.pointerId);
38454
- const x = event.clientX - oRect.left;
38455
- const y = event.clientY - oRect.top;
38456
- marqueeRef.current = {
38457
- startX: x,
38458
- startY: y,
38459
- currentX: x,
38460
- currentY: y,
38461
- pointerId: event.pointerId,
38462
- pastThreshold: false,
38463
- target: event.currentTarget
38464
- };
38465
- },
38466
- [deps.overlayRef]
38467
- );
38468
- const cancel = useCallback58(() => {
38469
- if (!marqueeRef.current) return;
38470
- releaseCapture(marqueeRef.current);
38471
- reset();
38472
- }, [reset]);
38473
- useEffect50(() => {
38474
- const cancelBandBeforeHostEscape = (e) => {
38475
- if (!matchesKey(e, "cancel") || !marqueeRef.current) return;
38476
- e.preventDefault();
38477
- e.stopPropagation();
38478
- cancel();
38479
- };
38480
- window.addEventListener("keydown", cancelBandBeforeHostEscape, { capture: true });
38481
- return () => window.removeEventListener("keydown", cancelBandBeforeHostEscape, { capture: true });
38482
- }, [cancel]);
38483
- const isSelectedElement = useCallback58(
38484
- (element) => deps.selectionRef?.current?.element === element || (deps.groupSelectionsRef?.current ?? []).some((s) => s.element === element),
38485
- [deps.selectionRef, deps.groupSelectionsRef]
38486
- );
38487
- const showCandidates = useCallback58(
38488
- (rect, mode) => {
38489
- const iframe = deps.iframeRef.current;
38490
- const overlay = deps.overlayRef.current;
38491
- if (!iframe || !overlay) return;
38492
- const acp = deps.activeCompositionPathRef.current ?? "index.html";
38493
- candidatesRef.current ??= collectMarqueeCandidates(iframe, overlay, acp);
38494
- let hits = hitsWithin(rect, candidatesRef.current);
38495
- if (mode === "subtract") hits = hits.filter((h) => isSelectedElement(h.element));
38496
- setCandidateRects(hits.map((h) => h.rect));
38497
- },
38498
- [deps.overlayRef, deps.iframeRef, deps.activeCompositionPathRef, isSelectedElement]
38499
- );
38500
- const onPointerMove = useCallback58(
38501
- (event) => {
38502
- const m = marqueeRef.current;
38503
- if (m) {
38504
- if (!movesGesture(m, event)) return;
38505
- const oRect = deps.overlayRef.current?.getBoundingClientRect();
38506
- if (!oRect) return;
38507
- m.currentX = event.clientX - oRect.left;
38508
- m.currentY = event.clientY - oRect.top;
38509
- if (!m.pastThreshold) {
38510
- const dx = m.currentX - m.startX;
38511
- const dy = m.currentY - m.startY;
38512
- if (Math.hypot(dx, dy) < MARQUEE_THRESHOLD_PX) return;
38513
- m.pastThreshold = true;
38514
- candidatesRef.current = null;
38515
- }
38516
- const rect = {
38517
- left: Math.min(m.startX, m.currentX),
38518
- top: Math.min(m.startY, m.currentY),
38519
- width: Math.abs(m.currentX - m.startX),
38520
- height: Math.abs(m.currentY - m.startY)
38521
- };
38522
- const mode = resolveMarqueeMode(event);
38523
- setMarqueeRect({ ...rect, mode });
38524
- showCandidates(rect, mode);
38525
- return;
38526
- }
38527
- deps.gestures?.onPointerMove(event);
38528
- },
38529
- [deps.gestures, deps.overlayRef, showCandidates]
38530
- );
38531
- const onPointerUp = useCallback58(
38532
- (event) => {
38533
- const m = marqueeRef.current;
38534
- if (m) {
38535
- releaseCapture(m);
38536
- if (m.pastThreshold) {
38537
- commitMarquee(
38538
- {
38539
- left: Math.min(m.startX, m.currentX),
38540
- top: Math.min(m.startY, m.currentY),
38541
- width: Math.abs(m.currentX - m.startX),
38542
- height: Math.abs(m.currentY - m.startY)
38543
- },
38544
- resolveMarqueeMode(event)
38545
- );
38546
- } else {
38547
- deps.onMarqueeSelectRef.current?.([], "replace");
38548
- }
38549
- reset();
38550
- return;
38551
- }
38552
- deps.gestures?.onPointerUp(event);
38553
- },
38554
- [deps.gestures, commitMarquee, deps.onMarqueeSelectRef, reset]
38555
- );
38556
- const onPointerCancel = useCallback58(() => {
38557
- if (marqueeRef.current) return cancel();
38558
- if (deps.selectionRef) deps.gestures?.clearPointerState(deps.selectionRef);
38559
- }, [deps.gestures, deps.selectionRef, cancel]);
38560
- return {
38561
- marqueeRect,
38562
- candidateRects,
38563
- begin,
38564
- cancel,
38565
- onPointerMove,
38566
- onPointerUp,
38567
- onPointerCancel
38568
- };
38569
- }
38570
-
38571
- // src/components/editor/MarqueeOverlay.tsx
38572
- import { Fragment as Fragment27, jsx as jsx99, jsxs as jsxs69 } from "react/jsx-runtime";
38573
- function MarqueeOverlay({ candidateRects, marqueeRect }) {
38574
- const subtracting = marqueeRect?.mode === "subtract";
38575
- const candidateClass = subtracting ? "border-danger bg-danger/5" : "border-studio-accent bg-studio-accent/5";
38576
- const bandClass = subtracting ? "border-danger bg-danger/10" : "border-studio-accent bg-studio-accent/10";
38577
- return /* @__PURE__ */ jsxs69(Fragment27, { children: [
38578
- candidateRects.map((r, i) => /* @__PURE__ */ jsx99(
38579
- "div",
38580
- {
38581
- "aria-hidden": "true",
38582
- className: `pointer-events-none absolute rounded-xs border ${candidateClass}`,
38583
- style: { left: r.left, top: r.top, width: r.width, height: r.height }
38584
- },
38585
- i
38586
- )),
38587
- marqueeRect && /* @__PURE__ */ jsx99(
38588
- "div",
38589
- {
38590
- "aria-hidden": "true",
38591
- "data-marquee-mode": marqueeRect.mode,
38592
- className: `pointer-events-none absolute border border-dashed ${bandClass}`,
38593
- style: {
38594
- left: marqueeRect.left,
38595
- top: marqueeRect.top,
38596
- width: marqueeRect.width,
38597
- height: marqueeRect.height
38598
- }
38599
- }
38600
- )
38601
- ] });
38602
- }
38603
-
38604
- // src/components/editor/useZOrderCrossedFlash.tsx
38605
- import { useCallback as useCallback59, useEffect as useEffect51, useRef as useRef68, useState as useState51 } from "react";
38606
- import { jsx as jsx100 } from "react/jsx-runtime";
38607
- var Z_ORDER_CROSSED_FLASH_MS = 600;
38608
- function useZOrderCrossedFlash({ overlayRef, iframeRef }) {
38609
- const [zOrderFlashRect, setZOrderFlashRect] = useState51(null);
38610
- const timeoutRef = useRef68(null);
38611
- useEffect51(
38612
- () => () => {
38613
- if (timeoutRef.current) clearTimeout(timeoutRef.current);
38614
- },
38615
- []
38616
- );
38617
- const handleZOrderCrossed = useCallback59(
38618
- (crossed) => {
38619
- const overlayEl = overlayRef.current;
38620
- const iframe = iframeRef.current;
38621
- if (!overlayEl || !iframe) return;
38622
- const rect = toVisibleOverlayRect(overlayEl, iframe, crossed);
38623
- if (!rect || rect.width <= 0 || rect.height <= 0) return;
38624
- if (timeoutRef.current) clearTimeout(timeoutRef.current);
38625
- setZOrderFlashRect(rect);
38626
- timeoutRef.current = setTimeout(() => {
38627
- timeoutRef.current = null;
38628
- setZOrderFlashRect(null);
38629
- }, Z_ORDER_CROSSED_FLASH_MS);
38630
- },
38631
- [overlayRef, iframeRef]
38632
- );
38633
- return { zOrderFlashRect, handleZOrderCrossed };
38634
- }
38635
- function ZOrderCrossedFlash({ rect }) {
38636
- if (!rect) return null;
38637
- return /* @__PURE__ */ jsx100(
38638
- "div",
38639
- {
38640
- "aria-hidden": "true",
38641
- "data-dom-edit-z-flash": "true",
38642
- className: "pointer-events-none absolute rounded-md border-2 border-studio-accent shadow-[0_0_0_2px_rgba(60,230,172,0.35)] animate-pulse",
38643
- style: { left: rect.left, top: rect.top, width: rect.width, height: rect.height }
38644
- }
38645
- );
38646
- }
38647
-
38648
- // src/components/editor/useCanvasContextMenuState.ts
38649
- import { useCallback as useCallback60, useEffect as useEffect52, useState as useState52 } from "react";
38650
- function useCanvasContextMenuState({
38651
- selection,
38652
- selectionRef,
38653
- hoverSelectionRef,
38654
- onCanvasPointerMoveRef,
38655
- onSelectionChangeRef
38656
- }) {
38657
- const [contextMenu, setContextMenu] = useState52(null);
38658
- const closeContextMenu = useCallback60(() => setContextMenu(null), []);
38659
- useEffect52(() => {
38660
- if (!contextMenu) return;
38661
- if (!selection || selection.element !== contextMenu.sel.element) {
38662
- setContextMenu(null);
38663
- }
38664
- }, [selection, contextMenu]);
38665
- const handleContextMenu = useCallback60(
38666
- async (event) => {
38667
- event.preventDefault();
38668
- const currentSel = selectionRef.current;
38669
- let activeSel = currentSel;
38670
- if (!currentSel) {
38671
- const pointerEvent = event;
38672
- const resolved2 = await onCanvasPointerMoveRef.current(pointerEvent);
38673
- if (!resolved2) return;
38674
- onSelectionChangeRef.current(resolved2, { revealPanel: true });
38675
- activeSel = resolved2;
38676
- } else {
38677
- const hover = hoverSelectionRef.current;
38678
- if (hover && hover.element !== currentSel.element) {
38679
- onSelectionChangeRef.current(hover, { revealPanel: true });
38680
- activeSel = hover;
38681
- }
38682
- }
38683
- if (!activeSel) return;
38684
- setContextMenu({ x: event.clientX, y: event.clientY, sel: activeSel });
38685
- },
38686
- [selectionRef, hoverSelectionRef, onCanvasPointerMoveRef, onSelectionChangeRef]
38687
- );
38688
- return { contextMenu, closeContextMenu, handleContextMenu };
38689
- }
38690
-
38691
- // src/components/editor/useDomEditOverlayRects.ts
38692
- 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";
38373
+ // src/components/editor/previewLayers.ts
38374
+ import { MAX_DESCRIBE_HANDLES as MAX_DESCRIBE_HANDLES4 } from "@hyperframes/core/runtime/editing-port";
38698
38375
 
38699
38376
  // src/player/lib/previewElements.ts
38700
38377
  import {
@@ -38702,7 +38379,8 @@ import {
38702
38379
  MAX_DESCRIBE_HANDLES,
38703
38380
  MAX_ELEMENT_ENTRIES,
38704
38381
  MAX_ELEMENT_VALUE,
38705
- MAX_GEOMETRY_CHILDREN
38382
+ MAX_GEOMETRY_CHILDREN,
38383
+ MAX_SNAP_TARGETS
38706
38384
  } from "@hyperframes/core/runtime/editing-port";
38707
38385
  var isFields = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
38708
38386
  var isHandle = (value) => typeof value === "string" && EDITING_ELEMENT_HANDLE.test(value);
@@ -38798,8 +38476,44 @@ async function previewGeometry(iframe, handles, children) {
38798
38476
  children: children && childrenOk ? boxes : null
38799
38477
  };
38800
38478
  }
38479
+ var isFlag = (value) => typeof value === "boolean";
38480
+ var isFiniteFields = (value, keys) => isFields(value) && keys.every((key2) => Number.isFinite(value[key2]));
38481
+ var readGestureStart = (value) => {
38482
+ if (!readGeometry(value) || !isFields(value)) return null;
38483
+ const { layout, move, gsap: gsap3 } = value;
38484
+ const valid = [
38485
+ isFiniteFields(layout, ["width", "height"]),
38486
+ move === null || isFiniteFields(move, ["a", "b", "c", "d"]),
38487
+ gsap3 === null || isFields(gsap3) && isFiniteFields(gsap3, ["x", "y"]) && isFlag(gsap3.moving)
38488
+ ];
38489
+ return valid.includes(false) ? null : value;
38490
+ };
38491
+ async function previewGestureStart(iframe, handles) {
38492
+ if (!handles.length || handles.length > MAX_DESCRIBE_HANDLES) return null;
38493
+ const reply = await previewRequest(iframe, "gesture-start", { handles: [...handles] });
38494
+ const elements = reply?.elements;
38495
+ const snap = reply?.snap;
38496
+ if (!Array.isArray(elements) || elements.length !== handles.length) return null;
38497
+ if (!Array.isArray(snap) || snap.length > MAX_SNAP_TARGETS || !snap.every(isBox)) return null;
38498
+ return { elements: elements.map(readGestureStart), snap };
38499
+ }
38500
+ var LAYER_KINDS = /* @__PURE__ */ new Set(["image", "video", "audio", "vector", "group", "text", "shape"]);
38501
+ var isLayer = (value) => isFields(value) && isHandle(value.handle) && isCount(value.depth) && isCount(value.childCount) && Number.isFinite(value.zIndex) && LAYER_KINDS.has(value.kind);
38502
+ async function previewLayers(iframe, group, offset = 0) {
38503
+ const params = { ...group ? { group } : {}, ...offset ? { offset } : {} };
38504
+ const reply = await previewRequest(iframe, "layers", params);
38505
+ const layers = reply?.layers;
38506
+ const { truncated, missingGroup } = reply ?? {};
38507
+ if (!Array.isArray(layers) || typeof truncated !== "boolean") return null;
38508
+ if (typeof missingGroup !== "boolean") return null;
38509
+ return layers.every(isLayer) ? { layers, truncated, missingGroup } : null;
38510
+ }
38801
38511
 
38802
38512
  // src/components/editor/previewOverlayRects.ts
38513
+ import {
38514
+ MAX_DESCRIBE_HANDLES as MAX_DESCRIBE_HANDLES2,
38515
+ ROTATION_GATE_EPSILON_DEG as ROTATION_GATE_EPSILON_DEG2
38516
+ } from "@hyperframes/core/runtime/editing-port";
38803
38517
  var clientRect = ({ x, y, width, height }) => ({ left: x, top: y, width, height });
38804
38518
  var baseRect = (scale, box) => frameRectToOverlay(scale, clientRect(box.rect), box.source);
38805
38519
  function orientedRect(scale, box) {
@@ -38821,40 +38535,1088 @@ function groupAwareRect(scale, geometry, oriented) {
38821
38535
  const union = resolveDomEditGroupOverlayRect(members);
38822
38536
  return union ? { ...union, editScaleX: rect.editScaleX, editScaleY: rect.editScaleY } : rect;
38823
38537
  }
38824
- function visibleRect(scale, box) {
38825
- const rect = orientedRect(scale, box);
38826
- return { ...rect, ...hugRectForClipPath(rect, box.clipPath) };
38538
+ function flatVisibleRect(scale, box) {
38539
+ const rect = baseRect(scale, box);
38540
+ return { ...rect, ...hugRectForClipPath(rect, box.clipPath) };
38541
+ }
38542
+ function visibleRect(scale, box) {
38543
+ const rect = orientedRect(scale, box);
38544
+ return { ...rect, ...hugRectForClipPath(rect, box.clipPath) };
38545
+ }
38546
+ async function measurePreviewOverlay(iframe, overlayEl, targets) {
38547
+ const handles = [.../* @__PURE__ */ new Set([targets.selection, targets.hover, ...targets.group])].filter(
38548
+ (handle) => Boolean(handle)
38549
+ );
38550
+ const reply = handles.length ? await previewGeometry(iframe, handles, targets.selection ?? void 0) : { elements: [], children: null };
38551
+ const scale = reply && computeOverlayRootScale(overlayEl, iframe, null);
38552
+ if (!reply || !scale) return null;
38553
+ const read2 = (handle) => handle ? reply.elements[handles.indexOf(handle)] ?? null : null;
38554
+ const selected = read2(targets.selection);
38555
+ const shown3 = selected?.visible ? selected : null;
38556
+ const hovered = read2(targets.hover);
38557
+ return {
38558
+ selection: shown3 && groupAwareRect(scale, shown3, true),
38559
+ children: shown3 ? (reply.children ?? []).map((box) => visibleRect(scale, box)).filter((rect) => rect.width > 2 && rect.height > 2) : [],
38560
+ group: targets.group.map((handle) => {
38561
+ const member = read2(handle);
38562
+ const rect = member && groupAwareRect(scale, member, false);
38563
+ return rect && { ...rect, ...hugRectForClipPath(rect, member.clipPath) };
38564
+ }),
38565
+ hover: hovered && groupAwareRect(scale, hovered, true)
38566
+ };
38567
+ }
38568
+ async function measurePreviewVisibleRects(iframe, overlayEl, handles) {
38569
+ const measured = [];
38570
+ for (let at = 0; at < handles.length; at += MAX_DESCRIBE_HANDLES2) {
38571
+ const reply = await previewGeometry(iframe, handles.slice(at, at + MAX_DESCRIBE_HANDLES2));
38572
+ const scale = reply && computeOverlayRootScale(overlayEl, iframe, null);
38573
+ if (!reply || !scale) return null;
38574
+ for (const box of reply.elements) {
38575
+ measured.push(
38576
+ box && { rect: flatVisibleRect(scale, box), frame: box.rect, visible: box.visible }
38577
+ );
38578
+ }
38579
+ }
38580
+ return measured;
38581
+ }
38582
+
38583
+ // src/components/editor/previewSelection.ts
38584
+ import { resolveEditingAffordances } from "@hyperframes/core/editing";
38585
+ import {
38586
+ MAX_ELEMENT_ENTRIES as MAX_ELEMENT_ENTRIES2,
38587
+ MAX_ELEMENT_VALUE as MAX_ELEMENT_VALUE2
38588
+ } from "@hyperframes/core/runtime/editing-port";
38589
+
38590
+ // src/components/editor/previewDrafts.ts
38591
+ import { MAX_DESCRIBE_HANDLES as MAX_DESCRIBE_HANDLES3 } from "@hyperframes/core/runtime/editing-port";
38592
+ var standIns = /* @__PURE__ */ new WeakMap();
38593
+ var queues = /* @__PURE__ */ new WeakMap();
38594
+ function registerPreviewStandIn(standIn, iframe, handle) {
38595
+ standIns.set(standIn, { iframe, handle });
38596
+ }
38597
+ function queueFor(iframe) {
38598
+ let queue2 = queues.get(iframe);
38599
+ if (!queue2) {
38600
+ queue2 = { ops: [], drawn: /* @__PURE__ */ new Map(), sending: false };
38601
+ queues.set(iframe, queue2);
38602
+ }
38603
+ return queue2;
38604
+ }
38605
+ function send2(iframe, queue2) {
38606
+ if (queue2.sending || !queue2.ops.length) return;
38607
+ const drafts = queue2.ops.splice(0, MAX_DESCRIBE_HANDLES3);
38608
+ queue2.sending = true;
38609
+ void previewRequest(iframe, "draft", { drafts }).finally(() => {
38610
+ queue2.sending = false;
38611
+ send2(iframe, queue2);
38612
+ });
38613
+ }
38614
+ function drawPreviewDraft(element, part) {
38615
+ const target = standIns.get(element);
38616
+ if (!target) return;
38617
+ const queue2 = queueFor(target.iframe);
38618
+ const drawn = { translate: null, size: null, ...queue2.drawn.get(target.handle), ...part };
38619
+ queue2.drawn.set(target.handle, drawn);
38620
+ const op = { handle: target.handle, ...drawn };
38621
+ const last = queue2.ops.map((queued) => queued.handle).lastIndexOf(target.handle);
38622
+ const waiting = queue2.ops[last];
38623
+ if (waiting && !("end" in waiting)) queue2.ops[last] = op;
38624
+ else queue2.ops.push(op);
38625
+ send2(target.iframe, queue2);
38626
+ }
38627
+ function endPreviewDraft(element, end) {
38628
+ const target = standIns.get(element);
38629
+ if (!target) return;
38630
+ const queue2 = queueFor(target.iframe);
38631
+ if (!queue2.drawn.delete(target.handle)) return;
38632
+ queue2.ops.push({ handle: target.handle, end });
38633
+ send2(target.iframe, queue2);
38634
+ }
38635
+
38636
+ // src/hooks/draggedGsapPosition.ts
38637
+ var cssValue = (style, prop) => {
38638
+ const value = style.getPropertyValue(prop).trim();
38639
+ return value === "none" ? "" : value;
38640
+ };
38641
+ function readCssRotation(element, withRotate = true) {
38642
+ const view = element.ownerDocument.defaultView;
38643
+ if (!view) return 0;
38644
+ const style = view.getComputedStyle(element);
38645
+ const rotate2 = withRotate ? cssValue(style, "rotate") : "";
38646
+ const scale = cssValue(style, "scale");
38647
+ const transform = cssValue(style, "transform");
38648
+ const angle = (list) => {
38649
+ if (!list) return 0;
38650
+ const m = new view.DOMMatrix(list);
38651
+ return Math.atan2(m.b, m.a) * 180 / Math.PI;
38652
+ };
38653
+ const folded = [rotate2 && `rotate(${rotate2})`, scale && `scale(${scale.split(/\s+/).join(",")})`];
38654
+ try {
38655
+ return angle([...folded, transform].join(" ").trim());
38656
+ } catch {
38657
+ return angle(transform);
38658
+ }
38659
+ }
38660
+ function readDragStamp(element) {
38661
+ const read2 = (name) => Number.parseFloat(element.getAttribute(name) ?? "");
38662
+ return {
38663
+ origX: read2("data-hf-drag-initial-offset-x") || 0,
38664
+ origY: read2("data-hf-drag-initial-offset-y") || 0,
38665
+ baseX: read2("data-hf-drag-gsap-base-x"),
38666
+ baseY: read2("data-hf-drag-gsap-base-y"),
38667
+ at: readEditMoment(element)
38668
+ };
38669
+ }
38670
+ function readEditMoment(element) {
38671
+ const raw = element.getAttribute(STUDIO_EDIT_MOMENT_ATTR);
38672
+ return raw ? JSON.parse(raw) : void 0;
38673
+ }
38674
+ var freezeDragStamp = (element) => ({
38675
+ ...readDragStamp(element),
38676
+ frozen: true
38677
+ });
38678
+ function computeDraggedGsapPosition(element, studioOffset, fallbackBase, stamp = readDragStamp(element)) {
38679
+ const rotStyle = element.style.getPropertyValue("--hf-studio-rotation");
38680
+ const rotDeg = Number.parseFloat(rotStyle) || 0;
38681
+ const rad = -rotDeg * Math.PI / 180;
38682
+ const cos = Math.cos(rad);
38683
+ const sin = Math.sin(rad);
38684
+ const deltaX = studioOffset.x - stamp.origX;
38685
+ const deltaY = studioOffset.y - stamp.origY;
38686
+ const adjX = deltaX * cos - deltaY * sin;
38687
+ const adjY = deltaX * sin + deltaY * cos;
38688
+ const baseGsapX = Number.isFinite(stamp.baseX) ? stamp.baseX : fallbackBase.x;
38689
+ const baseGsapY = Number.isFinite(stamp.baseY) ? stamp.baseY : fallbackBase.y;
38690
+ return {
38691
+ newX: roundTo3(baseGsapX + adjX),
38692
+ newY: roundTo3(baseGsapY + adjY),
38693
+ baseGsapX,
38694
+ baseGsapY
38695
+ };
38696
+ }
38697
+ function restoreDragOffset(element, stamp = readDragStamp(element)) {
38698
+ if (stamp.frozen) return;
38699
+ element.style.setProperty("--hf-studio-offset-x", `${stamp.origX}px`);
38700
+ element.style.setProperty("--hf-studio-offset-y", `${stamp.origY}px`);
38701
+ element.removeAttribute("data-hf-drag-initial-offset-x");
38702
+ element.removeAttribute("data-hf-drag-initial-offset-y");
38703
+ }
38704
+
38705
+ // src/components/editor/plainTranslate.ts
38706
+ var TOKEN = /\s*(?:(\d*\.?\d+(?:e[-+]?\d+)?)(px|%)?|([a-z]+)\(|([-+*/(),]))/giy;
38707
+ var FUNCTIONS = {
38708
+ "(": ([a = Number.NaN]) => a,
38709
+ "calc(": ([a = Number.NaN]) => a,
38710
+ "min(": (args) => Math.min(...args),
38711
+ "max(": (args) => Math.max(...args),
38712
+ "clamp(": ([lo = Number.NaN, v = Number.NaN, hi = Number.NaN]) => Math.max(lo, Math.min(v, hi))
38713
+ };
38714
+ function tokenize(value, side) {
38715
+ const tokens = [];
38716
+ const end = value.trimEnd().length;
38717
+ TOKEN.lastIndex = 0;
38718
+ for (let m = TOKEN.exec(value); m; m = TOKEN.lastIndex < end ? TOKEN.exec(value) : null) {
38719
+ if (m[1]) tokens.push(Number(m[1]) * (m[2] === "%" ? side / 100 : 1));
38720
+ else tokens.push(m[3] ? `${m[3].toLowerCase()}(` : m[4] ?? "");
38721
+ }
38722
+ return TOKEN.lastIndex < end ? [] : tokens;
38723
+ }
38724
+ function evaluateLength(value, side) {
38725
+ const tokens = tokenize(value, side);
38726
+ let i = 0;
38727
+ const next = () => tokens[i++];
38728
+ const take = (...ops) => ops.includes(tokens[i]) && next();
38729
+ function sum() {
38730
+ let total2 = product();
38731
+ for (let op = take("+", "-"); op; op = take("+", "-"))
38732
+ total2 += (op === "+" ? 1 : -1) * product();
38733
+ return total2;
38734
+ }
38735
+ function product() {
38736
+ let total2 = unary();
38737
+ for (let op = take("*", "/"); op; op = take("*", "/"))
38738
+ total2 = op === "*" ? total2 * unary() : total2 / unary();
38739
+ return total2;
38740
+ }
38741
+ function unary() {
38742
+ return take("-") ? -unary() : atom();
38743
+ }
38744
+ function atom() {
38745
+ const token = next();
38746
+ if (typeof token === "number") return token;
38747
+ const fn = FUNCTIONS[token ?? ""];
38748
+ if (!fn) return Number.NaN;
38749
+ const args = [sum()];
38750
+ while (take(",")) args.push(sum());
38751
+ return take(")") ? fn(args) : Number.NaN;
38752
+ }
38753
+ const total = tokens.length ? sum() : Number.NaN;
38754
+ return i === tokens.length ? total : Number.NaN;
38755
+ }
38756
+ var CONTENT_BOXES = /* @__PURE__ */ new Set(["content-box", "fill-box"]);
38757
+ var TRANSLATE_PX_PROPERTIES = [
38758
+ "translate",
38759
+ "width",
38760
+ "height",
38761
+ "box-sizing",
38762
+ "transform-box",
38763
+ ...["left", "right", "top", "bottom"].flatMap((s) => [`padding-${s}`, `border-${s}-width`])
38764
+ ];
38765
+ function referenceBox(read2, size, a, b) {
38766
+ const n = (prop) => Number.parseFloat(read2(prop)) || 0;
38767
+ const pad2 = n(`padding-${a}`) + n(`padding-${b}`) + n(`border-${a}-width`) + n(`border-${b}-width`);
38768
+ const content = n(size) - (read2("box-sizing") === "border-box" ? pad2 : 0);
38769
+ return CONTENT_BOXES.has(read2("transform-box")) ? content : content + pad2;
38770
+ }
38771
+ function translatePx(value, read2) {
38772
+ if (value === "none") return { x: 0, y: 0 };
38773
+ const [x = "0px", y = "0px"] = splitTopLevelWhitespace(value);
38774
+ const side = (size, a, b) => read2 ? referenceBox(read2, size, a, b) : Number.NaN;
38775
+ return {
38776
+ x: evaluateLength(x, side("width", "left", "right")),
38777
+ y: evaluateLength(y, side("height", "top", "bottom"))
38778
+ };
38779
+ }
38780
+ var frameTranslates = /* @__PURE__ */ new WeakMap();
38781
+ function rememberFrameTranslate(el, px) {
38782
+ frameTranslates.set(el, { inline: el.style.getPropertyValue("translate"), px });
38783
+ }
38784
+ function readTranslatePx(el) {
38785
+ const cs = el.ownerDocument.defaultView?.getComputedStyle(el);
38786
+ const inline = el.style.getPropertyValue("translate");
38787
+ const frame3 = cs ? void 0 : frameTranslates.get(el);
38788
+ if (frame3?.inline === inline) return frame3.px;
38789
+ return translatePx(cs?.translate || inline || "none", cs && ((p) => cs.getPropertyValue(p)));
38790
+ }
38791
+ function readTranslatePxLeavingPercent(el) {
38792
+ const value = el.ownerDocument.defaultView?.getComputedStyle(el).translate || "none";
38793
+ const [x = "0px", y = "0px"] = value === "none" ? [] : splitTopLevelWhitespace(value);
38794
+ const px = (part) => roundTo3(evaluateLength(part, 0)) || 0;
38795
+ return { x: px(x), y: px(y) };
38796
+ }
38797
+ var UNREADABLE_TRANSLATE = "Studio can't read this layer's translate. Move it in the Code tab.";
38798
+ var MOVING_LAYER_UNREADABLE = "This preview can't save a move of a layer its animation moves yet. Move it in the Code tab.";
38799
+ function formatTranslatePx(p) {
38800
+ return `${roundTo3(p.x)}px ${roundTo3(p.y)}px`;
38801
+ }
38802
+ var LEGACY_OFFSET_VARS = [STUDIO_OFFSET_X_PROP, STUDIO_OFFSET_Y_PROP];
38803
+ function writePlainMove(el, p) {
38804
+ writeTranslatePx(el, p);
38805
+ const patches = [
38806
+ { type: "inline-style", property: "translate", value: formatTranslatePx(p) },
38807
+ {
38808
+ type: "attribute",
38809
+ property: STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR,
38810
+ value: el.getAttribute(STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR)
38811
+ }
38812
+ ];
38813
+ for (const prop of LEGACY_OFFSET_VARS.filter((v) => el.style.getPropertyValue(v))) {
38814
+ el.style.removeProperty(prop);
38815
+ patches.push({ type: "inline-style", property: prop, value: null });
38816
+ }
38817
+ if (el.hasAttribute(STUDIO_PATH_OFFSET_ATTR)) {
38818
+ el.removeAttribute(STUDIO_PATH_OFFSET_ATTR);
38819
+ patches.push({ type: "attribute", property: STUDIO_PATH_OFFSET_ATTR, value: null });
38820
+ }
38821
+ return patches;
38822
+ }
38823
+ function writeTranslatePx(el, p) {
38824
+ if (!el.hasAttribute(STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR)) {
38825
+ const own = el.style.getPropertyValue("translate");
38826
+ el.setAttribute(STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR, styleUsesStudioOffset(own) ? "" : own);
38827
+ }
38828
+ el.style.setProperty("translate", formatTranslatePx(p));
38829
+ }
38830
+ function readMoveOffset(el, plainTranslate = editsPlainCss(el, "move")) {
38831
+ return plainTranslate ? readTranslatePx(el) : readStudioPathOffset(el);
38832
+ }
38833
+ function readShownRotation(el) {
38834
+ return editsPlainCss(el, "rotate") ? { angle: roundTo3(readCssRotation(el)) } : readStudioRotation(el);
38835
+ }
38836
+
38837
+ // src/components/editor/previewSelection.ts
38838
+ var inertDocument;
38839
+ var inert = () => inertDocument ??= document.implementation.createHTMLDocument("");
38840
+ function inertElement(tag) {
38841
+ try {
38842
+ return inert().createElement(tag);
38843
+ } catch {
38844
+ return inert().createElement("div");
38845
+ }
38846
+ }
38847
+ var GESTURE_START_STYLES = [
38848
+ "translate",
38849
+ STUDIO_OFFSET_X_PROP,
38850
+ STUDIO_OFFSET_Y_PROP,
38851
+ STUDIO_WIDTH_PROP,
38852
+ STUDIO_HEIGHT_PROP
38853
+ ];
38854
+ var GESTURE_START_ATTRS = [
38855
+ STUDIO_PATH_OFFSET_ATTR,
38856
+ STUDIO_ORIGINAL_TRANSLATE_ATTR,
38857
+ STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR
38858
+ ];
38859
+ var standIns2 = /* @__PURE__ */ new WeakMap();
38860
+ var standInHandles = /* @__PURE__ */ new WeakMap();
38861
+ var standInAncestors = /* @__PURE__ */ new WeakMap();
38862
+ function standInFor(iframe, element) {
38863
+ const client = previewEditingClient(iframe);
38864
+ const byHandle = standIns2.get(client) ?? /* @__PURE__ */ new Map();
38865
+ standIns2.set(client, byHandle);
38866
+ let standIn = byHandle.get(element.handle);
38867
+ if (!standIn) {
38868
+ standIn = inertElement(element.tag);
38869
+ for (const name of GESTURE_START_STYLES) {
38870
+ const value = element.inlineStyles[name];
38871
+ if (value && !mayBeCut(value)) standIn.style.setProperty(name, value);
38872
+ }
38873
+ for (const name of GESTURE_START_ATTRS) {
38874
+ const value = attr(element, name);
38875
+ if (value !== null && !mayBeCut(value)) standIn.setAttribute(name, value);
38876
+ }
38877
+ byHandle.set(element.handle, standIn);
38878
+ standInHandles.set(standIn, element.handle);
38879
+ registerPreviewStandIn(standIn, iframe, element.handle);
38880
+ }
38881
+ return standIn;
38882
+ }
38883
+ function readable(element) {
38884
+ const probe2 = inertElement(element.tag);
38885
+ for (const [name, value] of element.attributes) {
38886
+ if (name !== "id" && name !== "class" && !name.startsWith("data-")) continue;
38887
+ try {
38888
+ probe2.setAttribute(name, value);
38889
+ } catch {
38890
+ }
38891
+ }
38892
+ for (const [name, value] of Object.entries(element.inlineStyles)) {
38893
+ probe2.style.setProperty(name, value);
38894
+ }
38895
+ probe2.textContent = element.text;
38896
+ return probe2;
38897
+ }
38898
+ var attr = (element, name) => element.attributes.find(([key2]) => key2 === name)?.[1] ?? null;
38899
+ var mayBeCut = (value) => value.length >= MAX_ELEMENT_VALUE2 || value.startsWith("data:") && value.endsWith(",");
38900
+ function valuesWhole(element) {
38901
+ if (!element.truncated) return true;
38902
+ const styles = Object.values(element.inlineStyles);
38903
+ if (element.attributes.length >= MAX_ELEMENT_ENTRIES2 || styles.length >= MAX_ELEMENT_ENTRIES2)
38904
+ return false;
38905
+ return ![...element.attributes.map(([, value]) => value), ...styles].some(mayBeCut);
38906
+ }
38907
+ var hasAudio = (element) => element.tag === "video" && attr(element, "muted") === null && isVideoAudible({ tag: "video", hasAudioAttr: attr(element, "data-has-audio"), muted: false });
38908
+ var validSelector = (selector) => {
38909
+ try {
38910
+ inert().querySelector(selector);
38911
+ return true;
38912
+ } catch {
38913
+ return false;
38914
+ }
38915
+ };
38916
+ async function findPreviewElementForSelection(iframe, selection, activeCompositionPath) {
38917
+ for (const { selector, index: index2 } of selectionLookups(selection)) {
38918
+ if (!validSelector(selector)) continue;
38919
+ const reply = await queryPreviewElements(iframe, selector);
38920
+ if (!reply) return void 0;
38921
+ const fromFile = reply.matches.filter(
38922
+ ({ source }) => !selection.sourceFile || resolveElementSourceFile(source, activeCompositionPath) === selection.sourceFile
38923
+ );
38924
+ const match = fromFile[index2];
38925
+ if (!match) {
38926
+ if (reply.truncated) return void 0;
38927
+ continue;
38928
+ }
38929
+ const [element] = await describePreviewElements(iframe, [match.handle]) ?? [];
38930
+ return element ?? void 0;
38931
+ }
38932
+ return null;
38933
+ }
38934
+ async function findByClipId(iframe, element, sourceFile, path) {
38935
+ if (!element.id || element.domId || element.selector || element.compositionSrc) return null;
38936
+ const byId = await findPreviewElementForSelection(iframe, { id: element.id, sourceFile }, path);
38937
+ if (byId !== null) return byId;
38938
+ return findPreviewElementForSelection(iframe, { hfId: element.id, sourceFile }, path);
38939
+ }
38940
+ async function findPreviewElementForTimelineElement(iframe, element, options) {
38941
+ const { target, sourceFile, rootFallback } = timelineElementLookup(element, options);
38942
+ const path = options.activeCompositionPath;
38943
+ const found = target && await findPreviewElementForSelection(iframe, target, path);
38944
+ if (found !== null) return found;
38945
+ const byClipId = await findByClipId(iframe, element, sourceFile, path);
38946
+ if (byClipId !== null) return byClipId;
38947
+ if (!rootFallback) return null;
38948
+ const reply = await queryPreviewElements(iframe, "[data-composition-id]");
38949
+ if (!reply) return void 0;
38950
+ const root = reply.matches[0];
38951
+ if (!root || resolveElementSourceFile(root.source, path) !== sourceFile) return null;
38952
+ const [described] = await describePreviewElements(iframe, [root.handle]) ?? [];
38953
+ return described ?? void 0;
38954
+ }
38955
+ async function previewChain(iframe, target) {
38956
+ const [lineage] = await previewAncestors(iframe, [target.handle]) ?? [];
38957
+ if (!lineage) return null;
38958
+ const ancestors = lineage.length ? await describePreviewElements(iframe, lineage) : [];
38959
+ if (!ancestors || ancestors.some((entry3) => entry3 === null)) return null;
38960
+ const chain = [target, ...ancestors];
38961
+ const linked = chain.every((node, i) => node.parent === (chain[i + 1]?.handle ?? null));
38962
+ return linked ? chain : null;
38963
+ }
38964
+ function chainReader(chain) {
38965
+ const root = chain.at(-1);
38966
+ const body = chain.at(-2);
38967
+ return {
38968
+ attr,
38969
+ selector: (node) => node.selector ?? void 0,
38970
+ isDocumentRoot: (node) => node === root || node === body && node.tag === "body"
38971
+ };
38972
+ }
38973
+ async function compositionRoot2(iframe, documentElement) {
38974
+ const reply = await queryPreviewElements(iframe, "[data-composition-id]");
38975
+ if (!reply) return null;
38976
+ const first = reply.matches[0];
38977
+ const [root] = first ? await describePreviewElements(iframe, [first.handle]) ?? [null] : [];
38978
+ if (root === null) return null;
38979
+ const element = root ?? documentElement;
38980
+ const { x, y, width, height } = element.rect;
38981
+ return {
38982
+ rect: { left: x, top: y, width, height },
38983
+ width: attr(element, "data-width"),
38984
+ height: attr(element, "data-height")
38985
+ };
38986
+ }
38987
+ function chainIndex(chain, read2, options) {
38988
+ const active = options.activeGroupElement;
38989
+ const activeHandle = active ? standInHandles.get(active) : void 0;
38990
+ return selectionTargetIndex(chain, read2, {
38991
+ exactTarget: options.exactTarget,
38992
+ preferClipAncestor: options.preferClipAncestor,
38993
+ activeGroupIndex: active ? chain.findIndex((node) => node.handle === activeHandle) : null
38994
+ });
38995
+ }
38996
+ function previewIdentity(current2, path) {
38997
+ const selector = current2.selector ?? void 0;
38998
+ return {
38999
+ id: current2.id || void 0,
39000
+ hfId: attr(current2, "data-hf-id")?.trim() || void 0,
39001
+ selector,
39002
+ selectorIndex: selector ? previewElementSelectorIndex(current2, path) : void 0,
39003
+ sourceFile: previewElementSourceFile(current2, path)
39004
+ };
39005
+ }
39006
+ async function isPreviewCompositionRoot(iframe, chain, index2, computedStyles) {
39007
+ const current2 = chain[index2];
39008
+ if (attr(current2, "data-composition-id") !== null && !compositionSourceOf(current2)) return true;
39009
+ const parent = chain[index2 + 1];
39010
+ const underBody = parent?.tag === "body" && chainReader(chain).isDocumentRoot(parent);
39011
+ if (!underBody || attr(current2, "data-hf-allow-root-edit") !== null) return false;
39012
+ const { x, y, width, height } = current2.rect;
39013
+ const rect = { left: x, top: y, width, height };
39014
+ const root = await compositionRoot2(iframe, chain.at(-1));
39015
+ return root && coversCompositionRoot({ rect, computedStyles }, root);
39016
+ }
39017
+ var compositionSourceOf = (element) => attr(element, "data-composition-src") ?? attr(element, "data-composition-file") ?? void 0;
39018
+ async function resolvePreviewSelection(iframe, target, options) {
39019
+ const chain = await previewChain(iframe, target);
39020
+ const index2 = chain && chainIndex(chain, chainReader(chain), options);
39021
+ if (!chain || index2 === null) return null;
39022
+ const current2 = chain[index2];
39023
+ if (!valuesWhole(current2)) return null;
39024
+ const element = standInFor(iframe, current2);
39025
+ standInAncestors.set(
39026
+ element,
39027
+ chain.slice(index2 + 1).map((node) => node.handle)
39028
+ );
39029
+ const identity = previewIdentity(current2, options.activeCompositionPath);
39030
+ const compositionSrc = compositionSourceOf(current2);
39031
+ const probe2 = readable(current2);
39032
+ const inlineStyles = getInlineStyles(probe2);
39033
+ const styles = await previewComputedStyles(iframe, current2, [
39034
+ .../* @__PURE__ */ new Set([...CURATED_STYLE_PROPERTIES, ...TRANSLATE_PX_PROPERTIES])
39035
+ ]);
39036
+ if (!styles) return null;
39037
+ rememberFrameTranslate(
39038
+ element,
39039
+ translatePx(styles.translate ?? "none", (p) => styles[p] ?? "")
39040
+ );
39041
+ const computedStyles = Object.fromEntries(
39042
+ CURATED_STYLE_PROPERTIES.flatMap((p) => p in styles ? [[p, styles[p]]] : [])
39043
+ );
39044
+ const isCompositionRoot = await isPreviewCompositionRoot(iframe, chain, index2, computedStyles);
39045
+ if (isCompositionRoot === null) return null;
39046
+ const isInsideLocked = chainLocked(chain, chainReader(chain), index2);
39047
+ const { sourceFile } = identity;
39048
+ const existsInSource = await existsInSourceFile(
39049
+ options.previous,
39050
+ element,
39051
+ sourceFile,
39052
+ identity,
39053
+ options
39054
+ );
39055
+ const capabilities = resolveEditingAffordances(
39056
+ capabilityFacts({
39057
+ hasStableTarget: Boolean(identity.selector || identity.hfId),
39058
+ tag: current2.tag,
39059
+ inlineStyles,
39060
+ computedStyles,
39061
+ isCompositionHost: Boolean(compositionSrc),
39062
+ isCompositionRoot,
39063
+ isInsideLockedComposition: isInsideLocked,
39064
+ isMasterView: options.isMasterView,
39065
+ existsInSource: existsInSource ?? true
39066
+ })
39067
+ ).capabilities;
39068
+ const { x, y, width, height } = current2.rect;
39069
+ return {
39070
+ element,
39071
+ handle: current2.handle,
39072
+ hasAudio: hasAudio(current2),
39073
+ src: attr(current2, "src"),
39074
+ ...identity,
39075
+ compositionPath: sourceFile,
39076
+ compositionSrc,
39077
+ isCompositionHost: Boolean(compositionSrc),
39078
+ isInsideLockedComposition: isInsideLocked,
39079
+ label: buildElementLabel(probe2),
39080
+ tagName: current2.tag,
39081
+ boundingBox: { x, y, width, height },
39082
+ textContent: current2.text.trim() || null,
39083
+ dataAttributes: getDataAttributes(probe2),
39084
+ inlineStyles,
39085
+ computedStyles,
39086
+ textFields: [],
39087
+ capabilities,
39088
+ existsInSource
39089
+ };
39090
+ }
39091
+ function liveElementForSelection(iframe, selection, activeCompositionPath) {
39092
+ let doc = null;
39093
+ try {
39094
+ doc = iframe?.contentDocument ?? null;
39095
+ } catch {
39096
+ return void 0;
39097
+ }
39098
+ return doc ? findElementForSelection(doc, selection, activeCompositionPath) : void 0;
39099
+ }
39100
+ async function findSelectionElement(iframe, selection, activeCompositionPath) {
39101
+ return iframe && previewFrameOpaque(iframe) ? findPreviewElementForSelection(iframe, selection, activeCompositionPath) : liveElementForSelection(iframe, selection, activeCompositionPath);
39102
+ }
39103
+ async function resolveFoundSelection(iframe, found, options) {
39104
+ if (isHtmlElement(found)) return resolveDomEditSelection(found, options);
39105
+ return iframe ? resolvePreviewSelection(iframe, found, options) : null;
39106
+ }
39107
+ async function findOpaqueTimelineElement(iframe, element, lookup2) {
39108
+ if (!iframe || !previewFrameOpaque(iframe)) return null;
39109
+ return await findPreviewElementForTimelineElement(iframe, element, lookup2) ?? null;
39110
+ }
39111
+ var standInHandle = (element) => standInHandles.get(element);
39112
+ function elementWithin(container, element) {
39113
+ const handle = standInHandles.get(container);
39114
+ if (handle === void 0) return container.contains(element);
39115
+ return element === container || (standInAncestors.get(element)?.includes(handle) ?? false);
39116
+ }
39117
+ function selectionDataAttribute(selection, name) {
39118
+ if (!selection.handle) return selection.element.getAttribute(name);
39119
+ return selection.dataAttributes[name.slice("data-".length)] ?? null;
39120
+ }
39121
+ var pointerAnswers = /* @__PURE__ */ new WeakMap();
39122
+ async function previewPointerTarget(iframe, clientX, clientY) {
39123
+ const { x, y } = framePointFraction(iframe, clientX, clientY);
39124
+ const reply = await previewPointerTargets(iframe, x, y);
39125
+ if (reply) pointerAnswers.set(iframe, { x: clientX, y: clientY, found: reply.target !== null });
39126
+ return reply;
39127
+ }
39128
+ function pointerMayHitElement(iframe, clientX, clientY) {
39129
+ if (!previewFrameOpaque(iframe))
39130
+ return Boolean(getPreviewTargetFromPointer(iframe, clientX, clientY));
39131
+ const answer = pointerAnswers.get(iframe);
39132
+ const near4 = answer && Math.hypot(answer.x - clientX, answer.y - clientY) <= 2;
39133
+ return near4 ? answer.found : true;
39134
+ }
39135
+ async function findPointerTarget(iframe, clientX, clientY) {
39136
+ if (!previewFrameOpaque(iframe)) return getPreviewTargetFromPointer(iframe, clientX, clientY);
39137
+ const reply = await previewPointerTarget(iframe, clientX, clientY);
39138
+ if (!reply?.target) return reply ? null : void 0;
39139
+ const [described] = await describePreviewElements(iframe, [reply.target.handle]) ?? [];
39140
+ return described ?? void 0;
39141
+ }
39142
+ async function findPointerTargets(iframe, clientX, clientY) {
39143
+ if (!previewFrameOpaque(iframe)) return getAllPreviewTargetsFromPointer(iframe, clientX, clientY);
39144
+ const reply = await previewPointerTarget(iframe, clientX, clientY);
39145
+ const handles = reply?.stack.map((hit) => hit.handle) ?? [];
39146
+ const described = handles.length ? await describePreviewElements(iframe, handles) : [];
39147
+ return (described ?? []).filter((element) => element !== null);
39148
+ }
39149
+ var selectionElementLive = (selection) => selection.handle !== void 0 || selection.element.isConnected;
39150
+
39151
+ // src/components/editor/previewLayers.ts
39152
+ async function describeAll(iframe, handles) {
39153
+ const described = [];
39154
+ for (let at = 0; at < handles.length; at += MAX_DESCRIBE_HANDLES4) {
39155
+ const part = await describePreviewElements(
39156
+ iframe,
39157
+ handles.slice(at, at + MAX_DESCRIBE_HANDLES4)
39158
+ );
39159
+ if (!part) return null;
39160
+ described.push(...part);
39161
+ }
39162
+ return described;
39163
+ }
39164
+ function layerItem(iframe, layer, element, path) {
39165
+ const probe2 = readable(element);
39166
+ const identity = previewIdentity(element, path);
39167
+ return {
39168
+ ...identity,
39169
+ key: getDomEditLayerKey(identity),
39170
+ element: standInFor(iframe, element),
39171
+ label: buildElementLabel(probe2),
39172
+ tagName: element.tag,
39173
+ depth: layer.depth,
39174
+ childCount: layer.childCount,
39175
+ preview: {
39176
+ handle: layer.handle,
39177
+ zIndex: layer.zIndex,
39178
+ kind: layer.kind,
39179
+ dataAttributes: getDataAttributes(probe2)
39180
+ }
39181
+ };
39182
+ }
39183
+ async function collectPreviewLayerItems(iframe, options, maxItems = Number.POSITIVE_INFINITY) {
39184
+ const group = options.activeGroupElement && standInHandle(options.activeGroupElement);
39185
+ const reply = await previewLayers(iframe, group ?? void 0);
39186
+ const layers = reply?.layers.slice(0, maxItems) ?? [];
39187
+ const described = reply && await describeAll(
39188
+ iframe,
39189
+ layers.map((layer) => layer.handle)
39190
+ );
39191
+ if (!reply || !described) return null;
39192
+ const items = layers.flatMap((layer, index2) => {
39193
+ const element = described[index2];
39194
+ return element ? [layerItem(iframe, layer, element, options.activeCompositionPath)] : [];
39195
+ });
39196
+ return { items, missingGroup: reply.missingGroup };
39197
+ }
39198
+ var MAX_LAYER_PAGES = 64;
39199
+ async function allPreviewLayers(iframe) {
39200
+ const layers = [];
39201
+ for (let page = 0; page < MAX_LAYER_PAGES; page += 1) {
39202
+ const reply = await previewLayers(iframe, void 0, layers.length);
39203
+ if (!reply) return null;
39204
+ layers.push(...reply.layers);
39205
+ if (!reply.truncated || !reply.layers.length) break;
39206
+ }
39207
+ return layers;
39208
+ }
39209
+ function layerDataAttribute(layer, name) {
39210
+ if (!layer.preview) return layer.element.getAttribute(name);
39211
+ return layer.preview.dataAttributes[name.slice("data-".length)] ?? null;
39212
+ }
39213
+ async function compositionViewport(iframe) {
39214
+ const roots = await queryPreviewElements(iframe, "[data-composition-id]");
39215
+ const root = roots?.matches[0] ?? (await queryPreviewElements(iframe, "html"))?.matches[0];
39216
+ const [described] = root && await describePreviewElements(iframe, [root.handle]) || [];
39217
+ if (!described) return null;
39218
+ const declared = (name) => Number.parseFloat(described.attributes.find(([key2]) => key2 === name)?.[1] ?? "");
39219
+ const [width, height] = [declared("data-width"), declared("data-height")];
39220
+ return {
39221
+ width: width > 0 ? width : described.rect.width || 1,
39222
+ height: height > 0 ? height : described.rect.height || 1
39223
+ };
39224
+ }
39225
+ async function collectPreviewMarqueeCandidates(iframe, overlayEl) {
39226
+ const layers = await allPreviewLayers(iframe);
39227
+ const handles = layers?.map((layer) => layer.handle) ?? [];
39228
+ const viewport2 = handles.length ? await compositionViewport(iframe) : null;
39229
+ const described = viewport2 && await describeAll(iframe, handles);
39230
+ const measured = described && await measurePreviewVisibleRects(iframe, overlayEl, handles);
39231
+ if (!described || !measured || !viewport2) return [];
39232
+ return handles.flatMap((_, index2) => {
39233
+ const description = described[index2];
39234
+ const box = measured[index2];
39235
+ if (!description || !box?.visible || coversComposition(box.frame, viewport2)) return [];
39236
+ const { left, top, width, height } = box.rect;
39237
+ const element = standInFor(iframe, description);
39238
+ return [{ element, rect: { left, top, width, height }, description }];
39239
+ });
39240
+ }
39241
+ async function resolvePreviewMarqueeHits(iframe, hits, activeCompositionPath) {
39242
+ const isMasterView = !activeCompositionPath || activeCompositionPath === "index.html";
39243
+ const options = { activeCompositionPath, isMasterView, skipSourceProbe: true };
39244
+ const picks = [];
39245
+ for (const hit of hits) {
39246
+ const selection = await resolvePreviewSelection(iframe, hit.description, options);
39247
+ if (selection) picks.push(selection);
39248
+ }
39249
+ return picks;
39250
+ }
39251
+
39252
+ // src/components/editor/marqueeCommit.ts
39253
+ function currentMarqueeCandidates(cached5, iframe, overlay, path) {
39254
+ if (cached5?.every((hit) => hit.element.ownerDocument === iframe.contentDocument)) return cached5;
39255
+ return collectMarqueeCandidates(iframe, overlay, path);
39256
+ }
39257
+ var MARQUEE_THRESHOLD_PX = 4;
39258
+ function collectMarqueeCandidates(iframe, overlayEl, activeCompositionPath) {
39259
+ const doc = iframe.contentDocument;
39260
+ if (!doc) return [];
39261
+ const root = doc.querySelector("[data-composition-id]") ?? doc.body;
39262
+ const isMasterView = !activeCompositionPath || activeCompositionPath === "index.html";
39263
+ const items = collectDomEditLayerItems(root, { activeCompositionPath, isMasterView });
39264
+ const rootEl = doc.querySelector("[data-composition-id]") ?? doc.documentElement;
39265
+ const declW = Number.parseFloat(rootEl?.getAttribute("data-width") ?? "");
39266
+ const declH = Number.parseFloat(rootEl?.getAttribute("data-height") ?? "");
39267
+ const viewport2 = {
39268
+ width: declW > 0 ? declW : rootEl.getBoundingClientRect().width || 1,
39269
+ height: declH > 0 ? declH : rootEl.getBoundingClientRect().height || 1
39270
+ };
39271
+ const candidates = [];
39272
+ for (const item of items) {
39273
+ const el = item.element;
39274
+ if (!isElementComputedVisible(el)) continue;
39275
+ if (coversComposition(el.getBoundingClientRect(), viewport2)) continue;
39276
+ const overlayRect = toVisibleOverlayRect(overlayEl, iframe, el);
39277
+ if (!overlayRect) continue;
39278
+ candidates.push({
39279
+ element: el,
39280
+ rect: {
39281
+ left: overlayRect.left,
39282
+ top: overlayRect.top,
39283
+ width: overlayRect.width,
39284
+ height: overlayRect.height
39285
+ }
39286
+ });
39287
+ }
39288
+ return candidates;
39289
+ }
39290
+ function hitsWithin(rect, candidates) {
39291
+ return candidates.filter((candidate) => rectsOverlap(rect, candidate.rect));
39292
+ }
39293
+ async function resolveDomEditSelections(elements, activeCompositionPath) {
39294
+ const isMasterView = !activeCompositionPath || activeCompositionPath === "index.html";
39295
+ const hits = [];
39296
+ for (const element of elements) {
39297
+ const sel = await resolveDomEditSelection(element, {
39298
+ activeCompositionPath,
39299
+ isMasterView,
39300
+ skipSourceProbe: true
39301
+ });
39302
+ if (sel) hits.push(sel);
39303
+ }
39304
+ return hits;
39305
+ }
39306
+ function bandCandidates(iframe, overlay, acp, measured) {
39307
+ if (!previewFrameOpaque(iframe))
39308
+ return currentMarqueeCandidates(measured.cached, iframe, overlay, acp);
39309
+ return measured.measuring ?? collectPreviewMarqueeCandidates(iframe, overlay);
38827
39310
  }
38828
- async function measurePreviewOverlay(iframe, overlayEl, targets) {
38829
- const handles = [.../* @__PURE__ */ new Set([targets.selection, targets.hover, ...targets.group])].filter(
38830
- (handle) => Boolean(handle)
39311
+ function resolveMarqueeHits(iframe, hits, acp) {
39312
+ const elements = hits.map((hit) => hit.element);
39313
+ if (!previewFrameOpaque(iframe)) return resolveDomEditSelections(elements, acp);
39314
+ return resolvePreviewMarqueeHits(iframe, hits, acp);
39315
+ }
39316
+ function trackMarqueeSelection(result) {
39317
+ if (result?.changed && result.count > 1) trackPreviewFeatureUsed("multi_select", "drag");
39318
+ }
39319
+ function releaseCapture(m) {
39320
+ try {
39321
+ m.target.releasePointerCapture(m.pointerId);
39322
+ } catch {
39323
+ }
39324
+ }
39325
+ function useMarqueeGestures(deps) {
39326
+ const marqueeRef = useRef67(null);
39327
+ const [marqueeRect, setMarqueeRect] = useState50(null);
39328
+ const [candidateRects, setCandidateRects] = useState50([]);
39329
+ const candidatesRef = useRef67(null);
39330
+ const opaqueCandidatesRef = useRef67(null);
39331
+ const bandRef = useRef67(null);
39332
+ const commitMarquee = useCallback58(
39333
+ async (rect, mode) => {
39334
+ const iframe = deps.iframeRef.current;
39335
+ const overlay = deps.overlayRef.current;
39336
+ if (!iframe || !overlay || !deps.onMarqueeSelectRef.current) return;
39337
+ const acp = deps.activeCompositionPathRef.current ?? "index.html";
39338
+ const measured = { cached: candidatesRef.current, measuring: opaqueCandidatesRef.current };
39339
+ const hits = hitsWithin(rect, await bandCandidates(iframe, overlay, acp, measured));
39340
+ const resolveHits = deps.resolveHits;
39341
+ const picks = resolveHits ? await resolveHits(hits.map((hit) => hit.element)) : await resolveMarqueeHits(iframe, hits, acp);
39342
+ const applySelection = deps.onMarqueeSelectRef.current;
39343
+ if (!applySelection) return;
39344
+ const result = applySelection(picks, mode);
39345
+ trackMarqueeSelection(result);
39346
+ },
39347
+ [
39348
+ deps.iframeRef,
39349
+ deps.overlayRef,
39350
+ deps.onMarqueeSelectRef,
39351
+ deps.activeCompositionPathRef,
39352
+ deps.resolveHits
39353
+ ]
38831
39354
  );
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);
39355
+ const reset = useCallback58(() => {
39356
+ marqueeRef.current = null;
39357
+ setMarqueeRect(null);
39358
+ setCandidateRects([]);
39359
+ candidatesRef.current = null;
39360
+ opaqueCandidatesRef.current = null;
39361
+ bandRef.current = null;
39362
+ }, []);
39363
+ const begin = useCallback58(
39364
+ (event) => {
39365
+ const oRect = deps.overlayRef.current?.getBoundingClientRect();
39366
+ if (!oRect) return;
39367
+ event.currentTarget.setPointerCapture(event.pointerId);
39368
+ const x = event.clientX - oRect.left;
39369
+ const y = event.clientY - oRect.top;
39370
+ marqueeRef.current = {
39371
+ startX: x,
39372
+ startY: y,
39373
+ currentX: x,
39374
+ currentY: y,
39375
+ pointerId: event.pointerId,
39376
+ pastThreshold: false,
39377
+ target: event.currentTarget
39378
+ };
39379
+ },
39380
+ [deps.overlayRef]
39381
+ );
39382
+ const cancel = useCallback58(() => {
39383
+ if (!marqueeRef.current) return;
39384
+ releaseCapture(marqueeRef.current);
39385
+ reset();
39386
+ }, [reset]);
39387
+ useEffect50(() => {
39388
+ const cancelBandBeforeHostEscape = (e) => {
39389
+ if (!matchesKey(e, "cancel") || !marqueeRef.current) return;
39390
+ e.preventDefault();
39391
+ e.stopPropagation();
39392
+ cancel();
39393
+ };
39394
+ window.addEventListener("keydown", cancelBandBeforeHostEscape, { capture: true });
39395
+ return () => window.removeEventListener("keydown", cancelBandBeforeHostEscape, { capture: true });
39396
+ }, [cancel]);
39397
+ const isSelectedElement = useCallback58(
39398
+ (element) => deps.selectionRef?.current?.element === element || (deps.groupSelectionsRef?.current ?? []).some((s) => s.element === element),
39399
+ [deps.selectionRef, deps.groupSelectionsRef]
39400
+ );
39401
+ const showCandidates = useCallback58(
39402
+ (rect, mode) => {
39403
+ const iframe = deps.iframeRef.current;
39404
+ const overlay = deps.overlayRef.current;
39405
+ if (!iframe || !overlay) return;
39406
+ const acp = deps.activeCompositionPathRef.current ?? "index.html";
39407
+ bandRef.current = { rect, mode };
39408
+ if (!candidatesRef.current && previewFrameOpaque(iframe)) {
39409
+ if (opaqueCandidatesRef.current) return;
39410
+ const measuring = collectPreviewMarqueeCandidates(iframe, overlay);
39411
+ opaqueCandidatesRef.current = measuring;
39412
+ void measuring.then((hits2) => {
39413
+ if (opaqueCandidatesRef.current !== measuring || !bandRef.current) return;
39414
+ candidatesRef.current = hits2;
39415
+ showCandidates(bandRef.current.rect, bandRef.current.mode);
39416
+ });
39417
+ return;
39418
+ }
39419
+ candidatesRef.current ??= collectMarqueeCandidates(iframe, overlay, acp);
39420
+ let hits = hitsWithin(rect, candidatesRef.current);
39421
+ if (mode === "subtract") hits = hits.filter((h) => isSelectedElement(h.element));
39422
+ setCandidateRects(hits.map((h) => h.rect));
39423
+ },
39424
+ [deps.overlayRef, deps.iframeRef, deps.activeCompositionPathRef, isSelectedElement]
39425
+ );
39426
+ const onPointerMove = useCallback58(
39427
+ (event) => {
39428
+ const m = marqueeRef.current;
39429
+ if (m) {
39430
+ if (!movesGesture(m, event)) return;
39431
+ const oRect = deps.overlayRef.current?.getBoundingClientRect();
39432
+ if (!oRect) return;
39433
+ m.currentX = event.clientX - oRect.left;
39434
+ m.currentY = event.clientY - oRect.top;
39435
+ if (!m.pastThreshold) {
39436
+ const dx = m.currentX - m.startX;
39437
+ const dy = m.currentY - m.startY;
39438
+ if (Math.hypot(dx, dy) < MARQUEE_THRESHOLD_PX) return;
39439
+ m.pastThreshold = true;
39440
+ candidatesRef.current = null;
39441
+ opaqueCandidatesRef.current = null;
39442
+ }
39443
+ const rect = {
39444
+ left: Math.min(m.startX, m.currentX),
39445
+ top: Math.min(m.startY, m.currentY),
39446
+ width: Math.abs(m.currentX - m.startX),
39447
+ height: Math.abs(m.currentY - m.startY)
39448
+ };
39449
+ const mode = resolveMarqueeMode(event);
39450
+ setMarqueeRect({ ...rect, mode });
39451
+ showCandidates(rect, mode);
39452
+ return;
39453
+ }
39454
+ deps.gestures?.onPointerMove(event);
39455
+ },
39456
+ [deps.gestures, deps.overlayRef, showCandidates]
39457
+ );
39458
+ const onPointerUp = useCallback58(
39459
+ (event) => {
39460
+ const m = marqueeRef.current;
39461
+ if (m) {
39462
+ releaseCapture(m);
39463
+ if (m.pastThreshold) {
39464
+ commitMarquee(
39465
+ {
39466
+ left: Math.min(m.startX, m.currentX),
39467
+ top: Math.min(m.startY, m.currentY),
39468
+ width: Math.abs(m.currentX - m.startX),
39469
+ height: Math.abs(m.currentY - m.startY)
39470
+ },
39471
+ resolveMarqueeMode(event)
39472
+ );
39473
+ } else {
39474
+ deps.onMarqueeSelectRef.current?.([], "replace");
39475
+ }
39476
+ reset();
39477
+ return;
39478
+ }
39479
+ deps.gestures?.onPointerUp(event);
39480
+ },
39481
+ [deps.gestures, commitMarquee, deps.onMarqueeSelectRef, reset]
39482
+ );
39483
+ const onPointerCancel = useCallback58(() => {
39484
+ if (marqueeRef.current) return cancel();
39485
+ if (deps.selectionRef) deps.gestures?.clearPointerState(deps.selectionRef);
39486
+ }, [deps.gestures, deps.selectionRef, cancel]);
38839
39487
  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)
39488
+ marqueeRect,
39489
+ candidateRects,
39490
+ begin,
39491
+ cancel,
39492
+ onPointerMove,
39493
+ onPointerUp,
39494
+ onPointerCancel
38848
39495
  };
38849
39496
  }
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));
39497
+
39498
+ // src/components/editor/MarqueeOverlay.tsx
39499
+ import { Fragment as Fragment27, jsx as jsx99, jsxs as jsxs69 } from "react/jsx-runtime";
39500
+ function MarqueeOverlay({ candidateRects, marqueeRect }) {
39501
+ const subtracting = marqueeRect?.mode === "subtract";
39502
+ const candidateClass = subtracting ? "border-danger bg-danger/5" : "border-studio-accent bg-studio-accent/5";
39503
+ const bandClass = subtracting ? "border-danger bg-danger/10" : "border-studio-accent bg-studio-accent/10";
39504
+ return /* @__PURE__ */ jsxs69(Fragment27, { children: [
39505
+ candidateRects.map((r, i) => /* @__PURE__ */ jsx99(
39506
+ "div",
39507
+ {
39508
+ "aria-hidden": "true",
39509
+ className: `pointer-events-none absolute rounded-xs border ${candidateClass}`,
39510
+ style: { left: r.left, top: r.top, width: r.width, height: r.height }
39511
+ },
39512
+ i
39513
+ )),
39514
+ marqueeRect && /* @__PURE__ */ jsx99(
39515
+ "div",
39516
+ {
39517
+ "aria-hidden": "true",
39518
+ "data-marquee-mode": marqueeRect.mode,
39519
+ className: `pointer-events-none absolute border border-dashed ${bandClass}`,
39520
+ style: {
39521
+ left: marqueeRect.left,
39522
+ top: marqueeRect.top,
39523
+ width: marqueeRect.width,
39524
+ height: marqueeRect.height
39525
+ }
39526
+ }
39527
+ )
39528
+ ] });
39529
+ }
39530
+
39531
+ // src/components/editor/useZOrderCrossedFlash.tsx
39532
+ import { useCallback as useCallback59, useEffect as useEffect51, useRef as useRef68, useState as useState51 } from "react";
39533
+ import { jsx as jsx100 } from "react/jsx-runtime";
39534
+ var Z_ORDER_CROSSED_FLASH_MS = 600;
39535
+ function useZOrderCrossedFlash({ overlayRef, iframeRef }) {
39536
+ const [zOrderFlashRect, setZOrderFlashRect] = useState51(null);
39537
+ const timeoutRef = useRef68(null);
39538
+ useEffect51(
39539
+ () => () => {
39540
+ if (timeoutRef.current) clearTimeout(timeoutRef.current);
39541
+ },
39542
+ []
39543
+ );
39544
+ const handleZOrderCrossed = useCallback59(
39545
+ (crossed) => {
39546
+ const overlayEl = overlayRef.current;
39547
+ const iframe = iframeRef.current;
39548
+ if (!overlayEl || !iframe) return;
39549
+ const rect = toVisibleOverlayRect(overlayEl, iframe, crossed);
39550
+ if (!rect || rect.width <= 0 || rect.height <= 0) return;
39551
+ if (timeoutRef.current) clearTimeout(timeoutRef.current);
39552
+ setZOrderFlashRect(rect);
39553
+ timeoutRef.current = setTimeout(() => {
39554
+ timeoutRef.current = null;
39555
+ setZOrderFlashRect(null);
39556
+ }, Z_ORDER_CROSSED_FLASH_MS);
39557
+ },
39558
+ [overlayRef, iframeRef]
39559
+ );
39560
+ return { zOrderFlashRect, handleZOrderCrossed };
39561
+ }
39562
+ function ZOrderCrossedFlash({ rect }) {
39563
+ if (!rect) return null;
39564
+ return /* @__PURE__ */ jsx100(
39565
+ "div",
39566
+ {
39567
+ "aria-hidden": "true",
39568
+ "data-dom-edit-z-flash": "true",
39569
+ className: "pointer-events-none absolute rounded-md border-2 border-studio-accent shadow-[0_0_0_2px_rgba(60,230,172,0.35)] animate-pulse",
39570
+ style: { left: rect.left, top: rect.top, width: rect.width, height: rect.height }
39571
+ }
39572
+ );
39573
+ }
39574
+
39575
+ // src/components/editor/useCanvasContextMenuState.ts
39576
+ import { useCallback as useCallback60, useEffect as useEffect52, useState as useState52 } from "react";
39577
+ function useCanvasContextMenuState({
39578
+ selection,
39579
+ selectionRef,
39580
+ hoverSelectionRef,
39581
+ onCanvasPointerMoveRef,
39582
+ onSelectionChangeRef
39583
+ }) {
39584
+ const [contextMenu, setContextMenu] = useState52(null);
39585
+ const closeContextMenu = useCallback60(() => setContextMenu(null), []);
39586
+ useEffect52(() => {
39587
+ if (!contextMenu) return;
39588
+ if (!selection || selection.element !== contextMenu.sel.element) {
39589
+ setContextMenu(null);
39590
+ }
39591
+ }, [selection, contextMenu]);
39592
+ const handleContextMenu = useCallback60(
39593
+ async (event) => {
39594
+ event.preventDefault();
39595
+ const currentSel = selectionRef.current;
39596
+ let activeSel = currentSel;
39597
+ if (!currentSel) {
39598
+ const pointerEvent = event;
39599
+ const resolved2 = await onCanvasPointerMoveRef.current(pointerEvent);
39600
+ if (!resolved2) return;
39601
+ onSelectionChangeRef.current(resolved2, { revealPanel: true });
39602
+ activeSel = resolved2;
39603
+ } else {
39604
+ const hover = hoverSelectionRef.current;
39605
+ if (hover && hover.element !== currentSel.element) {
39606
+ onSelectionChangeRef.current(hover, { revealPanel: true });
39607
+ activeSel = hover;
39608
+ }
39609
+ }
39610
+ if (!activeSel) return;
39611
+ setContextMenu({ x: event.clientX, y: event.clientY, sel: activeSel });
39612
+ },
39613
+ [selectionRef, hoverSelectionRef, onCanvasPointerMoveRef, onSelectionChangeRef]
39614
+ );
39615
+ return { contextMenu, closeContextMenu, handleContextMenu };
38855
39616
  }
38856
39617
 
38857
39618
  // src/components/editor/useDomEditOverlayRects.ts
39619
+ import { useRef as useRef69, useState as useState53 } from "react";
38858
39620
  function childRectsEqual(a, b) {
38859
39621
  if (a.length !== b.length) return false;
38860
39622
  for (let i = 0; i < a.length; i++) {
@@ -39539,6 +40301,7 @@ function restoreStyleProperty(element, property, value) {
39539
40301
  else element.style.removeProperty(property);
39540
40302
  }
39541
40303
  function restoreStudioBoxSize(element, previous) {
40304
+ endPreviewDraft(element, "restore");
39542
40305
  forgetStudioBoxSizeDraftBase(element);
39543
40306
  restoreStyleProperty(element, "width", previous.width);
39544
40307
  restoreStyleProperty(element, "height", previous.height);
@@ -39591,6 +40354,10 @@ function restoreStudioRotation(element, previous) {
39591
40354
  );
39592
40355
  }
39593
40356
  function restoreStudioPathOffset(element, previous) {
40357
+ endPreviewDraft(element, "restore");
40358
+ restoreStudioPathOffsetStyles(element, previous);
40359
+ }
40360
+ function restoreStudioPathOffsetStyles(element, previous) {
39594
40361
  if (previous.translate) element.style.setProperty("translate", previous.translate);
39595
40362
  else element.style.removeProperty("translate");
39596
40363
  if (previous.x) element.style.setProperty(STUDIO_OFFSET_X_PROP, previous.x);
@@ -39905,189 +40672,6 @@ function installStudioManualEditSeekReapply(win, apply) {
39905
40672
  return wrappedHfSeek || wrappedPlayerSeek || wrappedPlayerRenderSeek || wrappedTimelineSeek || wrappedPlayerPlay || wrappedTimelinePlay || wrappedPlayerPause || wrappedTimelinePause || wrappedNamedTimelineSeek || wrappedNamedTimelinePlay || wrappedNamedTimelinePause;
39906
40673
  }
39907
40674
 
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
40675
  // src/components/editor/manualOffsetDrag.ts
40092
40676
  function getOffsetDragGsap(element) {
40093
40677
  const win = element.ownerDocument.defaultView;
@@ -40233,7 +40817,7 @@ function measureManualOffsetDragScreenToOffsetMatrix(element, initialOffset, opt
40233
40817
  }
40234
40818
  return { ok: true, matrix: screenToOffset };
40235
40819
  } finally {
40236
- restoreStudioPathOffset(element, snapshot3);
40820
+ restoreStudioPathOffsetStyles(element, snapshot3);
40237
40821
  }
40238
40822
  }
40239
40823
  function resolveManualOffsetForPointerDelta(input) {
@@ -40247,14 +40831,15 @@ function resolveManualOffsetForPointerDelta(input) {
40247
40831
  };
40248
40832
  }
40249
40833
  function createManualOffsetDragMember(input) {
40250
- const plainTranslate = !!input.gesture && editsPlainCss(input.element, input.gesture === "resize" ? "resize" : "move");
40834
+ const { start, gesture } = input;
40835
+ const plainTranslate = start && gesture !== "resize" ? !start.gsap : !!gesture && editsPlainCss(input.element, gesture === "resize" ? "resize" : "move");
40251
40836
  const initialOffset = plainTranslate ? readTranslatePx(input.element) : readAppliedStudioPathOffset(input.element);
40252
40837
  if (!finitePoint(initialOffset))
40253
40838
  return { ok: false, reason: UNREADABLE_TRANSLATE, selection: input.selection };
40254
40839
  const win = input.element.ownerDocument.defaultView;
40255
40840
  const gsapX = !plainTranslate && win?.gsap?.getProperty?.(input.element, "x") || 0;
40256
40841
  const gsapY = !plainTranslate && win?.gsap?.getProperty?.(input.element, "y") || 0;
40257
- const baseGsap = { x: gsapX, y: gsapY };
40842
+ const baseGsap = start?.gsap ? { x: start.gsap.x, y: start.gsap.y } : { x: gsapX, y: gsapY };
40258
40843
  if (!plainTranslate) stampGestureBase(input.element, initialOffset, baseGsap);
40259
40844
  if (win?.__timelines) {
40260
40845
  const paused = [];
@@ -40282,6 +40867,7 @@ function createManualOffsetDragMember(input) {
40282
40867
  scaleY: input.rect.editScaleY,
40283
40868
  plainTranslate
40284
40869
  });
40870
+ endPreviewDraft(input.element, "keep");
40285
40871
  if (!measured.ok) {
40286
40872
  const scaleX = input.rect.editScaleX || 1;
40287
40873
  const scaleY = input.rect.editScaleY || 1;
@@ -40297,7 +40883,7 @@ function createManualOffsetDragMember(input) {
40297
40883
  baseGsap,
40298
40884
  initialPathOffset,
40299
40885
  gestureToken,
40300
- screenToOffset: { a: w / scaleX, b: 0, c: 0, d: w / scaleY },
40886
+ screenToOffset: start?.screenToOffset ?? { a: w / scaleX, b: 0, c: 0, d: w / scaleY },
40301
40887
  originRect: input.rect
40302
40888
  }
40303
40889
  };
@@ -40327,6 +40913,8 @@ function resolveManualOffsetDragMemberOffset(member, dx, dy) {
40327
40913
  });
40328
40914
  }
40329
40915
  function drawMemberOffset(member, offset, commit2) {
40916
+ const { x, y } = member.initialOffset;
40917
+ drawPreviewDraft(member.element, { translate: { x: offset.x - x, y: offset.y - y } });
40330
40918
  if (member.plainTranslate) writeTranslatePx(member.element, offset);
40331
40919
  else if (applyOffsetDragDraftViaGsap(member.element, offset, member.baseGsap)) return;
40332
40920
  else if (commit2) applyStudioPathOffset(member.element, offset);
@@ -40392,6 +40980,7 @@ function endManualOffsetDragMembers(members) {
40392
40980
  for (const member of members) {
40393
40981
  if (!isStudioManualEditGestureCurrent(member.element, member.gestureToken)) continue;
40394
40982
  endStudioManualEditGesture(member.element, member.gestureToken);
40983
+ endPreviewDraft(member.element, "keep");
40395
40984
  member.element.removeAttribute("data-hf-drag-initial-offset-x");
40396
40985
  member.element.removeAttribute("data-hf-drag-initial-offset-y");
40397
40986
  member.element.removeAttribute("data-hf-drag-gsap-base-x");
@@ -40445,6 +41034,13 @@ function showMemberPosition(member, position) {
40445
41034
  if (!member.plainTranslate)
40446
41035
  stampGestureBase(member.element, member.initialOffset, member.baseGsap);
40447
41036
  }
41037
+ function redrawMemberOnFrame(member) {
41038
+ const { element, initialOffset } = member;
41039
+ const offset = member.plainTranslate ? readTranslatePx(element) : readAppliedStudioPathOffset(element);
41040
+ const translate = { x: offset.x - initialOffset.x, y: offset.y - initialOffset.y };
41041
+ if (Number.isFinite(translate.x) && Number.isFinite(translate.y) && (translate.x || translate.y))
41042
+ drawPreviewDraft(element, { translate });
41043
+ }
40448
41044
  function manualOffsetMoveRevert(members) {
40449
41045
  const startPlacement = members.map((member) => placementOf(member.element));
40450
41046
  return () => {
@@ -40456,7 +41052,10 @@ function manualOffsetMoveRevert(members) {
40456
41052
  placement: startPlacement[i]
40457
41053
  })
40458
41054
  );
40459
- return () => members.forEach((member, i) => showMemberPosition(member, shown3[i]));
41055
+ return () => members.forEach((member, i) => {
41056
+ showMemberPosition(member, shown3[i]);
41057
+ redrawMemberOnFrame(member);
41058
+ });
40460
41059
  };
40461
41060
  }
40462
41061
  var GSAP_LOOK_PROPS = ["x", "y", "rotation", "scaleX", "scaleY"];
@@ -40570,6 +41169,9 @@ function readRotationBase(element, plain) {
40570
41169
  return gsapRotation + readStudioRotation(element).angle;
40571
41170
  }
40572
41171
 
41172
+ // src/components/editor/snapTargetCollection.ts
41173
+ import { snapCandidates } from "@hyperframes/core/runtime/editing-port";
41174
+
40573
41175
  // src/components/editor/snapEngine.ts
40574
41176
  var SNAP_THRESHOLD_PX = 6;
40575
41177
  var SNAP_ENGAGE_TRAVEL_PX = 4;
@@ -40867,30 +41469,20 @@ function readPositiveDimension2(value) {
40867
41469
  const parsed = Number.parseFloat(value);
40868
41470
  return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
40869
41471
  }
40870
- var IGNORED_TAGS = /* @__PURE__ */ new Set(["script", "style", "link", "meta", "base", "template", "br", "wbr"]);
40871
- function isHtmlElement7(node) {
40872
- return node.nodeType === 1;
40873
- }
40874
- function collectVisibleElements(root, excludeElements, maxItems) {
40875
- const result = [];
40876
- const visit = (el) => {
40877
- if (result.length >= maxItems) return;
40878
- for (const child of Array.from(el.children)) {
40879
- if (!isHtmlElement7(child)) continue;
40880
- if (IGNORED_TAGS.has(child.tagName.toLowerCase())) continue;
40881
- if (child.hasAttribute("data-composition-id")) continue;
40882
- if (excludeElements.has(child)) continue;
40883
- if (!isElementVisibleForOverlay(child)) continue;
40884
- result.push(child);
40885
- visit(child);
40886
- }
40887
- };
40888
- visit(root);
40889
- return result;
41472
+ function snapContextFromRects(composition, rects) {
41473
+ const prefs = readStudioUiPreferences();
41474
+ const entries = rects.flatMap((rect, i) => rect ? [{ rect, id: `snap-target-${i}` }] : []);
41475
+ const gridSpacing = prefs.gridSpacing ?? 50;
41476
+ const snapToGrid = prefs.snapToGrid ?? false;
41477
+ return {
41478
+ targets: extractSnapTargets(entries),
41479
+ compositionTarget: buildCompositionSnapTarget(composition),
41480
+ gridEdges: snapToGrid && gridSpacing > 0 ? buildGridSnapEdges(composition, gridSpacing, composition.editScaleX) : null,
41481
+ snapEnabled: prefs.snapEnabled ?? true
41482
+ };
40890
41483
  }
40891
41484
  function collectSnapContext(input) {
40892
- const prefs = readStudioUiPreferences();
40893
- const snapEnabled = prefs.snapEnabled ?? true;
41485
+ const snapEnabled = readStudioUiPreferences().snapEnabled ?? true;
40894
41486
  const doc = input.iframe.contentDocument;
40895
41487
  if (!doc) {
40896
41488
  return { targets: [], compositionTarget: null, gridEdges: null, snapEnabled };
@@ -40906,32 +41498,19 @@ function collectSnapContext(input) {
40906
41498
  }
40907
41499
  const iframeRect = input.iframe.getBoundingClientRect();
40908
41500
  const overlayRect = input.overlayEl.getBoundingClientRect();
40909
- const rootScaleX = iframeRect.width / rootWidth;
40910
- const rootScaleY = iframeRect.height / rootHeight;
40911
41501
  const compositionOverlayRect = {
40912
41502
  left: iframeRect.left - overlayRect.left,
40913
41503
  top: iframeRect.top - overlayRect.top,
40914
41504
  width: iframeRect.width,
40915
41505
  height: iframeRect.height,
40916
- editScaleX: rootScaleX,
40917
- editScaleY: rootScaleY
41506
+ editScaleX: iframeRect.width / rootWidth,
41507
+ editScaleY: iframeRect.height / rootHeight
40918
41508
  };
40919
- const compositionTarget = buildCompositionSnapTarget(compositionOverlayRect);
40920
- const MAX_SNAP_TARGETS = 80;
40921
- const elements = collectVisibleElements(root, input.excludeElements, MAX_SNAP_TARGETS);
40922
- const entries = [];
40923
- for (let i = 0; i < elements.length; i++) {
40924
- const rect = toVisibleOverlayRect(input.overlayEl, input.iframe, elements[i]);
40925
- if (rect) entries.push({ rect, id: `snap-target-${i}` });
40926
- }
40927
- const targets = extractSnapTargets(entries);
40928
- let gridEdges = null;
40929
- const gridSpacing = prefs.gridSpacing ?? 50;
40930
- const snapToGrid = prefs.snapToGrid ?? false;
40931
- if (snapToGrid && gridSpacing > 0) {
40932
- gridEdges = buildGridSnapEdges(compositionOverlayRect, gridSpacing, rootScaleX);
40933
- }
40934
- return { targets, compositionTarget, gridEdges, snapEnabled };
41509
+ const elements = snapCandidates(root, input.excludeElements);
41510
+ const rects = elements.map(
41511
+ (element) => toVisibleOverlayRect(input.overlayEl, input.iframe, element)
41512
+ );
41513
+ return snapContextFromRects(compositionOverlayRect, rects);
40935
41514
  }
40936
41515
  function buildExcludeElements(input) {
40937
41516
  const elements = /* @__PURE__ */ new Set();
@@ -41047,7 +41626,7 @@ function notifyBlockedPress(e, opts, selection) {
41047
41626
  if (e.button !== 0 || selection.capabilities.commitCheckPending) return;
41048
41627
  opts.onBlockedMoveRef.current(selection);
41049
41628
  }
41050
- function startGroupDrag(e, opts, at) {
41629
+ function startGroupDrag(e, opts, at, snap) {
41051
41630
  const items = opts.groupOverlayItemsRef.current;
41052
41631
  if (items.length <= 1) return false;
41053
41632
  const blockedSelection = items.find(
@@ -41059,6 +41638,13 @@ function startGroupDrag(e, opts, at) {
41059
41638
  notifyBlockedPress(e, opts, blockedSelection);
41060
41639
  return false;
41061
41640
  }
41641
+ const moving2 = items.find((item) => item.start?.gsap?.moving)?.selection;
41642
+ if (moving2) {
41643
+ e.preventDefault();
41644
+ e.stopPropagation();
41645
+ opts.onBlockedMoveRef.current(moving2, MOVING_LAYER_UNREADABLE);
41646
+ return false;
41647
+ }
41062
41648
  opts.onManualDragStartRef.current?.();
41063
41649
  const dragItems = filterNestedDomEditGroupItems(items);
41064
41650
  const members = [];
@@ -41069,7 +41655,8 @@ function startGroupDrag(e, opts, at) {
41069
41655
  element: item.element,
41070
41656
  rect: item.rect,
41071
41657
  gesture: "drag",
41072
- at
41658
+ at,
41659
+ start: item.start
41073
41660
  });
41074
41661
  if (!result.ok) {
41075
41662
  restoreManualOffsetDragMembers(members);
@@ -41099,14 +41686,14 @@ function startGroupDrag(e, opts, at) {
41099
41686
  });
41100
41687
  const overlayEl = opts.overlayRef.current;
41101
41688
  const iframe = opts.iframeRef.current;
41102
- const snapContext = overlayEl && iframe ? collectSnapContext({
41689
+ const snapContext = snap ?? (overlayEl && iframe ? collectSnapContext({
41103
41690
  overlayEl,
41104
41691
  iframe,
41105
41692
  excludeElements: buildExcludeElements({
41106
41693
  iframe,
41107
41694
  groupSelections: items.map((i) => i.selection)
41108
41695
  })
41109
- }) : void 0;
41696
+ }) : void 0);
41110
41697
  e.preventDefault();
41111
41698
  e.stopPropagation();
41112
41699
  e.currentTarget.setPointerCapture(e.pointerId);
@@ -41128,6 +41715,7 @@ function startGroupDrag(e, opts, at) {
41128
41715
  }
41129
41716
  function startGesture(kind, e, opts, options) {
41130
41717
  const at = options?.at;
41718
+ const start = options?.start;
41131
41719
  const sel = options?.selection ?? opts.selectionRef.current;
41132
41720
  const rect = options?.rect ?? opts.overlayRectRef.current;
41133
41721
  const box = opts.boxRef.current;
@@ -41141,8 +41729,8 @@ function startGesture(kind, e, opts, options) {
41141
41729
  if (kind === "resize" && (!Number.isFinite(rect.width) || !Number.isFinite(rect.height)))
41142
41730
  return false;
41143
41731
  const size = readStudioBoxSize(sel.element);
41144
- const layoutWidth = sel.element.offsetWidth;
41145
- const layoutHeight = sel.element.offsetHeight;
41732
+ const layoutWidth = start?.layout.width ?? sel.element.offsetWidth;
41733
+ const layoutHeight = start?.layout.height ?? sel.element.offsetHeight;
41146
41734
  const actualWidth = size.width > 0 ? size.width : layoutWidth > 0 ? layoutWidth : rect.width / rect.editScaleX;
41147
41735
  const actualHeight = size.height > 0 ? size.height : layoutHeight > 0 ? layoutHeight : rect.height / rect.editScaleY;
41148
41736
  const rawContentScaleX = rect.width / (rect.editScaleX * actualWidth);
@@ -41157,6 +41745,11 @@ function startGesture(kind, e, opts, options) {
41157
41745
  let manualEditDragToken;
41158
41746
  let pathOffsetMember;
41159
41747
  if (kind === "drag") {
41748
+ if (start?.gsap?.moving) {
41749
+ opts.onBlockedMoveRef.current(sel, MOVING_LAYER_UNREADABLE);
41750
+ e.preventDefault();
41751
+ return false;
41752
+ }
41160
41753
  opts.onManualDragStartRef.current?.();
41161
41754
  const result = createManualOffsetDragMember({
41162
41755
  key: selectionCacheKey(sel),
@@ -41164,7 +41757,8 @@ function startGesture(kind, e, opts, options) {
41164
41757
  element: sel.element,
41165
41758
  rect,
41166
41759
  gesture: "drag",
41167
- at
41760
+ at,
41761
+ start
41168
41762
  });
41169
41763
  if (!result.ok) {
41170
41764
  opts.onBlockedMoveRef.current(result.selection, result.reason);
@@ -41183,7 +41777,8 @@ function startGesture(kind, e, opts, options) {
41183
41777
  element: sel.element,
41184
41778
  rect,
41185
41779
  gesture: "resize",
41186
- at
41780
+ at,
41781
+ start
41187
41782
  });
41188
41783
  if (result.ok) {
41189
41784
  pathOffsetMember = result.member;
@@ -41214,7 +41809,7 @@ function startGesture(kind, e, opts, options) {
41214
41809
  const corners = elementCornerOverlayPoints(overlayEl, iframe, sel.element);
41215
41810
  if (corners) resizeFixedCenterStart = overlayCornersCentroid(corners);
41216
41811
  }
41217
- const snapContext = (kind === "drag" || kind === "resize") && overlayEl && iframe ? collectSnapContext({
41812
+ const snapContext = (kind === "drag" || kind === "resize") && overlayEl && iframe ? options?.snap ?? collectSnapContext({
41218
41813
  overlayEl,
41219
41814
  iframe,
41220
41815
  excludeElements: buildExcludeElements({ iframe, selection: sel })
@@ -41291,294 +41886,43 @@ function editMoment(stamp) {
41291
41886
  return stamp?.at ?? playheadMoment();
41292
41887
  }
41293
41888
 
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
41889
+ // src/components/editor/previewGestureStartRead.ts
41890
+ async function measurePreviewGestureStart(iframe, overlayEl, handles) {
41891
+ const reply = await previewGestureStart(iframe, handles);
41892
+ const scale = reply && computeOverlayRootScale(overlayEl, iframe, null);
41893
+ if (!reply || !scale) return null;
41894
+ const { iframeRect, overlayRect, rootScaleX: sx, rootScaleY: sy } = scale;
41895
+ const screenToOffset = (move) => move && invertManualOffsetDragMatrix({
41896
+ a: move.a * sx,
41897
+ b: move.b * sy,
41898
+ c: move.c * sx,
41899
+ d: move.d * sy
41435
41900
  });
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)
41901
+ const composition = {
41902
+ left: iframeRect.left - overlayRect.left,
41903
+ top: iframeRect.top - overlayRect.top,
41904
+ width: iframeRect.width,
41905
+ height: iframeRect.height,
41906
+ editScaleX: sx,
41907
+ editScaleY: sy
41445
41908
  };
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
41909
  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
41910
+ elements: reply.elements.map(
41911
+ (start) => start && {
41912
+ rect: groupAwareRect(scale, start, true),
41913
+ start: {
41914
+ layout: start.layout,
41915
+ screenToOffset: screenToOffset(start.move),
41916
+ gsap: start.gsap
41917
+ }
41918
+ }
41919
+ ),
41920
+ snap: snapContextFromRects(
41921
+ composition,
41922
+ reply.snap.map((box) => flatVisibleRect(scale, box))
41923
+ )
41523
41924
  };
41524
41925
  }
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
41926
 
41583
41927
  // src/components/editor/previewGestureStarts.ts
41584
41928
  var MAX_SETTLED_WAIT_FRAMES = 60;
@@ -41668,16 +42012,19 @@ function createPreviewGestureStarts(opts, moveActiveGesture, releaseActiveGestur
41668
42012
  );
41669
42013
  const handles = found.map((element) => element?.handle);
41670
42014
  if (!overlay || !handles.length || !handles.every(Boolean)) return null;
41671
- const rects = await measurePreviewRects(iframe, overlay, handles);
42015
+ const read2 = await measurePreviewGestureStart(iframe, overlay, handles);
41672
42016
  const shown3 = selections.flatMap((selection, i) => {
41673
- const rect = rects?.[i];
41674
- return rect ? [{ selection: { ...selection, handle: handles[i] }, rect }] : [];
42017
+ const element = read2?.elements[i];
42018
+ return element ? [{ selection: { ...selection, handle: handles[i] }, ...element }] : [];
41675
42019
  });
41676
- return shown3.length === selections.length ? shown3 : null;
42020
+ return read2 && shown3.length === selections.length ? { shown: shown3, snap: read2.snap } : null;
41677
42021
  };
41678
42022
  const startOnShownPreview = (e, pressed, start, draw = null, targets = () => []) => {
41679
42023
  const at = playheadMoment();
41680
- if (!isPreviewChanging() && !opts.waitingPressRef.current) return start(e, at, false);
42024
+ const iframe = opts.iframeRef.current;
42025
+ const channel = iframe && previewFrameOpaque(iframe) ? iframe : null;
42026
+ if (!channel && !isPreviewChanging() && !opts.waitingPressRef.current)
42027
+ return start(e, at, false);
41681
42028
  e.preventDefault();
41682
42029
  e.stopPropagation();
41683
42030
  e.currentTarget.setPointerCapture(e.pointerId);
@@ -41712,8 +42059,6 @@ function createPreviewGestureStarts(opts, moveActiveGesture, releaseActiveGestur
41712
42059
  settledFrames = settled ? settledFrames + 1 : 0;
41713
42060
  return elements.length;
41714
42061
  };
41715
- const iframe = opts.iframeRef.current;
41716
- const channel = iframe && previewFrameOpaque(iframe) ? iframe : null;
41717
42062
  let overChannel;
41718
42063
  let asked = false;
41719
42064
  const channelStep = (frame3) => {
@@ -41779,11 +42124,12 @@ function createPreviewGestureStarts(opts, moveActiveGesture, releaseActiveGestur
41779
42124
  (pressed, at, waited, overChannel) => {
41780
42125
  if (!waited) return startGroupDrag(pressed, opts, at);
41781
42126
  if (overChannel) {
41782
- const measured2 = items.map((item, i) => ({ ...item, ...overChannel[i] }));
42127
+ const measured2 = items.map((item, i) => ({ ...item, ...overChannel.shown[i] }));
41783
42128
  return startGroupDrag(
41784
42129
  pressed,
41785
42130
  { ...opts, groupOverlayItemsRef: { current: measured2 } },
41786
- at
42131
+ at,
42132
+ overChannel.snap
41787
42133
  );
41788
42134
  }
41789
42135
  const overlay = opts.overlayRef.current;
@@ -41825,13 +42171,15 @@ function createPreviewGestureStarts(opts, moveActiveGesture, releaseActiveGestur
41825
42171
  },
41826
42172
  (pressed, at, waited, overChannel) => {
41827
42173
  if (!waited) return startGesture(kind, pressed, opts, { ...options, at });
41828
- const shown3 = overChannel ? overChannel[0] : shownOnPage(target);
42174
+ const shown3 = overChannel ? overChannel.shown[0] : shownOnPage(target);
41829
42175
  return !!shown3 && startGesture(kind, pressed, opts, {
41830
42176
  selection: shown3.selection,
41831
42177
  rect: shown3.rect,
41832
42178
  resizeHandle: options?.resizeHandle,
41833
42179
  resizeCorner: options?.resizeCorner,
41834
- at
42180
+ at,
42181
+ start: shown3.start,
42182
+ snap: overChannel?.snap
41835
42183
  });
41836
42184
  },
41837
42185
  draw,
@@ -41874,7 +42222,34 @@ function resolveAnchoredResizeDraft(g, member, element, overlayEl, iframe, measu
41874
42222
  angle: g.actualRotation
41875
42223
  };
41876
42224
  }
42225
+ function resolveUnmeasuredResizeDraft(g, element, { written }) {
42226
+ const width = g.originWidth * written.width / g.actualWidth;
42227
+ const height = g.originHeight * written.height / g.actualHeight;
42228
+ if (g.pathOffsetMember) {
42229
+ const anchor2 = {
42230
+ dx: (g.actualWidth - written.width) / 2 * g.editScaleX,
42231
+ dy: (g.actualHeight - written.height) / 2 * g.editScaleY
42232
+ };
42233
+ g.lastResizeAnchor = anchor2;
42234
+ applyManualOffsetDragDraft(g.pathOffsetMember, anchor2.dx, anchor2.dy);
42235
+ }
42236
+ drawPreviewDraft(element, { size: written });
42237
+ return {
42238
+ left: g.originLeft + (g.originWidth - width) / 2,
42239
+ top: g.originTop + (g.originHeight - height) / 2,
42240
+ width,
42241
+ height,
42242
+ editScaleX: g.editScaleX,
42243
+ editScaleY: g.editScaleY,
42244
+ angle: g.actualRotation
42245
+ };
42246
+ }
42247
+ function endResizeWithoutMember(element, token) {
42248
+ if (!token || isStudioManualEditGestureCurrent(element, token)) endPreviewDraft(element, "keep");
42249
+ endStudioManualEditGesture(element, token);
42250
+ }
41877
42251
  function resolveResizeDraftRect(g, element, overlayEl, iframe, measureOrientedRect, sizes) {
42252
+ if (iframe && previewFrameOpaque(iframe)) return resolveUnmeasuredResizeDraft(g, element, sizes);
41878
42253
  if (g.pathOffsetMember) {
41879
42254
  return resolveAnchoredResizeDraft(
41880
42255
  g,
@@ -42445,7 +42820,7 @@ function createDomEditOverlayGestureHandlers(opts) {
42445
42820
  logGestureCommitFailure("resize commit failed", error);
42446
42821
  }).finally(() => {
42447
42822
  if (member) endManualOffsetDragMembers([member]);
42448
- else endStudioManualEditGesture(sel.element, g.manualEditDragToken);
42823
+ else endResizeWithoutMember(sel.element, g.manualEditDragToken);
42449
42824
  });
42450
42825
  edit.settle(saved2);
42451
42826
  logResizeSettle(sel.element, "post-release");
@@ -44603,7 +44978,7 @@ function placeCaretAtEnd(element) {
44603
44978
  }
44604
44979
 
44605
44980
  // src/components/editor/domEditInlineText.ts
44606
- import { isRichTextFormattingTag as isRichTextFormattingTag2 } from "@hyperframes/core/rich-text-sanitize";
44981
+ import { hasOnlyFormattingChildren } from "@hyperframes/core/runtime/editing-port";
44607
44982
  function canEditTextInline(selection) {
44608
44983
  if (!selection) return false;
44609
44984
  if (!isTextEditableSelection(selection)) return false;
@@ -44620,17 +44995,6 @@ function canEditElementTextInline(element) {
44620
44995
  if (element.isContentEditable) return false;
44621
44996
  return (element.textContent ?? "").trim().length > 0;
44622
44997
  }
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
44998
  var DOUBLE_PRESS_MS = 450;
44635
44999
  var DOUBLE_PRESS_SLOP_PX = 6;
44636
45000
  function isDoublePress(previous, next) {
@@ -49339,7 +49703,7 @@ function keyframeCount(anim) {
49339
49703
  }
49340
49704
 
49341
49705
  // src/components/editor/MotionPathOverlay.tsx
49342
- import { isHtmlElement as isHtmlElement9 } from "@hyperframes/core/runtime/dom-realm";
49706
+ import { isHtmlElement as isHtmlElement8 } from "@hyperframes/core/runtime/dom-realm";
49343
49707
 
49344
49708
  // src/components/editor/MotionPathNode.tsx
49345
49709
  import { Fragment as Fragment33, jsx as jsx115, jsxs as jsxs80 } from "react/jsx-runtime";
@@ -50001,7 +50365,7 @@ function elementHome(el) {
50001
50365
 
50002
50366
  // src/components/editor/useMotionPathData.ts
50003
50367
  import { useEffect as useEffect64, useRef as useRef81, useState as useState60 } from "react";
50004
- import { isHtmlElement as isHtmlElement8 } from "@hyperframes/core/runtime/dom-realm";
50368
+ import { isHtmlElement as isHtmlElement7 } from "@hyperframes/core/runtime/dom-realm";
50005
50369
  function transformWDivisor(el) {
50006
50370
  const t2 = el.ownerDocument?.defaultView?.getComputedStyle(el).transform;
50007
50371
  if (!t2 || !t2.startsWith("matrix3d(")) return 1;
@@ -50057,7 +50421,7 @@ function useMotionPathData(iframeRef, selector) {
50057
50421
  target = el.contentDocument?.querySelector(selector) ?? null;
50058
50422
  } catch {
50059
50423
  }
50060
- const live = isHtmlElement8(target) ? target : null;
50424
+ const live = isHtmlElement7(target) ? target : null;
50061
50425
  const vis = live ? isElementVisibleForOverlay(live) : true;
50062
50426
  setVisibleInPreview((prev) => prev === vis ? prev : vis);
50063
50427
  if (live) {
@@ -50178,7 +50542,7 @@ var MotionPathOverlay = memo31(function MotionPathOverlay2({
50178
50542
  return;
50179
50543
  }
50180
50544
  const live = frame3.contentDocument?.querySelector(createSelector);
50181
- if (!isHtmlElement9(live)) return;
50545
+ if (!isHtmlElement8(live)) return;
50182
50546
  e.stopPropagation();
50183
50547
  e.preventDefault();
50184
50548
  const sc = r.width / compW;
@@ -52282,9 +52646,14 @@ function useTimelineSelectionPreviewSync({
52282
52646
  const currentDomEditGroupSelections = domEditGroupSelectionsRef.current;
52283
52647
  const currentSelections = currentDomEditGroupSelections.length > 1 ? currentDomEditGroupSelections : currentDomEditSelection ? [currentDomEditSelection] : [];
52284
52648
  const currentIds = currentSelections.map(
52285
- (selection) => resolveTimelineIdForSelection(selection, timelineElements, activeCompPath)
52649
+ (selection) => resolveTimelineIdForSelection(selection, timelineElements, activeCompPath, true)
52286
52650
  ).filter((id) => Boolean(id));
52287
- const currentAnchor = currentDomEditSelection ? resolveTimelineIdForSelection(currentDomEditSelection, timelineElements, activeCompPath) : null;
52651
+ const currentAnchor = currentDomEditSelection ? resolveTimelineIdForSelection(
52652
+ currentDomEditSelection,
52653
+ timelineElements,
52654
+ activeCompPath,
52655
+ true
52656
+ ) : null;
52288
52657
  if (selectedIds.length === 0) {
52289
52658
  missingSelectionKeyRef.current = "";
52290
52659
  unresolvedAttemptsRef.current = { id: "", count: 0 };
@@ -77419,7 +77788,7 @@ function useEditorSave({
77419
77788
  if (lastFailureToastAtRef.current === null || now2 - lastFailureToastAtRef.current >= FAILURE_BURST_MS) {
77420
77789
  lastFailureToastAtRef.current = now2;
77421
77790
  showToast(
77422
- `Couldn't save ${path}. Your latest edits are NOT persisted. Check the preview server; editing again retries the save.`,
77791
+ heldFileWords(error) ?? `Couldn't save ${path}. Your latest edits are NOT persisted. Check the preview server; editing again retries the save.`,
77423
77792
  "error"
77424
77793
  );
77425
77794
  }
@@ -77508,7 +77877,8 @@ async function fetchProjectFile(projectId, path, query) {
77508
77877
  const response = await studioApiFetch(
77509
77878
  `/api/projects/${encodeURIComponent(projectId)}/files/${encodeURIComponent(path)}${query}`
77510
77879
  );
77511
- if (!response.ok) throw new Error(`Failed to read ${path}`);
77880
+ if (!response.ok)
77881
+ throw await createStudioSaveHttpError(response, `Failed to read ${path}`, { path });
77512
77882
  const data = await response.json();
77513
77883
  return { content: data.content, version: data.version ?? response.headers.get("etag") };
77514
77884
  }
@@ -77561,7 +77931,9 @@ function useProjectFileWriter({ projectId }) {
77561
77931
  } else if (preflight.status === 404) {
77562
77932
  expectedVersion = null;
77563
77933
  } else {
77564
- throw await createStudioSaveHttpError(preflight, `Failed to read ${path} before save`);
77934
+ throw await createStudioSaveHttpError(preflight, `Failed to read ${path} before save`, {
77935
+ path
77936
+ });
77565
77937
  }
77566
77938
  }
77567
77939
  await retryStudioSave(async () => {
@@ -77598,7 +77970,8 @@ function useProjectFileWriter({ projectId }) {
77598
77970
  attemptedContent: content
77599
77971
  });
77600
77972
  }
77601
- if (!response.ok) throw await createStudioSaveHttpError(response, `Failed to save ${path}`);
77973
+ if (!response.ok)
77974
+ throw await createStudioSaveHttpError(response, `Failed to save ${path}`, { path });
77602
77975
  const result = await response.json();
77603
77976
  const version = result.version ?? response.headers.get("etag");
77604
77977
  if (!version)
@@ -78950,7 +79323,9 @@ async function insertTimelineComposition(input) {
78950
79323
  buildProjectApiPath(input.projectId, `/files/${encodeURIComponent(input.targetPath)}`)
78951
79324
  );
78952
79325
  if (!current2.ok) {
78953
- throw await createStudioSaveHttpError(current2, `Failed to read ${input.targetPath}`);
79326
+ throw await createStudioSaveHttpError(current2, `Failed to read ${input.targetPath}`, {
79327
+ path: input.targetPath
79328
+ });
78954
79329
  }
78955
79330
  const snapshot3 = await current2.json();
78956
79331
  if (typeof snapshot3.version !== "string") throw new Error("Missing composition file version");
@@ -81883,6 +82258,7 @@ import { HF_AUDIO_GROUP_TAG as HF_AUDIO_GROUP_TAG7 } from "@hyperframes/core/aud
81883
82258
  function announceTimelineSelection(deps, group, primary, replaceSet = false) {
81884
82259
  const {
81885
82260
  timelineElements,
82261
+ activeCompPath,
81886
82262
  getTimelineSelectionSet: getTimelineSelectionSet2,
81887
82263
  setSelectedTimelineElementId,
81888
82264
  setTimelineSelectionSet
@@ -81892,7 +82268,7 @@ function announceTimelineSelection(deps, group, primary, replaceSet = false) {
81892
82268
  setSelectedTimelineElementId(null);
81893
82269
  return;
81894
82270
  }
81895
- const timelineIdFor = (selection) => findMatchingTimelineElementId(selection, timelineElements) ?? findTimelineIdByAncestor(
82271
+ const timelineIdFor = (selection) => findMatchingTimelineElementId(selection, timelineElements, activeCompPath || "index.html") ?? findTimelineIdByAncestor(
81896
82272
  selection.element,
81897
82273
  timelineElements,
81898
82274
  selection.sourceFile || "index.html"
@@ -81962,6 +82338,7 @@ function useDomSelection({
81962
82338
  (group, primary, replaceSet) => announceTimelineSelection(
81963
82339
  {
81964
82340
  timelineElements,
82341
+ activeCompPath,
81965
82342
  getTimelineSelectionSet: getTimelineSelectionSet2,
81966
82343
  setSelectedTimelineElementId,
81967
82344
  setTimelineSelectionSet
@@ -81971,6 +82348,7 @@ function useDomSelection({
81971
82348
  replaceSet
81972
82349
  ),
81973
82350
  [
82351
+ activeCompPath,
81974
82352
  getTimelineSelectionSet2,
81975
82353
  setSelectedTimelineElementId,
81976
82354
  setTimelineSelectionSet,
@@ -82342,6 +82720,7 @@ function usePreviewInteraction({
82342
82720
  }) {
82343
82721
  const cycleRef = useRef149(null);
82344
82722
  const lastDownRef = useRef149(null);
82723
+ const hoverSeqRef = useRef149(0);
82345
82724
  const pausePreviewPlayback = useCallback130(() => {
82346
82725
  const pausedTime = pauseStudioPreviewPlayback(previewIframeRef.current);
82347
82726
  const playerStore = usePlayerStore.getState();
@@ -82457,6 +82836,7 @@ function usePreviewInteraction({
82457
82836
  const handlePreviewCanvasPointerMove = useCallback130(
82458
82837
  // fallow-ignore-next-line complexity
82459
82838
  async (e, options) => {
82839
+ const seq = ++hoverSeqRef.current;
82460
82840
  if (captionEditMode || compositionLoading) {
82461
82841
  updateDomEditHoverSelection(null);
82462
82842
  return null;
@@ -82465,7 +82845,7 @@ function usePreviewInteraction({
82465
82845
  preferClipAncestor: options?.preferClipAncestor ?? false,
82466
82846
  skipSourceProbe: true
82467
82847
  });
82468
- updateDomEditHoverSelection(nextSelection);
82848
+ if (seq === hoverSeqRef.current) updateDomEditHoverSelection(nextSelection);
82469
82849
  return nextSelection;
82470
82850
  },
82471
82851
  [
@@ -82476,6 +82856,7 @@ function usePreviewInteraction({
82476
82856
  ]
82477
82857
  );
82478
82858
  const handlePreviewCanvasPointerLeave = useCallback130(() => {
82859
+ hoverSeqRef.current += 1;
82479
82860
  updateDomEditHoverSelection(null);
82480
82861
  }, [updateDomEditHoverSelection]);
82481
82862
  const handleBlockedDomMove = useCallback130(
@@ -96784,25 +97165,13 @@ import { memo as memo62, useCallback as useCallback192 } from "react";
96784
97165
  import { memo as memo52, useState as useState153, useCallback as useCallback176, useEffect as useEffect151, useRef as useRef184 } from "react";
96785
97166
 
96786
97167
  // 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
- }
97168
+ import { isCompositionHost, layerKindOf } from "@hyperframes/core/runtime/editing-port";
96800
97169
 
96801
97170
  // src/components/editor/useLayerDrag.ts
96802
97171
  import { useRef as useRef183, useState as useState152, useCallback as useCallback175 } from "react";
96803
97172
  var DRAG_THRESHOLD_PX4 = 4;
96804
97173
  function isLayerDraggable(layer) {
96805
- if (!(layer.selector || layer.id)) return false;
97174
+ if (!(layer.selector || layer.id) || layer.preview) return false;
96806
97175
  let el = layer.element;
96807
97176
  while (el) {
96808
97177
  if (el.hasAttribute("data-timeline-locked")) return false;
@@ -96977,8 +97346,8 @@ function sortLayersByZIndex(layers) {
96977
97346
  return layers;
96978
97347
  }
96979
97348
  chunks.sort((a, b) => {
96980
- const zA = getElementZIndex(a.root.element);
96981
- const zB = getElementZIndex(b.root.element);
97349
+ const zA = a.root.preview?.zIndex ?? getElementZIndex(a.root.element);
97350
+ const zB = b.root.preview?.zIndex ?? getElementZIndex(b.root.element);
96982
97351
  if (zA !== zB) return zB - zA;
96983
97352
  return b.domIndex - a.domIndex;
96984
97353
  });
@@ -97078,9 +97447,24 @@ var LayersPanel = memo52(function LayersPanel2({ host }) {
97078
97447
  });
97079
97448
  const isMasterView = !activeCompPath || activeCompPath === "index.html";
97080
97449
  const livePreviewIframe = useLivePreviewIframe();
97450
+ const opaqueRead = useRef184(null);
97081
97451
  const collectLayers = useCallback176(() => {
97082
97452
  const iframe = previewIframeRef.current;
97083
97453
  if (!iframe) return;
97454
+ if (previewFrameOpaque(iframe)) {
97455
+ if (opaqueRead.current) return void (opaqueRead.current.again = true);
97456
+ const read2 = { again: false };
97457
+ opaqueRead.current = read2;
97458
+ const scope = { activeCompositionPath: activeCompPath, activeGroupElement };
97459
+ void collectPreviewLayerItems(iframe, scope, LAYERS_PANEL_MAX_ROWS).then((reply) => {
97460
+ if (opaqueRead.current !== read2) return;
97461
+ opaqueRead.current = null;
97462
+ if (reply?.missingGroup) return setActiveGroupElement(null);
97463
+ if (reply) setLayers(sortLayersByZIndex(reply.items));
97464
+ if (read2.again) collectLayers();
97465
+ });
97466
+ return;
97467
+ }
97084
97468
  let doc = null;
97085
97469
  try {
97086
97470
  doc = iframe.contentDocument;
@@ -97101,6 +97485,7 @@ var LayersPanel = memo52(function LayersPanel2({ host }) {
97101
97485
  setLayers(sortLayersByZIndex(items));
97102
97486
  }, [previewIframeRef, activeCompPath, isMasterView, activeGroupElement, setActiveGroupElement]);
97103
97487
  useEffect151(() => {
97488
+ opaqueRead.current = null;
97104
97489
  collectLayers();
97105
97490
  }, [collectLayers, refreshKey, zEditVersion, livePreviewIframe]);
97106
97491
  useEffect151(() => {
@@ -97127,15 +97512,20 @@ var LayersPanel = memo52(function LayersPanel2({ host }) {
97127
97512
  };
97128
97513
  }, [collectLayers]);
97129
97514
  const resolveSelection = useCallback176(
97130
- (layer) => {
97131
- const doc = previewIframeRef.current?.contentDocument;
97132
- const el = liveLayerElement(layer, doc, activeCompPath);
97133
- return resolveDomEditSelection(el, {
97515
+ async (layer) => {
97516
+ const iframe = previewIframeRef.current;
97517
+ const options = {
97134
97518
  activeCompositionPath: activeCompPath,
97135
97519
  isMasterView,
97136
97520
  preferClipAncestor: false,
97137
97521
  activeGroupElement
97138
- });
97522
+ };
97523
+ if (layer.preview && iframe) {
97524
+ const [described] = await describePreviewElements(iframe, [layer.preview.handle]) ?? [];
97525
+ return described ? resolvePreviewSelection(iframe, described, options) : null;
97526
+ }
97527
+ const el = liveLayerElement(layer, iframe?.contentDocument, activeCompPath);
97528
+ return resolveDomEditSelection(el, options);
97139
97529
  },
97140
97530
  [activeCompPath, isMasterView, previewIframeRef, activeGroupElement]
97141
97531
  );
@@ -97143,7 +97533,8 @@ var LayersPanel = memo52(function LayersPanel2({ host }) {
97143
97533
  async (layer) => {
97144
97534
  const selection = await resolveSelection(layer);
97145
97535
  if (!selection) return;
97146
- let matchedId = findMatchingTimelineElementId(selection, timelineElements);
97536
+ const scope = activeCompPath || "index.html";
97537
+ let matchedId = findMatchingTimelineElementId(selection, timelineElements, scope);
97147
97538
  if (!matchedId) {
97148
97539
  const sourceFile = selection.sourceFile ?? "index.html";
97149
97540
  let ancestor = layer.element.parentElement;
@@ -97166,7 +97557,7 @@ var LayersPanel = memo52(function LayersPanel2({ host }) {
97166
97557
  }
97167
97558
  }
97168
97559
  },
97169
- [currentTime, resolveSelection, timelineElements]
97560
+ [activeCompPath, currentTime, resolveSelection, timelineElements]
97170
97561
  );
97171
97562
  const handleSelectLayer = useCallback176(
97172
97563
  async (layer) => {
@@ -97181,7 +97572,7 @@ var LayersPanel = memo52(function LayersPanel2({ host }) {
97181
97572
  const handleLayerDoubleClick = useCallback176(
97182
97573
  async (layer) => {
97183
97574
  const selection = await resolveSelection(layer);
97184
- if (selection?.element.hasAttribute("data-hf-group")) {
97575
+ if (selection && selectionDataAttribute(selection, "data-hf-group") !== null) {
97185
97576
  setActiveGroupElement(selection.element);
97186
97577
  } else {
97187
97578
  await handleSelectLayer(layer);
@@ -97327,8 +97718,8 @@ var LayersPanel = memo52(function LayersPanel2({ host }) {
97327
97718
  const draggable = isLayerDraggable(layer);
97328
97719
  const isCollapsed = collapsed[layer.key] ?? false;
97329
97720
  const hasChildren = layer.childCount > 0;
97330
- const isCompHost = isCompositionHost(layer.element);
97331
- const kind = layerKindOf(layer.element, hasChildren);
97721
+ const isCompHost = layer.preview ? layerDataAttribute(layer, "data-composition-src") !== null || layerDataAttribute(layer, "data-composition-file") !== null : isCompositionHost(layer.element);
97722
+ const kind = layer.preview?.kind ?? layerKindOf(layer.element, hasChildren);
97332
97723
  const KindIcon = KIND_ICON[kind];
97333
97724
  const kindName = kind[0].toUpperCase() + kind.slice(1);
97334
97725
  const hint = draggable ? layer.element.hasAttribute("data-hf-group") ? "Double-click to enter group" : void 0 : "This layer can't be reordered";