From 903051c40b02ee0993a4584e7175f301a4d7b26a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Tue, 24 Nov 2026 09:15:47 +0000 Subject: [PATCH] fix(studio): class and descendant tween keyframe markers show in a sealed preview (#8675) * fix(studio): class and descendant tween keyframe markers show in a sealed preview * fix(studio): a sealed frame that does not answer keeps the shown keyframe markers * fix(studio): a sealed frame removed during the markup read keeps the shown keyframe markers --- .../gsapKeyframeCacheHelpers.sealed.test.ts | 66 ++++++++++++++ .../src/hooks/gsapKeyframeCacheHelpers.ts | 25 +++++- .../hooks/gsapKeyframeMarkers.browser.test.ts | 89 +++++++++++++++++++ packages/studio/src/hooks/gsapShared.ts | 13 ++- .../studio/src/hooks/keyframeCacheAstLoad.ts | 6 +- .../studio/src/hooks/useGsapScriptCommits.ts | 8 +- .../studio/src/hooks/useGsapTweenCache.ts | 4 +- 7 files changed, 199 insertions(+), 12 deletions(-) create mode 100644 packages/studio/src/hooks/gsapKeyframeCacheHelpers.sealed.test.ts create mode 100644 packages/studio/src/hooks/gsapKeyframeMarkers.browser.test.ts diff --git a/packages/studio/src/hooks/gsapKeyframeCacheHelpers.sealed.test.ts b/packages/studio/src/hooks/gsapKeyframeCacheHelpers.sealed.test.ts new file mode 100644 index 0000000000..b9a89856d7 --- /dev/null +++ b/packages/studio/src/hooks/gsapKeyframeCacheHelpers.sealed.test.ts @@ -0,0 +1,66 @@ +// @vitest-environment happy-dom +import { beforeEach, expect, it, vi } from "vitest"; +import type { GsapAnimation } from "@hyperframes/core/gsap-parser"; + +const { previewDocumentCopy, previewFrameOpaque } = vi.hoisted(() => ({ + previewDocumentCopy: vi.fn(), + previewFrameOpaque: vi.fn(), +})); +vi.mock("../player/lib/previewChannel", async (importOriginal) => { + const original = await importOriginal(); + return { ...original, previewFrameOpaque, previewDocumentCopy }; +}); + +import { usePlayerStore } from "../player/store/playerStore"; +import { cacheCommittedKeyframes } from "./gsapKeyframeCacheHelpers"; + +const iframe = document.createElement("iframe"); +const dots: GsapAnimation = { + id: "dots", + targetSelector: ".dot", + method: "to", + position: 0, + properties: {}, + duration: 4, + resolvedStart: 0, + propertyGroup: "position", + keyframes: { format: "percentage", keyframes: [{ percentage: 50, properties: { x: 100 } }] }, +}; +const shown = { + format: "percentage" as const, + keyframes: [{ percentage: 10, properties: { x: 1 } }], +}; + +beforeEach(() => { + previewDocumentCopy.mockReset(); + previewFrameOpaque.mockReset().mockReturnValue(true); + usePlayerStore.setState({ + keyframeCache: new Map([["index.html#d1", shown]]), + gsapAnimations: new Map(), + elements: [], + }); +}); + +it("files a class tween under the sealed frame's matching elements", async () => { + const markup = '
'; + previewDocumentCopy.mockResolvedValue(new DOMParser().parseFromString(markup, "text/html")); + await cacheCommittedKeyframes(iframe, [dots], "index.html", "d1", {}); + expect(previewDocumentCopy).toHaveBeenCalledWith(iframe); + const keys = [...usePlayerStore.getState().keyframeCache.keys()].filter((k) => k.includes("#")); + expect(keys.sort()).toEqual(["index.html#d1", "index.html#d2"]); +}); + +it("keeps the shown markers when the sealed frame does not answer", async () => { + previewDocumentCopy.mockResolvedValue(null); + await cacheCommittedKeyframes(iframe, [dots], "index.html", "d1", {}); + expect(usePlayerStore.getState().keyframeCache.get("index.html#d1")).toBe(shown); +}); + +it("keeps the shown markers when the sealed frame is removed while it is read", async () => { + previewDocumentCopy.mockImplementation(async () => { + previewFrameOpaque.mockReturnValue(false); + return null; + }); + await cacheCommittedKeyframes(iframe, [dots], "index.html", "d1", {}); + expect(usePlayerStore.getState().keyframeCache.get("index.html#d1")).toBe(shown); +}); diff --git a/packages/studio/src/hooks/gsapKeyframeCacheHelpers.ts b/packages/studio/src/hooks/gsapKeyframeCacheHelpers.ts index b0920bc5b2..f25d204cd3 100644 --- a/packages/studio/src/hooks/gsapKeyframeCacheHelpers.ts +++ b/packages/studio/src/hooks/gsapKeyframeCacheHelpers.ts @@ -3,10 +3,16 @@ * Extracted from useGsapScriptCommits to keep file sizes under the 600-line limit. */ import type { GsapAnimation } from "@hyperframes/core/gsap-parser"; +import { previewFrameOpaque } from "../player/lib/previewChannel"; import { usePlayerStore, type KeyframeCacheEntry } from "../player/store/playerStore"; import { trackStudioEvent } from "../utils/studioTelemetry"; import { sameData } from "../utils/sameData"; -import { resolveClipTimingBasis, resolveSelectorElementIds, toClipKeyframes } from "./gsapShared"; +import { + resolveClipTimingBasis, + resolveSelectorElementIds, + toClipKeyframes, + tweenTargetDocument, +} from "./gsapShared"; import { deduplicateKeyframes, synthesizeFlatTweenKeyframes, @@ -64,6 +70,23 @@ export function publishKeyframeCache(edit: (draft: KeyframeCacheDraft) => void): }); } +/** Files a write's parsed tweens under the preview elements they animate, as its timeline keyframe markers. */ +export async function cacheCommittedKeyframes( + iframe: HTMLIFrameElement | null, + animations: GsapAnimation[], + targetPath: string, + selectionId: string | undefined, + mutation: Record, +): Promise { + // Read before the await: a frame removed meanwhile no longer reads as sealed. + const sealed = iframe !== null && previewFrameOpaque(iframe); + const doc = await tweenTargetDocument(iframe); + // A sealed frame that did not answer (replaced, or gone) would attribute nothing and clear the + // selection's markers; the cache reload after the write fills them from the new frame instead. + if (!doc && sealed) return; + updateKeyframeCacheFromParsed(animations, targetPath, selectionId, mutation, doc); +} + export function updateKeyframeCacheFromParsed( animations: GsapAnimation[], targetPath: string, diff --git a/packages/studio/src/hooks/gsapKeyframeMarkers.browser.test.ts b/packages/studio/src/hooks/gsapKeyframeMarkers.browser.test.ts new file mode 100644 index 0000000000..6a295ded50 --- /dev/null +++ b/packages/studio/src/hooks/gsapKeyframeMarkers.browser.test.ts @@ -0,0 +1,89 @@ +// Real Chrome: after a tween write, a class or descendant tween's keyframe markers land on the elements it +// animates, in a preview Studio cannot script (a sandboxed frame) exactly as in a same-origin one. +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import type { Browser } from "puppeteer-core"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import type { GsapAnimation } from "@hyperframes/core/gsap-parser"; +import { closeTestChrome, launchTestChrome } from "../../tests/chromeTestUtils"; +import { buildStudioBundle, openPreview, type Studio } from "../../tests/sealedPreviewHarness"; + +vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 }); +const require = createRequire(import.meta.url); +const MODES = process.env.HF_PARITY_MODE ? [process.env.HF_PARITY_MODE] : ["unsealed", "sealed"]; +let browser: Browser; +let studioBundle: string; + +beforeAll(async () => { + browser = await launchTestChrome(); + studioBundle = await buildStudioBundle([ + `export { cacheCommittedKeyframes } from "./hooks/gsapKeyframeCacheHelpers";`, + ]); +}); + +afterAll(() => closeTestChrome(browser)); + +function previewHtml(): string { + const gsap = readFileSync(require.resolve("gsap/dist/gsap.min.js"), "utf8"); + const runtime = readFileSync(require.resolve("@hyperframes/core/runtime"), "utf8"); + const clip = (id: string, cls: string) => + `
`; + return ` + +
+
${clip("blk1", "block")}${clip("blk2", "block")}
+ ${clip("outside", "block")}${clip("d1", "dot")}${clip("d2", "dot")} +
+ + + `; +} + +const tween = (id: string, targetSelector: string): GsapAnimation => ({ + id, + targetSelector, + method: "to", + position: 0, + properties: {}, + duration: 4, + resolvedStart: 0, + propertyGroup: "position", + keyframes: { format: "percentage", keyframes: [{ percentage: 50, properties: { x: 100 } }] }, +}); + +describe.each(MODES)("keyframe markers after a tween write, %s preview", (mode) => { + it("files class and descendant tweens under every element they animate", async () => { + const { page } = await openPreview(browser, studioBundle, previewHtml(), mode); + const marked = await page.evaluate( + async (animations) => { + const studio = (window as unknown as { hfStudio: Studio & Record }) + .hfStudio; + studio.usePlayerStore.setState({ keyframeCache: new Map(), gsapAnimations: new Map() }); + // The edit was to the `.dot` tween with d1 selected. + await studio.cacheCommittedKeyframes( + document.querySelector("iframe"), + animations, + "index.html", + "d1", + { targetSelector: ".dot" }, + ); + const keys = [...studio.usePlayerStore.getState().keyframeCache.keys()] as string[]; + return keys.filter((k) => k.startsWith("index.html#")).sort(); + }, + [tween("dots", ".dot"), tween("blocks", "#stat3 .block")], + ); + expect(marked).toEqual([ + "index.html#blk1", + "index.html#blk2", + "index.html#d1", + "index.html#d2", + ]); + await page.close(); + }); +}); diff --git a/packages/studio/src/hooks/gsapShared.ts b/packages/studio/src/hooks/gsapShared.ts index 53f3944b45..a9375f0ac5 100644 --- a/packages/studio/src/hooks/gsapShared.ts +++ b/packages/studio/src/hooks/gsapShared.ts @@ -14,7 +14,7 @@ import { resolveTweenDuration, } from "../utils/globalTimeCompiler"; import { toCompositionTime } from "../player/store/timelineElement"; -import { previewFrameOpaque } from "../player/lib/previewChannel"; +import { previewDocumentCopy, previewFrameOpaque } from "../player/lib/previewChannel"; import { frameGsap, frameQuery } from "./gsapFrameSnapshot"; // ── Types ───────────────────────────────────────────────────────────────────── @@ -136,6 +136,17 @@ function wholeSelectorElementId(selector: string): string | null { return WHOLE_SELECTOR_ID.test(trimmed) ? idFromSelector(trimmed) : null; } +/** + * The document {@link resolveSelectorElementIds} matches tween selectors against: the frame's own, or a + * sealed frame's full markup, so a class or descendant tween attributes the same in both. + */ +export async function tweenTargetDocument( + iframe: HTMLIFrameElement | null | undefined, +): Promise { + if (!iframe) return null; + return previewFrameOpaque(iframe) ? previewDocumentCopy(iframe) : iframe.contentDocument; +} + /** * Resolve a tween's target selector to the ids of the element(s) it animates. * A whole-selector `#id` resolves directly; anything else (a class like `.dot`, diff --git a/packages/studio/src/hooks/keyframeCacheAstLoad.ts b/packages/studio/src/hooks/keyframeCacheAstLoad.ts index bb71cc8346..0b15a6ebe9 100644 --- a/packages/studio/src/hooks/keyframeCacheAstLoad.ts +++ b/packages/studio/src/hooks/keyframeCacheAstLoad.ts @@ -106,9 +106,9 @@ async function requestParsedAnimations( export async function populateKeyframeCacheFromAst( projectId: string, sf: string, - doc: Document | null | undefined, + doc: Document | null | undefined | Promise, ): Promise { - const parsed = await fetchParsedAnimations(projectId, sf); + const [parsed, targets] = await Promise.all([fetchParsedAnimations(projectId, sf), doc]); if (!parsed) return false; const { elements, domClipChildren } = usePlayerStore.getState(); const mergedByElement = new Map>(); @@ -120,7 +120,7 @@ export async function populateKeyframeCacheFromAst( if (!kfData) continue; // Attribute the tween to every element it animates (handles class / // group / descendant selectors, not just `#id`). - for (const id of resolveSelectorElementIds(anim.targetSelector, doc)) { + for (const id of resolveSelectorElementIds(anim.targetSelector, targets)) { // kfData is already resolved (real keyframes OR a synthesized flat // tween), so a flat tween joins the store like a keyframed one. No // property-group filter: this map must cover every tween the cache diff --git a/packages/studio/src/hooks/useGsapScriptCommits.ts b/packages/studio/src/hooks/useGsapScriptCommits.ts index 50cc299241..0189f7429f 100644 --- a/packages/studio/src/hooks/useGsapScriptCommits.ts +++ b/packages/studio/src/hooks/useGsapScriptCommits.ts @@ -23,7 +23,7 @@ import { markStudioSaveErrorAlreadyToasted, } from "../utils/studioSaveDiagnostics"; import type { CutoverDeps } from "../utils/sdkCutover"; -import { updateKeyframeCacheFromParsed } from "./gsapKeyframeCacheHelpers"; +import { cacheCommittedKeyframes } from "./gsapKeyframeCacheHelpers"; import { patchRuntimeTweenInPlace } from "./gsapRuntimePatch"; import { lastTweenPatch } from "@hyperframes/core/runtime/patch-tween"; import { previewFrameOpaque } from "../player/lib/previewChannel"; @@ -196,14 +196,12 @@ function syncCommittedGsapMutation({ forceReloadSdkSession?.(); if (options.skipReload) return; if (result.parsed?.animations) { - updateKeyframeCacheFromParsed( + void cacheCommittedKeyframes( + iframe, result.parsed.animations, targetPath, selection.id ?? undefined, mutation, - // The live preview document is what resolves a class / descendant tween to - // the elements it really animates; without it only whole-id selectors do. - iframe?.contentDocument, ); } refreshMutationPreview(iframe, result, options, reloadPreview, onCacheInvalidate, nestedFiles); diff --git a/packages/studio/src/hooks/useGsapTweenCache.ts b/packages/studio/src/hooks/useGsapTweenCache.ts index 02f7457d59..2c9ee4016e 100644 --- a/packages/studio/src/hooks/useGsapTweenCache.ts +++ b/packages/studio/src/hooks/useGsapTweenCache.ts @@ -11,7 +11,7 @@ import { publishKeyframeCache, writeGsapAnimationsForElement, } from "./gsapKeyframeCacheHelpers"; -import { resolveClipTimingBasis, toClipKeyframes } from "./gsapShared"; +import { resolveClipTimingBasis, toClipKeyframes, tweenTargetDocument } from "./gsapShared"; import { deduplicateKeyframes, isStaticPositionHold, @@ -307,7 +307,7 @@ export function usePopulateKeyframeCacheForFile( if (!sameData) pruneKeyframeCacheToFiles(files); if (stale.length === 0) return; runtimeScanDoneRef.current = ""; - const doc = previewDocument(iframeRef?.current); + const doc = tweenTargetDocument(iframeRef?.current); for (const sf of stale) { void populateKeyframeCacheFromAst(projectId, sf, doc).then((loaded) => { if (!loaded && loadedRef.current.dataKey === dataKey) loadedRef.current.files.delete(sf);