Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/canvas/browser/layout.ts

Raw
import {
	exportToCanvas,
	FONT_FAMILY,
	restoreElements,
} from "@excalidraw/excalidraw";
import { requestedDocument } from "../src/document.ts";
import type { CanvasDraw, CanvasState } from "../src/store.ts";
import { nativeAdditions, nativeRelabels } from "./drawing.ts";

declare global {
	interface Window {
		canvasGenerate?: (state: CanvasState, draw: CanvasDraw) => Promise<unknown>;
	}
}

async function loadFonts(state: CanvasState, draw: CanvasDraw): Promise<void> {
	const samples = new Map<number, string>();
	const add = (family: unknown, text: string): void => {
		const value = typeof family === "number" ? family : FONT_FAMILY.Excalifont;
		if (
			!Object.values(FONT_FAMILY).includes(
				value as typeof FONT_FAMILY.Excalifont,
			)
		)
			throw new Error("Unsupported canvas font family.");
		samples.set(value, (samples.get(value) ?? "") + text);
	};
	for (const element of draw.additions) {
		if (typeof element.text === "string")
			add(element["fontFamily"], element.text);
		const label = element["label"];
		if (
			label &&
			typeof label === "object" &&
			"text" in label &&
			typeof label.text === "string"
		)
			add(undefined, label.text);
	}
	for (const relabel of draw.relabels)
		add(
			state.elements.find((element) => element.id === relabel.id)?.[
				"fontFamily"
			],
			relabel.text,
		);
	if (draw.mermaid) add(undefined, draw.mermaid.definition);
	if (!samples.size) return;
	// Public export loads and registers the pinned local font faces, including
	// Unicode subsets. Merely fonts.check() succeeds even for missing families.
	// Restore without measuring first so fallback metrics never enter text caches.
	const probes = restoreElements(
		[...samples].map(([fontFamily, text], index) => ({
			id: `font-probe-${index}`,
			type: "text" as const,
			x: 0,
			y: index * 30,
			width: 1,
			height: 25,
			text: [...new Set(text)].join("") || " ",
			originalText: text || " ",
			fontSize: 20,
			fontFamily,
			lineHeight: 1.25,
			isDeleted: false,
		})) as unknown as Parameters<typeof restoreElements>[0],
		null,
		{ refreshDimensions: false, repairBindings: false },
	);
	await exportToCanvas({ elements: probes, files: {}, maxWidthOrHeight: 1 });
	for (const family of samples.keys()) {
		if (family === FONT_FAMILY.Helvetica) continue;
		const name = Object.entries(FONT_FAMILY).find(
			([, value]) => value === family,
		)?.[0];
		if (
			![...document.fonts].some(
				(face) =>
					face.family.replaceAll('"', "") === name && face.status === "loaded",
			)
		)
			throw new Error("Canvas layout font did not load.");
	}
}

window.canvasGenerate = async (state, draw) => {
	await loadFonts(state, draw);
	const additions = await nativeAdditions(draw);
	const relabeled = await nativeRelabels(draw, state);
	return requestedDocument(state, draw, additions, relabeled);
};