diff --git a/packages/studio/src/components/editor/PropertyPanel.tsx b/packages/studio/src/components/editor/PropertyPanel.tsx index 645b4988d5..b561a29b56 100644 --- a/packages/studio/src/components/editor/PropertyPanel.tsx +++ b/packages/studio/src/components/editor/PropertyPanel.tsx @@ -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); diff --git a/packages/studio/src/components/editor/propertyPanelHelpers.ts b/packages/studio/src/components/editor/propertyPanelHelpers.ts index c0e341f7c1..75c5371878 100644 --- a/packages/studio/src/components/editor/propertyPanelHelpers.ts +++ b/packages/studio/src/components/editor/propertyPanelHelpers.ts @@ -506,88 +506,3 @@ export function readGsapRuntimeValuesForPanel( return null; } } - -export function readGsapBorderRadiusForPanel( - gsapRuntimeValues: Record | null, - gsapAnimations: GsapAnimation[], - element: DomEditSelection, - previewIframeRef: React.RefObject, -): { 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, -): 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"); -} diff --git a/packages/studio/src/components/editor/propertyPanelSealedReads.browser.test.ts b/packages/studio/src/components/editor/propertyPanelSealedReads.browser.test.ts new file mode 100644 index 0000000000..9d381f5317 --- /dev/null +++ b/packages/studio/src/components/editor/propertyPanelSealedReads.browser.test.ts @@ -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 ` + + + +
+
Intro
+
+
+ + + `; +} + +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; + }; + 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")); + }, +); diff --git a/packages/studio/src/components/editor/propertyPanelSealedReads.ts b/packages/studio/src/components/editor/propertyPanelSealedReads.ts new file mode 100644 index 0000000000..277f8fe0f6 --- /dev/null +++ b/packages/studio/src/components/editor/propertyPanelSealedReads.ts @@ -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 | null, + gsapAnimations: GsapAnimation[], + element: DomEditSelection, + iframe: HTMLIFrameElement | null, +): PanelBorderRadius | Promise | 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 { + 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( + read: T | Promise | 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; +} diff --git a/packages/studio/src/player/lib/previewChannel.ts b/packages/studio/src/player/lib/previewChannel.ts index 4cfaecba90..8f8834d31d 100644 --- a/packages/studio/src/player/lib/previewChannel.ts +++ b/packages/studio/src/player/lib/previewChannel.ts @@ -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 { +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 { + return (await documentMarkup(iframe))?.html ?? null; +} + +export async function previewDocumentCopy(iframe: HTMLIFrameElement): Promise { + 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; }