diff --git a/packages/core/src/runtime/editing/textStyleReads.test.ts b/packages/core/src/runtime/editing/textStyleReads.test.ts
new file mode 100644
index 0000000000..1a1bfcaf59
--- /dev/null
+++ b/packages/core/src/runtime/editing/textStyleReads.test.ts
@@ -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 = ``;
+ 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; }`,
+ `
Hi
Yo
`,
+ );
+ 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; }`,
+ `Hi
`,
+ );
+ 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; }`, `Hi
`);
+ 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(``, `Hi
`);
+ 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);
+ });
+});
diff --git a/packages/core/src/runtime/editing/textStyleReads.ts b/packages/core/src/runtime/editing/textStyleReads.ts
new file mode 100644
index 0000000000..18fca155e6
--- /dev/null
+++ b/packages/core/src/runtime/editing/textStyleReads.ts
@@ -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 | null } {
+ const element = elementForHandle(handle);
+ if (!element) return { styles: null };
+ const inline = (element as Partial).style;
+ const rules = sameOriginRules().filter(isStyleRule);
+ const styles: Record = {};
+ 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();
+ 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 };
+}
diff --git a/packages/core/src/runtime/editingAgent.test.ts b/packages/core/src/runtime/editingAgent.test.ts
index 4850632b05..c0ce3c9cd0 100644
--- a/packages/core/src/runtime/editingAgent.test.ts
+++ b/packages/core/src/runtime/editingAgent.test.ts
@@ -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"],
diff --git a/packages/core/src/runtime/editingAgent.ts b/packages/core/src/runtime/editingAgent.ts
index deb9af533e..9dca5a6e5f 100644
--- a/packages/core/src/runtime/editingAgent.ts
+++ b/packages/core/src/runtime/editingAgent.ts
@@ -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) }),
diff --git a/packages/core/src/runtime/editingPort.test.ts b/packages/core/src/runtime/editingPort.test.ts
index 3f15d26547..69d119331d 100644
--- a/packages/core/src/runtime/editingPort.test.ts
+++ b/packages/core/src/runtime/editingPort.test.ts
@@ -76,6 +76,8 @@ describe("createEditingPortClient", () => {
"wait-for-seek",
"set-loop-start",
"computed-styles",
+ "authored-styles",
+ "font-faces",
"elements-at-point",
"pointer-targets",
"describe",
diff --git a/packages/core/src/runtime/editingPort.ts b/packages/core/src/runtime/editingPort.ts
index 143adaa7d6..87bac06128 100644
--- a/packages/core/src/runtime/editingPort.ts
+++ b/packages/core/src/runtime/editingPort.ts
@@ -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 | null };
};
+ "authored-styles": {
+ params: { handle: EditingElementHandle; properties: string[] };
+ result: { styles: Record | 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,
diff --git a/packages/studio/src/index.ts b/packages/studio/src/index.ts
index 34c455dbd1..26440dacec 100644
--- a/packages/studio/src/index.ts
+++ b/packages/studio/src/index.ts
@@ -46,8 +46,10 @@ export {
} from "./player";
export { usePreviewIframeStore } from "./player/store/previewIframeStore";
export {
+ previewAuthoredStyles,
previewDocumentCopy,
previewEditingClient,
+ previewFontFaces,
previewFrameOpaque,
} from "./player/lib/previewChannel";
export {
diff --git a/packages/studio/src/player/lib/previewChannel.ts b/packages/studio/src/player/lib/previewChannel.ts
index 8f8834d31d..1d613e1b6b 100644
--- a/packages/studio/src/player/lib/previewChannel.ts
+++ b/packages/studio/src/player/lib/previewChannel.ts
@@ -162,7 +162,19 @@ export async function previewComputedStyles(
): Promise | 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 | null> {
+ const reply = await previewRequest(iframe, "authored-styles", { handle, properties });
+ return readStyles(reply?.styles, properties);
+}
+
+function readStyles(styles: unknown, properties: string[]): Record | null {
if (typeof styles !== "object" || styles === null) return null;
const read: Record = {};
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 {
+ 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 {
const reply = await previewRequest(iframe, "assets-unloaded", {});
return typeof reply?.unloaded === "boolean" ? reply.unloaded : null;
diff --git a/packages/studio/src/player/lib/previewTextStyleReads.browser.test.ts b/packages/studio/src/player/lib/previewTextStyleReads.browser.test.ts
new file mode 100644
index 0000000000..e7f1e722cf
--- /dev/null
+++ b/packages/studio/src/player/lib/previewTextStyleReads.browser.test.ts
@@ -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 `
+
+
+
+
+
Hello
+ Plain
+
+
+ `;
+}
+
+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 | null>;
+ previewFontFaces(iframe: HTMLIFrameElement): Promise;
+ };
+ 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")' }],
+ });
+ },
+);
diff --git a/packages/studio/src/sealedPreviewExports.test.ts b/packages/studio/src/sealedPreviewExports.test.ts
index 8ac52ba07a..589d0606ee 100644
--- a/packages/studio/src/sealedPreviewExports.test.ts
+++ b/packages/studio/src/sealedPreviewExports.test.ts
@@ -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);
});