fix(studio): property panel corner radius and copied source line read a sealed preview (#8662)

* test(studio): property panel corner radii and source line read the same sealed

* fix(studio): property panel corner radius and copied source line read a sealed preview

* refactor(studio): the panel's sealed reads live in their own module, under the file-size cap
This commit is contained in:
Miguel Ángel
2026-11-24 08:36:39 +00:00
committed by GitHub
parent bfadf5b2b3
commit e6ba081bb9
5 changed files with 257 additions and 95 deletions
@@ -7,13 +7,11 @@ import { useStudioShellContext } from "../../contexts/StudioContext";
import { readStudioBoxSize } from "./manualEdits";
import { readMoveOffset, readShownRotation } from "./plainTranslate";
import {
buildElementInfoText,
EMPTY_STYLES,
formatPxMetricValue,
parsePxMetricValue,
RESPONSIVE_GRID,
readGsapRuntimeValuesForPanel,
readGsapBorderRadiusForPanel,
isSelectedElementHidden,
selectionIdentityKey,
} from "./propertyPanelHelpers";
@@ -37,6 +35,11 @@ import { TimingSection } from "./propertyPanelTimingSection";
import { type PropertyPanelProps } from "./propertyPanelHelpers";
import { GestureRecordPanelButton } from "./GestureRecordControl";
import { PropertyPanelEmptyState } from "./PropertyPanelEmptyState";
import {
readElementInfoText,
readGsapBorderRadiusForPanel,
useAnswered,
} from "./propertyPanelSealedReads";
import { DesignPanelInputProvider } from "../../contexts/DesignPanelInputContext";
import { isAudioDomElement } from "../../utils/timelineInspector";
import { useManualEditDisabledFlags } from "./previewReadOnlyContext";
@@ -144,14 +147,20 @@ export const PropertyPanel = memo(function PropertyPanel(props: PropertyPanelPro
// eslint-disable-next-line react-hooks/exhaustive-deps -- iframeRef is stable; currentTime drives re-reads during playback
[gsapAnimIdForMemo, gsapAnimations, element, currentTime, sealedReads],
);
const gsapBorderRadius = useMemo(
const borderRadiusRead = useMemo(
() =>
element
? readGsapBorderRadiusForPanel(gsapRuntimeValues, gsapAnimations, element, iframeRef)
? readGsapBorderRadiusForPanel(
gsapRuntimeValues,
gsapAnimations,
element,
iframeRef.current,
)
: null,
// eslint-disable-next-line react-hooks/exhaustive-deps
[gsapRuntimeValues, gsapAnimations, element, currentTime],
);
const gsapBorderRadius = useAnswered(borderRadiusRead, element);
// The 3D Transform panel should be reachable on ANY element, not only ones GSAP is
// already animating — otherwise you can't add depth/rotation to a fresh static
// element (the panel never appears, the classic chicken-and-egg). Default to
@@ -236,11 +245,10 @@ export const PropertyPanel = memo(function PropertyPanel(props: PropertyPanelPro
const displayR = gsapRuntimeValues?.rotation ?? manualRotation.angle;
const handleCopyElementInfo = () => {
const text = buildElementInfoText(element, sourceLabel, gsapAnimations, previewIframeRef);
// Claim the copy only once the write actually lands — a denied clipboard
// permission otherwise reports a copy that never happened.
navigator.clipboard
.writeText(text)
void readElementInfoText(element, sourceLabel, gsapAnimations, previewIframeRef?.current)
.then((text) => navigator.clipboard.writeText(text))
.then(() => {
showToast(`Copied element info for ${element.label}. Paste it into any AI agent`, "info");
setClipboardCopied(true);
@@ -506,88 +506,3 @@ export function readGsapRuntimeValuesForPanel(
return null;
}
}
export function readGsapBorderRadiusForPanel(
gsapRuntimeValues: Record<string, number> | null,
gsapAnimations: GsapAnimation[],
element: DomEditSelection,
previewIframeRef: React.RefObject<HTMLIFrameElement | null>,
): { tl: number; tr: number; br: number; bl: number } | null {
if (!gsapRuntimeValues || !("borderRadius" in gsapRuntimeValues)) {
const hasBRProp = gsapAnimations.some(
(a) =>
"borderRadius" in a.properties ||
a.keyframes?.keyframes.some((kf) => "borderRadius" in kf.properties),
);
if (!hasBRProp) return null;
}
const iframe = previewIframeRef?.current;
if (!iframe?.contentDocument) return null;
try {
const el = findPreviewNode(iframe.contentDocument, element);
if (!el || !iframe.contentWindow) return null;
const cs = iframe.contentWindow.getComputedStyle(el);
const parse = (v: string) => Number.parseFloat(v) || 0;
return {
tl: parse(cs.borderTopLeftRadius),
tr: parse(cs.borderTopRightRadius),
br: parse(cs.borderBottomRightRadius),
bl: parse(cs.borderBottomLeftRadius),
};
} catch {
return null;
}
}
/**
* Builds the multi-line "element info" text copied to the clipboard for an AI
* agent. Shared by both the legacy and flat inspector headers (the flat split
* needs the same string), so it lives here rather than as a PropertyPanel
* closure. Pure — the caller owns the clipboard write, toast, and copied state.
*/
// fallow-ignore-next-line complexity
export function buildElementInfoText(
element: DomEditSelection,
sourceLabel: string,
gsapAnimations: GsapAnimation[],
previewIframeRef?: React.RefObject<HTMLIFrameElement | null>,
): string {
const file = element.sourceFile ?? "index.html";
let lineNum: number | null = null;
try {
const src = previewIframeRef?.current?.contentDocument?.documentElement?.outerHTML ?? "";
if (src && element.id) {
const idx = src.indexOf(`id="${element.id}"`);
if (idx > -1) lineNum = src.slice(0, idx).split("\n").length;
}
if (!lineNum && element.selector) {
const tag = element.tagName.toLowerCase();
const cls = element.selector.startsWith(".") ? element.selector.slice(1).split(".")[0] : null;
const search = cls ? `class="${cls}` : `<${tag}`;
const idx = src.indexOf(search);
if (idx > -1) lineNum = src.slice(0, idx).split("\n").length;
}
} catch {}
const fileLoc = lineNum ? `${file}:${lineNum}` : file;
const lines = [
`Element: ${element.label} (${sourceLabel})`,
`File: ${fileLoc}`,
`Position: x=${Math.round(element.boundingBox.x)}, y=${Math.round(element.boundingBox.y)}`,
`Size: ${Math.round(element.boundingBox.width)}×${Math.round(element.boundingBox.height)}`,
`Tag: <${element.tagName}>`,
];
if (element.computedStyles["z-index"] && element.computedStyles["z-index"] !== "auto") {
lines.push(`Z-index: ${element.computedStyles["z-index"]}`);
}
if (gsapAnimations.length > 0) {
const anim = gsapAnimations[0];
lines.push(
`Animation: ${anim.method}() ${anim.duration}s at ${anim.position}s, ease: ${anim.ease ?? "default"}`,
);
const props = Object.entries(anim.properties)
.map(([k, v]) => `${k}: ${v}`)
.join(", ");
if (props) lines.push(`Properties: ${props}`);
}
return lines.join("\n");
}
@@ -0,0 +1,93 @@
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 } 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 { readElementInfoText, readGsapBorderRadiusForPanel } from "./components/editor/propertyPanelSealedReads";`,
]);
});
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");
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 }
#root { position: relative; width: 100%; height: 100% }</style>
</head><body>
<div id="root" data-composition-id="main" data-start="0" data-duration="4" data-width="1920" data-height="1080">
<div id="intro" class="clip" data-start="0" data-duration="4" data-track-index="2">Intro</div>
<div id="card" class="clip card" data-start="0" data-duration="4" data-track-index="1"
style="position: absolute; width: 400px; height: 300px; background: red; border-radius: 0px"></div>
</div>
<script>${gsap}</script>
<script>(function () {
window.__timelines = window.__timelines || {};
var tl = gsap.timeline({ paused: true });
tl.to("#card", { borderRadius: "40px 80px 120px 20px", duration: 4, ease: "none" }, 0);
window.__timelines.main = tl;
})();</script>
<script>${runtime}</script></body></html>`;
}
async function panelReads(mode: string) {
const preview = await openPreview(browser, studioBundle, previewHtml(), mode);
try {
await preview.seek(2);
return await preview.page.evaluate(async () => {
type Studio = {
previewRequest(
iframe: HTMLIFrameElement,
kind: "query",
params: { selector: string },
): Promise<{ matches: Array<{ handle: string }> } | null>;
readGsapBorderRadiusForPanel(...args: unknown[]): unknown;
readElementInfoText(...args: unknown[]): Promise<string>;
};
const studio = (window as unknown as { hfStudio: Studio }).hfStudio;
const iframe = document.querySelector("iframe")!;
const query = await studio.previewRequest(iframe, "query", { selector: "#card" });
const element = {
element: null,
handle: query?.matches[0]?.handle,
id: "card",
selector: "#card",
sourceFile: "index.html",
tagName: "div",
label: "card",
boundingBox: { x: 0, y: 0, width: 400, height: 300 },
computedStyles: {},
};
const animations = [{ properties: { borderRadius: "40px 80px 120px 20px" } }];
const radius = await studio.readGsapBorderRadiusForPanel(null, animations, element, iframe);
const info = await studio.readElementInfoText(element, "#card", [], iframe);
return { radius, file: info.split("\n").find((line) => line.startsWith("File:")) };
});
} finally {
await preview.page.close();
}
}
it.each(MODES)(
"the property panel reads corner radii and the source line in a %s preview",
async (mode) => {
const reads = await panelReads(mode);
expect(reads.radius).toEqual({ tl: 20, tr: 40, br: 60, bl: 10 });
expect(reads.file).toMatch(/^File: index\.html:\d+$/);
expect(reads.file).not.toBe("File: index.html:1");
expect(reads).toEqual(await panelReads("unsealed"));
},
);
@@ -0,0 +1,136 @@
import { useEffect, useState } from "react";
import type { GsapAnimation } from "@hyperframes/parsers/gsap-parser";
import type { DomEditSelection } from "./domEditing";
import { findPreviewNode } from "./domEditingElement";
import {
previewComputedStyles,
previewDocumentMarkup,
previewFrameOpaque,
} from "../../player/lib/previewChannel";
type PanelBorderRadius = { tl: number; tr: number; br: number; bl: number };
const RADIUS_CORNERS = [
"border-top-left-radius",
"border-top-right-radius",
"border-bottom-right-radius",
"border-bottom-left-radius",
] as const;
function cornerRadii(read: (corner: string) => string | undefined): PanelBorderRadius {
const [tl, tr, br, bl] = RADIUS_CORNERS.map(
(corner) => Number.parseFloat(read(corner) ?? "") || 0,
);
return { tl: tl!, tr: tr!, br: br!, bl: bl! };
}
/** The element's computed corner radii while GSAP animates them: at once from a readable frame, else asked of it. */
export function readGsapBorderRadiusForPanel(
gsapRuntimeValues: Record<string, number> | null,
gsapAnimations: GsapAnimation[],
element: DomEditSelection,
iframe: HTMLIFrameElement | null,
): PanelBorderRadius | Promise<PanelBorderRadius | null> | null {
if (!gsapRuntimeValues || !("borderRadius" in gsapRuntimeValues)) {
const hasBRProp = gsapAnimations.some(
(a) =>
"borderRadius" in a.properties ||
a.keyframes?.keyframes.some((kf) => "borderRadius" in kf.properties),
);
if (!hasBRProp) return null;
}
if (!iframe) return null;
if (previewFrameOpaque(iframe)) {
if (!element.handle) return null;
return previewComputedStyles(iframe, { handle: element.handle }, [...RADIUS_CORNERS]).then(
(styles) => styles && cornerRadii((corner) => styles[corner]),
);
}
try {
const el = iframe.contentDocument && findPreviewNode(iframe.contentDocument, element);
if (!el || !iframe.contentWindow) return null;
const cs = iframe.contentWindow.getComputedStyle(el);
return cornerRadii((corner) => cs.getPropertyValue(corner));
} catch {
return null;
}
}
/**
* The "element info" text copied for an AI agent, its line found in the frame's markup `src`; both inspector
* headers share it. Pure — the caller owns the clipboard write, toast, and copied state.
*/
// fallow-ignore-next-line complexity
function buildElementInfoText(
element: DomEditSelection,
sourceLabel: string,
gsapAnimations: GsapAnimation[],
src: string,
): string {
const file = element.sourceFile ?? "index.html";
let lineNum: number | null = null;
if (src && element.id) {
const idx = src.indexOf(`id="${element.id}"`);
if (idx > -1) lineNum = src.slice(0, idx).split("\n").length;
}
if (!lineNum && element.selector) {
const tag = element.tagName.toLowerCase();
const cls = element.selector.startsWith(".") ? element.selector.slice(1).split(".")[0] : null;
const search = cls ? `class="${cls}` : `<${tag}`;
const idx = src.indexOf(search);
if (idx > -1) lineNum = src.slice(0, idx).split("\n").length;
}
const fileLoc = lineNum ? `${file}:${lineNum}` : file;
const lines = [
`Element: ${element.label} (${sourceLabel})`,
`File: ${fileLoc}`,
`Position: x=${Math.round(element.boundingBox.x)}, y=${Math.round(element.boundingBox.y)}`,
`Size: ${Math.round(element.boundingBox.width)}×${Math.round(element.boundingBox.height)}`,
`Tag: <${element.tagName}>`,
];
if (element.computedStyles["z-index"] && element.computedStyles["z-index"] !== "auto") {
lines.push(`Z-index: ${element.computedStyles["z-index"]}`);
}
if (gsapAnimations.length > 0) {
const anim = gsapAnimations[0];
lines.push(
`Animation: ${anim.method}() ${anim.duration}s at ${anim.position}s, ease: ${anim.ease ?? "default"}`,
);
const props = Object.entries(anim.properties)
.map(([k, v]) => `${k}: ${v}`)
.join(", ");
if (props) lines.push(`Properties: ${props}`);
}
return lines.join("\n");
}
export async function readElementInfoText(
element: DomEditSelection,
sourceLabel: string,
gsapAnimations: GsapAnimation[],
iframe: HTMLIFrameElement | null | undefined,
): Promise<string> {
let src = "";
try {
if (iframe && previewFrameOpaque(iframe)) src = (await previewDocumentMarkup(iframe)) ?? "";
else src = iframe?.contentDocument?.documentElement?.outerHTML ?? "";
} catch {}
return buildElementInfoText(element, sourceLabel, gsapAnimations, src);
}
export function useAnswered<T extends object>(
read: T | Promise<T | null> | null,
owner: unknown,
): T | null {
const [answered, setAnswered] = useState<{ owner: unknown; value: T | null } | null>(null);
useEffect(() => {
if (!(read instanceof Promise)) return;
let current = true;
void read.then((value) => current && setAnswered({ owner, value }));
return () => {
current = false;
};
}, [read, owner]);
if (!(read instanceof Promise)) return read;
return answered && answered.owner === owner ? answered.value : null;
}
@@ -177,12 +177,22 @@ export async function previewAssetsUnloaded(iframe: HTMLIFrameElement): Promise<
return typeof reply?.unloaded === "boolean" ? reply.unloaded : null;
}
export async function previewDocumentCopy(iframe: HTMLIFrameElement): Promise<Document | null> {
async function documentMarkup(iframe: HTMLIFrameElement) {
const reply = await previewRequest(iframe, "document-markup", {});
if (typeof reply?.html !== "string" || typeof reply.baseURI !== "string") return null;
const doc = new DOMParser().parseFromString(reply.html, "text/html");
return { html: reply.html, baseURI: reply.baseURI };
}
export async function previewDocumentMarkup(iframe: HTMLIFrameElement): Promise<string | null> {
return (await documentMarkup(iframe))?.html ?? null;
}
export async function previewDocumentCopy(iframe: HTMLIFrameElement): Promise<Document | null> {
const markup = await documentMarkup(iframe);
if (!markup) return null;
const doc = new DOMParser().parseFromString(markup.html, "text/html");
const base = doc.createElement("base");
base.setAttribute("href", reply.baseURI);
base.setAttribute("href", markup.baseURI);
doc.head.prepend(base);
return doc;
}