mirror of
https://github.com/narrrl/narl-workspace.git
synced 2026-11-04 00:47:01 +01:00
A ```typst (or ```typ) block is compiled by the typst crate into SVG and
shown as an image where it stands, so math, tables and figures can be
written in typst beside the markdown around them. It shows its source while
it is set, and the error typst gives, with the block's line, when it cannot
be.
Each block is a document of its own: its source is the only file in its
world and the fonts are typst-assets', inside the binary, so nothing is read
from disk or fetched — packages and images are refused. The page fits what
is on it, is transparent, and carries the theme's text colour. Answers are
cached by source, two blocks are laid out at a time off the async threads,
and comemo's memo is evicted after each compile.
A share page asks POST /api/share/{token}/typst, which takes the reader's
cookie and typesets only a block the shared document holds.
typst brings a palette crate whose AsRef impls on arrays made four
`kek.as_ref().into()` in the vault ambiguous; they deref instead.
34 lines
1.2 KiB
TypeScript
34 lines
1.2 KiB
TypeScript
/*
|
|
* ```typst blocks, typeset on the server. A block shows as its source until
|
|
* its SVG arrives, as math does until KaTeX has loaded; the answers are
|
|
* state, so markdown rendered without one renders again once it is here.
|
|
* Each block is asked for once per page load, however often the page is
|
|
* drawn — while writing, the preview asks only for a block that changed.
|
|
*/
|
|
import { api } from './api'
|
|
|
|
type Answer = { svg: string } | { error: string }
|
|
|
|
let answers = $state.raw(new Map<string, Answer>())
|
|
const asked = new Set<string>()
|
|
|
|
/** Forget a block once it is this far out of date: the preview of a long session asks for many. */
|
|
const KEEP = 200
|
|
|
|
export function typeset(source: string, share?: string): Answer | null {
|
|
const key = `${share ?? ''}\n${source}`
|
|
const answer = answers.get(key)
|
|
if (answer || asked.has(key)) return answer ?? null
|
|
asked.add(key)
|
|
api
|
|
.typeset(source, share)
|
|
.then((done) => (done.svg !== undefined ? { svg: done.svg } : { error: done.error ?? 'typst said nothing' }))
|
|
.catch((e: Error) => ({ error: e.message }))
|
|
.then((done) => {
|
|
const next = new Map(answers)
|
|
if (next.size >= KEEP) next.delete(next.keys().next().value!)
|
|
answers = next.set(key, done)
|
|
})
|
|
return null
|
|
}
|