@hyperframes/studio 0.9.58 → 0.9.61

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 (57) hide show
  1. package/dist/assets/hyperframes-player-Cm0hYGm2.js +573 -0
  2. package/dist/assets/{index-D7ICtobF.js → index-BGrNWeLK.js} +199 -199
  3. package/dist/assets/{index-ww7-RmuM.js → index-REqr_dLu.js} +1 -1
  4. package/dist/assets/{pausedVideoDecoder-Dbe8Cmab.js → pausedVideoDecoder-DqLDSq8J.js} +1 -1
  5. package/dist/{chunk-5EEM5WO4.js → chunk-3KCEIESB.js} +1 -1
  6. package/dist/{chunk-G6FJSL7X.js → chunk-JTUKMELR.js} +34 -6
  7. package/dist/index.d.ts +29 -1
  8. package/dist/index.html +1 -1
  9. package/dist/index.js +734 -217
  10. package/dist/player.js +2 -2
  11. package/dist/ui.js +1 -1
  12. package/package.json +8 -8
  13. package/src/captions/components/CaptionOverlay.sealed.test.ts +273 -0
  14. package/src/captions/components/CaptionOverlay.tsx +112 -57
  15. package/src/captions/components/CaptionOverlayUtils.ts +319 -33
  16. package/src/captions/components/CaptionPropertyPanel.tsx +17 -0
  17. package/src/components/editor/LayersPanel.opaque.test.ts +2 -2
  18. package/src/components/editor/previewDrafts.test.ts +2 -2
  19. package/src/components/editor/previewGestureStartRead.test.ts +2 -2
  20. package/src/components/editor/previewLayers.test.ts +2 -2
  21. package/src/components/editor/previewOverlayRects.test.ts +2 -2
  22. package/src/components/editor/previewPointerTargets.test.ts +2 -2
  23. package/src/components/editor/previewSelection.test.ts +2 -2
  24. package/src/components/editor/useColorGradingController.sealed.test.ts +165 -0
  25. package/src/components/editor/useColorGradingController.ts +20 -1
  26. package/src/components/editor/useColorGradingPreviews.ts +127 -43
  27. package/src/components/nle/NLEPreview.test.ts +24 -0
  28. package/src/components/nle/NLEPreview.tsx +2 -6
  29. package/src/components/nle/previewStage.ts +11 -1
  30. package/src/components/panels/VariablesPanel.test.tsx +90 -1
  31. package/src/components/panels/VariablesPanel.tsx +41 -17
  32. package/src/components/panels/renderHandoff.test.ts +86 -0
  33. package/src/components/panels/renderHandoff.ts +28 -0
  34. package/src/components/ui/Menu.test.tsx +77 -0
  35. package/src/components/ui/Menu.tsx +47 -4
  36. package/src/components/ui/Popover.tsx +5 -2
  37. package/src/elementAnimations.test.ts +13 -0
  38. package/src/hooks/useCaptionDetection.ts +175 -54
  39. package/src/hooks/useMusicBeatAnalysis.test.tsx +131 -0
  40. package/src/hooks/useMusicBeatAnalysis.ts +51 -66
  41. package/src/hooks/usePersistentEditHistory.test.ts +84 -0
  42. package/src/hooks/usePersistentEditHistory.ts +36 -3
  43. package/src/hooks/useRenderClipContent.test.ts +21 -0
  44. package/src/hooks/useRenderClipContent.ts +3 -1
  45. package/src/index.ts +2 -0
  46. package/src/player/hooks/useShadowPreviewReload.ts +7 -0
  47. package/src/player/hooks/useTimelinePlayer.shadowReload.test.ts +20 -0
  48. package/src/player/lib/previewElements.test.ts +4 -0
  49. package/src/player/lib/previewElements.ts +1 -0
  50. package/src/sealedPreviewExports.test.ts +1 -0
  51. package/src/utils/gsapUndoRestore.sealed.test.ts +73 -0
  52. package/src/utils/gsapUndoRestore.ts +66 -0
  53. package/src/utils/studioPendingEdits.test.ts +20 -0
  54. package/src/utils/studioPendingEdits.ts +11 -4
  55. package/src/utils/timelineInspector.test.ts +49 -2
  56. package/src/utils/timelineInspector.ts +21 -2
  57. package/dist/assets/hyperframes-player-B78JDyI_.js +0 -565
package/dist/index.js CHANGED
@@ -91,7 +91,7 @@ import {
91
91
  whileScriptWrites,
92
92
  writeStudioUiPreferences,
93
93
  zoomToSelectedClips
94
- } from "./chunk-5EEM5WO4.js";
94
+ } from "./chunk-3KCEIESB.js";
95
95
  import {
96
96
  Button,
97
97
  ContextMenu,
@@ -124,7 +124,7 @@ import {
124
124
  fieldText,
125
125
  menuItemBase,
126
126
  popupSurface
127
- } from "./chunk-G6FJSL7X.js";
127
+ } from "./chunk-JTUKMELR.js";
128
128
  import {
129
129
  DEFAULT_STUDIO_KEYS
130
130
  } from "./chunk-USW3YBOG.js";
@@ -1605,6 +1605,12 @@ function isMusicTrack(element) {
1605
1605
  const id = element.domId ?? element.id ?? "";
1606
1606
  return MUSIC_ID_RE.test(id);
1607
1607
  }
