perf(core): the font step parses the page once for all its readers (#7650)

This commit is contained in:
Miguel Ángel
2026-11-13 15:58:02 +00:00
committed by GitHub
parent d79e72c024
commit 9f0a4edb43
4 changed files with 99 additions and 10 deletions
@@ -1,4 +1,4 @@
import { parseHTML } from "linkedom";
import { readPage } from "./pageTree.js";
import postcss from "postcss";
function screenStylesheet(media: string | null): boolean {
@@ -66,7 +66,7 @@ function stylesheetUrls(element: StylesheetElement): string[] {
export function authoredGoogleFontStylesheets(html: string): Map<string, string[]> {
const byFamily = new Map<string, string[]>();
const { document } = parseHTML(html);
const document = readPage(html);
for (const element of document.querySelectorAll("link, style")) {
for (const url of stylesheetUrls(element)) {
for (const family of googleStylesheetFamilies(url)) {
@@ -0,0 +1,62 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const parses = vi.hoisted(() => ({ count: 0 }));
vi.mock("linkedom", async (importOriginal) => {
const original = await importOriginal<typeof import("linkedom")>();
return {
...original,
parseHTML: (...args: Parameters<typeof original.parseHTML>) => {
parses.count += 1;
return original.parseHTML(...args);
},
};
});
import {
injectDeterministicFontFaces,
normalizeSystemFontPrimaryFamilies,
} from "./deterministicFonts.js";
const page = (note: string, family: string) =>
`<!doctype html><html><head><style>.a{font-family:${family}}</style></head><body><!-- ${note} --><p class="a">Hello</p></body></html>`;
const offline = () => Promise.reject(new Error("offline"));
describe("the font step parses the page once", () => {
beforeEach(() => {
parses.count = 0;
});
it("builds the page's tree once for normalizing and once for injecting", async () => {
const html = page("both steps", "-apple-system, Inter");
const normalized = normalizeSystemFontPrimaryFamilies(html);
expect(parses.count).toBe(1);
parses.count = 0;
const injected = await injectDeterministicFontFaces(normalized, { fetchImpl: offline });
expect(parses.count).toBe(1);
expect(injected).toContain("data-hyperframes-deterministic-fonts");
});
it("reads a page that needs no normalizing once across both steps", async () => {
const html = page("unchanged", "Inter");
const same = normalizeSystemFontPrimaryFamilies(html);
expect(same).toBe(html);
const injected = await injectDeterministicFontFaces(same, { fetchImpl: offline });
expect(parses.count).toBe(1);
expect(injected).toContain("data-hyperframes-deterministic-fonts");
});
it("gives the same page the same output as when each step parses on its own", async () => {
const html = page("same output", "-apple-system, Inter");
const together = await injectDeterministicFontFaces(normalizeSystemFontPrimaryFamilies(html), {
fetchImpl: offline,
});
// another page in between drops the shared tree, so the steps below parse for themselves
await injectDeterministicFontFaces(page("other", "Inter"), { fetchImpl: offline });
const normalized = normalizeSystemFontPrimaryFamilies(html);
await injectDeterministicFontFaces(page("other again", "Inter"), { fetchImpl: offline });
const apart = await injectDeterministicFontFaces(normalized, { fetchImpl: offline });
expect(together).toBe(apart);
});
});
+10 -8
View File
@@ -15,7 +15,7 @@ import { fontShorthandFamilies } from "@hyperframes/parsers/composition";
import { FONT_ALIAS_MAP, resolveAliasDisplayName } from "./aliases.js";
import { extractSfntFace } from "./sfntNames.js";
import { locateSystemFontVariants, SYSTEM_FONT_SIZE_LIMIT } from "./systemFontLocator.js";
import { parseHTML } from "linkedom";
import { forgetPage, readPage, takePage } from "./pageTree.js";
import postcss, { type AtRule, type Declaration, type Rule } from "postcss";
import { EMBEDDED_FONT_DATA } from "./fontData.generated.js";
import { fontToDataUri } from "./fontCompression.js";
@@ -214,7 +214,7 @@ export function normalizeSystemFontPrimaryFamilies(
html: string,
deterministicPrimary = "Inter",
): string {
const { document } = parseHTML(html);
const document = readPage(html);
const customProperties = collectFontFamilyCustomProperties(html);
const replacePrimary: PrimaryReplacer = (value) =>
systemPrimaryReplacement(value, deterministicPrimary, customProperties);
@@ -244,7 +244,9 @@ export function normalizeSystemFontPrimaryFamilies(
changed = true;
}
return changed ? document.toString() : html;
if (!changed) return html;
forgetPage();
return document.toString();
}
/** Surfaces font-family is declared on in served HTML. */
@@ -307,7 +309,7 @@ function* iterateInlineStyleFontFamilyDeclarations(
* `font-family: var(--font)`.
*/
export function collectFontFamilyCustomProperties(html: string): Map<string, string> {
const { document } = parseHTML(html);
const document = readPage(html);
const customProperties = new Map<string, string>();
for (const styleEl of Array.from(document.querySelectorAll("style"))) {
@@ -402,7 +404,7 @@ export function resolveFontFamilyDeclarationFamilies(
export function* iterateFontFamilyDeclarations(
html: string,
): Generator<FontFamilyDeclaration, void, void> {
const { document } = parseHTML(html);
const document = readPage(html);
for (const styleEl of Array.from(document.querySelectorAll("style"))) {
yield* iterateCssFontFamilyDeclarations(styleEl.textContent ?? "");
@@ -966,7 +968,7 @@ function declareLinkedFontFamilies(
}
function collectDeclaredFontFamilies(html: string): DeclaredFontFamilies {
const { document } = parseHTML(html);
const document = readPage(html);
const declared = new Map<string, DeclaredFontFamily>();
const register: DeclaredFontRegister = (family, fontFaceRule) => {
const key = normalizeFamilyName(family);
@@ -1990,7 +1992,7 @@ function hasTextTransformKeyword(html: string, keyword: RegExp): boolean {
}
function extractGoogleFontsText(html: string): string | undefined {
const { document } = parseHTML(html);
const document = readPage(html);
const decodedBodyText = document.body?.textContent ?? "";
const locales = collectLangAttributes(document);
@@ -2119,7 +2121,7 @@ export async function injectDeterministicFontFaces(
return html;
}
const { document } = parseHTML(html);
const document = takePage(html);
const head = document.querySelector("head");
if (!head) {
return html;
+25
View File
@@ -0,0 +1,25 @@
import { parseHTML } from "linkedom";
export type PageDocument = ReturnType<typeof parseHTML>["document"];
/** The tree of the page the font step read last, so its readers share one parse of it. */
let lastPage: { html: string; document: PageDocument } | undefined;
export function readPage(html: string): PageDocument {
if (lastPage?.html === html) return lastPage.document;
const { document } = parseHTML(html);
lastPage = { html, document };
return document;
}
/** The page's tree for a step that edits it: handed over, and no longer the page the readers share. */
export function takePage(html: string): PageDocument {
const document = readPage(html);
lastPage = undefined;
return document;
}
/** The tree handed out was edited: it no longer reads as the page it came from. */
export function forgetPage(): void {
lastPage = undefined;
}