Virtual whiteboard for sketching hand-drawn like diagrams
fix(packages/excalidraw): load export fonts into a worker's font set, warn without one (#12374)
David Luzarbee01e3a1281
diff --git a/packages/excalidraw/fonts/Fonts.ts b/packages/excalidraw/fonts/Fonts.tsindex 3180091123..19c4490549 100644--- a/packages/excalidraw/fonts/Fonts.ts+++ b/packages/excalidraw/fonts/Fonts.ts@@ -44,6 +44,15 @@ import { NunitoFontFaces } from "./Nunito";import { VirgilFontFaces } from "./Virgil";import { XiaolaiFontFaces } from "./Xiaolai";+/** warned once per process, not per export (e.g. on a server) */+let warnedNoFontFaceSet = false;++/** a worker's own font set (`WorkerGlobalScope.fonts`), if this is one */+const getWorkerFontFaceSet = (): FontFaceSet | null =>+ typeof self !== "undefined" && "fonts" in self+ ? (self as unknown as { fonts: FontFaceSet }).fonts+ : null;+export class Fonts {public static readonly loadedFontsCache = new Set<string>();@@ -169,29 +178,49 @@ export class Fonts {return Fonts.loadFontFaces(sceneFamilies,charsPerFamily,- this.ownerDocument,+ this.ownerDocument.fonts,);};/*** Load font faces for passed elements - use when the scene is unavailable (i.e. export).+ *+ * Loads into the document's font set, or in a worker into the worker's own+ * (`self.fonts`, what an `OffscreenCanvas` there measures with). Where there+ * is neither -- e.g. a DOM shim without `FontFaceSet` (`linkedom`), or Node+ * -- nothing is loaded: the host makes the fonts available itself, and is+ * warned once if the elements use fonts that would need loading.*/public static loadElementsFonts = async (elements: readonly ExcalidrawElement[],ownerDocument?: Document,): Promise<FontFace[]> => {- const doc =- ownerDocument ?? (typeof document !== "undefined" ? document : null);+ const fontFaceSet =+ (ownerDocument ?? (typeof document !== "undefined" ? document : null))+ ?.fonts ?? getWorkerFontFaceSet();++ const fontFamilies = Fonts.getUniqueFamilies(elements);- // NOTE: headless environments should register fonts prior to rendering- if (!doc?.fonts) {+ if (!fontFaceSet) {+ // local fonts (e.g. Helvetica) are never loaded anyway+ if (+ !warnedNoFontFaceSet &&+ fontFamilies.some((family) => !FONT_METADATA[family]?.local)+ ) {+ warnedNoFontFaceSet = true;+ console.warn(+ "Excalidraw: there is no font set (`document.fonts`, or a worker's " ++ "`self.fonts`) to load the exported fonts into, so text is " ++ "measured and drawn with whatever fonts this environment has. " ++ "Load them yourself in `config.environment.loadFonts`.",+ );+ }return [];}- const fontFamilies = Fonts.getUniqueFamilies(elements);const charsPerFamily = Fonts.getCharsPerFamily(elements);- return Fonts.loadFontFaces(fontFamilies, charsPerFamily, doc);+ return Fonts.loadFontFaces(fontFamilies, charsPerFamily, fontFaceSet);};/**@@ -237,9 +266,9 @@ export class Fonts {private static async loadFontFaces(fontFamilies: Array<ExcalidrawTextElement["fontFamily"]>,charsPerFamily: Record<number, Set<string>>,- ownerDocument: Document,+ fontFaceSet: FontFaceSet,) {- // add all registered font faces into the `document.fonts` (if not added already)+ // add all registered font faces into the font set (if not added already)for (const { fontFaces, metadata } of Fonts.registered.values()) {// skip registering font faces for local fonts (i.e. Helvetica)if (metadata.local) {@@ -247,8 +276,8 @@ export class Fonts {}for (const { fontFace } of fontFaces) {- if (!ownerDocument.fonts.has(fontFace)) {- ownerDocument.fonts.add(fontFace);+ if (!fontFaceSet.has(fontFace)) {+ fontFaceSet.add(fontFace);}}}@@ -257,7 +286,7 @@ export class Fonts {const iterator = Fonts.fontFacesLoader(fontFamilies,charsPerFamily,- ownerDocument,+ fontFaceSet,);const concurrency = 10;const fontFaces = await new PromisePool(iterator, concurrency).all();@@ -267,7 +296,7 @@ export class Fonts {private static *fontFacesLoader(fontFamilies: Array<ExcalidrawTextElement["fontFamily"]>,charsPerFamily: Record<number, Set<string>>,- ownerDocument: Document,+ fontFaceSet: FontFaceSet,): Generator<Promise<void | readonly [number, FontFace[]]>> {for (const [index, fontFamily] of fontFamilies.entries()) {const font = getFontString({@@ -279,12 +308,12 @@ export class Fonts {// instead, we are always checking chars used in the family, so that no required font faces remain unloadedconst text = Fonts.getCharacters(charsPerFamily, fontFamily);- if (!ownerDocument.fonts.check(font, text)) {+ if (!fontFaceSet.check(font, text)) {yield promiseTry(async () => {try {// WARN: browser prioritizes loading only font faces with unicode ranges for characters which are present in the document (html & canvas), other font faces could stay unloaded// we might want to retry here, i.e. in case CDN is down, but so far I didn't experience any issues - maybe it handles retry-like logic under the hood- const fontFaces = await ownerDocument.fonts.load(font, text);+ const fontFaces = await fontFaceSet.load(font, text);return [index, fontFaces];} catch (e) {diff --git a/packages/excalidraw/tests/scene/export.test.ts b/packages/excalidraw/tests/scene/export.test.tsindex 34256e489f..2ffb7fab8f 100644--- a/packages/excalidraw/tests/scene/export.test.ts+++ b/packages/excalidraw/tests/scene/export.test.ts@@ -549,6 +549,71 @@ describe("export inputs", () => {).toContain("F...");});+ describe("without a document font set (e.g. a DOM shim like linkedom)", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("exports without loading fonts, warning once", async () => {+ const consoleWarn = vi+ .spyOn(console, "warn")+ .mockImplementation(() => {});+ // jsdom implements no `document.fonts`; only the test document is mocked+ vi.stubGlobal("document", document.implementation.createHTMLDocument());++ // a local font is never loaded, so nothing is missing+ await exportScene({+ type: "svg",+ data: {+ elements: [+ API.createElement({+ type: "text",+ text: "hi",+ fontFamily: FONT_FAMILY.Helvetica,+ }),+ ],+ },+ });+ expect(consoleWarn).not.toHaveBeenCalled();++ for (let i = 0; i < 2; i++) {+ const svg = await exportScene({+ type: "svg",+ data: {+ elements: [API.createElement({ type: "text", text: "hi" })],+ },+ });+ expect(svg.querySelector("text")?.textContent).toBe("hi");+ }+ expect(consoleWarn).toHaveBeenCalledTimes(1);+ expect(consoleWarn).toHaveBeenCalledWith(+ expect.stringContaining("config.environment.loadFonts"),+ );+ consoleWarn.mockRestore();+ });++ it("loads fonts into a worker's own font set", async () => {+ const fonts = {+ has: () => true,+ add: vi.fn(),+ check: () => false,+ load: vi.fn(async () => []),+ };+ vi.stubGlobal("document", document.implementation.createHTMLDocument());+ vi.stubGlobal("self", { fonts });++ await exportScene({+ type: "svg",+ data: { elements: [API.createElement({ type: "text", text: "hi" })] },+ });++ expect(fonts.load).toHaveBeenCalledWith(+ expect.stringContaining("Excalifont"),+ "hi",+ );+ });+ });+it("renders frame decorations per config.frames", async () => {const elements = [API.createElement({ type: "frame" })];const countFrameNames = (svg: SVGSVGElement) =>