mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-25 08:32:45 +00:00
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
This commit is contained in:
@@ -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<typeof import("../player/lib/previewChannel")>();
|
||||
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 = '<div id="d1" class="dot"></div><div id="d2" class="dot"></div><div id="x"></div>';
|
||||
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);
|
||||
});
|
||||
@@ -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<string, unknown>,
|
||||
): Promise<void> {
|
||||
// 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,
|
||||
|
||||
@@ -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) =>
|
||||
`<div id="${id}" class="${cls}" data-start="0" data-duration="4"></div>`;
|
||||
return `<!doctype html><html><head><meta charset="UTF-8" />
|
||||
<meta name="hyperframes-studio-preview" content="1" /></head><body>
|
||||
<div id="root" data-composition-id="main" data-start="0" data-duration="4" data-width="1920" data-height="1080">
|
||||
<div id="stat3">${clip("blk1", "block")}${clip("blk2", "block")}</div>
|
||||
${clip("outside", "block")}${clip("d1", "dot")}${clip("d2", "dot")}
|
||||
</div>
|
||||
<script>${gsap}</script>
|
||||
<script>(function () {
|
||||
window.__timelines = window.__timelines || {};
|
||||
var tl = gsap.timeline({ paused: true });
|
||||
tl.to(".dot", { x: 100, duration: 4 }, 0);
|
||||
tl.to("#stat3 .block", { y: 50, duration: 4 }, 0);
|
||||
window.__timelines.main = tl;
|
||||
})();</script>
|
||||
<script>${runtime}</script></body></html>`;
|
||||
}
|
||||
|
||||
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<string, Function> })
|
||||
.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();
|
||||
});
|
||||
});
|
||||
@@ -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<Document | null> {
|
||||
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`,
|
||||
|
||||
@@ -106,9 +106,9 @@ async function requestParsedAnimations(
|
||||
export async function populateKeyframeCacheFromAst(
|
||||
projectId: string,
|
||||
sf: string,
|
||||
doc: Document | null | undefined,
|
||||
doc: Document | null | undefined | Promise<Document | null>,
|
||||
): Promise<boolean> {
|
||||
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<string, GsapKeyframesData<MergeableKeyframe>>();
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user