perf(studio): load the font lists when the font picker first opens

Selecting an element no longer fetches and dedupes the 1.7k-name Google font list, so the response cannot land inside a drag frame. The lists are fetched once per session on the first open.
This commit is contained in:
Miguel Ángel
2026-09-30 16:40:30 -04:00
parent 7b0ec69704
commit c0956ba5a3
2 changed files with 83 additions and 30 deletions
@@ -8,7 +8,11 @@ import { sortFontOptions } from "./propertyPanelHelpers";
vi.mock("./propertyPanelHelpers", async (importOriginal) => {
const actual = await importOriginal<typeof import("./propertyPanelHelpers")>();
return { ...actual, sortFontOptions: vi.fn(actual.sortFontOptions) };
return {
...actual,
sortFontOptions: vi.fn(actual.sortFontOptions),
uniqueFontFamilies: vi.fn(actual.uniqueFontFamilies),
};
});
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -56,7 +60,7 @@ describe("FontFamilyField font list", () => {
root.render(<FontFamilyField flat value={value} importedFonts={[]} onCommit={vi.fn()} />);
try {
await act(async () => render("Arial"));
// The font lists arrive and the value changes while the dropdown is closed, as during a drag.
// The value changes while the dropdown is closed, as during a drag.
await act(async () => render("Georgia"));
expect(sortFontOptions).not.toHaveBeenCalled();
@@ -71,3 +75,38 @@ describe("FontFamilyField font list", () => {
}
});
});
describe("FontFamilyField session font lists", () => {
it("fetches the lists on the first open, once per session, and never on selection", async () => {
vi.resetModules();
const { FontFamilyField: Field } = await import("./propertyPanelFont");
const { uniqueFontFamilies } = await import("./propertyPanelHelpers");
const host = document.createElement("div");
document.body.append(host);
let root = createRoot(host);
const render = (value: string) =>
root.render(<Field flat value={value} importedFonts={[]} onCommit={vi.fn()} />);
const toggle = () =>
host.querySelector<HTMLButtonElement>('[data-flat-font-trigger="true"]')?.click();
try {
await act(async () => render("Arial"));
await act(async () => render("Georgia"));
expect(fetch).not.toHaveBeenCalled();
expect(uniqueFontFamilies).not.toHaveBeenCalled();
await act(async () => toggle());
expect(fetch).toHaveBeenCalledTimes(2);
expect(host.textContent).toContain("Roboto Slab");
act(() => root.unmount());
root = createRoot(host);
await act(async () => render("Arial"));
await act(async () => toggle());
expect(fetch).toHaveBeenCalledTimes(2);
expect(host.textContent).toContain("Roboto Slab");
} finally {
act(() => root.unmount());
host.remove();
}
});
});
@@ -117,6 +117,36 @@ function loadImportedFontStylesheet(asset: ImportedFontAsset): void {
document.head.appendChild(style);
}
let installedFontsRequest: Promise<string[]> | null = null;
let googleFontsRequest: Promise<string[]> | null = null;
let googleFontKeys: ReadonlySet<string> = new Set(
POPULAR_GOOGLE_FONT_FAMILIES.map((f) => f.toLowerCase()),
);
async function fetchFontList(url: string): Promise<string[]> {
try {
const response = await fetch(url);
const data = (response.ok ? await response.json() : null) as { fonts?: string[] } | null;
return Array.isArray(data?.fonts) ? data.fonts : [];
} catch {
return [];
}
}
function sessionInstalledFonts(): Promise<string[]> {
installedFontsRequest ??= fetchFontList("/api/fonts");
return installedFontsRequest;
}
function sessionGoogleFonts(): Promise<string[]> {
googleFontsRequest ??= fetchFontList("/api/fonts/google").then((fonts) => {
const families = uniqueFontFamilies([...fonts, ...POPULAR_GOOGLE_FONT_FAMILIES]);
googleFontKeys = new Set(families.map((f) => f.toLowerCase()));
return families;
});
return googleFontsRequest;
}
/* ------------------------------------------------------------------ */
/* FontFamilyField */
/* ------------------------------------------------------------------ */
@@ -175,39 +205,24 @@ export function FontFamilyField({
}, [open]);
useEffect(() => {
if (!open) return;
let cancelled = false;
void fetch("/api/fonts")
.then((r) => (r.ok ? r.json() : null))
.then((data: { fonts?: string[] } | null) => {
if (cancelled || !Array.isArray(data?.fonts)) return;
setLocalFonts((cur) => uniqueFontFamilies([...cur, ...data.fonts!]));
})
.catch(() => undefined);
return () => {
cancelled = true;
};
}, []);
useEffect(() => {
let cancelled = false;
void sessionInstalledFonts().then((fonts) => {
if (!cancelled) setLocalFonts((cur) => uniqueFontFamilies([...cur, ...fonts]));
});
setLoadingGoogleFonts(true);
void fetch("/api/fonts/google")
.then((r) => (r.ok ? r.json() : null))
.then((data: { fonts?: string[] } | null) => {
if (cancelled || !Array.isArray(data?.fonts)) return;
setGoogleFonts(uniqueFontFamilies([...data.fonts!, ...POPULAR_GOOGLE_FONT_FAMILIES]));
})
.catch(() => undefined)
.finally(() => {
if (!cancelled) setLoadingGoogleFonts(false);
});
void sessionGoogleFonts().then((fonts) => {
if (cancelled) return;
setGoogleFonts(fonts);
setLoadingGoogleFonts(false);
});
return () => {
cancelled = true;
};
}, []);
}, [open]);
useEffect(() => {
if (googleFonts.some((f) => f.toLowerCase() === currentFamily.toLowerCase())) {
if (googleFontKeys.has(currentFamily.toLowerCase())) {
loadGoogleFontStylesheet(currentFamily);
}
const imported = importedFonts.find(
@@ -278,11 +293,10 @@ export function FontFamilyField({
const options = useMemo(() => {
if (!open) return [];
const documentFonts = collectDocumentFontFamilies();
const googleSet = new Set(googleFonts.map((f) => f.toLowerCase()));
const taggedLocal = localFonts.map(
(family): FontOption => ({
family,
source: googleSet.has(family.toLowerCase()) ? "Google" : "Local",
source: googleFontKeys.has(family.toLowerCase()) ? "Google" : "Local",
}),
);
return sortFontOptions(