1608
+ var MAX_BEAT_SOURCE_SECONDS = 15 * 60;
1609
+ function fitsBeatAnalysis({
1610
+ sourceDuration
1611
+ }) {
1612
+ return sourceDuration != null && sourceDuration <= MAX_BEAT_SOURCE_SECONDS;
1613
+ }
1608
1614
  function resolveBeatSourceTrack(elements) {
1609
1615
  const explicit = elements.find(isMusicTrack);
1610
1616
  if (explicit) return { element: explicit, isFallback: false };
@@ -1612,6 +1618,7 @@ function resolveBeatSourceTrack(elements) {
1612
1618
  for (const el of elements) {
1613
1619
  if (!isMusicSourceElement(el)) continue;
1614
1620
  if (el.timelineRole && el.timelineRole !== "music") continue;
1621
+ if (!fitsBeatAnalysis(el)) continue;
1615
1622
  if (!best || el.duration > best.duration) best = el;
1616
1623
  }
1617
1624
  return best ? { element: best, isFallback: true } : null;
@@ -2021,42 +2028,43 @@ function cacheAnalysis(url, promise) {
2021
2028
  analysisCache.delete(oldest);
2022
2029
  }
2023
2030
  }
2024
- async function resolveBeats(beatPath, detected, io) {
2025
- if (!beatPath) return { ...detected, hasFile: false };
2026
- try {
2027
- const content = await io.readOptionalProjectFile(beatPath);
2028
- const parsed = content ? parseBeats(content) : null;
2029
- if (parsed && parsed.times.length > 0) {
2030
- return { times: parsed.times, strengths: parsed.strengths, hasFile: true };
2031
- }
2032
- } catch {
2033
- }
2034
- return { ...detected, hasFile: false };
2035
- }
2036
- async function readHasSavedBeats(io, beatPath) {
2031
+ async function readSavedBeats(io, beatPath) {
2037
2032
  try {
2038
2033
  const content = await io.readOptionalProjectFile(beatPath);
2039
2034
  const parsed = content ? parseBeats(content) : null;
2040
- return !!(parsed && parsed.times.length > 0);
2035
+ return parsed && parsed.times.length > 0 ? { times: parsed.times, strengths: parsed.strengths } : null;
2041
2036
  } catch {
2042
- return false;
2037
+ return null;
2043
2038
  }
2044
2039
  }
2045
- async function loadBeatAnalysis(musicSrc, beatPath, io) {
2040
+ async function decodeTrack(musicSrc) {
2046
2041
  let promise = analysisCache.get(musicSrc);
2047
2042
  if (!promise) {
2048
2043
  promise = analyzeMusicFromUrl(musicSrc, { pause: whenTimelineIdle });
2049
2044
  cacheAnalysis(musicSrc, promise);
2050
2045
  }
2051
- try {
2052
- const analysis = await promise;
2053
- const detected = { times: analysis.beatTimes, strengths: analysis.beatStrengths };
2054
- const { times, strengths } = await resolveBeats(beatPath, detected, io);
2055
- return { analysis, times, strengths };
2056
- } catch {
2057
- return null;
2058
- }
2046
+ return promise.catch(() => null);
2059
2047
  }
2048
+ async function loadTrack(musicSrc, beatPath, io, isFallbackTrack, decodable) {
2049
+ const saved2 = await readSavedBeats(io, beatPath);
2050
+ if (!isFallbackTrack && !saved2) return null;
2051
+ if (!decodable) return saved2 && { analysis: savedOnly(saved2), ...saved2 };
2052
+ const analysis = await decodeTrack(musicSrc);
2053
+ if (!analysis) return null;
2054
+ return {
2055
+ analysis,
2056
+ ...saved2 ?? { times: analysis.beatTimes, strengths: analysis.beatStrengths }
2057
+ };
2058
+ }
2059
+ var savedOnly = ({ times, strengths }) => ({
2060
+ beatTimes: times,
2061
+ beatStrengths: strengths,
2062
+ bpm: null,
2063
+ bpmConfidence: "uncertain",
2064
+ channelData: null,
2065
+ sampleRate: 0,
2066
+ peak: 0
2067
+ });
2060
2068
  function useAdjustedBeatAnalysis() {
2061
2069
  const beatAnalysis = usePlayerStore((s) => s.beatAnalysis);
2062
2070
  const musicElement = usePlayerStore((s) => getTimelineElementIndexes(s.elements).musicElement);
@@ -2077,13 +2085,16 @@ function useMusicBeatAnalysis() {
2077
2085
  const writeProjectFile = fileManager?.writeProjectFile;
2078
2086
  const ioRef = useRef5(null);
2079
2087
  ioRef.current = readOptionalProjectFile && writeProjectFile ? { readOptionalProjectFile, writeProjectFile } : null;
2080
- const { musicSrc, isFallbackTrack } = useMemo2(() => {
2088
+ const { musicSrc, isFallbackTrack, decodable } = useMemo2(() => {
2081
2089
  const resolved2 = resolveBeatSourceTrack(elements);
2082
2090
  return {
2083
2091
  musicSrc: resolved2?.element.src ?? null,
2084
- isFallbackTrack: resolved2?.isFallback ?? false
2092
+ isFallbackTrack: resolved2?.isFallback ?? false,
2093
+ decodable: resolved2 ? fitsBeatAnalysis(resolved2.element) : false
2085
2094
  };
2086
2095
  }, [elements]);
2096
+ const decodableRef = useRef5(decodable);
2097
+ decodableRef.current = decodable;
2087
2098
  useEffect5(() => {
2088
2099
  if (!musicSrc) {
2089
2100
  setBeatAnalysis(null);
@@ -2102,16 +2113,7 @@ function useMusicBeatAnalysis() {
2102
2113
  const io = ioRef.current;
2103
2114
  (async () => {
2104
2115
  if (!beatPath || !io) return;
2105
- if (!isFallbackTrack) {
2106
- const hasSavedBeats = await readHasSavedBeats(io, beatPath);
2107
- if (cancelled) return;
2108
- if (!hasSavedBeats) {
2109
- setBeatAnalysis(null);
2110
- return;
2111
- }
2112
- }
2113
- if (cancelled) return;
2114
- const result = await loadBeatAnalysis(musicSrc, beatPath, io);
2116
+ const result = await loadTrack(musicSrc, beatPath, io, isFallbackTrack, decodableRef.current);
2115
2117
  if (cancelled) return;
2116
2118
  if (!result) {
2117
2119
  setBeatAnalysis(null);
@@ -5237,9 +5239,9 @@ function idFromSelector(selector) {
5237
5239
  if (!selector) return null;
5238
5240
  const hash = selector.match(/^#([\w-]+)/);
5239
5241
  if (hash) return hash[1] ?? null;
5240
- const attribute = selector.match(/^\[id="((?:\\.|[^"\\])*)"\]/);
5241
- if (!attribute) return null;
5242
- return (attribute[1] ?? "").replace(/\\(["\\])/g, "$1");
5242
+ const attribute2 = selector.match(/^\[id="((?:\\.|[^"\\])*)"\]/);
5243
+ if (!attribute2) return null;
5244
+ return (attribute2[1] ?? "").replace(/\\(["\\])/g, "$1");
5243
5245
  }
5244
5246
  var WHOLE_SELECTOR_ID = /^(#[\w-]+|\[id="(?:\\.|[^"\\])*"\])$/;
5245
5247
  function wholeSelectorElementId(selector) {
@@ -10051,6 +10053,10 @@ var historyClaims = () => 0;
10051
10053
  function setStudioPendingEditClaimClock(read2) {
10052
10054
  historyClaims = read2 ?? (() => 0);
10053
10055
  }
10056
+ var allSettled = null;
10057
+ function setStudioPendingEditsSettled(run) {
10058
+ allSettled = run;
10059
+ }
10054
10060
  var NOT_SAVED = () => Promise.resolve(false);
10055
10061
  var cancelWaitingPress = null;
10056
10062
  function setStudioWaitingPressCancel(cancel) {
@@ -10121,10 +10127,11 @@ function trackStudioPendingEdit(result) {
10121
10127
  showAgain: null,
10122
10128
  claimsAtBegin: historyClaims()
10123
10129
  });
10124
- promise.then(
10125
- () => pendingEdits.delete(promise),
10126
- () => pendingEdits.delete(promise)
10127
- );
10130
+ const done = () => {
10131
+ pendingEdits.delete(promise);
10132
+ if (!pendingEdits.size) allSettled?.();
10133
+ };
10134
+ promise.then(done, done);
10128
10135
  return promise;
10129
10136
  }
10130
10137
  var flushedSavesStillWriting = null;
@@ -16987,11 +16994,11 @@ function patchTagAttribute(tag, name, edit) {
16987
16994
  const attributes = scanHtmlOpeningTags(tag)[0]?.attributes.filter((attr3) => attr3.name === name.toLowerCase()) ?? [];
16988
16995
  const parts = [];
16989
16996
  let cursor = 0;
16990
- for (const attribute of attributes) {
16991
- let start = attribute.start;
16997
+ for (const attribute2 of attributes) {
16998
+ let start = attribute2.start;
16992
16999
  while (start > cursor && /[\t\n\f\r ]/.test(tag[start - 1])) start--;
16993
17000
  parts.push(tag.slice(cursor, start));
16994
- cursor = attribute.end;
17001
+ cursor = attribute2.end;
16995
17002
  }
16996
17003
  parts.push(tag.slice(cursor));
16997
17004
  return parts.join("");
@@ -17144,8 +17151,8 @@ function findTagByClass(html2, target) {
17144
17151
  }
17145
17152
  function servedSource(html2, target) {
17146
17153
  if (!target.hfId || findTagByTarget(html2, target)) return html2;
17147
- const stamped = stampHfIdsInPlace(html2);
17148
- return findTagByTarget(stamped, target) ? stamped : html2;
17154
+ const stamped2 = stampHfIdsInPlace(html2);
17155
+ return findTagByTarget(stamped2, target) ? stamped2 : html2;
17149
17156
  }
17150
17157
  function findTagByTarget(html2, target) {
17151
17158
  if (target.hfId) {
@@ -31833,6 +31840,10 @@ function shadowPagePhase(iframe) {
31833
31840
  return "no-player";
31834
31841
  }
31835
31842
  var pageGotTo = (iframe) => shadowPlayerReachable(iframe) ? "" : ` Its page had got to: ${shadowPagePhase(iframe)}.`;
31843
+ function hyperframesPlayerOf(iframe) {
31844
+ const root = iframe.getRootNode();
31845
+ return root instanceof ShadowRoot ? root.host : null;
31846
+ }
31836
31847
  function isDocumentHidden() {
31837
31848
  return typeof document !== "undefined" && document.visibilityState === "hidden";
31838
31849
  }
@@ -32004,6 +32015,7 @@ function useShadowPreviewReload({
32004
32015
  live?.pause();
32005
32016
  const retired = iframeRef.current;
32006
32017
  iframeRef.current = shadow;
32018
+ hyperframesPlayerOf(shadow)?.toggleAttribute("inert", false);
32007
32019
  pending2.commit();
32008
32020
  shadowIframeRef.current = null;
32009
32021
  attachIframeShortcutListeners();
@@ -32110,6 +32122,7 @@ function useShadowPreviewReload({
32110
32122
  armReadyTimerRef.current = armReadyTimer;
32111
32123
  const setShadowIframeNode = useCallback40((node) => {
32112
32124
  shadowIframeRef.current = node;
32125
+ if (node) hyperframesPlayerOf(node)?.toggleAttribute("inert", true);
32113
32126
  const gen = budgetGenRef.current;
32114
32127
  if (!node || !shadowFrameLeftPageRef.current || gen == null || gen !== shadowGenRef.current)
32115
32128
  return;
@@ -34113,6 +34126,13 @@ var SHADOW_IFRAME_STYLE = {
34113
34126
  clipPath: "inset(100%)",
34114
34127
  pointerEvents: "none"
34115
34128
  };
34129
+ var RENDERING_SHADOW_IFRAME_STYLE = {
34130
+ position: "absolute",
34131
+ inset: 0,
34132
+ opacity: 0,
34133
+ pointerEvents: "none"
34134
+ };
34135
+ var shadowIframeStyle = (sandboxOrigin) => sandboxOrigin === "opaque" ? RENDERING_SHADOW_IFRAME_STYLE : SHADOW_IFRAME_STYLE;
34116
34136
  function resolvePreviewStageSize(viewportWidth, viewportHeight, compositionSize, portrait, gutterPx = 0, insetPx = PREVIEW_STAGE_INSET_PX) {
34117
34137
  const availableWidth = Math.max(0, viewportWidth - 2 * (insetPx + gutterPx));
34118
34138
  const availableHeight = Math.max(0, viewportHeight - 2 * (insetPx + gutterPx));
@@ -34679,7 +34699,7 @@ var NLEPreview = memo24(function NLEPreview2({
34679
34699
  suppressLoadingOverlay: true,
34680
34700
  noLoadTimeout: true,
34681
34701
  sandboxOrigin,
34682
- style: SHADOW_IFRAME_STYLE
34702
+ style: shadowIframeStyle(sandboxOrigin)
34683
34703
  },
34684
34704
  `${activeKey}-${slot.gen}`
34685
34705
  )
@@ -37200,6 +37220,36 @@ function resolveCaptionNudge(event, target) {
37200
37220
  }
37201
37221
 
37202
37222
  // src/captions/components/CaptionOverlayUtils.ts
37223
+ import {
37224
+ isPlainRecord as isPlainRecord2,
37225
+ MAX_CAPTION_TRANSFORM,
37226
+ MAX_DESCRIBE_HANDLES
37227
+ } from "@hyperframes/core/runtime/editing-port";
37228
+ function overlayPlacement(iframe, overlayEl) {
37229
+ const iframeDisplayRect = iframe.getBoundingClientRect();
37230
+ const overlayRect = overlayEl.getBoundingClientRect();
37231
+ const nativeW = parseFloat(iframe.style.width) || iframeDisplayRect.width;
37232
+ const cssScale = iframeDisplayRect.width / nativeW;
37233
+ const offsetX = iframeDisplayRect.left - overlayRect.left;
37234
+ const offsetY = iframeDisplayRect.top - overlayRect.top;
37235
+ return (x, y, width, height) => ({
37236
+ x: x * cssScale + offsetX,
37237
+ y: y * cssScale + offsetY,
37238
+ width: width * cssScale,
37239
+ height: height * cssScale
37240
+ });
37241
+ }
37242
+ function splitIntoSpans(doc, text3, into) {
37243
+ const frag = doc.createDocumentFragment();
37244
+ for (const word of text3.split(/\s+/).filter(Boolean)) {
37245
+ const span = doc.createElement("span");
37246
+ span.textContent = word + " ";
37247
+ span.style.display = "inline";
37248
+ frag.appendChild(span);
37249
+ into.push(span);
37250
+ }
37251
+ return frag;
37252
+ }
37203
37253
  function readWordBoxes(iframe, model, overlayEl) {
37204
37254
  let doc = null;
37205
37255
  let win = null;
@@ -37210,12 +37260,7 @@ function readWordBoxes(iframe, model, overlayEl) {
37210
37260
  return [];
37211
37261
  }
37212
37262
  if (!doc || !win) return [];
37213
- const iframeDisplayRect = iframe.getBoundingClientRect();
37214
- const overlayRect = overlayEl.getBoundingClientRect();
37215
- const nativeW = parseFloat(iframe.style.width) || iframeDisplayRect.width;
37216
- const cssScale = iframeDisplayRect.width / nativeW;
37217
- const offsetX = iframeDisplayRect.left - overlayRect.left;
37218
- const offsetY = iframeDisplayRect.top - overlayRect.top;
37263
+ const place = overlayPlacement(iframe, overlayEl);
37219
37264
  const groupEls = doc.querySelectorAll(".caption-group");
37220
37265
  const boxes = [];
37221
37266
  for (let gi = 0; gi < model.groupOrder.length; gi++) {
@@ -37239,29 +37284,14 @@ function readWordBoxes(iframe, model, overlayEl) {
37239
37284
  if (resolvedWordEls.length === 0 && groupEl.textContent?.trim()) {
37240
37285
  const textNode = groupEl.childNodes[0];
37241
37286
  if (textNode && textNode.nodeType === Node.TEXT_NODE) {
37242
- const words = (textNode.textContent || "").split(/\s+/).filter(Boolean);
37243
- const frag = doc.createDocumentFragment();
37244
- for (const word of words) {
37245
- const span = doc.createElement("span");
37246
- span.textContent = word + " ";
37247
- span.style.display = "inline";
37248
- frag.appendChild(span);
37249
- resolvedWordEls.push(span);
37250
- }
37251
- groupEl.replaceChild(frag, textNode);
37287
+ groupEl.replaceChild(
37288
+ splitIntoSpans(doc, textNode.textContent || "", resolvedWordEls),
37289
+ textNode
37290
+ );
37252
37291
  } else {
37253
37292
  const singleSpan = groupEl.querySelector(":scope > span");
37254
37293
  if (singleSpan && singleSpan.textContent?.trim()) {
37255
- const words = singleSpan.textContent.split(/\s+/).filter(Boolean);
37256
- const frag = doc.createDocumentFragment();
37257
- for (const word of words) {
37258
- const span = doc.createElement("span");
37259
- span.textContent = word + " ";
37260
- span.style.display = "inline";
37261
- frag.appendChild(span);
37262
- resolvedWordEls.push(span);
37263
- }
37264
- singleSpan.replaceWith(frag);
37294
+ singleSpan.replaceWith(splitIntoSpans(doc, singleSpan.textContent, resolvedWordEls));
37265
37295
  }
37266
37296
  }
37267
37297
  }
@@ -37275,10 +37305,7 @@ function readWordBoxes(iframe, model, overlayEl) {
37275
37305
  groupId,
37276
37306
  groupIndex: gi,
37277
37307
  wordIndex: wi,
37278
- x: rect.left * cssScale + offsetX,
37279
- y: rect.top * cssScale + offsetY,
37280
- width: rect.width * cssScale,
37281
- height: rect.height * cssScale
37308
+ ...place(rect.left, rect.top, rect.width, rect.height)
37282
37309
  });
37283
37310
  }
37284
37311
  }
@@ -37362,6 +37389,17 @@ function isCaptionPreviewVisible() {
37362
37389
  function applyCaptionModelToIframe(model) {
37363
37390
  const iframe = registeredIframe?.current;
37364
37391
  if (!iframe) return;
37392
+ if (previewFrameOpaque(iframe)) {
37393
+ model.groupOrder.forEach(
37394
+ (groupId, group) => model.groups.get(groupId)?.segmentIds.forEach((segmentId, word) => {
37395
+ const s = model.segments.get(segmentId)?.style;
37396
+ if (!s) return;
37397
+ const set = { x: s.x ?? 0, y: s.y ?? 0, scale: s.scaleX ?? 1, rotation: s.rotation ?? 0 };
37398
+ void frameWordTransform(iframe, { group, word, set });
37399
+ })
37400
+ );
37401
+ return;
37402
+ }
37365
37403
  let win = null;
37366
37404
  try {
37367
37405
  win = iframe.contentWindow;
@@ -37383,8 +37421,9 @@ function applyCaptionModelToIframe(model) {
37383
37421
  }
37384
37422
  }
37385
37423
  function computeTransformStyle(el, iframeWin) {
37386
- const wrapper = getOrCreateWrapper(el);
37387
- const { x, y, scale, rotation } = readGsapTransform(wrapper, iframeWin);
37424
+ return transformStyle(readGsapTransform(getOrCreateWrapper(el), iframeWin));
37425
+ }
37426
+ function transformStyle({ x, y, scale, rotation }) {
37388
37427
  const style = {};
37389
37428
  if (Math.abs(x) > 0.5) style.x = x;
37390
37429
  if (Math.abs(y) > 0.5) style.y = y;
@@ -37395,6 +37434,138 @@ function computeTransformStyle(el, iframeWin) {
37395
37434
  if (Math.abs(rotation) > 0.1) style.rotation = rotation;
37396
37435
  return style;
37397
37436
  }
37437
+ var allFinite = (value, keys) => isPlainRecord2(value) && keys.every((key) => Number.isFinite(value[key]));
37438
+ var allBounded = (value, keys) => isPlainRecord2(value) && keys.every(
37439
+ (key) => Number.isFinite(value[key]) && Math.abs(value[key]) <= MAX_CAPTION_TRANSFORM
37440
+ );
37441
+ function readFrameWord(value) {
37442
+ if (!isPlainRecord2(value)) return null;
37443
+ const ok = allBounded(value.transform, ["x", "y", "scale", "rotation"]) && allFinite(value.rect, ["x", "y", "width", "height"]);
37444
+ return ok ? value : null;
37445
+ }
37446
+ function findCaptionWord(model, segmentId) {
37447
+ for (let group = 0; group < model.groupOrder.length; group++) {
37448
+ const word = model.groups.get(model.groupOrder[group])?.segmentIds.indexOf(segmentId) ?? -1;
37449
+ if (word >= 0) return { group, word };
37450
+ }
37451
+ return null;
37452
+ }
37453
+ async function readFrameWordBoxes(iframe, model, overlayEl) {
37454
+ const words = model.groupOrder.map((id) => model.groups.get(id)?.segmentIds.length ?? 0);
37455
+ const reply = await previewRequest(iframe, "caption-words", { words });
37456
+ const boxes = reply?.boxes;
37457
+ if (!Array.isArray(boxes)) return null;
37458
+ const place = overlayPlacement(iframe, overlayEl);
37459
+ return boxes.flatMap((box) => {
37460
+ if (!isPlainRecord2(box) || !allFinite(box.rect, ["x", "y", "width", "height"])) return [];
37461
+ const { group, word } = box;
37462
+ if (!Number.isSafeInteger(group) || !Number.isSafeInteger(word)) return [];
37463
+ const groupId = model.groupOrder[group];
37464
+ const segmentId = groupId && model.groups.get(groupId)?.segmentIds[word];
37465
+ if (!segmentId) return [];
37466
+ const { x, y, width, height } = box.rect;
37467
+ const at = place(x, y, width, height);
37468
+ return [{ segmentId, groupId, groupIndex: group, wordIndex: word, ...at }];
37469
+ });
37470
+ }
37471
+ var transformQueues = /* @__PURE__ */ new WeakMap();
37472
+ function sendTransforms(iframe, queue2) {
37473
+ if (queue2.sending || !queue2.ops.length) return;
37474
+ const ops = queue2.ops.splice(0, MAX_DESCRIBE_HANDLES);
37475
+ queue2.sending = true;
37476
+ const entries = ops.map((op) => op.entry);
37477
+ void previewRequest(iframe, "caption-transform", { entries }).then((reply) => {
37478
+ const words = reply?.words;
37479
+ ops.forEach((op, i) => {
37480
+ const word = Array.isArray(words) ? readFrameWord(words[i]) : null;
37481
+ op.done.forEach((done) => done(word));
37482
+ });
37483
+ }).finally(() => {
37484
+ queue2.sending = false;
37485
+ sendTransforms(iframe, queue2);
37486
+ });
37487
+ }
37488
+ function frameWordTransform(iframe, entry3) {
37489
+ let queue2 = transformQueues.get(iframe);
37490
+ if (!queue2) transformQueues.set(iframe, queue2 = { ops: [], sending: false });
37491
+ const { ops } = queue2;
37492
+ const promise = new Promise((resolve2) => {
37493
+ const last = ops[ops.length - 1];
37494
+ const sameWord = last?.entry.group === entry3.group && last.entry.word === entry3.word;
37495
+ if (last && sameWord && last.entry.set && entry3.set) {
37496
+ last.entry = { ...entry3, set: { ...last.entry.set, ...entry3.set } };
37497
+ last.done.push(resolve2);
37498
+ } else ops.push({ entry: entry3, done: [resolve2] });
37499
+ });
37500
+ sendTransforms(iframe, queue2);
37501
+ return promise;
37502
+ }
37503
+ function dragTransform(i, clientX, clientY, cssScale) {
37504
+ const orig = { x: i.origTX, y: i.origTY, scale: i.origScale, rotation: i.origRotation };
37505
+ if (i.type === "move") {
37506
+ const dx2 = (clientX - i.startMX) / cssScale;
37507
+ const dy = (clientY - i.startMY) / cssScale;
37508
+ return { ...orig, x: i.origTX + dx2, y: i.origTY + dy };
37509
+ }
37510
+ if (i.type === "scale") {
37511
+ const cx = i.startMX - i.startDxFromCenter;
37512
+ const startDist = Math.abs(i.startDxFromCenter);
37513
+ const currentDist = Math.abs(clientX - cx);
37514
+ const factor = startDist > 5 ? currentDist / startDist : 1;
37515
+ return { ...orig, scale: Math.max(0.1, i.origScale * factor) };
37516
+ }
37517
+ const dx = clientX - i.startMX;
37518
+ return { ...orig, rotation: i.origRotation + dx / 200 * 90 };
37519
+ }
37520
+ var restOf = (drag) => drag && { x: drag.origTX, y: drag.origTY, scale: drag.origScale, rotation: drag.origRotation };
37521
+ function toDragStart(type, { transform: t2, rect }, press) {
37522
+ const { startMX, startMY, cssScale, left } = press;
37523
+ const orig = { origTX: t2.x, origTY: t2.y, origScale: t2.scale, origRotation: t2.rotation };
37524
+ if (type === "move") return { type, startMX, startMY, ...orig };
37525
+ if (type === "rotate") return { type, startMX, ...orig };
37526
+ const boxCenterX = rect.x * cssScale + left + rect.width * cssScale / 2;
37527
+ return { type, startMX, startDxFromCenter: startMX - boxCenterX, ...orig };
37528
+ }
37529
+ async function nudgeFrameWord(iframe, word, dx, dy) {
37530
+ const now2 = await frameWordTransform(iframe, word);
37531
+ if (!now2) return null;
37532
+ const { x, y } = now2.transform;
37533
+ return frameWordTransform(iframe, { ...word, set: { x: x + dx, y: y + dy } });
37534
+ }
37535
+ function sealedNudger(live, onMoved) {
37536
+ let nudging = Promise.resolve();
37537
+ return (iframe, model, segmentIds, dx, dy) => {
37538
+ for (const segmentId of segmentIds) {
37539
+ const word = findCaptionWord(model, segmentId);
37540
+ if (!word) continue;
37541
+ nudging = nudging.then(async () => {
37542
+ if (!live()) return;
37543
+ const moved = await nudgeFrameWord(iframe, word, dx, dy);
37544
+ if (moved && live()) onMoved(segmentId, moved.transform);
37545
+ });
37546
+ }
37547
+ return nudging;
37548
+ };
37549
+ }
37550
+ function moveSealedDrag(drag, clientX, clientY, cssScale) {
37551
+ drag.last = drag.start.then(async (start) => {
37552
+ if (!start) return null;
37553
+ const set = dragTransform(start, clientX, clientY, cssScale);
37554
+ return (await frameWordTransform(drag.iframe, { ...drag.word, set }))?.transform ?? null;
37555
+ });
37556
+ }
37557
+ function restoreSealedDrag(drag) {
37558
+ void drag.start.then((start) => {
37559
+ const set = restOf(start);
37560
+ if (set) void frameWordTransform(drag.iframe, { ...drag.word, set });
37561
+ });
37562
+ }
37563
+ function pressSealedDrag(iframe, type, word, segmentId, press) {
37564
+ const start = frameWordTransform(iframe, word).then(
37565
+ (read2) => read2 && toDragStart(type, read2, press)
37566
+ );
37567
+ return { iframe, word, segmentId, start, last: start.then(restOf) };
37568
+ }
37398
37569
 
37399
37570
  // src/captions/components/CaptionOverlay.tsx
37400
37571
  import { Fragment as Fragment26, jsx as jsx98, jsxs as jsxs68 } from "react/jsx-runtime";
@@ -37402,7 +37573,9 @@ var HANDLE = 8;
37402
37573
  var HANDLE_HIT = 24;
37403
37574
  var ROTATION_OFFSET = 20;
37404
37575
  function syncToStore(segmentId, el, iframeWin) {
37405
- const style = computeTransformStyle(el, iframeWin);
37576
+ storeStyle(segmentId, computeTransformStyle(el, iframeWin));
37577
+ }
37578
+ function storeStyle(segmentId, style) {
37406
37579
  if (Object.keys(style).length > 0) {
37407
37580
  useCaptionStore.getState().updateSegmentStyle(segmentId, style);
37408
37581
  }
@@ -37419,19 +37592,46 @@ var CaptionOverlay = memo27(function CaptionOverlay2({ iframeRef }) {
37419
37592
  const modelRef = useRef66(model);
37420
37593
  modelRef.current = model;
37421
37594
  const cancelDragRef = useRef66(null);
37422
- const interactionRef = useRef66(null);
37595
+ const interactionRef = useRef66(
37596
+ null
37597
+ );
37598
+ const sealedDragRef = useRef66(null);
37599
+ const liveRef = useRef66(false);
37423
37600
  useEffect50(() => {
37424
37601
  if (!isEditMode) return;
37602
+ liveRef.current = true;
37425
37603
  const unregisterIframe = registerCaptionIframe(iframeRef);
37426
37604
  let prevBoxes = [];
37427
37605
  let rafId = null;
37606
+ let disposed = false;
37607
+ let reading = false;
37608
+ let readAgain = false;
37428
37609
  const tick = () => {
37429
37610
  rafId = null;
37430
37611
  const iframe = iframeRef.current;
37431
37612
  const m = modelRef.current;
37432
37613
  const overlay = overlayRef.current;
37433
37614
  if (!iframe || !m || !overlay) return;
37434
- const next = readWordBoxes(iframe, m, overlay);
37615
+ if (previewFrameOpaque(iframe)) return readSealed(iframe, m, overlay);
37616
+ show(readWordBoxes(iframe, m, overlay));
37617
+ };
37618
+ const readSealed = (iframe, m, overlay) => {
37619
+ if (reading) {
37620
+ readAgain = true;
37621
+ return;
37622
+ }
37623
+ reading = true;
37624
+ void readFrameWordBoxes(iframe, m, overlay).then((next) => {
37625
+ reading = false;
37626
+ if (disposed) return;
37627
+ if (next) show(next);
37628
+ if (readAgain) {
37629
+ readAgain = false;
37630
+ scheduleTick();
37631
+ }
37632
+ });
37633
+ };
37634
+ const show = (next) => {
37435
37635
  if (next.length === prevBoxes.length && next.every(
37436
37636
  (b, i) => Math.abs(b.x - prevBoxes[i].x) < 0.5 && Math.abs(b.y - prevBoxes[i].y) < 0.5
37437
37637
  ))
@@ -37474,6 +37674,12 @@ var CaptionOverlay = memo27(function CaptionOverlay2({ iframeRef }) {
37474
37674
  }
37475
37675
  };
37476
37676
  const cancelActiveDrag = () => {
37677
+ const sealed = sealedDragRef.current;
37678
+ if (sealed) {
37679
+ sealedDragRef.current = null;
37680
+ restoreSealedDrag(sealed);
37681
+ return true;
37682
+ }
37477
37683
  const i = interactionRef.current;
37478
37684
  if (!i) return false;
37479
37685
  const win = getWin();
@@ -37510,6 +37716,10 @@ var CaptionOverlay = memo27(function CaptionOverlay2({ iframeRef }) {
37510
37716
  e.preventDefault();
37511
37717
  const { dx, dy } = nudge;
37512
37718
  const iframe = iframeRef.current;
37719
+ if (iframe && previewFrameOpaque(iframe)) {
37720
+ void nudgeSealed(iframe, m, sel, dx, dy).then(scheduleTick);
37721
+ return;
37722
+ }
37513
37723
  const win = iframe?.contentWindow;
37514
37724
  if (!iframe || !win) return;
37515
37725
  for (const segId of sel) {
@@ -37529,8 +37739,14 @@ var CaptionOverlay = memo27(function CaptionOverlay2({ iframeRef }) {
37529
37739
  }
37530
37740
  scheduleTick();
37531
37741
  };
37742
+ const nudgeSealed = sealedNudger(
37743
+ () => !disposed,
37744
+ (segId, moved) => storeStyle(segId, transformStyle(moved))
37745
+ );
37532
37746
  window.addEventListener("keydown", handleKeyDown);
37533
37747
  return () => {
37748
+ disposed = true;
37749
+ liveRef.current = false;
37534
37750
  unregisterIframe();
37535
37751
  unsubPlayer();
37536
37752
  unsubPlayback();
@@ -37550,12 +37766,28 @@ var CaptionOverlay = memo27(function CaptionOverlay2({ iframeRef }) {
37550
37766
  const nativeW = parseFloat(iframe.style.width) || rect.width;
37551
37767
  return rect.width / nativeW;
37552
37768
  }, [iframeRef]);
37769
+ const startSealedDrag = useCallback57(
37770
+ (type, word, segmentId, e) => {
37771
+ const iframe = iframeRef.current;
37772
+ if (!iframe) return;
37773
+ const press = {
37774
+ startMX: e.clientX,
37775
+ startMY: e.clientY,
37776
+ cssScale: getCssScale(),
37777
+ left: iframe.getBoundingClientRect().left
37778
+ };
37779
+ sealedDragRef.current = pressSealedDrag(iframe, type, word, segmentId, press);
37780
+ },
37781
+ [iframeRef, getCssScale]
37782
+ );
37553
37783
  const startMove = useCallback57(
37554
37784
  (groupIndex, wordIndex, segmentId, e) => {
37555
37785
  e.stopPropagation();
37556
37786
  e.currentTarget.setPointerCapture(e.pointerId);
37557
37787
  const iframe = iframeRef.current;
37558
37788
  if (!iframe) return;
37789
+ if (previewFrameOpaque(iframe))
37790
+ return startSealedDrag("move", { group: groupIndex, word: wordIndex }, segmentId, e);
37559
37791
  const wordEl = getWordEl(iframe, groupIndex, wordIndex);
37560
37792
  const win = iframe.contentWindow;
37561
37793
  if (!wordEl || !win) return;
@@ -37572,7 +37804,7 @@ var CaptionOverlay = memo27(function CaptionOverlay2({ iframeRef }) {
37572
37804
  origRotation: state.rotation
37573
37805
  };
37574
37806
  },
37575
- [iframeRef]
37807
+ [iframeRef, startSealedDrag]
37576
37808
  );
37577
37809
  const startScale = useCallback57(
37578
37810
  (groupIndex, wordIndex, segmentId, e) => {
@@ -37581,6 +37813,8 @@ var CaptionOverlay = memo27(function CaptionOverlay2({ iframeRef }) {
37581
37813
  e.currentTarget.setPointerCapture(e.pointerId);
37582
37814
  const iframe = iframeRef.current;
37583
37815
  if (!iframe) return;
37816
+ if (previewFrameOpaque(iframe))
37817
+ return startSealedDrag("scale", { group: groupIndex, word: wordIndex }, segmentId, e);
37584
37818
  const wordEl = getWordEl(iframe, groupIndex, wordIndex);
37585
37819
  const win = iframe.contentWindow;
37586
37820
  if (!wordEl || !win) return;
@@ -37600,7 +37834,7 @@ var CaptionOverlay = memo27(function CaptionOverlay2({ iframeRef }) {
37600
37834
  origRotation: state.rotation
37601
37835
  };
37602
37836
  },
37603
- [iframeRef, getCssScale]
37837
+ [iframeRef, getCssScale, startSealedDrag]
37604
37838
  );
37605
37839
  const startRotate = useCallback57(
37606
37840
  (box, e) => {
@@ -37609,6 +37843,13 @@ var CaptionOverlay = memo27(function CaptionOverlay2({ iframeRef }) {
37609
37843
  e.currentTarget.setPointerCapture(e.pointerId);
37610
37844
  const iframe = iframeRef.current;
37611
37845
  if (!iframe) return;
37846
+ if (previewFrameOpaque(iframe))
37847
+ return startSealedDrag(
37848
+ "rotate",
37849
+ { group: box.groupIndex, word: box.wordIndex },
37850
+ box.segmentId,
37851
+ e
37852
+ );
37612
37853
  const wordEl = getWordEl(iframe, box.groupIndex, box.wordIndex);
37613
37854
  const win = iframe.contentWindow;
37614
37855
  if (!wordEl || !win) return;
@@ -37624,7 +37865,7 @@ var CaptionOverlay = memo27(function CaptionOverlay2({ iframeRef }) {
37624
37865
  origScale: state.scale
37625
37866
  };
37626
37867
  },
37627
- [iframeRef]
37868
+ [iframeRef, startSealedDrag]
37628
37869
  );
37629
37870
  const getIframeWin = useCallback57(() => {
37630
37871
  try {
@@ -37635,31 +37876,26 @@ var CaptionOverlay = memo27(function CaptionOverlay2({ iframeRef }) {
37635
37876
  }, [iframeRef]);
37636
37877
  const handlePointerMove = useCallback57(
37637
37878
  (e) => {
37879
+ const sealed = sealedDragRef.current;
37880
+ if (sealed) return moveSealedDrag(sealed, e.clientX, e.clientY, getCssScale());
37638
37881
  const i = interactionRef.current;
37639
37882
  if (!i) return;
37640
37883
  const win = getIframeWin();
37641
37884
  if (!win) return;
37642
- if (i.type === "move") {
37643
- const cssScale = getCssScale();
37644
- const dx = (e.clientX - i.startMX) / cssScale;
37645
- const dy = (e.clientY - i.startMY) / cssScale;
37646
- writeTransform(i.wordEl, win, i.origTX + dx, i.origTY + dy, i.origScale, i.origRotation);
37647
- } else if (i.type === "scale") {
37648
- const cx = i.startMX - i.startDxFromCenter;
37649
- const startDist = Math.abs(i.startDxFromCenter);
37650
- const currentDist = Math.abs(e.clientX - cx);
37651
- const factor = startDist > 5 ? currentDist / startDist : 1;
37652
- const newScale = Math.max(0.1, i.origScale * factor);
37653
- writeTransform(i.wordEl, win, i.origTX, i.origTY, newScale, i.origRotation);
37654
- } else if (i.type === "rotate") {
37655
- const dx = e.clientX - i.startMX;
37656
- const delta = dx / 200 * 90;
37657
- writeTransform(i.wordEl, win, i.origTX, i.origTY, i.origScale, i.origRotation + delta);
37658
- }
37885
+ const t2 = dragTransform(i, e.clientX, e.clientY, getCssScale());
37886
+ writeTransform(i.wordEl, win, t2.x, t2.y, t2.scale, t2.rotation);
37659
37887
  },
37660
37888
  [getCssScale, getIframeWin]
37661
37889
  );
37662
37890
  const handlePointerUp = useCallback57(() => {
37891
+ const sealed = sealedDragRef.current;
37892
+ if (sealed) {
37893
+ sealedDragRef.current = null;
37894
+ void sealed.last.then(
37895
+ (t2) => t2 && liveRef.current && storeStyle(sealed.segmentId, transformStyle(t2))
37896
+ );
37897
+ return;
37898
+ }
37663
37899
  const i = interactionRef.current;
37664
37900
  if (i) {
37665
37901
  const win = getIframeWin();
@@ -38552,12 +38788,12 @@ function isDomEditGestureTap(g, e) {
38552
38788
  }
38553
38789
 
38554
38790
  // src/components/editor/previewLayers.ts
38555
- import { MAX_DESCRIBE_HANDLES as MAX_DESCRIBE_HANDLES4 } from "@hyperframes/core/runtime/editing-port";
38791
+ import { MAX_DESCRIBE_HANDLES as MAX_DESCRIBE_HANDLES5 } from "@hyperframes/core/runtime/editing-port";
38556
38792
 
38557
38793
  // src/player/lib/previewElements.ts
38558
38794
  import {
38559
38795
  EDITING_ELEMENT_HANDLE,
38560
- MAX_DESCRIBE_HANDLES,
38796
+ MAX_DESCRIBE_HANDLES as MAX_DESCRIBE_HANDLES2,
38561
38797
  MAX_ELEMENT_ENTRIES,
38562
38798
  MAX_ELEMENT_VALUE,
38563
38799
  MAX_GEOMETRY_CHILDREN,
@@ -38585,6 +38821,7 @@ function readHit(value) {
38585
38821
  function readPreviewElement(value) {
38586
38822
  if (!readHit(value) || !isFields(value)) return null;
38587
38823
  if (value.parent !== null && !isHandle(value.parent)) return null;
38824
+ if (value.label !== void 0 && !isText(value.label)) return null;
38588
38825
  if (!isTextOrNull(value.id) || !isTextOrNull(value.selector)) return null;
38589
38826
  if (!isSource(value.source) || typeof value.locked !== "boolean") return null;
38590
38827
  if (!isTextRecord(value.inlineStyles) || !isText(value.text)) return null;
@@ -38604,7 +38841,7 @@ async function previewPointerTargets(iframe, rootFractionX, rootFractionY) {
38604
38841
  return { target: readHit(reply.target), stack: stack.map(readHit).filter((hit) => hit !== null) };
38605
38842
  }
38606
38843
  async function describePreviewElements(iframe, handles) {
38607
- if (!handles.length || handles.length > MAX_DESCRIBE_HANDLES) return null;
38844
+ if (!handles.length || handles.length > MAX_DESCRIBE_HANDLES2) return null;
38608
38845
  const reply = await previewRequest(iframe, "describe", { handles: [...handles] });
38609
38846
  const elements = reply?.elements;
38610
38847
  if (!Array.isArray(elements) || elements.length !== handles.length) return null;
@@ -38614,7 +38851,7 @@ async function describePreviewElements(iframe, handles) {
38614
38851
  });
38615
38852
  }
38616
38853
  async function previewAncestors(iframe, handles) {
38617
- if (!handles.length || handles.length > MAX_DESCRIBE_HANDLES) return null;
38854
+ if (!handles.length || handles.length > MAX_DESCRIBE_HANDLES2) return null;
38618
38855
  const reply = await previewRequest(iframe, "ancestors", { handles: [...handles] });
38619
38856
  const chains = reply?.ancestors;
38620
38857
  if (!Array.isArray(chains) || chains.length !== handles.length) return null;
@@ -38651,7 +38888,7 @@ var readGeometry = (value) => {
38651
38888
  return membersOk ? value : null;
38652
38889
  };
38653
38890
  async function previewGeometry(iframe, handles, children) {
38654
- if (!handles.length || handles.length > MAX_DESCRIBE_HANDLES) return null;
38891
+ if (!handles.length || handles.length > MAX_DESCRIBE_HANDLES2) return null;
38655
38892
  const params = { handles: [...handles], ...children ? { children } : {} };
38656
38893
  const reply = await previewRequest(iframe, "geometry", params);
38657
38894
  const elements = reply?.elements;
@@ -38676,7 +38913,7 @@ var readGestureStart = (value) => {
38676
38913
  return valid.includes(false) ? null : value;
38677
38914
  };
38678
38915
  async function previewGestureStart(iframe, handles) {
38679
- if (!handles.length || handles.length > MAX_DESCRIBE_HANDLES) return null;
38916
+ if (!handles.length || handles.length > MAX_DESCRIBE_HANDLES2) return null;
38680
38917
  const reply = await previewRequest(iframe, "gesture-start", { handles: [...handles] });
38681
38918
  const elements = reply?.elements;
38682
38919
  const snap = reply?.snap;
@@ -38698,7 +38935,7 @@ async function previewLayers(iframe, group, offset = 0) {
38698
38935
 
38699
38936
  // src/components/editor/previewOverlayRects.ts
38700
38937
  import {
38701
- MAX_DESCRIBE_HANDLES as MAX_DESCRIBE_HANDLES2,
38938
+ MAX_DESCRIBE_HANDLES as MAX_DESCRIBE_HANDLES3,
38702
38939
  ROTATION_GATE_EPSILON_DEG as ROTATION_GATE_EPSILON_DEG2
38703
38940
  } from "@hyperframes/core/runtime/editing-port";
38704
38941
  var clientRect = ({ x, y, width, height }) => ({ left: x, top: y, width, height });
@@ -38754,8 +38991,8 @@ async function measurePreviewOverlay(iframe, overlayEl, targets) {
38754
38991
  }
38755
38992
  async function measurePreviewVisibleRects(iframe, overlayEl, handles) {
38756
38993
  const measured = [];
38757
- for (let at = 0; at < handles.length; at += MAX_DESCRIBE_HANDLES2) {
38758
- const reply = await previewGeometry(iframe, handles.slice(at, at + MAX_DESCRIBE_HANDLES2));
38994
+ for (let at = 0; at < handles.length; at += MAX_DESCRIBE_HANDLES3) {
38995
+ const reply = await previewGeometry(iframe, handles.slice(at, at + MAX_DESCRIBE_HANDLES3));
38759
38996
  const scale = reply && computeOverlayRootScale(overlayEl, iframe, null);
38760
38997
  if (!reply || !scale) return null;
38761
38998
  for (const box of reply.elements) {
@@ -38775,7 +39012,7 @@ import {
38775
39012
  } from "@hyperframes/core/runtime/editing-port";
38776
39013
 
38777
39014
  // src/components/editor/previewDrafts.ts
38778
- import { MAX_DESCRIBE_HANDLES as MAX_DESCRIBE_HANDLES3 } from "@hyperframes/core/runtime/editing-port";
39015
+ import { MAX_DESCRIBE_HANDLES as MAX_DESCRIBE_HANDLES4 } from "@hyperframes/core/runtime/editing-port";
38779
39016
  var standIns = /* @__PURE__ */ new WeakMap();
38780
39017
  var queues = /* @__PURE__ */ new WeakMap();
38781
39018
  function registerPreviewStandIn(standIn, iframe, handle) {
@@ -38791,7 +39028,7 @@ function queueFor(iframe) {
38791
39028
  }
38792
39029
  function send2(iframe, queue2) {
38793
39030
  if (queue2.sending || !queue2.ops.length) return;
38794
- const drafts = queue2.ops.splice(0, MAX_DESCRIBE_HANDLES3);
39031
+ const drafts = queue2.ops.splice(0, MAX_DESCRIBE_HANDLES4);
38795
39032
  queue2.sending = true;
38796
39033
  void previewRequest(iframe, "draft", { drafts }).finally(() => {
38797
39034
  queue2.sending = false;
@@ -39338,10 +39575,10 @@ var selectionElementLive = (selection) => selection.handle !== void 0 || selecti
39338
39575
  // src/components/editor/previewLayers.ts
39339
39576
  async function describeAll(iframe, handles) {
39340
39577
  const described = [];
39341
- for (let at = 0; at < handles.length; at += MAX_DESCRIBE_HANDLES4) {
39578
+ for (let at = 0; at < handles.length; at += MAX_DESCRIBE_HANDLES5) {
39342
39579
  const part = await describePreviewElements(
39343
39580
  iframe,
39344
- handles.slice(at, at + MAX_DESCRIBE_HANDLES4)
39581
+ handles.slice(at, at + MAX_DESCRIBE_HANDLES5)
39345
39582
  );
39346
39583
  if (!part) return null;
39347
39584
  described.push(...part);
@@ -40479,9 +40716,9 @@ function captureStudioPathOffset(element) {
40479
40716
  originalInlineTranslate: element.getAttribute(STUDIO_ORIGINAL_INLINE_TRANSLATE_ATTR)
40480
40717
  };
40481
40718
  }
40482
- function restoreAttribute(element, attribute, value) {
40483
- if (value == null) element.removeAttribute(attribute);
40484
- else element.setAttribute(attribute, value);
40719
+ function restoreAttribute(element, attribute2, value) {
40720
+ if (value == null) element.removeAttribute(attribute2);
40721
+ else element.setAttribute(attribute2, value);
40485
40722
  }
40486
40723
  function restoreStyleProperty(element, property, value) {
40487
40724
  if (value) element.style.setProperty(property, value);
@@ -40571,11 +40808,11 @@ function restoreStudioPathOffsetStyles(element, previous) {
40571
40808
  element.removeAttribute("data-hf-drag-gsap-base-y");
40572
40809
  }
40573
40810
  }
40574
- function restoreOriginalBoxSizeProperty(element, property, attribute) {
40575
- const original = element.getAttribute(attribute);
40811
+ function restoreOriginalBoxSizeProperty(element, property, attribute2) {
40812
+ const original = element.getAttribute(attribute2);
40576
40813
  if (original == null || original === "") element.style.removeProperty(property);
40577
40814
  else element.style.setProperty(property, original);
40578
- element.removeAttribute(attribute);
40815
+ element.removeAttribute(attribute2);
40579
40816
  }
40580
40817
  function restoreOriginalRotationProperty(element) {
40581
40818
  const original = element.getAttribute(STUDIO_ORIGINAL_INLINE_ROTATE_ATTR);
@@ -55574,8 +55811,9 @@ function renderAudioClip(el, pid, sessionEpoch, labelColor, context, labelInset)
55574
55811
  const encodedRelative = srcRelative ? encodePreviewPath(srcRelative) : null;
55575
55812
  const waveformUrl = encodedRelative ? buildProjectApiPath(pid, `/waveform/${encodedRelative}`) : void 0;
55576
55813
  const { start, end } = trimFractions(el);
55814
+ const serverPeaksOrShortFile = waveformUrl !== void 0 || fitsBeatAnalysis(el);
55577
55815
  const waveform = createElement(AudioWaveform, {
55578
- audioUrl,
55816
+ audioUrl: serverPeaksOrShortFile ? audioUrl : "",
55579
55817
  waveformUrl,
55580
55818
  label: "",
55581
55819
  labelColor,
@@ -58437,6 +58675,56 @@ function readRuntime(iframe) {
58437
58675
  return null;
58438
58676
  }
58439
58677
  }
58678
+ var PORT_PREVIEW_TIMEOUT_MS = 15e3;
58679
+ var isImageData = (value) => typeof value === "string" && value.startsWith("data:image/");
58680
+ function portBatch(batch) {
58681
+ if (typeof batch !== "object" || batch === null) return null;
58682
+ const { width, height, images } = batch;
58683
+ if (!Number.isFinite(width) || !Number.isFinite(height) || !Array.isArray(images)) return null;
58684
+ return {
58685
+ width,
58686
+ height,
58687
+ images: images.map((image) => {
58688
+ const { id, dataUrl } = image ?? {};
58689
+ return { id: String(id), dataUrl: isImageData(dataUrl) ? dataUrl : null };
58690
+ })
58691
+ };
58692
+ }
58693
+ function portRuntime(iframe) {
58694
+ return {
58695
+ renderPreviews: async (target, candidates, { maxDimension, useMediaTime = false }) => {
58696
+ const params = { target, candidates, maxDimension, useMediaTime };
58697
+ const reply = await previewRequest(
58698
+ iframe,
58699
+ "color-grading-previews",
58700
+ params,
58701
+ PORT_PREVIEW_TIMEOUT_MS
58702
+ );
58703
+ return portBatch(reply?.batch);
58704
+ }
58705
+ };
58706
+ }
58707
+ function previewRuntime(iframe) {
58708
+ return iframe && previewFrameOpaque(iframe) ? portRuntime(iframe) : readRuntime(iframe);
58709
+ }
58710
+ function playInSealedFrame(iframe, target, sessionRef, animate) {
58711
+ if (!iframe || !previewFrameOpaque(iframe)) return false;
58712
+ const stopPlayback = () => void previewRequest(iframe, "color-grading-playback", { target: null });
58713
+ const session = { stopPlayback, timer: null };
58714
+ sessionRef.current = session;
58715
+ void previewRequest(iframe, "color-grading-playback", { target }).then((reply) => {
58716
+ if (sessionRef.current !== session) return;
58717
+ if (reply?.started) animate(portRuntime(iframe), session);
58718
+ else sessionRef.current = null;
58719
+ });
58720
+ return true;
58721
+ }
58722
+ var STATUS_STATES = /* @__PURE__ */ new Set(["missing", "inactive", "pending", "active", "unavailable"]);
58723
+ async function readSealedColorGradingStatus(iframe, target) {
58724
+ const reply = await previewRequest(iframe, "color-grading-status", { target });
58725
+ const { state, message } = reply?.status ?? {};
58726
+ return STATUS_STATES.has(state) && typeof message === "string" ? { state, message } : { state: "pending", message: "Waiting for runtime" };
58727
+ }
58440
58728
  function previewMaxDimension() {
58441
58729
  return Math.min(320, Math.ceil(160 * Math.max(1, window.devicePixelRatio || 1)));
58442
58730
  }
@@ -58524,7 +58812,7 @@ function useColorGradingPreviews({
58524
58812
  }));
58525
58813
  const attempt = async () => {
58526
58814
  if (cancelled || complete || inFlight) return;
58527
- const runtime = readRuntime(iframe);
58815
+ const runtime = previewRuntime(iframe);
58528
58816
  if (!runtime) return;
58529
58817
  inFlight = true;
58530
58818
  try {
@@ -58602,44 +58890,49 @@ function useColorGradingPreviews({
58602
58890
  stopAnimatedPreview();
58603
58891
  postColorGrading(next ?? gradingRef.current);
58604
58892
  if (!next || !options) return;
58605
- const runtime = readRuntime(previewIframeRef?.current);
58606
- const stopPlayback = runtime?.startPreviewPlayback?.(target);
58607
- if (!runtime || !stopPlayback) return;
58608
- const session = { stopPlayback, timer: null };
58609
- animatedRef.current = session;
58610
- const renderFrame = async () => {
58611
- try {
58612
- const batch = await runtime.renderPreviews(
58613
- target,
58614
- [{ id: options.animatedPreview.id, grading: toPreviewColorGrading(next) }],
58615
- { maxDimension: previewMaxDimension(), useMediaTime: true }
58616
- );
58617
- const image = batch?.images[0]?.dataUrl;
58618
- if (animatedRef.current !== session || !batch || !image) return;
58619
- setState((current2) => ({
58620
- ...current2,
58621
- previews: {
58622
- ...current2.previews,
58623
- [options.animatedPreview.kind]: {
58624
- ...current2.previews[options.animatedPreview.kind],
58625
- status: "ready",
58626
- images: {
58627
- ...current2.previews[options.animatedPreview.kind].images,
58628
- [options.animatedPreview.id]: image
58629
- },
58630
- width: batch.width,
58631
- height: batch.height
58893
+ const animate = (runtime2, session2) => {
58894
+ const renderFrame = async () => {
58895
+ try {
58896
+ const batch = await runtime2.renderPreviews(
58897
+ target,
58898
+ [{ id: options.animatedPreview.id, grading: toPreviewColorGrading(next) }],
58899
+ { maxDimension: previewMaxDimension(), useMediaTime: true }
58900
+ );
58901
+ const image = batch?.images[0]?.dataUrl;
58902
+ if (animatedRef.current !== session2 || !batch || !image) return;
58903
+ setState((current2) => ({
58904
+ ...current2,
58905
+ previews: {
58906
+ ...current2.previews,
58907
+ [options.animatedPreview.kind]: {
58908
+ ...current2.previews[options.animatedPreview.kind],
58909
+ status: "ready",
58910
+ images: {
58911
+ ...current2.previews[options.animatedPreview.kind].images,
58912
+ [options.animatedPreview.id]: image
58913
+ },
58914
+ width: batch.width,
58915
+ height: batch.height
58916
+ }
58632
58917
  }
58918
+ }));
58919
+ } catch {
58920
+ } finally {
58921
+ if (animatedRef.current === session2) {
58922
+ session2.timer = window.setTimeout(() => void renderFrame(), 100);
58633
58923
  }
58634
- }));
58635
- } catch {
58636
- } finally {
58637
- if (animatedRef.current === session) {
58638
- session.timer = window.setTimeout(() => void renderFrame(), 100);
58639
58924
  }
58640
- }
58925
+ };
58926
+ void renderFrame();
58641
58927
  };
58642
- void renderFrame();
58928
+ const iframe = previewIframeRef?.current;
58929
+ if (playInSealedFrame(iframe, target, animatedRef, animate)) return;
58930
+ const runtime = readRuntime(iframe);
58931
+ const stopPlayback = runtime?.startPreviewPlayback?.(target);
58932
+ if (!runtime || !stopPlayback) return;
58933
+ const session = { stopPlayback, timer: null };
58934
+ animatedRef.current = session;
58935
+ animate(runtime, session);
58643
58936
  },
58644
58937
  [gradingRef, postColorGrading, previewIframeRef, stopAnimatedPreview, target]
58645
58938
  );
@@ -58663,7 +58956,7 @@ function useColorGradingPreviews({
58663
58956
  async ({
58664
58957
  grading: requestedGrading = gradingRef.current
58665
58958
  } = {}) => {
58666
- const runtime = readRuntime(previewIframeRef?.current);
58959
+ const runtime = previewRuntime(previewIframeRef?.current);
58667
58960
  if (!runtime) return null;
58668
58961
  const batch = await runtime.renderPreviews(
58669
58962
  target,
@@ -58824,8 +59117,9 @@ function useColorGradingController({
58824
59117
  }),
58825
59118
  [element.hfId, element.id, element.selector, element.selectorIndex]
58826
59119
  );
59120
+ const statusReadRef = useRef95(0);
58827
59121
  const refreshRuntimeStatus = useCallback86(() => {
58828
- setRuntimeStatus(readRuntimeColorGradingStatus(previewIframeRef?.current, target));
59122
+ refreshStatus(previewIframeRef?.current, target, statusReadRef, setRuntimeStatus);
58829
59123
  }, [previewIframeRef, target]);
58830
59124
  useEffect82(() => {
58831
59125
  setMediaMetadata(null);
@@ -59077,6 +59371,16 @@ function useColorGradingController({
59077
59371
  }
59078
59372
  };
59079
59373
  }
59374
+ function refreshStatus(iframe, target, reads, apply) {
59375
+ if (!iframe || !previewFrameOpaque(iframe)) {
59376
+ apply(readRuntimeColorGradingStatus(iframe, target));
59377
+ return;
59378
+ }
59379
+ const read2 = ++reads.current;
59380
+ void readSealedColorGradingStatus(iframe, target).then((status) => {
59381
+ if (read2 === reads.current) apply(status);
59382
+ });
59383
+ }
59080
59384
 
59081
59385
  // src/components/editor/propertyPanelColorGradingSection.tsx
59082
59386
  import { jsx as jsx137, jsxs as jsxs97 } from "react/jsx-runtime";
@@ -69247,7 +69551,7 @@ import { timeAtSourceTime as timeAtSourceTime2 } from "@hyperframes/core/speed-r
69247
69551
  var DECODE_SAMPLE_RATE2 = 48e3;
69248
69552
  function useFxLevelling(element, chain, automation, onSetAttributeQuiet, onSetAttributeLive, setAnalysing) {
69249
69553
  const decoded = useRef109(null);
69250
- const decodeTrack = async () => {
69554
+ const decodeTrack2 = async () => {
69251
69555
  const el = element.element;
69252
69556
  const src = el?.getAttribute("src");
69253
69557
  const doc = el?.ownerDocument;
@@ -69279,7 +69583,7 @@ function useFxLevelling(element, chain, automation, onSetAttributeQuiet, onSetAt
69279
69583
  const runLeveller = async () => {
69280
69584
  setAnalysing(true);
69281
69585
  try {
69282
- const audio = await decodeTrack();
69586
+ const audio = await decodeTrack2();
69283
69587
  if (!audio) return;
69284
69588
  const result = measureLevelling(audio);
69285
69589
  if (!result) return;
@@ -69311,7 +69615,7 @@ function useFxLevelling(element, chain, automation, onSetAttributeQuiet, onSetAt
69311
69615
  const startLevelAudition = async (run) => {
69312
69616
  setAuditioningLevel(true);
69313
69617
  try {
69314
- const audio = await decodeTrack();
69618
+ const audio = await decodeTrack2();
69315
69619
  if (!audio || run !== auditionRun.current) return;
69316
69620
  const result = measureLevelling(audio);
69317
69621
  if (!result || run !== auditionRun.current) return;
@@ -77521,6 +77825,7 @@ function useCaptionSync(projectId) {
77521
77825
 
77522
77826
  // src/hooks/usePersistentEditHistory.ts
77523
77827
  import { useCallback as useCallback104, useEffect as useEffect118, useMemo as useMemo71, useRef as useRef133, useState as useState121 } from "react";
77828
+ var APP_KEEPS_NO_HISTORY = 404;
77524
77829
  var EMPTY3 = { entries: [], back: null, forward: null };
77525
77830
  var OWN_ENTRIES_KEPT = 100;
77526
77831
  function createOwnHistory() {
@@ -77649,10 +77954,20 @@ function redoneAt(view) {
77649
77954
  const undo = view.entries.find((entry3) => entry3.id === view.forward?.id);
77650
77955
  return view.entries.find((entry3) => entry3.id === undo?.undoes)?.endedAt ?? null;
77651
77956
  }
77957
+ function closeHeldClaimWithAClaimOfNothing(projectId, heldClaimRef, refresh2) {
77958
+ if (!heldClaimRef.current) return Promise.resolve();
77959
+ heldClaimRef.current = null;
77960
+ return post(historyUrl(projectId, "/claim"), { label: "Edited in Studio", paths: [] }).then(
77961
+ (reply) => {
77962
+ if (reply.ok) void refresh2();
77963
+ }
77964
+ );
77965
+ }
77652
77966
  function usePersistentEditHistory({ projectId }) {
77653
77967
  const [view, setView] = useState121(EMPTY3);
77654
77968
  const [loaded, setLoaded] = useState121(false);
77655
77969
  const heldClaimRef = useRef133(null);
77970
+ const claimsAfterTheClose = useRef133(Promise.resolve());
77656
77971
  const projectIdRef = useRef133(projectId);
77657
77972
  projectIdRef.current = projectId;
77658
77973
  const [own] = useState121(createOwnHistory);
@@ -77679,11 +77994,23 @@ function usePersistentEditHistory({ projectId }) {
77679
77994
  setStudioPendingEditClaimClock(own.claimCount);
77680
77995
  return () => setStudioPendingEditClaimClock(null);
77681
77996
  }, [own]);
77997
+ useEffect118(() => {
77998
+ if (!projectId) return;
77999
+ setStudioPendingEditsSettled(() => {
78000
+ claimsAfterTheClose.current = closeHeldClaimWithAClaimOfNothing(
78001
+ projectId,
78002
+ heldClaimRef,
78003
+ refresh2
78004
+ );
78005
+ });
78006
+ return () => setStudioPendingEditsSettled(null);
78007
+ }, [projectId, refresh2]);
77682
78008
  const recordEdit = useCallback104(
77683
78009
  async ({ label, coalesceKey, coalesceMs, files, targets, created = [] }) => {
77684
78010
  if (!projectId) return;
77685
78011
  const paths = [...Object.keys(files), ...created];
77686
78012
  own.overtake();
78013
+ await claimsAfterTheClose.current;
77687
78014
  const reply = await post(historyUrl(projectId, "/claim"), {
77688
78015
  label,
77689
78016
  paths,
@@ -77722,7 +78049,8 @@ function usePersistentEditHistory({ projectId }) {
77722
78049
  );
77723
78050
  heldClaimRef.current = null;
77724
78051
  void refresh2();
77725
- if (!posted.ok && posted.status === 404) return { ok: false, reason: "empty" };
78052
+ if (!posted.ok && posted.status === APP_KEEPS_NO_HISTORY)
78053
+ return { ok: false, reason: "empty" };
77726
78054
  if (!posted.ok) return { ok: false, reason: "failed", message: posted.error };
77727
78055
  const reply = posted.body;
77728
78056
  if (!reply.ok) {
@@ -78792,6 +79120,47 @@ function repaintWhileReloading(win, doc, restored) {
78792
79120
  extractGsapScriptText(restored)
78793
79121
  );
78794
79122
  }
79123
+ var restoredAttributes = (el) => el.getAttributeNames().map((name) => [name, el.getAttribute(name) ?? ""]);
79124
+ var stamped = (html2) => html2.includes("data-hf-id") ? html2 : ensureHfIds2(html2);
79125
+ function sealedFile(file, isActive) {
79126
+ if (extractGsapScriptText(file.restored) !== extractGsapScriptText(file.previous)) return null;
79127
+ const prevDoc = parseRestoreSource(stamped(file.previous));
79128
+ const nextDoc = parseRestoreSource(stamped(file.restored));
79129
+ const scripted = restoreScripted(prevDoc, nextDoc, isActive);
79130
+ const keys = diffRestoreDocs(prevDoc, nextDoc);
79131
+ const restoredByKey = identityElementMap(nextDoc);
79132
+ if (scripted === null || !keys || !restoredByKey) return null;
79133
+ const elements = keys.map((key) => ({
79134
+ key,
79135
+ attributes: restoredAttributes(restoredByKey.get(key))
79136
+ }));
79137
+ return { scripted, elements };
79138
+ }
79139
+ function sealedRestore(activeDocPath, files) {
79140
+ const restore2 = { scopes: [], scripted: false };
79141
+ for (const [path, file] of Object.entries(files)) {
79142
+ const isActive = path === activeDocPath;
79143
+ const found = sealedFile(file, isActive);
79144
+ if (!found) return null;
79145
+ restore2.scripted ||= found.scripted;
79146
+ if (found.elements.length)
79147
+ restore2.scopes.push({ file: isActive ? null : path, elements: found.elements });
79148
+ }
79149
+ return restore2.scopes.length ? restore2 : null;
79150
+ }
79151
+ function applySealedRestore(iframe, activeDocPath, files, currentTime, reloadPreview) {
79152
+ const restore2 = sealedRestore(activeDocPath, files);
79153
+ if (!restore2) {
79154
+ reloadPreview();
79155
+ return "full";
79156
+ }
79157
+ void previewRequest(iframe, "restore-attributes", { ...restore2, time: currentTime }).then(
79158
+ (reply) => {
79159
+ if (!reply?.applied) reloadPreview();
79160
+ }
79161
+ );
79162
+ return "soft";
79163
+ }
78795
79164
  function applyUndoRestoreToPreview(iframe, activeCompPath, files, currentTime, reload, nestedFiles) {
78796
79165
  const activeDocPath = activeCompPath ?? "index.html";
78797
79166
  const paths = files ? Object.keys(files) : [];
@@ -78799,6 +79168,8 @@ function applyUndoRestoreToPreview(iframe, activeCompPath, files, currentTime, r
78799
79168
  markScenesStale(iframe, paths);
78800
79169
  reload();
78801
79170
  };
79171
+ if (iframe && files && previewFrameOpaque(iframe))
79172
+ return applySealedRestore(iframe, activeDocPath, files, currentTime, reloadPreview);
78802
79173
  const doc = iframe?.contentDocument;
78803
79174
  const win = iframe?.contentWindow;
78804
79175
  const plan = doc && files && win ? planRestoreTargets(doc, activeDocPath, files) : null;
@@ -91804,6 +92175,76 @@ function parseTranscriptArray(parsed) {
91804
92175
  }
91805
92176
 
91806
92177
  // src/hooks/useCaptionDetection.ts
92178
+ import { MAX_DESCRIBE_HANDLES as MAX_DESCRIBE_HANDLES6 } from "@hyperframes/core/runtime/editing-port";
92179
+ var GROUP_SELECTOR2 = ".caption-group, .caption-line, .caption-block";
92180
+ var WORD_SELECTOR2 = ".word, .caption-word";
92181
+ var attribute = (el, name) => el?.attributes.find(([key]) => key === name)?.[1] ?? null;
92182
+ var CAPTION_STYLES = [
92183
+ "font-size",
92184
+ "font-weight",
92185
+ "font-family",
92186
+ "color",
92187
+ "text-transform",
92188
+ "letter-spacing",
92189
+ "background-color",
92190
+ "border-radius",
92191
+ "padding-top",
92192
+ "padding-right",
92193
+ "padding-bottom",
92194
+ "padding-left"
92195
+ ];
92196
+ async function frameStyles(iframe, handle) {
92197
+ if (!handle) return null;
92198
+ const styles = await previewComputedStyles(iframe, { handle }, CAPTION_STYLES);
92199
+ if (!styles) return null;
92200
+ const camel = (name) => name.replace(/-(\w)/g, (_, c) => c.toUpperCase());
92201
+ return Object.fromEntries(CAPTION_STYLES.map((name) => [camel(name), styles[name] ?? ""]));
92202
+ }
92203
+ async function frameCaptionDom(iframe) {
92204
+ const [all, groups, words] = await Promise.all(
92205
+ [`${GROUP_SELECTOR2}, ${WORD_SELECTOR2}`, GROUP_SELECTOR2, WORD_SELECTOR2].map(
92206
+ (selector) => queryPreviewElements(iframe, selector)
92207
+ )
92208
+ );
92209
+ if (!all || !groups || !words || all.truncated) return null;
92210
+ const handles = all.matches.map((match) => match.handle);
92211
+ const chains = [];
92212
+ for (let i = 0; i < handles.length; i += MAX_DESCRIBE_HANDLES6) {
92213
+ const part = await previewAncestors(iframe, handles.slice(i, i + MAX_DESCRIBE_HANDLES6));
92214
+ if (!part) return null;
92215
+ chains.push(...part);
92216
+ }
92217
+ const isGroup = new Set(groups.matches.map((match) => match.handle));
92218
+ const isWord = new Set(words.matches.map((match) => match.handle));
92219
+ const doc = document.implementation.createHTMLDocument("");
92220
+ const mirrored = /* @__PURE__ */ new Map();
92221
+ handles.forEach((handle, i) => {
92222
+ const el = doc.createElement("span");
92223
+ if (isGroup.has(handle)) el.classList.add("caption-group");
92224
+ if (isWord.has(handle)) el.classList.add("word");
92225
+ const parent = chains[i]?.find((ancestor) => mirrored.has(ancestor));
92226
+ (parent ? mirrored.get(parent) : doc.body).append(el);
92227
+ mirrored.set(handle, el);
92228
+ });
92229
+ const firstWord = words.matches[0]?.handle;
92230
+ const firstGroup = groups.matches[0]?.handle;
92231
+ const styles = /* @__PURE__ */ new Map([
92232
+ [mirrored.get(firstWord ?? ""), await frameStyles(iframe, firstWord)],
92233
+ [mirrored.get(firstGroup ?? ""), await frameStyles(iframe, firstGroup)]
92234
+ ]);
92235
+ const win = { getComputedStyle: (el) => styles.get(el) ?? {} };
92236
+ return { doc, win };
92237
+ }
92238
+ async function frameCaptionModel(iframe, content) {
92239
+ const [root] = (await queryPreviewElements(iframe, "[data-composition-id]"))?.matches ?? [];
92240
+ const rootEl = root ? (await describePreviewElements(iframe, [root.handle]))?.[0] : null;
92241
+ const frame3 = await frameCaptionDom(iframe);
92242
+ if (!frame3) return null;
92243
+ const w = parseInt(attribute(rootEl, "data-width") ?? "1920", 10);
92244
+ const h = parseInt(attribute(rootEl, "data-height") ?? "1080", 10);
92245
+ const dur = parseFloat(attribute(rootEl, "data-duration") ?? "0");
92246
+ return parseCaptionComposition(frame3.doc, frame3.win, content, w, h, dur);
92247
+ }
91807
92248
  function useCaptionDetection({
91808
92249
  projectId,
91809
92250
  activeCompPath,
@@ -91829,12 +92270,56 @@ function useCaptionDetection({
91829
92270
  useEffect136(() => {
91830
92271
  if (!projectId) return;
91831
92272
  let activating = false;
92273
+ let disposed = false;
92274
+ const pickCaptionSource = (hostSrcs, captionCompId) => {
92275
+ const host = hostSrcs.find((src) => src && src.includes("captions"));
92276
+ if (host) return host;
92277
+ for (const [id, src] of compIdToSrc) {
92278
+ if (id.includes("caption") || src.includes("caption")) return src;
92279
+ }
92280
+ if (activeCompPath?.includes("captions")) return activeCompPath;
92281
+ return captionCompId === null ? null : compIdToSrc.get(captionCompId) || null;
92282
+ };
92283
+ const loadCaptions = (srcPath, parse) => studioApiFetch(buildProjectApiPath(projectId, `/files/${encodeURIComponent(srcPath)}`)).then((r) => r.json()).then(async (data) => {
92284
+ if (disposed || !data.content || useCaptionStore.getState().isEditMode) return;
92285
+ const model = await parse(data.content);
92286
+ if (disposed || !model || useCaptionStore.getState().isEditMode) return;
92287
+ const store = useCaptionStore.getState();
92288
+ store.setModel(model);
92289
+ store.setSourceFilePath(srcPath);
92290
+ store.setEditMode(true);
92291
+ captionSync.loadOverrides();
92292
+ }).catch(() => {
92293
+ });
92294
+ const frameCaptionSource = async (iframe) => {
92295
+ if (!(await queryPreviewElements(iframe, ".caption-group"))?.matches.length) return null;
92296
+ const hosts = await queryPreviewElements(
92297
+ iframe,
92298
+ "[data-composition-src], [data-composition-file]"
92299
+ );
92300
+ const handles = (hosts?.matches ?? []).slice(0, MAX_DESCRIBE_HANDLES6).map((m) => m.handle);
92301
+ const described = handles.length ? await describePreviewElements(iframe, handles) : [];
92302
+ const hostSrcs = (described ?? []).map(
92303
+ (el) => attribute(el, "data-composition-src") || attribute(el, "data-composition-file")
92304
+ );
92305
+ const captionComp = await queryPreviewElements(iframe, '[data-composition-id*="caption"]');
92306
+ return pickCaptionSource(hostSrcs, captionComp?.matches[0]?.source.compositionId ?? null);
92307
+ };
91832
92308
  const tryActivateCaptions = () => {
91833
92309
  const captionState = useCaptionStore.getState();
91834
92310
  if (captionState.isEditMode || captionState.dismissed || activating) {
91835
92311
  return;
91836
92312
  }
91837
92313
  const iframe = previewIframeRef.current;
92314
+ if (iframe && previewFrameOpaque(iframe)) {
92315
+ activating = true;
92316
+ void frameCaptionSource(iframe).then(
92317
+ (src) => src && !disposed ? loadCaptions(src, (content) => frameCaptionModel(iframe, content)) : null
92318
+ ).finally(() => {
92319
+ activating = false;
92320
+ });
92321
+ return;
92322
+ }
91838
92323
  let doc = null;
91839
92324
  let win = null;
91840
92325
  try {
@@ -91846,50 +92331,24 @@ function useCaptionDetection({
91846
92331
  if (!doc || !win) return;
91847
92332
  const groups = doc.querySelectorAll(".caption-group");
91848
92333
  if (groups.length === 0) return;
91849
- let captionSrcPath = null;
91850
- const compHosts = doc.querySelectorAll("[data-composition-src], [data-composition-file]");
91851
- for (const host of compHosts) {
91852
- const src = host.getAttribute("data-composition-src") || host.getAttribute("data-composition-file");
91853
- if (src && src.includes("captions")) {
91854
- captionSrcPath = src;
91855
- break;
91856
- }
91857
- }
91858
- if (!captionSrcPath) {
91859
- for (const [id, src] of compIdToSrc) {
91860
- if (id.includes("caption") || src.includes("caption")) {
91861
- captionSrcPath = src;
91862
- break;
91863
- }
91864
- }
91865
- }
91866
- if (!captionSrcPath && activeCompPath?.includes("captions")) {
91867
- captionSrcPath = activeCompPath;
91868
- }
91869
- if (!captionSrcPath) {
91870
- const captionComp = doc.querySelector('[data-composition-id*="caption"]');
91871
- if (captionComp) {
91872
- const compId = captionComp.getAttribute("data-composition-id") || "";
91873
- captionSrcPath = compIdToSrc.get(compId) || null;
91874
- }
91875
- }
92334
+ const hostSrcs = [
92335
+ ...doc.querySelectorAll("[data-composition-src], [data-composition-file]")
92336
+ ].map(
92337
+ (host) => host.getAttribute("data-composition-src") || host.getAttribute("data-composition-file")
92338
+ );
92339
+ const captionComp = doc.querySelector('[data-composition-id*="caption"]');
92340
+ const captionCompId = captionComp ? captionComp.getAttribute("data-composition-id") || "" : null;
92341
+ const captionSrcPath = pickCaptionSource(hostSrcs, captionCompId);
91876
92342
  if (!captionSrcPath) return;
91877
92343
  activating = true;
91878
- const srcPath = captionSrcPath;
91879
- studioApiFetch(buildProjectApiPath(projectId, `/files/${encodeURIComponent(srcPath)}`)).then((r) => r.json()).then((data) => {
91880
- if (!data.content || !doc || !win || useCaptionStore.getState().isEditMode) return;
91881
- const root = doc.querySelector("[data-composition-id]");
92344
+ const frameDoc = doc;
92345
+ const frameWin = win;
92346
+ void loadCaptions(captionSrcPath, async (content) => {
92347
+ const root = frameDoc.querySelector("[data-composition-id]");
91882
92348
  const w = parseInt(root?.getAttribute("data-width") ?? "1920", 10);
91883
92349
  const h = parseInt(root?.getAttribute("data-height") ?? "1080", 10);
91884
92350
  const dur = parseFloat(root?.getAttribute("data-duration") ?? "0");
91885
- const model = parseCaptionComposition(doc, win, data.content, w, h, dur);
91886
- if (!model) return;
91887
- const store = useCaptionStore.getState();
91888
- store.setModel(model);
91889
- store.setSourceFilePath(srcPath);
91890
- store.setEditMode(true);
91891
- captionSync.loadOverrides();
91892
- }).catch(() => {
92351
+ return parseCaptionComposition(frameDoc, frameWin, content, w, h, dur);
91893
92352
  }).finally(() => {
91894
92353
  activating = false;
91895
92354
  });
@@ -91905,6 +92364,7 @@ function useCaptionDetection({
91905
92364
  window.addEventListener("message", handleMessage);
91906
92365
  tryActivateCaptions();
91907
92366
  return () => {
92367
+ disposed = true;
91908
92368
  window.removeEventListener("message", handleMessage);
91909
92369
  };
91910
92370
  }, [activeCompPath, projectId, compIdToSrc, captionSync, previewIframeRef, livePreviewIframe]);
@@ -98296,6 +98756,21 @@ var CaptionPropertyPanel = memo54(function CaptionPropertyPanel2({
98296
98756
  (updates) => {
98297
98757
  const iframe = iframeRef.current;
98298
98758
  if (!iframe || !model) return;
98759
+ if (previewFrameOpaque(iframe)) {
98760
+ const parts = {
98761
+ x: updates.x,
98762
+ y: updates.y,
98763
+ scale: updates.scaleX,
98764
+ rotation: updates.rotation
98765
+ };
98766
+ const set = Object.fromEntries(Object.entries(parts).filter(([, v]) => v !== void 0));
98767
+ if (Object.keys(set).length === 0) return;
98768
+ for (const segId of selectedSegmentIds) {
98769
+ const word = findCaptionWord(model, segId);
98770
+ if (word) void frameWordTransform(iframe, { ...word, set });
98771
+ }
98772
+ return;
98773
+ }
98299
98774
  let doc = null;
98300
98775
  try {
98301
98776
  doc = iframe.contentDocument;
@@ -101161,10 +101636,30 @@ function VariablesOtherCompositions({
101161
101636
 
101162
101637
  // src/components/panels/VariablesPanel.tsx
101163
101638
  import { isScalarVariableValue as isScalar } from "@hyperframes/core/variables";
101164
- import { jsx as jsx253, jsxs as jsxs201 } from "react/jsx-runtime";
101165
- function shellSingleQuote(value) {
101166
- return `'${value.replace(/'/g, `'\\''`)}'`;
101639
+ import { RENDER_VARIABLES_FILE as RENDER_VARIABLES_FILE2 } from "@hyperframes/core/project-folders";
101640
+
101641
+ // src/components/panels/renderHandoff.ts
101642
+ import { RENDER_VARIABLES_FILE } from "@hyperframes/core/project-folders";
101643
+ var SHELL_WORD = /^[A-Za-z0-9_][A-Za-z0-9_./-]*$/;
101644
+ function renderHandoffCommand(compPath) {
101645
+ if (!SHELL_WORD.test(compPath)) return null;
101646
+ return `npx hyperframes render -c ${compPath} --variables-file ${RENDER_VARIABLES_FILE}`;
101647
+ }
101648
+ async function saveRenderVariables(projectId, values) {
101649
+ try {
101650
+ const response = await studioApiFetch(buildProjectApiPath(projectId, "/render-variables"), {
101651
+ method: "PUT",
101652
+ headers: { "Content-Type": "application/json" },
101653
+ body: JSON.stringify(values)
101654
+ });
101655
+ return response.ok;
101656
+ } catch {
101657
+ return false;
101658
+ }
101167
101659
  }
101660
+
101661
+ // src/components/panels/VariablesPanel.tsx
101662
+ import { jsx as jsx253, jsxs as jsxs201 } from "react/jsx-runtime";
101168
101663
  function formatIssue(issue) {
101169
101664
  switch (issue.kind) {
101170
101665
  case "undeclared":
@@ -101279,20 +101774,25 @@ function PreviewModeHeader({
101279
101774
  function HandoffFooter({
101280
101775
  effectiveValues,
101281
101776
  compPath,
101282
- onCopy
101777
+ onCopy,
101778
+ onCopyCommand
101283
101779
  }) {
101284
101780
  const json2 = JSON.stringify(effectiveValues);
101285
- const command = `npx hyperframes render ${shellSingleQuote(compPath)} --variables ${shellSingleQuote(json2)}`;
101781
+ const command = renderHandoffCommand(compPath);
101286
101782
  return /* @__PURE__ */ jsxs201("div", { className: "space-y-1.5 rounded-lg border border-neutral-800/70 bg-neutral-900/40 p-2", children: [
101287
101783
  /* @__PURE__ */ jsx253("p", { className: "text-[9px] font-medium uppercase tracking-wider text-neutral-500", children: "Use this template" }),
101288
- /* @__PURE__ */ jsx253("code", { className: "block truncate font-mono text-[9px] text-neutral-500", title: command, children: command }),
101784
+ command ? /* @__PURE__ */ jsx253("code", { className: "block truncate font-mono text-[9px] text-neutral-500", title: command, children: command }) : /* @__PURE__ */ jsxs201("p", { className: "text-[9px] leading-relaxed text-neutral-500", children: [
101785
+ "Rename this composition to letters, digits, ",
101786
+ /* @__PURE__ */ jsx253("code", { className: "font-mono", children: "_ . / -" }),
101787
+ " to copy a render command. A shell would read other characters in its name as syntax."
101788
+ ] }),
101289
101789
  /* @__PURE__ */ jsxs201("div", { className: "flex items-center gap-2", children: [
101290
- /* @__PURE__ */ jsx253(
101790
+ command && /* @__PURE__ */ jsx253(
101291
101791
  RowAction,
101292
101792
  {
101293
101793
  label: "Copy render command",
101294
- title: "CLI command rendering exactly what the preview shows",
101295
- onClick: () => onCopy(command, "Render command")
101794
+ title: `Saves what the preview shows to ${RENDER_VARIABLES_FILE2}. Run the command from the project folder.`,
101795
+ onClick: () => onCopyCommand(command)
101296
101796
  }
101297
101797
  ),
101298
101798
  /* @__PURE__ */ jsx253(
@@ -101323,7 +101823,7 @@ var VariablesPanel = memo60(function VariablesPanel2({
101323
101823
  reloadPreview,
101324
101824
  recordEdit
101325
101825
  }) {
101326
- const { activeCompPath, showToast } = useStudioShellContext();
101826
+ const { projectId, activeCompPath, showToast } = useStudioShellContext();
101327
101827
  const { refreshKey } = useStudioPlaybackContext();
101328
101828
  const { readProjectFile, writeProjectFile, compositions } = useFileManagerContext();
101329
101829
  const { domEditSelection } = useDomEditContext();
@@ -101377,6 +101877,19 @@ var VariablesPanel = memo60(function VariablesPanel2({
101377
101877
  },
101378
101878
  [showToast]
101379
101879
  );
101880
+ const copyRenderCommand = useCallback186(
101881
+ (command) => {
101882
+ const copied = copyTextToClipboard(command);
101883
+ const saved2 = saveRenderVariables(projectId, effectiveValues);
101884
+ void Promise.all([saved2, copied]).then(([wasSaved, wasCopied]) => {
101885
+ if (!wasCopied) showToast("Couldn't copy render command", "error");
101886
+ else if (!wasSaved)
101887
+ showToast(`Couldn't save the values to ${RENDER_VARIABLES_FILE2}`, "error");
101888
+ else showToast("Render command copied", "info");
101889
+ });
101890
+ },
101891
+ [projectId, effectiveValues, showToast]
101892
+ );
101380
101893
  const dropPreviewOverride = useCallback186(
101381
101894
  (id) => {
101382
101895
  if (previewValues && id in previewValues) {
@@ -101549,7 +102062,8 @@ var VariablesPanel = memo60(function VariablesPanel2({
101549
102062
  {
101550
102063
  effectiveValues,
101551
102064
  compPath: effectiveCompPath ?? "index.html",
101552
- onCopy: copyToClipboard
102065
+ onCopy: copyToClipboard,
102066
+ onCopyCommand: copyRenderCommand
101553
102067
  }
101554
102068
  ),
101555
102069
  addOpen ? /* @__PURE__ */ jsx253(
@@ -104879,6 +105393,7 @@ export {
104879
105393
  displayTrackOrder,
104880
105394
  extractSnapTargets,
104881
105395
  fadeHandleBoxes,
105396
+ fetchParsedAnimations,
104882
105397
  fieldBase,
104883
105398
  fieldText,
104884
105399
  findElementBlock,
@@ -104887,6 +105402,7 @@ export {
104887
105402
  flushStudioPendingEdits,
104888
105403
  formatCombo2 as formatCombo,
104889
105404
  formatTime,
105405
+ getAnimationsForElement,
104890
105406
  getPersistedRenderSettings,
104891
105407
  getStudioKeys,
104892
105408
  liveTime,
@@ -104919,6 +105435,7 @@ export {
104919
105435
  setStudioKeys,
104920
105436
  snapEngagedForTravel,
104921
105437
  standInFor,
105438
+ standInHandle,
104922
105439
  studioKeyClash,
104923
105440
  useAudioGainDialogStore,
104924
105441
  useAudioMetersVisible,