Something went wrong. Try again.
Local-first knowledge base made for Typst and the Atmosphere. typbase.at
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496import type { TypstState } from "@typbase/engine";import type { WorkspaceStore } from "@typbase/storage";import type { PageMeta } from "@typbase/typing";
import { stripCellAttributes } from "@typbase/codemirror";
import { escapeHtml, fileBase, fontFiles, fontPackFiles, inlineBlobs, renderFailure, setsPageConfiguration, styleExportHtml, type ExportFile, type ExportOptions,} from "~/lib/exportPage";import { pageContext, pageContextBinding, typstContextValue } from "~/lib/pageContext";import { pluginBundleSummary, pluginProjectFiles } from "~/lib/pluginBundle";import { EXPORT_TEXT_SCALE, publishPrelude, publishSyntaxTheme, publishThemePalette,} from "~/lib/publishPrelude";import { renderInWorker, setPublishRequestStore, type RenderOutcome } from "~/lib/renderWorker";
export interface WorkspaceExportOptions extends ExportOptions { /** Write each selected page's source and artifacts. */ separate: boolean; /** Write one merged document from the selected pages. */ combined: boolean;}
/** * Bundle stem for a page's rendered artifacts. Sources keep their `page.path`. * Renders live under `artifacts/` so the two never collide. */function artifactStem(path: string): string { return `artifacts/${path.replace(/\.typ$/i, "")}`;}
export async function buildWorkspaceExport( store: WorkspaceStore, pageIds: string[], options: WorkspaceExportOptions, typstState?: TypstState,): Promise<{ name: string; files: ExportFile[] }> { const pages = pageIds .map((id) => store.getPage(id)) .filter((page): page is PageMeta => Boolean(page)) .sort((a, b) => a.path.localeCompare(b.path)); if (!pages.length) throw new Error("Select at least one page."); if (!options.separate && !options.combined) { throw new Error("Choose per-page files, a combined document, or both."); }
const themeOptions = { theme: options.theme, pageSize: options.pageSize, } as const; const palette = publishThemePalette(store.getSettings(), themeOptions); const encoder = new TextEncoder(); const files: ExportFile[] = []; const names = new Set<string>(); const payloads = new Map<string, ExportFile>(); const index: Array<{ title: string; href: string }> = [];
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);
const renderInto = async (input: { source: string; /** Virtual page path handed to the renderer. */ pagePath: string; /** Bundle path of the source file, mirroring the workspace tree. */ sourceName: string; /** Artifact stem under `artifacts/`. Sheet suffixes are appended. */ stem: string; /** The page's `note` binding. Empty for the combined document. */ context: string; /** Page id for `sys.inputs`. Null for the combined document. */ pageId: string | null; title?: string; }): Promise<void> => { const { source, pagePath, sourceName, stem, context, pageId, title } = input; 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, });
if (options.html) { const rendered = await renderInWorker({ pagePath, source, prelude: htmlPrelude, wants: "html", spaceId: store.workspaceId, pageId, theme: palette, }); if (!rendered.html) { throw renderFailure(`The render produced no HTML for ${pagePath}`, rendered.diagnostics); }
collect(rendered); addFile({ name: `${stem}.html`, bytes: encoder.encode(styleExportHtml(await inlineBlobs(rendered.html, store), palette)), }); if (title) index.push({ title, href: `${stem}.html` }); }
if (options.pdf) { const rendered = await renderInWorker({ pagePath, source, prelude: pagedPrelude, wants: "pdf", spaceId: store.workspaceId, pageId, theme: palette, }); if (!rendered.pdf) { throw renderFailure(`The render produced no PDF for ${pagePath}`, rendered.diagnostics); }
collect(rendered); addFile({ name: `${stem}.pdf`, bytes: rendered.pdf }); }
if (options.svg) { const rendered = await renderInWorker({ pagePath, 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 for ${pagePath}`, rendered.diagnostics, ); }
collect(rendered); const many = rendered.svg.length > 1; rendered.svg.forEach((svg, sheet) => { addFile({ name: `${stem}${many ? `-${sheet + 1}` : ""}.svg`, bytes: encoder.encode(svg), }); }); }
if (options.project) { const projectSource = options.stripMarkers ? stripCellAttributes(source) : source; addFile({ name: sourceName, bytes: encoder.encode(`${pagedPrelude}\n${projectSource}`), }); } };
if (options.separate) { for (const page of pages) { const source = await store.loadPageText(page.id); await renderInto({ source, pagePath: page.path, sourceName: page.path, stem: artifactStem(page.path), context: pageContextBinding(store, page.id), pageId: page.id, title: page.title, }); } }
if (options.combined) { const sources: string[] = []; for (const page of pages) { sources.push(await store.loadPageText(page.id)); }
const htmlPrelude = await publishPrelude(store.getSettings(), { ...themeOptions, paged: false, textScale: EXPORT_TEXT_SCALE, }); const scalePages = !sources.some(setsPageConfiguration); const pagedPrelude = await publishPrelude(store.getSettings(), { ...themeOptions, paged: true, textScale: EXPORT_TEXT_SCALE, scaleMode: scalePages ? "none" : "text", });
// A combined document is one compile, so each page gets its own // `note` in a scoped block instead of a shared binding. const wrapper = (source: string, position: number, scale: boolean): string => { const page = pages[position]; if (!page) return source;
const binding = ` let note = ${typstContextValue(pageContext(pages, page))}\n`; const body = scale ? ` scale(${EXPORT_TEXT_SCALE * 100}%, reflow: true)[\n${source}\n ]` : ` [\n${source}\n ]`;
return `#{\n${binding}${body}\n}`; };
const paged = `${sources .map((source, position) => wrapper(source, position, scalePages)) .join("\n#context { pagebreak(weak: true) }\n")}\n`; const flowed = `${sources .map((source, position) => wrapper(source, position, false)) .join("\n\n#horizontalrule()\n\n")}\n`; const name = pages.every((page) => page.path.startsWith("daily/")) ? "daily" : "combined"; const pagePath = `${name}.typ`; const stem = `artifacts/${name}`;
if (options.html) { const rendered = await renderInWorker({ pagePath, source: flowed, prelude: htmlPrelude, wants: "html", spaceId: store.workspaceId, pageId: null, theme: palette, }); if (!rendered.html) { throw renderFailure("The combined render produced no HTML", rendered.diagnostics); }
collect(rendered); addFile({ name: `${stem}.html`, bytes: encoder.encode(styleExportHtml(await inlineBlobs(rendered.html, store), palette)), }); index.unshift({ title: name, href: `${stem}.html` }); }
if (options.pdf) { const rendered = await renderInWorker({ pagePath, source: paged, prelude: pagedPrelude, wants: "pdf", spaceId: store.workspaceId, pageId: null, theme: palette, }); if (!rendered.pdf) { throw renderFailure("The combined render produced no PDF", rendered.diagnostics); }
collect(rendered); addFile({ name: `${stem}.pdf`, bytes: rendered.pdf }); }
if (options.svg) { const rendered = await renderInWorker({ pagePath, source: paged, prelude: pagedPrelude, wants: "svg", merged: options.svgMerged, spaceId: store.workspaceId, pageId: null, theme: palette, }); if (!rendered.svg?.length) { throw renderFailure("The combined render produced no SVG pages", rendered.diagnostics); }
collect(rendered); const many = rendered.svg.length > 1; rendered.svg.forEach((svg, sheet) => { addFile({ name: `${stem}${many ? `-${sheet + 1}` : ""}.svg`, bytes: encoder.encode(svg), }); }); }
if (options.project) { const combined = options.stripMarkers ? stripCellAttributes(paged) : paged; addFile({ name: pagePath, bytes: encoder.encode(`${pagedPrelude}\n${combined}`), }); } }
if (options.project) { 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); const sources = pages.map( (page) => `${pageContextBinding(store, page.id)}\n${store.getPageText(page.id)}`, ); for (const font of await fontPackFiles(sources)) addFile(font); } for (const file of editorConfigFiles()) { addFile({ name: file.name, bytes: encoder.encode(file.text) }); } }
if (files.length > 1) { addFile({ name: "README.md", bytes: encoder.encode(buildWorkspaceReadme(pages.length, options)), }); if (index.length) { addFile({ name: "index.html", bytes: encoder.encode(buildWorkspaceIndex(index)), }); } }
return { name: pages.length === 1 ? fileBase(pages[0]!.title, pages[0]!.path) : "workspace", files, };}
function buildWorkspaceIndex(entries: Array<{ title: string; href: string }>): string { const items = entries .map((entry) => ` <li><a href="${entry.href}">${escapeHtml(entry.title)}</a></li>`) .join("\n");
return `<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <title>Workspace export</title> <style> body { margin: 0; padding: 2rem; font-family: system-ui, sans-serif; background: #f3f4f6; color: #1f2328; } ul { margin: 0; padding-left: 1.2rem; } li { margin-bottom: 0.35rem; } </style> </head> <body> <h1>Workspace export</h1> <ul>${items} </ul> </body></html>`;}
/** * Editor config so the bundle behaves the same in an external editor as it does * here. The one that matters is Tinymist's project root: every source imports * `/typbase/lib.typ`, and a root-absolute import only resolves against a root, * so without it every file opens with a wall of unresolved imports. * * Only written for a project export. A bundle of rendered artifacts is not * something anyone opens in an editor. */function editorConfigFiles(): { name: string; text: string }[] { const json = (value: unknown): string => `${JSON.stringify(value, null, 2)}\n`;
return [ { name: ".vscode/settings.json", text: json({ "tinymist.typstExtraArgs": ["--root", "."], }), }, { name: ".vscode/extensions.json", text: json({ recommendations: ["myriad-dreamin.tinymist"] }), }, { // Not editor-specific: the same line endings and indent whatever opens it. name: ".editorconfig", text: [ "root = true", "", "[*]", "charset = utf-8", "end_of_line = lf", "insert_final_newline = true", "indent_style = space", "indent_size = 2", "", ].join("\n"), }, ];}
function buildWorkspaceReadme(pageCount: number, options: WorkspaceExportOptions): string { const lines = [ "# Workspace export", "", `${pageCount} page${pageCount === 1 ? "" : "s"}, exported ${new Date().toISOString()}.`, "", "## Files", "", ];
if (options.separate) { lines.push( "- `artifacts/`: rendered HTML, PDF, and SVG, mirroring each page's path", "- `pages/`, `daily/`, ...: the page sources with the workspace prelude inlined", ); } if (options.combined) { lines.push("- `combined.*` or `daily.*`: the selected pages merged into one document"); } if (options.project) { lines.push("- `typbase/`: the library, referenced data and blobs, and optionally fonts"); const plugins = pluginBundleSummary(); if (plugins) lines.push(plugins); lines.push( "- `.vscode/`, `.editorconfig`: editor settings, including the Tinymist project root", ); } lines.push("");
if (options.project) { lines.push( "## Compiling the Typst source", "", "Compile from the extracted bundle root; the prelude imports `/typbase/lib.typ`:", "", "```sh", `typst compile --root .${options.fonts ? " --font-path typbase/fonts" : ""} pages/<page.path>`, "```", "", "Tinymist needs the same root, because the prelude's import is root-absolute.", "`.vscode/settings.json` already sets it, so opening the bundle folder in VS Code", "works without configuring anything.", "", ); }
return lines.join("\n");}