feat(core): a sealed preview answers a text toolbar's authored styles and fonts (#8761)

This commit is contained in:
Miguel Ángel
2026-11-24 20:40:20 +00:00
committed by GitHub
parent afd7469bca
commit 36d5763958
10 changed files with 304 additions and 1 deletions
@@ -0,0 +1,76 @@
import { afterEach, describe, expect, it } from "vitest";
import { MAX_ELEMENT_VALUE } from "../editingElement";
import { handleFor } from "../editingHandles";
import { MAX_FONT_FACES, authoredStyles, fontFaces } from "./textStyleReads";
afterEach(() => {
document.head.innerHTML = "";
document.body.innerHTML = "";
});
function page(css: string, body: string) {
document.head.innerHTML = `<style>${css}</style>`;
document.body.innerHTML = body;
return (id: string) => handleFor(document.getElementById(id)!);
}
describe("authored-styles", () => {
it("reads the inline value first, else the last same-origin rule that matches", () => {
const handle = page(
`h1 { font-size: 3rem; } .title { font-size: 48px; color: red; } p { font-size: 9px; }`,
`<h1 id="t" class="title" style="color: blue">Hi</h1><h1 id="u">Yo</h1>`,
);
expect(
authoredStyles({ handle: handle("t"), properties: ["font-size", "color", "letter-spacing"] }),
).toEqual({ styles: { "font-size": "48px", color: "blue" } });
expect(authoredStyles({ handle: handle("u"), properties: ["font-size"] })).toEqual({
styles: { "font-size": "3rem" },
});
});
it("skips a rule whose selector this engine cannot read", () => {
const handle = page(
`h1 { font-size: 2em; } h1:not-a-pseudo { font-size: 1px; }`,
`<h1 id="t">Hi</h1>`,
);
expect(authoredStyles({ handle: handle("t"), properties: ["font-size"] })).toEqual({
styles: { "font-size": "2em" },
});
});
it("answers null for a handle of an element already gone", () => {
const handle = page(`h1 { font-size: 2em; }`, `<h1 id="t">Hi</h1>`);
const gone = handle("t");
document.getElementById("t")!.remove();
expect(authoredStyles({ handle: gone, properties: ["font-size"] })).toEqual({ styles: null });
});
it("cuts a value at the element value limit", () => {
const long = `"${"a".repeat(MAX_ELEMENT_VALUE + 50)}"`;
const handle = page(``, `<h1 id="t">Hi</h1>`);
document.getElementById("t")!.style.setProperty("font-family", long);
const { styles } = authoredStyles({ handle: handle("t"), properties: ["font-family"] });
expect(styles?.["font-family"]).toHaveLength(MAX_ELEMENT_VALUE);
});
});
describe("font-faces", () => {
it("lists each same-origin @font-face rule's family", () => {
page(
`@font-face { font-family: "Brand Sans"; src: url("fonts/brand.woff2"); }
h1 { font-family: "Brand Sans"; }
@font-face { font-family: Inter; src: url("https://fonts.gstatic.com/inter.woff2"); }`,
``,
);
expect(fontFaces().ownFaces.map(({ family }) => family)).toEqual(['"Brand Sans"', "Inter"]);
});
it(`lists at most ${MAX_FONT_FACES} faces`, () => {
const faces = Array.from(
{ length: MAX_FONT_FACES + 5 },
(_, i) => `@font-face { font-family: F${i}; src: url("f${i}.woff2"); }`,
);
page(faces.join("\n"), ``);
expect(fontFaces().ownFaces).toHaveLength(MAX_FONT_FACES);
});
});
@@ -0,0 +1,73 @@
// Reads a text toolbar takes from the frame's own stylesheets and fonts, for a parent that cannot reach its document.
import type { EditingElementHandle } from "../editingElement";
import { MAX_ELEMENT_VALUE } from "../editingElement";
import { elementForHandle } from "../editingHandles";
export const MAX_FONT_FACES = 256;
const cut = (value: string) => value.slice(0, MAX_ELEMENT_VALUE);
function sameOriginRules(): CSSRule[] {
return [...document.styleSheets].flatMap((sheet) => {
try {
return [...sheet.cssRules];
} catch {
return [];
}
});
}
const isStyleRule = (rule: CSSRule): rule is CSSStyleRule => "selectorText" in rule;
const isFontFaceRule = (rule: CSSRule): rule is CSSFontFaceRule =>
rule.cssText.startsWith("@font-face");
function matches(element: Element, selector: string) {
try {
return element.matches(selector);
} catch {
return false;
}
}
/** Each property's inline value, else the last same-origin rule's that matches; null for an unknown handle. */
export function authoredStyles({
handle,
properties,
}: {
handle: EditingElementHandle;
properties: string[];
}): { styles: Record<string, string> | null } {
const element = elementForHandle(handle);
if (!element) return { styles: null };
const inline = (element as Partial<ElementCSSInlineStyle>).style;
const rules = sameOriginRules().filter(isStyleRule);
const styles: Record<string, string> = {};
for (const name of properties) {
const ruled = rules.filter(
(rule) => rule.style.getPropertyValue(name) && matches(element, rule.selectorText),
);
const value = inline?.getPropertyValue(name) || ruled.at(-1)?.style.getPropertyValue(name);
if (value) styles[name] = cut(value);
}
return { styles };
}
/** The families the document's fonts draw, and each same-origin `@font-face` rule's family and src. */
export function fontFaces(): {
families: string[];
ownFaces: Array<{ family: string; src: string }>;
} {
const families = new Set<string>();
for (const face of document.fonts ?? []) {
if (families.size >= MAX_FONT_FACES) break;
families.add(cut(face.family));
}
const ownFaces = sameOriginRules()
.filter(isFontFaceRule)
.slice(0, MAX_FONT_FACES)
.map((rule) => ({
family: cut(rule.style.getPropertyValue("font-family")),
src: cut(rule.style.getPropertyValue("src")),
}));
return { families: [...families], ownFaces };
}
@@ -193,6 +193,8 @@ describe("installEditingAgent", () => {
"wait-for-seek",
"set-loop-start",
"computed-styles",
"authored-styles",
"font-faces",
"elements-at-point",
"pointer-targets",
"describe",
@@ -273,6 +275,19 @@ describe("installEditingAgent", () => {
"invalid-params",
],
[{ v: 1, id: 16, kind: "computed-styles", params: { selector: "p" } }, 16, "invalid-params"],
...[
{ selector: "p", properties: ["font-size"] },
{ handle: H, properties: [] },
{ handle: H, properties: ["font-size;"] },
{ handle: H, properties: Array(65).fill("font-size") },
{ handle: "not a handle", properties: ["font-size"] },
{ handle: H, properties: ["font-size"], extra: 1 },
].map((params, index) => [
{ v: 1, id: 900 + index, kind: "authored-styles", params },
900 + index,
"invalid-params",
]),
[{ v: 1, id: 910, kind: "font-faces", params: { all: true } }, 910, "invalid-params"],
[{ v: 1, id: 160, kind: "console-errors", params: {} }, 160, "invalid-params"],
[{ v: 1, id: 161, kind: "console-errors", params: { from: -1 } }, 161, "invalid-params"],
[{ v: 1, id: 162, kind: "console-errors", params: { from: 1.5 } }, 162, "invalid-params"],
@@ -62,6 +62,7 @@ import { colorGradingPlayback } from "./editing/color-grading-playback";
import { assignAudioGroup } from "./editing/assignAudioGroup";
import { audioMeter } from "./editing/audioMeter";
import { documentMarkup } from "./editing/documentMarkup";
import { authoredStyles, fontFaces } from "./editing/textStyleReads";
import { setAudioGroupAttribute } from "./editing/setAudioGroupAttribute";
import { editElement } from "./editing/editElement";
import { endTextEdit, textEdit } from "./editing/textEdit";
@@ -197,6 +198,8 @@ const HANDLERS: Handlers = {
}
return { styles };
},
"authored-styles": authoredStyles,
"font-faces": () => fontFaces(),
"elements-at-point": ({ x, y }) => ({ elements: elementsAtPoint(x, y) }),
"pointer-targets": ({ x, y }) => pointerTargetsAt(x, y),
describe: ({ handles }) => ({ elements: describeHandles(handles) }),
@@ -76,6 +76,8 @@ describe("createEditingPortClient", () => {
"wait-for-seek",
"set-loop-start",
"computed-styles",
"authored-styles",
"font-faces",
"elements-at-point",
"pointer-targets",
"describe",
+16
View File
@@ -181,6 +181,8 @@ export const EDITING_REQUEST_KINDS = [
"wait-for-seek",
"set-loop-start",
"computed-styles",
"authored-styles",
"font-faces",
"elements-at-point",
"pointer-targets",
"describe",
@@ -299,6 +301,14 @@ export interface EditingRequests {
params: ({ selector: string } | { handle: EditingElementHandle }) & { properties: string[] };
result: { styles: Record<string, string> | null };
};
"authored-styles": {
params: { handle: EditingElementHandle; properties: string[] };
result: { styles: Record<string, string> | null };
};
"font-faces": {
params: NoParams;
result: { families: string[]; ownFaces: Array<{ family: string; src: string }> };
};
/** The stack under a viewport point, topmost first, up to MAX_POINT_STACK. Describe one to keep. */
"elements-at-point": {
params: { x: number; y: number };
@@ -638,6 +648,12 @@ const PARAM_PARSERS: {
const properties = styleProperties(params.properties);
return target && properties ? { ...target, properties } : null;
},
"authored-styles": (params) => {
if (!hasKeys(params, "handle,properties") || !isHandle(params.handle)) return null;
const properties = styleProperties(params.properties);
return properties?.length ? { handle: params.handle, properties } : null;
},
"font-faces": noParams,
"elements-at-point": point,
"pointer-targets": point,
describe: handleList,
+2
View File
@@ -46,8 +46,10 @@ export {
} from "./player";
export { usePreviewIframeStore } from "./player/store/previewIframeStore";
export {
previewAuthoredStyles,
previewDocumentCopy,
previewEditingClient,
previewFontFaces,
previewFrameOpaque,
} from "./player/lib/previewChannel";
export {
@@ -162,7 +162,19 @@ export async function previewComputedStyles(
): Promise<Record<string, string> | null> {
const element = typeof target === "string" ? { selector: target } : { handle: target.handle };
const reply = await previewRequest(iframe, "computed-styles", { ...element, properties });
const styles: unknown = reply?.styles;
return readStyles(reply?.styles, properties);
}
export async function previewAuthoredStyles(
iframe: HTMLIFrameElement,
handle: string,
properties: string[],
): Promise<Record<string, string> | null> {
const reply = await previewRequest(iframe, "authored-styles", { handle, properties });
return readStyles(reply?.styles, properties);
}
function readStyles(styles: unknown, properties: string[]): Record<string, string> | null {
if (typeof styles !== "object" || styles === null) return null;
const read: Record<string, string> = {};
for (const name of properties) {
@@ -172,6 +184,22 @@ export async function previewComputedStyles(
return read;
}
type FontFaces = { families: string[]; ownFaces: Array<{ family: string; src: string }> };
export async function previewFontFaces(iframe: HTMLIFrameElement): Promise<FontFaces | null> {
const reply = await previewRequest(iframe, "font-faces", {});
const { families, ownFaces } = reply ?? {};
const isText = (value: unknown): value is string => typeof value === "string";
const isFace = (face: unknown): face is FontFaces["ownFaces"][number] =>
typeof face === "object" &&
face !== null &&
isText((face as { family?: unknown }).family) &&
isText((face as { src?: unknown }).src);
if (!Array.isArray(families) || !families.every(isText)) return null;
if (!Array.isArray(ownFaces) || !ownFaces.every(isFace)) return null;
return { families, ownFaces: ownFaces.map(({ family, src }) => ({ family, src })) };
}
export async function previewAssetsUnloaded(iframe: HTMLIFrameElement): Promise<boolean | null> {
const reply = await previewRequest(iframe, "assets-unloaded", {});
return typeof reply?.unloaded === "boolean" ? reply.unloaded : null;
@@ -0,0 +1,85 @@
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 { previewAuthoredStyles, previewFontFaces } from "./player/lib/previewChannel";`,
`export { queryPreviewElements } from "./player/lib/previewElements";`,
]);
});
afterAll(() => closeTestChrome(browser));
function previewHtml(): string {
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>
@font-face { font-family: "Brand Sans"; src: url("fonts/brand.woff2"); }
h1 { font-size: 3rem; }
.title { font-size: 48px; color: rgb(200, 0, 0); }
</style>
</head><body>
<div id="root" data-composition-id="main" data-start="0" data-duration="4" data-width="1920" data-height="1080">
<h1 class="title" data-hf-id="t1" style="color: blue" data-start="0" data-duration="4">Hello</h1>
<h1 class="plain" data-hf-id="t2" data-start="0" data-duration="4">Plain</h1>
</div>
<script>document.fonts.add(new FontFace("Scripted", "url(fonts/scripted.woff2)"));</script>
<script>${runtime}</script></body></html>`;
}
async function textStyleReads(mode: string) {
const preview = await openPreview(browser, studioBundle, previewHtml(), mode);
try {
return await preview.page.evaluate(async () => {
type Studio = {
queryPreviewElements(
iframe: HTMLIFrameElement,
selector: string,
): Promise<{ matches: Array<{ handle: string }> } | null>;
previewAuthoredStyles(
iframe: HTMLIFrameElement,
handle: string,
properties: string[],
): Promise<Record<string, string> | null>;
previewFontFaces(iframe: HTMLIFrameElement): Promise<unknown>;
};
const studio = (window as unknown as { hfStudio: Studio }).hfStudio;
const iframe = document.querySelector("iframe")!;
const handleOf = async (selector: string) =>
(await studio.queryPreviewElements(iframe, selector))!.matches[0]!.handle;
const properties = ["font-size", "color", "letter-spacing"];
return {
title: await studio.previewAuthoredStyles(iframe, await handleOf(".title"), properties),
plain: await studio.previewAuthoredStyles(iframe, await handleOf(".plain"), properties),
fonts: await studio.previewFontFaces(iframe),
};
});
} finally {
await preview.page.close();
}
}
it.each(MODES)(
"the frame answers a text toolbar's authored styles and fonts the same in a %s preview",
async (mode) => {
const reads = await textStyleReads(mode);
expect(reads.title).toEqual({ "font-size": "48px", color: "blue" });
expect(reads.plain).toEqual({ "font-size": "3rem" });
expect(reads.fonts).toEqual({
families: ["Brand Sans", "Scripted"],
ownFaces: [{ family: '"Brand Sans"', src: 'url("fonts/brand.woff2")' }],
});
},
);
@@ -2,6 +2,7 @@ import { expect, it } from "vitest";
import * as studio from "@hyperframes/studio";
import * as elements from "./player/lib/previewElements";
import * as selection from "./components/editor/previewSelection";
import * as channel from "./player/lib/previewChannel";
it("exports a sealed preview's checked element reads and stand-ins as the ones Studio uses", () => {
expect(studio.describePreviewElements).toBe(elements.describePreviewElements);
@@ -18,4 +19,6 @@ it("exports a sealed preview's checked element reads and stand-ins as the ones S
expect(studio.readable).toBe(selection.readable);
expect(studio.standInFor).toBe(selection.standInFor);
expect(studio.standInHandle).toBe(selection.standInHandle);
expect(studio.previewAuthoredStyles).toBe(channel.previewAuthoredStyles);
expect(studio.previewFontFaces).toBe(channel.previewFontFaces);
});