Something went wrong. Try again.
Local-first knowledge base made for Typst and the Atmosphere. typbase.at
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308use std::path::PathBuf;
use dashmap::DashSet;use rustc_hash::FxHashMap;use serde::{Deserialize, Serialize};use time::{OffsetDateTime, UtcOffset};use tsify::Tsify;use typst::{ Feature, Features, Library, LibraryExt, World, diag::{FileError, FileResult}, foundations::{Bytes, Datetime, Dict, Duration, Value}, syntax::{FileId, Source}, text::{Font, FontBook}, utils::LazyHash,};use typst_ide::IdeWorld;use typst_syntax::{VirtualPath, VirtualRoot, package::PackageSpec};
use crate::fonts::FontLoader;
/// Implementation of Typst's `World` for Typbase, managing all loaded files,/// fonts, and compilation state.#[derive(Debug)]pub struct TypstWorld { /// The file [`World::main`] points at: the pristine synth, or the render /// source while a render session is active. pub main_id: Option<FileId>, /// All loaded files (sources and binaries) by id. pub files: FxHashMap<FileId, FileSlot>, /// Features the library is built with. features: Features, /// Values for `sys.inputs`, baked into the library at build time. inputs: Dict, /// The Typst standard library for this world. library: LazyHash<Library>, /// Font loader and font book. font_loader: FontLoader,
/// Sources requested by Typst but not yet loaded. pub requested_sources: DashSet<VirtualPath>, /// Files requested by Typst but not yet loaded. pub requested_files: DashSet<VirtualPath>, /// Packages requested by Typst but not yet loaded. pub requested_packages: DashSet<PackageSpec>,}
impl Default for TypstWorld { fn default() -> Self { let features: Features = [Feature::Html, Feature::A11yExtras].into_iter().collect(); let inputs = Dict::new(); let library = build_library(features.clone(), &inputs);
Self { main_id: None, files: FxHashMap::default(), features, inputs, library, font_loader: FontLoader::default(), requested_sources: DashSet::default(), requested_files: DashSet::default(), requested_packages: DashSet::default(), } }}
/// The library a world compiles with. `sys.inputs` is baked into the library's/// global scope, so changing the inputs rebuilds it.fn build_library(features: Features, inputs: &Dict) -> LazyHash<Library> { LazyHash::new( Library::builder() .with_features(features) .with_inputs(inputs.clone()) .build(), )}
impl TypstWorld { /// Replaces `sys.inputs`: the compiling page and workspace (both optional), /// the compile reason (`editor`, `resolve`, `render`, `chat`), and the /// output target (`html` or `paged`). Rebuilding the library drops memoized /// compiles, so callers set this when the values actually change. pub fn set_inputs( &mut self, page: Option<String>, workspace: Option<String>, reason: String, target: String, ) { let mut inputs = Dict::new(); if let Some(page) = page { inputs.insert("page".into(), Value::Str(page.into())); } if let Some(workspace) = workspace { inputs.insert("workspace".into(), Value::Str(workspace.into())); } inputs.insert("reason".into(), Value::Str(reason.into())); inputs.insert("target".into(), Value::Str(target.into()));
self.inputs = inputs; self.library = build_library(self.features.clone(), &self.inputs); }
pub fn insert_source(&mut self, id: FileId, text: String) { let source = Source::new(id, text);
self.files.insert(id, FileSlot::Source(source)); }
/// Inserts a prepared [`Source`]. Cloning a `Source` is cheap because its /// text is refcounted, so callers that need the same text under several /// ids should clone the source instead of the string. pub fn insert_source_object(&mut self, id: FileId, source: Source) { self.files.insert(id, FileSlot::Source(source)); }
/// Installed font faces. Tests and the debug lab use this to watch for /// duplicate installs. #[must_use] pub fn font_count(&self) -> usize { self.font_loader.fonts.len() }
pub fn remove_source(&mut self, id: &FileId) { self.files.remove(id); }
/// Drops every file loaded under `spec`'s package root. Returns how many /// files were removed so the caller can skip a recompile when nothing /// changed. pub fn remove_package(&mut self, spec: &PackageSpec) -> usize { let before = self.files.len(); self.files.retain(|id, _| { match id.root() { VirtualRoot::Package(root) => root != spec, VirtualRoot::Project => true, } });
before - self.files.len() }
pub fn insert_file(&mut self, id: FileId, bytes: Bytes) { self.files.insert(id, FileSlot::Bytes(bytes)); }
pub fn get_source(&self, id: FileId) -> Option<&Source> { self.get_file(id).and_then(|file| file.source()) }
pub fn get_file(&self, id: FileId) -> Option<&FileSlot> { // if !self.files.contains_key(&id) { // crate::error!("{id:#?} NOT FOUND"); // }
self.files.get(&id) }
// pub fn set_source(&mut self, id: &FileId, text: &str) { // self.files.get_mut(id).unwrap().replace(text); // }
pub fn install_font(&mut self, bytes: Vec<u8>) { self.font_loader.install(bytes); }
/// Drains the sources, files, and packages the compiler asked for since /// the last call and turns them into a request list. The JS side answers /// each request and recompiles. #[must_use] pub fn take_requests(&self) -> Vec<TypstRequest> { let mut requests = Vec::new();
self.requested_sources.retain(|source| { requests.push(TypstRequest::Source(PathBuf::from(source.get_with_slash()))); false });
self.requested_files.retain(|file| { requests.push(TypstRequest::File(PathBuf::from(file.get_with_slash()))); false });
self.requested_packages.retain(|package| { requests.push(TypstRequest::Package { namespace: package.namespace.to_string(), name: package.name.to_string(), version: package.version.to_string(), });
false });
requests }}
impl World for TypstWorld { fn library(&self) -> &LazyHash<Library> { &self.library }
fn book(&self) -> &LazyHash<FontBook> { &self.font_loader.book }
fn main(&self) -> FileId { self.main_id.unwrap() }
fn source(&self, id: FileId) -> FileResult<Source> { if let Some(source) = self.get_source(id) { Ok(source.clone()) } else { match id.root() { VirtualRoot::Project => self.requested_sources.insert(id.vpath().clone()), VirtualRoot::Package(spec) => self.requested_packages.insert(spec.clone()), };
Err(FileError::Other(None)) } }
fn file(&self, id: FileId) -> FileResult<Bytes> { if let Some(file) = self.get_file(id) { Ok(file.bytes()) } else { match id.root() { VirtualRoot::Project => self.requested_files.insert(id.vpath().clone()), VirtualRoot::Package(spec) => self.requested_packages.insert(spec.clone()), };
Err(FileError::Other(None)) } }
fn font(&self, index: usize) -> Option<Font> { Some(self.font_loader.fonts[index].clone()) }
fn today(&self, offset: Option<Duration>) -> Option<Datetime> { let now = if let Some(duration) = offset { #[allow(clippy::cast_possible_truncation)] OffsetDateTime::now_utc() .to_offset(UtcOffset::from_hms(duration.hours() as i8, 0, 0).unwrap()) } else { OffsetDateTime::now_utc() };
Some(Datetime::Date(now.date())) }}
impl IdeWorld for TypstWorld { fn upcast(&self) -> &dyn World { self }}
/// Slot for a loaded file in the world, either a source or binary.#[derive(Debug)]pub enum FileSlot { /// A Typst source file. Source(Source), /// A binary file (e.g., image, font, etc). Bytes(Bytes),}
impl FileSlot { #[must_use] pub const fn source(&self) -> Option<&Source> { match self { FileSlot::Source(source) => Some(source), FileSlot::Bytes(..) => None, } }
pub const fn source_mut(&mut self) -> Option<&mut Source> { match self { FileSlot::Source(source) => Some(source), FileSlot::Bytes(..) => None, } }
#[must_use] pub fn bytes(&self) -> Bytes { match self { FileSlot::Source(source) => Bytes::from_string(source.text().to_string()), FileSlot::Bytes(file) => file.clone(), } }}
/// A file, source, or package the compiler asked for but the world does not/// have. Every compile returns the requests it accumulated, and the caller/// resolves them (workspace source, blob bytes, package tarball) and recompiles.#[derive(Tsify, Serialize, Deserialize)]#[serde(tag = "type", content = "value", rename_all = "kebab-case")]pub enum TypstRequest { Source(PathBuf), File(PathBuf), Package { namespace: String, name: String, version: String, },}