import type { TypstState } from "@typbase/engine"; import type { WorkspaceStore } from "@typbase/storage"; import type { ThemePaletteTokens } from "@typbase/typing"; import { stripCellAttributes } from "@typbase/codemirror"; import { isTauri, saveExportFile, sniffMime } from "@typbase/storage"; import { installedPacksForText, readFontPack } from "~/lib/fontPacks"; import { pageContextBinding } from "~/lib/pageContext"; import { THEME_COLOR_KEYS, paletteSlots } from "~/lib/palette"; import { pluginBundleSummary, pluginProjectFiles } from "~/lib/pluginBundle"; import { EXPORT_TEXT_SCALE, publishPrelude, publishSyntaxTheme, publishThemePalette, } from "~/lib/publishPrelude"; import { renderInWorker, setPublishRequestStore, type RenderOutcome } from "~/lib/renderWorker"; import { createZip } from "~/lib/zip"; export interface ExportOptions { html: boolean; pdf: boolean; svg: boolean; /** SVG only: one merged file instead of one per page. */ svgMerged: boolean; /** Write the compilable Typst project: source, lib, data, fonts. */ project: boolean; /** Strip `//%` cell attributes from project sources. */ stripMarkers?: boolean; fonts: boolean; /** "light" (default) normalizes colors for reading/printing. */ theme: "light" | "workspace"; pageSize: "a4" | "letter"; } export interface ExportFile { /** Bundle-relative path. Forward slashes. */ name: string; bytes: Uint8Array; } export function slug(value: string): string { return value .trim() .toLowerCase() .replace(/[^a-z0-9]+/g, "-") .replace(/^-+|-+$/g, ""); } export function setsPageConfiguration(source: string): boolean { return /#set\s+page\b/.test(source); } export function renderFailure(action: string, diagnostics: unknown[] | undefined): Error { for (const entry of diagnostics ?? []) { const diagnostic = entry as { severity?: string; message?: string }; if (diagnostic.severity === "error" && diagnostic.message) { return new Error(`${action}: ${diagnostic.message}`); } } return new Error(`${action}; check the page diagnostics.`); } /** File stem from the page title, falling back to its path. */ export function fileBase(title: string, path: string): string { const fromPath = path .split("/") .pop() ?.replace(/\.typ$/i, "") ?? ""; return slug(title) || slug(fromPath) || "page"; } export async function buildExport( store: WorkspaceStore, pageId: string, options: ExportOptions, typstState?: TypstState, ): Promise<{ base: string; files: ExportFile[] }> { const page = store.getPage(pageId); if (!page) throw new Error(`No page named ${pageId}`); const source = await store.loadPageText(pageId); const base = fileBase(page.title, page.path); const themeOptions = { theme: options.theme, pageSize: options.pageSize, } as const; const context = pageContextBinding(store, pageId); const htmlPrelude = await publishPrelude(store.getSettings(), { ...themeOptions, paged: false, textScale: EXPORT_TEXT_SCALE, context, }); const pagedPrelude = await publishPrelude(store.getSettings(), { ...themeOptions, paged: true, textScale: EXPORT_TEXT_SCALE, scaleMode: setsPageConfiguration(source) ? "text" : "document", context, }); const palette = publishThemePalette(store.getSettings(), themeOptions); const encoder = new TextEncoder(); const files: ExportFile[] = []; const names = new Set(); const payloads = new Map(); const artifacts: { html?: string; pdf?: string; svg: string[] } = { svg: [] }; const addFile = (file: ExportFile): void => { if (names.has(file.name)) { throw new Error(`Two exported files would both be named ${file.name}; rename one page.`); } names.add(file.name); files.push(file); }; // Support files can arrive from both the render request payloads and the // plugin/project inventory. They describe the same generated source, so the // first copy wins. Page files still go through `addFile` and collide loudly. const addSupportFile = (file: ExportFile): void => { if (!names.has(file.name)) addFile(file); }; const collect = (outcome: RenderOutcome): void => { for (const payload of outcome.payloads) { // Packages were installed into the worker's world. The exported project // references them by spec instead of vendoring the tarball. if (payload.type === "package") continue; const bytes = payload.type === "file" ? payload.bytes : encoder.encode(payload.text); payloads.set(payload.path, { name: payload.path, bytes }); } }; setPublishRequestStore(store); if (options.html) { const rendered = await renderInWorker({ pagePath: page.path, source, prelude: htmlPrelude, wants: "html", spaceId: store.workspaceId, pageId, theme: palette, }); if (!rendered.html) { throw renderFailure("The render produced no HTML", rendered.diagnostics); } collect(rendered); artifacts.html = `${base}.html`; addFile({ name: artifacts.html, bytes: encoder.encode(styleExportHtml(await inlineBlobs(rendered.html, store), palette)), }); } if (options.pdf) { const rendered = await renderInWorker({ pagePath: page.path, source, prelude: pagedPrelude, wants: "pdf", spaceId: store.workspaceId, pageId, theme: palette, }); if (!rendered.pdf) { throw renderFailure("The render produced no PDF", rendered.diagnostics); } collect(rendered); artifacts.pdf = `${base}.pdf`; addFile({ name: artifacts.pdf, bytes: rendered.pdf }); } if (options.svg) { const rendered = await renderInWorker({ pagePath: page.path, source, prelude: pagedPrelude, wants: "svg", merged: options.svgMerged, spaceId: store.workspaceId, pageId, theme: palette, }); if (!rendered.svg?.length) { throw renderFailure("The render produced no SVG pages", rendered.diagnostics); } collect(rendered); const many = rendered.svg.length > 1; rendered.svg.forEach((svg, index) => { const name = `${base}${many ? `-${index + 1}` : ""}.svg`; artifacts.svg.push(name); addFile({ name, bytes: encoder.encode(svg) }); }); } if (options.project) { const projectSource = options.stripMarkers ? stripCellAttributes(source) : source; addFile({ name: `${base}.typ`, bytes: encoder.encode(`${pagedPrelude}\n${projectSource}`), }); if (typstState) { addFile({ name: "typbase/lib.typ", bytes: encoder.encode(typstState.typbaseLib()), }); } const syntax = await publishSyntaxTheme(store.getSettings(), themeOptions); addFile({ name: syntax.path, bytes: encoder.encode(syntax.text) }); for (const payload of payloads.values()) addSupportFile(payload); for (const plugin of await pluginProjectFiles(store)) { addSupportFile({ name: plugin.path, bytes: encoder.encode(plugin.text) }); } if (options.fonts) { for (const font of await fontFiles(store)) addFile(font); // The generated prelude carries the page title and context, which can // contain CJK even when the body does not. for (const font of await fontPackFiles([page.title, pagedPrelude, source])) addFile(font); } } // One artifact stays a single file. More than one becomes a zip with an // index that works without a local server. if (files.length > 1) { const readme = buildReadme(page.title, base, options); addFile({ name: "README.md", bytes: encoder.encode(readme) }); if (artifacts.html || artifacts.svg.length) { addFile({ name: "index.html", bytes: encoder.encode(buildIndex(page.title, artifacts)), }); } } return { base, files }; } /** Saves either the single file or a zip of the bundle. */ export async function saveExport(base: string, files: ExportFile[]): Promise { if (files.length === 1) { const [file] = files; if (file) await saveOne(file.name, file.bytes); return; } await saveOne( `${base}.zip`, createZip(files.map((file) => ({ name: file.name, bytes: file.bytes }))), ); } async function saveOne(name: string, bytes: Uint8Array): Promise { if (isTauri()) { // The native dialog is the only save path that works in the webview. // Anchor downloads there are treated as file: navigations and blocked. await saveExportFile(name, bytes); return; } const url = URL.createObjectURL(new Blob([bytes as BlobPart])); const anchor = document.createElement("a"); anchor.href = url; anchor.download = name; anchor.click(); // The download has started. Release the URL once it has had time to read. setTimeout(() => URL.revokeObjectURL(url), 10_000); } const BLOB_REFERENCE = /\/?typbase\/blob\/([0-9a-f]{16,64})(?:\.[a-z0-9]+)?/gi; /** * Replaces blob references in rendered HTML with data URIs, so the document * is self-contained wherever it is opened. */ export async function inlineBlobs(html: string, store: WorkspaceStore): Promise { const hashes = new Set(); for (const match of html.matchAll(BLOB_REFERENCE)) { hashes.add(match[1]!.toLowerCase()); } if (!hashes.size) return html; const uris = new Map(); for (const hash of hashes) { const bytes = await store.getBlob(hash); if (!bytes) continue; const mime = sniffMime(bytes); uris.set(hash, `data:${mime};base64,${base64(bytes)}`); } return html.replace(BLOB_REFERENCE, (reference, hash: string) => { return uris.get(hash.toLowerCase()) ?? reference; }); } function base64(bytes: Uint8Array): string { let binary = ""; for (const byte of bytes) { binary += String.fromCharCode(byte); } return btoa(binary); } /** * Every font the exported project needs: the bundled families, so it renders * without system fonts, plus the workspace's uploaded faces, which exist * nowhere else. A document set in an uploaded family compiles elsewhere only if * its bytes travel with it. */ export async function fontFiles(store?: WorkspaceStore): Promise { const { getTypstFontImports } = await import("~/composables/typst"); const files: ExportFile[] = []; const seen = new Set(); const add = (name: string, bytes: Uint8Array): void => { if (seen.has(name)) return; seen.add(name); files.push({ name: `typbase/fonts/${name}`, bytes }); }; for (const fontImports of getTypstFontImports()) { const urls = await Promise.all( fontImports.map(async (fontImport) => (await fontImport).default), ); for (const url of urls) { const response = await fetch(url); const bytes = new Uint8Array(await response.arrayBuffer()); const name = decodeURIComponent(url.split("?")[0]!.split("/").pop() ?? "font"); add(name, bytes); } } for (const font of store?.getSettings().customFonts ?? []) { for (const hash of font.hashes) { const bytes = await store?.getBlob(hash); if (!bytes) continue; // The extension follows the bytes, so a bundle keeps the `.otf`/`.ttf` // distinction Typst uses to pick a face. add( `${font.family.replace(/[^\w.-]+/g, "-")}-${hash.slice(0, 8)}.${fontExtension(bytes)}`, bytes, ); } } return files; } /** * Downloadable language faces for the scripts the sources actually use. * * A pack can be 10 MB, so an English export must not carry a Chinese font just * because one is installed on the device. The browser font stack handles HTML, * but a project compiled elsewhere needs the face in `typbase/fonts`. */ export async function fontPackFiles(sources: string[]): Promise { const files: ExportFile[] = []; for (const pack of installedPacksForText(...sources)) { // oxlint-disable-next-line no-await-in-loop const bytes = await readFontPack(pack); if (!bytes) continue; files.push({ name: `typbase/fonts/${pack.family.replace(/[^\w.-]+/g, "-")}-${pack.id}.${fontExtension(bytes)}`, bytes, }); } return files; } /** The extension matching the sfnt version, so a bundle is self-describing. */ function fontExtension(bytes: Uint8Array): string { const tag = String.fromCharCode(...bytes.slice(0, 4)); return tag === "OTTO" ? "otf" : tag === "ttcf" ? "ttc" : "ttf"; } export function escapeHtml(value: string): string { return value .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """); } function paletteColor(palette: ThemePaletteTokens, key: (typeof THEME_COLOR_KEYS)[number]): string { const slots = paletteSlots(palette); const slot = slots[THEME_COLOR_KEYS.indexOf(key)] ?? [127, 127, 127]; return `rgb(${slot.join(",")})`; } /** * Typst's HTML export has no page to apply the fill to, so the chosen palette's * surface and text colors are applied to the document root. Without this a * dark palette renders light text on the browser's white background. */ export function styleExportHtml(html: string, palette: ThemePaletteTokens): string { const style = ``; return html.includes("") ? html.replace("", `${style}`) : `${style}${html}`; } function buildIndex( title: string, artifacts: { html?: string; pdf?: string; svg: string[] }, ): string { const links = [ artifacts.html ? `
  • HTML document
  • ` : "", artifacts.pdf ? `
  • PDF document
  • ` : "", ] .filter(Boolean) .join("\n "); const sheets = artifacts.svg.map((name) => ` Page`).join("\n"); return ` ${escapeHtml(title)}

    ${escapeHtml(title)}

      ${links}
    ${sheets} `; } function buildReadme(title: string, base: string, options: ExportOptions): string { const lines = [ `# ${title}`, "", `Typbase export (${new Date().toISOString()}).`, "", "## Files", "", ]; lines.push(`- \`${base}.html\`, \`${base}.pdf\`, \`${base}*.svg\`: rendered artifacts`); if (options.project) { lines.push( `- \`${base}.typ\`: the note source with the workspace prelude inlined`, "- `typbase/`: the library, referenced data and blobs, and optionally fonts", ); const plugins = pluginBundleSummary(); if (plugins) lines.push(plugins); } lines.push(""); if (options.project) { lines.push( "## Compiling the Typst source", "", "The project imports `/typbase/lib.typ`, so compile it from the extracted bundle root:", "", "```sh", `typst compile --root .${options.fonts ? " --font-path typbase/fonts" : ""} ${base}.typ`, "```", "", "The prelude (theme, fonts, text size, heading styles) is inlined at the top of the file.", "", 'Tinymist needs the same root (`"tinymist.typstExtraArgs": ["--root", "."]`), because', "the prelude's import is root-absolute.", "", ); } return lines.join("\n"); }