Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions packages/studio/src/hooks/gsapRuntimeReaders.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ afterEach(() => {
});

describe("readAllAnimatedProperties group filter", () => {
it("keeps other tweens' out-of-group properties out of a grouped resolve", () => {
it("keeps other tweens' out-of-group properties out of a grouped resolve", async () => {
const el = document.createElement("div");
el.id = "clip";
document.body.appendChild(el);
Expand All @@ -58,7 +58,7 @@ describe("readAllAnimatedProperties group filter", () => {
otherTweenVars: { opacity: 0, rotationX: 52, rotationY: -47 },
});

const result = readAllAnimatedProperties(iframe, "#clip", rotationSetAnim(), "rotation");
const result = await readAllAnimatedProperties(iframe, "#clip", rotationSetAnim(), "rotation");

expect(result).toEqual({ rotation: -28.1 });
});
Expand All @@ -77,7 +77,7 @@ describe("color-grading opacity truth", () => {
});

describe("readAllAnimatedProperties with a sibling tween", () => {
it("leaves a sibling tween's rotation to that tween after an opacity keyframe edit", () => {
it("leaves a sibling tween's rotation to that tween after an opacity keyframe edit", async () => {
const el = document.createElement("div");
el.id = "clip";
document.body.appendChild(el);
Expand Down Expand Up @@ -107,7 +107,7 @@ describe("readAllAnimatedProperties with a sibling tween", () => {
} as unknown as GsapAnimation;

// commitKeyframeProps: these values plus the edit at the playhead, and backfilled into the rest.
const read = readAllAnimatedProperties(iframe, "#clip", anim);
const read = await readAllAnimatedProperties(iframe, "#clip", anim);
live.kill();
gsap.set(el, { clearProps: "all" });
const edited = build({
Expand Down
47 changes: 28 additions & 19 deletions packages/studio/src/hooks/gsapRuntimeReaders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
import { classifyPropertyGroup, type PropertyGroupName } from "@hyperframes/core/gsap-parser";
import { getIframeGsap, queryIframeElement } from "./gsapShared";
import { settleGsapSnapshot } from "./gsapFrameSnapshot";
import { previewComputedStyles, previewFrameOpaque } from "../player/lib/previewChannel";
import { gsapWritesChannels } from "./gsapRuntimeKeyframes";
import { roundTo3 } from "../utils/rounding";

Expand All @@ -27,24 +29,19 @@ export function readGsapProperty(
}

export const POSITION_PROPS = new Set(["x", "y", "xPercent", "yPercent"]);
export function readAllAnimatedProperties(
export async function readAllAnimatedProperties(
iframe: HTMLIFrameElement | null,
selector: string,
anim: GsapAnimation,
group?: PropertyGroupName,
): Record<string, number> {
): Promise<Record<string, number>> {
const result: Record<string, number> = {};
if (!iframe) return result;
await settleGsapSnapshot(iframe);
const gsap = getIframeGsap(iframe);
if (!gsap) return result;
const el = queryIframeElement(iframe, selector);
if (!el) return result;
let doc: Document | null = null;
try {
doc = iframe?.contentDocument ?? null;
} catch {
/* cross-origin guard — doc stays null */
}

const propKeys = new Set<string>();
if (anim.keyframes) {
Expand Down Expand Up @@ -91,27 +88,39 @@ export function readAllAnimatedProperties(
"backgroundPositionX",
"backgroundPositionY",
];
let computedStyle: CSSStyleDeclaration | null = null;
try {
computedStyle = doc?.defaultView?.getComputedStyle(el) ?? null;
} catch {}
const css = await computedCss(iframe, el, selector, COMPUTED_BASELINE.map(kebabCase));
for (const prop of COMPUTED_BASELINE) {
if (prop in result) continue;
if (!inGroup(prop)) continue;
if (gsapWritesChannels(el, [prop])) continue;
const gsapVal = Number(gsap.getProperty(el, prop));
if (!Number.isFinite(gsapVal)) continue;
let cssVal = NaN;
if (computedStyle) {
const raw = computedStyle.getPropertyValue(
prop.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`),
);
cssVal = parseFloat(raw);
}
const cssVal = parseFloat(css[kebabCase(prop)] ?? "");
if (Number.isFinite(cssVal) && Math.round(gsapVal * 1000) === Math.round(cssVal * 1000))
continue;
result[prop] = roundTo3(gsapVal);
}

return result;
}

const kebabCase = (prop: string) => prop.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);

/** The element's computed CSS for `names`: over the port for a sealed frame, as the live element answers. */
async function computedCss(
iframe: HTMLIFrameElement,
el: Element,
selector: string,
names: string[],
): Promise<Record<string, string>> {
if (previewFrameOpaque(iframe))
return (await previewComputedStyles(iframe, selector, names)) ?? {};
try {
const style = iframe.contentDocument?.defaultView?.getComputedStyle(el);
return style
? Object.fromEntries(names.map((name) => [name, style.getPropertyValue(name)]))
: {};
} catch {
return {};
}
}
67 changes: 67 additions & 0 deletions packages/studio/src/hooks/gsapSealedReads.browser.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Real Chrome: what a commit reads of an element's GSAP values, in a sealed preview and a same-origin one.
import { readFileSync } from "node:fs";
import { createRequire } from "node:module";
import type { Browser } from "puppeteer-core";
import { afterAll, beforeAll, expect, it, vi } from "vitest";
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"];
type Reads = Studio & {
readAllAnimatedProperties: typeof import("./gsapRuntimeReaders").readAllAnimatedProperties;
settleGsapSnapshot: typeof import("./gsapFrameSnapshot").settleGsapSnapshot;
};
let browser: Browser;
let studioBundle: string;

beforeAll(async () => {
browser = await launchTestChrome();
studioBundle = await buildStudioBundle([
`export { readAllAnimatedProperties } from "./hooks/gsapRuntimeReaders";`,
`export { settleGsapSnapshot } from "./hooks/gsapFrameSnapshot";`,
]);
});

afterAll(() => closeTestChrome(browser));

/** #box turns in one tween and rounds its corners in another, both over 0-2 s. */
function previewHtml(): string {
const gsap = readFileSync(require.resolve("gsap/dist/gsap.min.js"), "utf8");
const runtime = readFileSync(require.resolve("@hyperframes/core/runtime"), "utf8");
return `<!doctype html><html><head><meta charset="UTF-8" />
<meta name="hyperframes-studio-preview" content="1" />
<style>html, body { margin: 0; width: 1920px; height: 1080px; overflow: hidden }
#box { position: absolute; left: 100px; top: 100px; width: 200px; height: 200px; background: #f0c020 }</style>
</head><body>
<div id="root" data-composition-id="main" data-start="0" data-duration="4" data-width="1920" data-height="1080">
<div id="box" class="clip" data-start="0" data-duration="4" data-track-index="1"></div>
</div>
<script>${gsap}</script>
<script>
window.__timelines = window.__timelines || {};
var tl = gsap.timeline({ paused: true });
tl.to("#box", { rotation: 20, duration: 2, ease: "none" }, 0);
tl.to("#box", { borderRadius: "24px", duration: 2, ease: "none" }, 0);
window.__timelines.main = tl;
</script>
<script>${runtime}</script></body></html>`;
}

// fails without the fix: a sealed read saw no tween writing borderRadius and copied it into the rotation commit.
it.each(MODES)("a rotation commit reads only the rotation tween's channels (%s)", async (mode) => {
const preview = await openPreview(browser, studioBundle, previewHtml(), mode);
await preview.seek(1);
const read = await preview.page.evaluate(async () => {
const studio = (window as unknown as { hfStudio: Reads }).hfStudio;
const iframe = document.querySelector("iframe")!;
studio.usePlayerStore.setState({ currentTime: 1, isPlaying: false });
await studio.settleGsapSnapshot(iframe);
return studio.readAllAnimatedProperties(iframe, "#box", {
properties: { rotation: 20 },
} as never);
});
expect(read).toEqual({ rotation: 10 });
await preview.page.close();
});
2 changes: 1 addition & 1 deletion packages/studio/src/hooks/useAnimatedPropertyCommit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@ async function commitKeyframeProps(
);
}
const ct = usePlayerStore.getState().currentTime;
const runtimeProps = selector ? readAllAnimatedProperties(iframe, selector, anim) : {};
const runtimeProps = selector ? await readAllAnimatedProperties(iframe, selector, anim) : {};
const properties: Record<string, number | string> = { ...runtimeProps, ...props };

const backfillDefaults: Record<string, number | string> = { ...runtimeProps };
Expand Down
Loading