use std::{ io::{Cursor, Read}, num::NonZeroUsize, str::FromStr, }; use ecow::EcoVec; use rustc_hash::FxHashMap; use serde::{Deserialize, Serialize}; use tar::Archive; use tsify::{Ts, Tsify}; use typst::{ World, ecow::EcoString, foundations::Bytes, introspection::{HtmlPosition, PagedPosition}, layout::{Abs, Point}, syntax::{FileId, VirtualPath, package::PackageSpec}, }; use typst_ide::Tooltip; use typst_syntax::{LinkedNode, RootedPath, Side, Source, Tag, VirtualRoot}; use wasm_bindgen::prelude::*; use crate::{ bindings::{TypstCompletion, TypstFileId, TypstHighlight, TypstJump}, flatten::{CellSpan, CodeSpan, EquationSpan, FlattenedBlock, HeadingSpan, SectionSpan}, links::LinkSpan, source::{ RenderTarget, Side as MapSide, SourceContext, SpaceContext, SynthResult, sync_source_state, }, theme::ThemeColors, world::TypstWorld, }; /// Global state for Typst rendering and compilation in Typbase. /// /// Contains the world, all open source and space contexts, and manages the mapping /// between user/editor state and Typst's compilation model. #[wasm_bindgen] #[derive(Default, Debug)] pub struct TypstState { /// The Typst world, containing all loaded files and fonts. pub(crate) world: TypstWorld, /// Mapping from space IDs to their context (fonts, theme, locale). pub(crate) space_context_map: FxHashMap, /// Mapping from file IDs to their source context (main/raw sources, index /// mapping, etc). pub(crate) source_context_map: FxHashMap, /// Bumped whenever fonts, theme, or font settings change. The editor keys /// its compile cache on it, so installing system fonts mid-session makes /// open documents re-render. pub(crate) revision: u32, /// Workspace values the host supplies for autocomplete. Replaced when the /// page, category, daily, or plugin lists change, not on every query. pub(crate) completion_data: crate::complete::CompletionData, } #[wasm_bindgen] impl TypstState { #[must_use] #[wasm_bindgen(constructor)] pub fn new() -> Self { comemo::evict(0); let mut this = Self::default(); let id = FileId::new(RootedPath::new( VirtualRoot::Project, VirtualPath::new("typbase/lib.typ").expect("Invalid virtual path"), )); this.world .insert_source(id, String::from(crate::prelude::TYPBASE_LIB)); this.insert_syntax_theme(&ThemeColors::default()); this } #[wasm_bindgen(js_name = "setTheme")] pub fn set_theme(&mut self, id: &TypstFileId, theme: ThemeColors) { // The code-block theme travels with the palette: a per-theme virtual // file means switching themes can never serve the previous colors. self.insert_syntax_theme(&theme); self.get_space_context_mut(id).theme = theme; self.revision += 1; } #[wasm_bindgen(js_name = "setFont")] pub fn set_font(&mut self, id: &TypstFileId, font: String) { self.get_space_context_mut(id).font = font; self.revision += 1; } #[wasm_bindgen(js_name = "setMathFont")] pub fn set_math_font(&mut self, id: &TypstFileId, math_font: Option) { self.get_space_context_mut(id).math_font = math_font; self.revision += 1; } #[wasm_bindgen(js_name = "setCodeFont")] pub fn set_code_font(&mut self, id: &TypstFileId, code_font: Option) { self.get_space_context_mut(id).code_font = code_font; self.revision += 1; } #[wasm_bindgen(js_name = "setTextSize")] pub fn set_text_size(&mut self, id: &TypstFileId, text_size: f64) { self.get_space_context_mut(id).text_size = text_size; self.revision += 1; } /// Typographic features the generated prelude turns on or off. They live in /// the space context rather than in an app-side prelude so the editor, /// previews, plugin surfaces, exports, and published pages all read the /// same values from one place. #[wasm_bindgen(js_name = "setTypography")] pub fn set_typography(&mut self, id: &TypstFileId, ligatures: bool, kerning: bool) { let context = self.get_space_context_mut(id); context.ligatures = ligatures; context.kerning = kerning; self.revision += 1; } /// Applies or omits the Typbase document rules for headings, links, /// quotes, shapes, math, and code blocks. The theme, fonts, and syntax /// theme stay either way. #[wasm_bindgen(js_name = "setDocumentStyle")] pub fn set_document_style(&mut self, id: &TypstFileId, styled: bool) { let context = self.get_space_context_mut(id); if context.document_style != styled { context.document_style = styled; self.revision += 1; } } /// Host values for `sys.inputs`: the compiling page and workspace (both /// optional), the compile reason (`editor`, `resolve`, `render`, `chat`), /// and the output target (`html` or `paged`). The library bakes them into /// its global scope, so a change rebuilds it and drops memoized compiles. #[wasm_bindgen(js_name = "setInputs")] pub fn set_inputs( &mut self, page: Option, workspace: Option, reason: String, target: String, ) { self.world.set_inputs(page, workspace, reason, target); self.revision += 1; } /// Replaces the workspace values autocomplete uses: page ids and titles, /// categories, daily months and dates, and plugin instances. The host calls /// this when one of those lists changes, not on every completion query. #[wasm_bindgen(js_name = "setCompletionData")] pub fn set_completion_data_js(&mut self, data: JsValue) -> Result<(), JsError> { let data = serde_wasm_bindgen::from_value(data) .map_err(|error| JsError::new(&error.to_string()))?; self.set_completion_data(data); Ok(()) } /// The editor's line-height as a multiple of the text size. Frame crops /// move their top to the editor's line box so the rendered text sits on /// the same baseline as the source text. #[wasm_bindgen(js_name = "setLineHeightRatio")] pub fn set_line_height_ratio(&mut self, id: &TypstFileId, ratio: f64) { self.get_space_context_mut(id).line_height_ratio = ratio; self.revision += 1; } #[wasm_bindgen(js_name = "setLocale")] pub fn set_locale(&mut self, id: &TypstFileId, locale: String) { self.get_space_context_mut(id).locale = locale; self.revision += 1; } /// Monotonic counter bumped on font/theme/config changes. Re-render /// decisions key on this, not on the file path alone. #[wasm_bindgen(js_name = "revision")] #[must_use] pub fn revision(&self) -> u32 { self.revision } /// Test-only trap for the engine recovery e2e suite. Debug builds only, /// so nothing in a release bundle can call it. Takes `&mut self` on /// purpose: a trap here leaks the same borrow flag a real compile trap /// leaks, which is the case the recovery has to survive. #[cfg(debug_assertions)] #[wasm_bindgen(js_name = "debugPanic")] pub fn debug_panic(&mut self) { panic!("debugPanic"); } /// Current WASM heap size in bytes. The lab watches this to catch leaks. /// The wasm allocator rarely returns memory to the browser, so growth /// here usually means a compile loop. #[wasm_bindgen(js_name = "memoryBytes")] #[must_use] pub fn memory_bytes(&self) -> u32 { let memory = wasm_bindgen::memory(); let buffer = js_sys::Reflect::get(&memory, &"buffer".into()).ok(); let length = buffer .as_ref() .and_then(|buffer| js_sys::Reflect::get(buffer, &"byteLength".into()).ok()); length .and_then(|length| length.as_f64()) .unwrap_or_default() as u32 } #[wasm_bindgen(js_name = "createSourceId")] pub fn create_source_id(&mut self, path: &str, space_id: String) -> TypstFileId { let id = FileId::new(RootedPath::new( VirtualRoot::Project, VirtualPath::new(path) .expect("Invalid virtual path") .with_extension("typ"), )); let id_wrapper = TypstFileId::new(id); let source_ctx = SourceContext::new(id, space_id.clone()); self.world.insert_source(source_ctx.raw_id, String::new()); self.world.insert_source(source_ctx.synth_id, String::new()); self.world .insert_source(source_ctx.render_id, String::new()); self.world.insert_source(source_ctx.ide_id, String::new()); self.source_context_map.insert(id_wrapper, source_ctx); // The space context is workspace-shared: fonts/theme are applied to it // once. Creating another source id in the same workspace must keep the // existing context (with its theme), or the styles silently reset and // pages render default-black until something re-applies them. self.space_context_map .entry(space_id.clone()) .or_insert_with(SpaceContext::new); id_wrapper } #[wasm_bindgen(js_name = "createFileId")] pub fn create_file_id(&mut self, path: &str) -> TypstFileId { let id = FileId::new(RootedPath::new( VirtualRoot::Project, VirtualPath::new(path).expect("Invalid virtual path"), )); TypstFileId::new(id) } #[wasm_bindgen(js_name = "insertSource")] pub fn insert_source(&mut self, id: &TypstFileId, text: String) { self.world.insert_source(id.inner(), text); self.bump_source_revisions(); } #[wasm_bindgen(js_name = "insertFile")] pub fn insert_file(&mut self, id: &TypstFileId, bytes: Vec) { self.world.insert_file(id.inner(), Bytes::new(bytes)); self.bump_source_revisions(); } /// Drops cached span offsets for every note. A file just replaced may be /// imported by any of them, and its node numbers no longer mean the same /// thing. fn bump_source_revisions(&self) { for context in self.source_context_map.values() { context.bump_source_revision(); } } #[wasm_bindgen(js_name = "removeFile")] pub fn remove_file(&mut self, id: &TypstFileId) { // For a note, drop the context and every source file it created. Leaving // the raw and render files behind would leak one entry per closed // note. Plain project files (requests the caller satisfied by hand) // have no context and are removed as-is. if let Some(context) = self.source_context_map.remove(id) { self.world.remove_source(&context.synth_id); self.world.remove_source(&context.raw_id); self.world.remove_source(&context.render_id); self.world.remove_source(&context.ide_id); } else { self.world.remove_source(&id.inner()); } self.bump_source_revisions(); } #[wasm_bindgen(js_name = "installPackage")] pub fn install_package(&mut self, spec: &str, data: Vec) -> Result<(), JsValue> { let package_spec = PackageSpec::from_str(spec).map_err(|e| JsValue::from_str(&e.to_string()))?; let data = Cursor::new(data); let data = flate2::read::GzDecoder::new(data); let mut archive = Archive::new(data); let entries = archive .entries() .map_err(|error| JsValue::from_str(&error.to_string()))?; for entry in entries { let mut file = entry.map_err(|error| JsValue::from_str(&error.to_string()))?; // Directory entries (the leading `.` in Universe tarballs) have // no content and would insert an empty source at the root. if !file.header().entry_type().is_file() { continue; } let path = file .path() .map_err(|error| JsValue::from_str(&error.to_string()))?; let path = path .to_str() .ok_or_else(|| JsValue::from_str("package entry path is not utf-8"))?; let id = FileId::new(RootedPath::new( VirtualRoot::Package(package_spec.clone()), VirtualPath::new(path).map_err(|error| JsValue::from_str(&error.to_string()))?, )); let mut content = Vec::new(); file.read_to_end(&mut content) .map_err(|error| JsValue::from_str(&error.to_string()))?; match String::from_utf8(content.clone()) { Ok(content) => self.world.insert_source(id, content), Err(..) => self.world.insert_file(id, Bytes::new(content)), } } self.bump_source_revisions(); Ok(()) } #[wasm_bindgen(js_name = "removePackage")] pub fn remove_package(&mut self, spec: &str) -> Result<(), JsValue> { let package_spec = PackageSpec::from_str(spec).map_err(|e| JsValue::from_str(&e.to_string()))?; self.world.remove_package(&package_spec); self.bump_source_revisions(); Ok(()) } /// Clears Typst's global memoization caches. They make repeated compiles /// cheap but grow for the lifetime of the instance, so call this when /// memory matters more than speed, such as on a workspace switch. #[wasm_bindgen(js_name = "evictCaches")] pub fn evict_caches(&mut self) { comemo::evict(0); } /// Evicts entries unused across two eviction rounds. The heap watchdog /// uses this while typing: per-keystroke entries age out, shared entries /// such as the library and fonts stay warm. #[wasm_bindgen(js_name = "evictCachesAged")] pub fn evict_caches_aged(&mut self, max_age: usize) { comemo::evict(max_age); } #[wasm_bindgen(js_name = "installFont")] pub fn install_font(&mut self, bytes: Vec) { self.world.install_font(bytes); self.revision += 1; } /// Scripts in `text` that none of the installed fonts can draw. /// /// The app uses this to offer a downloadable font when a page contains /// Chinese, Arabic or another script the bundled faces do not cover. #[must_use] #[wasm_bindgen(js_name = "uncoveredScripts")] pub fn uncovered_scripts(&self, text: &str) -> Vec { crate::fonts::uncovered_scripts(&self.world.book(), text) } /// The families a font file declares, so an upload can be filed under the /// name the font itself declares. Empty when the bytes are not a font. #[must_use] #[wasm_bindgen(js_name = "fontFamilies")] pub fn font_families(bytes: Vec) -> Vec { crate::fonts::family_names(&bytes) } /// The faces a font file declares, with weights and styles. Site CSS needs /// one @font-face per uploaded file, not the same 400 normal descriptor for /// every face in a family. #[wasm_bindgen(js_name = "fontFaces")] pub fn font_faces(bytes: Vec) -> Result { serde_wasm_bindgen::to_value(&crate::fonts::face_info(&bytes)) .map_err(|error| JsError::new(&error.to_string())) } /// Index mapping self-test for the debug lab. Builds the synth exactly /// like a compile would, then verifies map invariants: segments tile both /// spaces, both directions stay in bounds, and neither regresses. #[wasm_bindgen(js_name = "checkIndex")] pub fn check_index( &mut self, id: &TypstFileId, text: &str, prelude: &str, ) -> Result, JsError> { let report = self.check_index_report(id, text, prelude); Ok(report.into_ts()?) } } impl TypstState { /// Replaces the values completion reads. The wasm binding /// `setCompletionData` deserializes the host object into this. pub(crate) fn set_completion_data(&mut self, data: crate::complete::CompletionData) { self.completion_data = data; } /// The raw-to-synth map for a note. Read-only. The debug lab and the /// benches use it to inspect segment counts. #[must_use] pub fn source_map(&self, id: &TypstFileId) -> Option<&crate::source::SourceMap> { self.source_context_map .get(id) .map(|context| &context.index_map) } /// Plain-Rust core of [`Self::check_index`]. Host tests call this /// directly, while the wasm boundary only serializes the report. #[must_use] pub fn check_index_report( &mut self, id: &TypstFileId, text: &str, prelude: &str, ) -> IndexCheckReport { let SynthResult { .. } = sync_source_state(id, text, prelude, RenderTarget::Svg, self); let context = self.source_context_map.get_mut(id).unwrap(); let raw_len = text.len(); let synth_len = context .synth_source(&self.world) .map(|source| source.text().len()) .unwrap_or_default(); let render_len = context .render_source(&self.world) .map(|source| source.text().len()) .unwrap_or_default(); let mut checked = 0_u32; let mut mismatches: Vec = Vec::new(); mismatches.extend(context.index_map.validate()); mismatches.extend(context.render_map.validate()); mismatches.extend(context.render_fixups.map().validate()); // raw -> synth must stay in bounds and never regress. let step = (raw_len / 2000).max(1); let mut last_before = 0; let mut last_after = 0; for raw in (0..=raw_len).step_by(step) { let before = context.map_raw_to_synth(raw, MapSide::Before); let after = context.map_raw_to_synth(raw, MapSide::After); if before > synth_len || after > synth_len { mismatches.push(format!( "raw->synth overflow at {raw}: before {before}, after {after}, synth_len {synth_len}" )); } if raw > 0 { if before < last_before { mismatches.push(format!( "raw->synth before regressed at {raw}: {before} < {last_before}" )); } if after < last_after { mismatches.push(format!( "raw->synth after regressed at {raw}: {after} < {last_after}" )); } } last_before = before; last_after = after; checked += 1; } // synth -> raw must never leave the raw source (prelude positions // clamp to raw 0). let synth_step = (synth_len / 2000).max(1); for synth in (0..=synth_len).step_by(synth_step) { let raw = context.map_synth_to_raw(synth); if raw > raw_len { mismatches.push(format!("synth->raw overflow at {synth}: {raw}")); } checked += 1; } // render -> raw must never leave the raw source either. let render_step = (render_len / 2000).max(1); for render in (0..=render_len).step_by(render_step) { let raw = context.map_render_to_raw(render); if raw > raw_len { mismatches.push(format!("render->raw overflow at {render}: {raw}")); } checked += 1; } let segments = context .index_map .segments() .iter() .map(|segment| { #[allow(clippy::cast_possible_truncation)] CheckedSegment { kind: segment.kind().label().to_string(), generated: segment.generated(), from: segment.from_start() as u32, from_end: segment.from_end() as u32, to: segment.to_start() as u32, to_end: segment.to_end() as u32, } }) .collect(); IndexCheckReport { ok: mismatches.is_empty(), checked, mismatches, segments, } } /// Plain-Rust core of [`Self::jump_paged`]. pub fn jump_paged_at(&self, id: &TypstFileId, x: f64, mut y: f64) -> Option { let context = self.source_context_map.get(id)?; let document = context.paged_document.as_ref()?; let index = document .pages() .iter() .rposition(|page| y >= page.frame.height().to_pt()) .unwrap_or_default(); let page_offset = document .pages() .iter() .map(|page| page.frame.height().to_pt()) .rfind(|height| y >= *height) .unwrap_or_default(); y -= page_offset; let position = PagedPosition { page: NonZeroUsize::new(index + 1).unwrap(), point: Point::new(Abs::pt(x), Abs::pt(y)), }; typst_ide::jump_from_click(&self.world, document, &position) .and_then(|jump| TypstJump::from_mapped(jump, context, &self.world)) } /// Plain-Rust core of [`Self::jump_html`]. pub fn jump_html_at(&self, id: &TypstFileId, element: Vec) -> Option { let context = self.source_context_map.get(id)?; let document = context.html_document.as_ref()?; typst_ide::jump_from_click( &self.world, document, &HtmlPosition::new(EcoVec::from(element)), ) .and_then(|jump| TypstJump::from_mapped(jump, context, &self.world)) } /// Picks the parse source and `World::main` for an IDE query at a raw /// cursor. /// /// Inside a range error recovery marked, the token under the cursor only /// exists in the pristine file (the patched trace file has a placeholder /// there), so parse that and give up on trace-based resolution, which /// needs a compilable main. Everywhere else the patched file is used: it /// is byte-identical to the pristine one outside the marks and it /// compiles, so tracing resolves property access. fn ide_query_sources(&self, id: &TypstFileId, raw_cursor: usize) -> Option<(FileId, Source)> { let context = self.source_context_map.get(id)?; let inside_marked = context .marked_raw_ranges .iter() .any(|range| range.start <= raw_cursor && raw_cursor <= range.end); if inside_marked { Some((context.synth_id, context.synth_source(&self.world)?.clone())) } else { Some((context.ide_id, context.ide_source(&self.world)?.clone())) } } /// Cursor position in raw-source bytes, clamped to the end of the source. /// /// The editor can be one keystroke ahead of the last compile: typing at /// the end of a block puts the cursor past the text the engine still /// contains. Returning `None` there cancels the IDE query, which reads as /// "no completion at the end of a block". Clamping keeps the query alive /// with the context from the previous keystroke. fn raw_cursor_byte(source: &Source, cursor_utf16: usize) -> usize { source .lines() .utf16_to_byte(cursor_utf16) .unwrap_or_else(|| source.text().len()) } /// Plain-Rust core of [`Self::autocomplete`]. pub fn autocomplete_at( &mut self, id: &TypstFileId, raw_cursor_utf16: usize, explicit: bool, ) -> Option { let synth_id = self.source_context_map.get(id)?.synth_id; let raw_cursor = { let raw_source = self.source_context_map.get(id)?.raw_source(&self.world)?; Self::raw_cursor_byte(raw_source, raw_cursor_utf16) }; let (main_id, parse_source) = self.ide_query_sources(id, raw_cursor)?; self.world.main_id = Some(main_id); let result = (|| { let raw_source = self .source_context_map .get(id)? .raw_source(&self.world)? .clone(); let raw_lines = raw_source.lines(); let raw_cursor = Self::raw_cursor_byte(&raw_source, raw_cursor_utf16); let raw_root = self .source_context_map .get_mut(id)? .parse_cached(raw_source.text()); // The stdlib's string arguments are not expressions Typst's IDE can // resolve, so they get a dedicated pass first. if let Some((raw_offset, completions)) = crate::complete::typbase_completions( &raw_root, raw_source.text(), raw_cursor, &self.completion_data, ) { return Some(Autocomplete { offset: raw_lines.byte_to_utf16(raw_offset)?, completions: completions.into(), }); } let context = self.source_context_map.get(id)?; // `Before` keeps the cursor at the end of the copied text. `After` // jumps past a generated block separator, which lands the cursor in // markup and kills completion at the end of a block. let synth_cursor = context.map_raw_to_synth(raw_cursor, MapSide::Before); let (synth_offset, completions) = typst_ide::autocomplete( &self.world, context.paged_document.as_ref(), &parse_source, synth_cursor, explicit, )?; let raw_offset = context.map_synth_to_raw(synth_offset); let raw_offset_utf16 = raw_lines.byte_to_utf16(raw_offset)?; Some(Autocomplete { offset: raw_offset_utf16, completions: completions .into_iter() .map(TypstCompletion::from) .collect::>(), }) })(); self.world.main_id = Some(synth_id); result } } #[wasm_bindgen] impl TypstState { /// The note's parse tree for `text`, parsed only when the cached one is for /// other bytes. fn parse_shared(&mut self, id: Option, text: &str) -> typst_syntax::SyntaxNode { match id .as_ref() .and_then(|id| self.source_context_map.get_mut(id)) { Some(context) => context.parse_cached(text), None => typst_syntax::parse(text), } } /// Plain-text flattening per block for the search index, plus the byte /// map back to raw source. #[wasm_bindgen(js_name = "flattenDocument")] pub fn flatten_document( &mut self, id: Option, text: &str, ) -> Result>, JsError> { let root = self.parse_shared(id, text); Ok(crate::flatten::flatten_document_root(&root, text) .into_iter() .map(|block| block.into_ts()) .collect::, _>>()?) } /// Extracts `#typbase.section` spans for the page doc's sections list. #[wasm_bindgen(js_name = "extractSections")] pub fn extract_sections( &mut self, id: Option, text: &str, ) -> Result>, JsError> { let root = self.parse_shared(id, text); Ok(crate::flatten::extract_sections_root(&root, text) .into_iter() .map(|span| span.into_ts()) .collect::, _>>()?) } /// Extracts top-level headings as UTF-16 spans for the page outline. /// Shares the note's parse tree, like the other syntax passes. #[wasm_bindgen(js_name = "extractHeadings")] pub fn extract_headings( &mut self, id: &TypstFileId, text: &str, ) -> Result>, JsError> { let root = self.parse_shared(Some(id.clone()), text); Ok(crate::flatten::extract_headings_root(&root, text) .into_iter() .map(|heading| heading.into_ts()) .collect::, _>>()?) } /// Extracts math equation ranges as UTF-16 spans. The editor marks them /// so math can use a monospaced face while prose keeps the text font. #[wasm_bindgen(js_name = "extractEquations")] pub fn extract_equations( &mut self, id: &TypstFileId, text: &str, ) -> Result>, JsError> { let root = self.parse_shared(Some(id.clone()), text); Ok(crate::flatten::extract_equations_root(&root, text) .into_iter() .map(|range| range.into_ts()) .collect::, _>>()?) } /// Extracts code expressions embedded with `#` (`#let x = 2`, `#f(1)`) as /// UTF-16 spans. The editor marks them so scripting uses the monospaced /// face while prose keeps the text font. #[wasm_bindgen(js_name = "extractCodeSpans")] pub fn extract_code_spans( &mut self, id: &TypstFileId, text: &str, ) -> Result>, JsError> { let root = self.parse_shared(Some(id.clone()), text); Ok(crate::flatten::extract_code_spans_root(&root, text) .into_iter() .map(|span| span.into_ts()) .collect::, _>>()?) } /// Extracts the app's link calls (`typbase.page-link`, `typbase.embed`, /// and `typbase://page/` URLs) with UTF-16 ranges. Shares the note's parse /// tree, like the other syntax passes. #[wasm_bindgen(js_name = "extractLinks")] pub fn extract_links( &mut self, id: Option, text: &str, ) -> Result>, JsError> { let root = self.parse_shared(id, text); Ok(crate::links::extract_links_root(&root, text) .into_iter() .map(|span| span.into_ts()) .collect::, _>>()?) } /// Extracts notebook cells as UTF-16 spans, ready for CodeMirror /// positions. Shares the note's parse tree, like the other syntax passes. #[wasm_bindgen(js_name = "extractCells")] pub fn extract_cells( &mut self, id: &TypstFileId, text: &str, ) -> Result>, JsError> { let root = self.parse_shared(Some(id.clone()), text); Ok(crate::flatten::extract_cells_root(&root, text) .into_iter() .map(|cell| cell.into_ts()) .collect::, _>>()?) } /// Brings the engine's sources and maps up to date with `text` without /// rendering anything. #[wasm_bindgen(js_name = "syncSource")] pub fn sync_source(&mut self, id: &TypstFileId, text: &str, prelude: &str) -> bool { if !self.source_context_map.contains_key(id) { return false; } let SynthResult { .. } = sync_source_state(id, text, prelude, RenderTarget::Svg, self); true } #[wasm_bindgen] pub fn highlight( &mut self, id: &TypstFileId, text: &str, ) -> Result>, JsError> { if !self.source_context_map.contains_key(id) { return Ok(Vec::new()); } // The world's raw source is rewritten below, before the compile // microtask runs, which is why the sync keeps its own copy of the text to // key on. Sharing the tree is the other half of that: this pass runs // first on every keystroke, and the delimiter repair and the synth behind // it all want a tree of the same bytes. let root = self .source_context_map .get_mut(id) .unwrap() .parse_cached(text); let Some(context) = self.source_context_map.get(id) else { return Ok(Vec::new()); }; let Some(raw_source) = context.raw_source_mut(&mut self.world) else { return Ok(Vec::new()); }; raw_source.replace(text); let mut queue = vec![LinkedNode::new(&root)]; let mut highlights = Vec::new(); let raw_lines = raw_source.lines(); while let Some(curr) = queue.pop() { let tag = typst_syntax::highlight(&curr); let range = curr.range(); let highlight = tag.and_then(|tag| { let raw_range_start_utf16 = raw_lines.byte_to_utf16(range.start)?; let raw_range_end_utf16 = raw_lines.byte_to_utf16(range.end)?; let raw_range_utf16 = raw_range_start_utf16..raw_range_end_utf16; let mut css_class = tag.css_class().to_string(); if tag == Tag::Heading { let node = curr.get(); let Some(marker_node) = node.children().next() else { unreachable!() }; let level = marker_node.leaf_text().len(); css_class += " typ-heading-level-"; css_class += level.to_string().as_str(); } Some(TypstHighlight { tag: css_class, range: raw_range_utf16, }) }); if let Some(highlight) = highlight { let idx = highlights .binary_search_by_key(&highlight.range.start, |highlight: &TypstHighlight| { highlight.range.start }); match idx { Ok(idx) | Err(idx) => highlights.insert(idx, highlight), } } for child in curr.children() { queue.push(child); } } Ok(highlights .into_iter() .map(|highlight| highlight.into_ts()) .collect::, _>>()?) } #[wasm_bindgen(js_name = "jumpPaged")] pub fn jump_paged( &mut self, id: &TypstFileId, x: f64, y: f64, ) -> Result>, JsError> { Ok(self .jump_paged_at(id, x, y) .map(|jump| jump.into_ts()) .transpose()?) } #[wasm_bindgen(js_name = "jumpHTML")] pub fn jump_html( &mut self, id: &TypstFileId, element: Vec, ) -> Result>, JsError> { Ok(self .jump_html_at(id, element) .map(|jump| jump.into_ts()) .transpose()?) } #[wasm_bindgen] pub fn autocomplete( &mut self, id: &TypstFileId, raw_cursor_utf16: usize, explicit: bool, ) -> Result>, JsError> { Ok(self .autocomplete_at(id, raw_cursor_utf16, explicit) .map(|value| value.into_ts()) .transpose()?) } #[wasm_bindgen] pub fn hover(&mut self, id: &TypstFileId, raw_cursor_utf16: usize, side: i8) -> Option { let synth_id = self.source_context_map.get(id)?.synth_id; let raw_cursor = { let raw_source = self.source_context_map.get(id)?.raw_source(&self.world)?; Self::raw_cursor_byte(raw_source, raw_cursor_utf16) }; let (main_id, parse_source) = self.ide_query_sources(id, raw_cursor)?; self.world.main_id = Some(main_id); let result = (|| { let context = self.source_context_map.get(id)?; // Same as autocomplete: the cursor belongs at the end of the copied // text, not after a generated separator. let synth_cursor = context.map_raw_to_synth(raw_cursor, MapSide::Before); let side = if side == -1 { Side::Before } else { Side::After }; let tooltip = typst_ide::tooltip( &self.world, context.paged_document.as_ref(), &parse_source, synth_cursor, side, ); tooltip.map(|tooltip| { match tooltip { Tooltip::Text(text) => text.to_string(), Tooltip::Code(code) => { if code.starts_with('<') && code.ends_with('>') { code.to_string() } else { typst_syntax::highlight_html(&typst_syntax::parse_code(&code)) } } } }) })(); self.world.main_id = Some(synth_id); result } #[wasm_bindgen] pub fn resize(&mut self, id: &TypstFileId, width: Option, height: Option) -> bool { let context = self.source_context_map.get_mut(id).unwrap(); // Callers measure panes in CSS pixels. The app treats a Typst point as // one screen pixel: a 600px pane compiles as a 600pt page, and frames // then render at 1px per pt inside the pane, so a 16pt body matches // the editor's 16px. Converting px to true pt (x0.75) would lay out a // 600pt page and stretch it back over 600px, rendering everything 4/3 // larger than the editor. let width = width .map(|px| px.to_string() + "pt") .unwrap_or_else(|| String::from("auto")); let width_changed = context.width != width; context.width = width; context.height = height; if width_changed { // Frame text boxes were laid out at the old width. context.frame_text = Default::default(); } width_changed } } impl TypstState { pub const fn world(&self) -> &TypstWorld { &self.world } pub const fn world_mut(&mut self) -> &mut TypstWorld { &mut self.world } /// Serves the generated tmTheme for a palette as a virtual project file. /// The prelude references it. The same file name is what exports bundle. fn insert_syntax_theme(&mut self, theme: &ThemeColors) { let path = theme.syntax_theme_path(); let file_id = FileId::new(RootedPath::new( VirtualRoot::Project, VirtualPath::new(path).expect("Invalid virtual path"), )); if self.world.files.contains_key(&file_id) { return; } self.world .insert_file(file_id, Bytes::from_string(theme.tm_theme())); } pub fn get_source_context(&self, id: &TypstFileId) -> &SourceContext { self.source_context_map.get(id).unwrap() } pub fn get_source_context_mut(&mut self, id: &TypstFileId) -> &mut SourceContext { self.source_context_map.get_mut(id).unwrap() } pub fn get_space_context(&self, id: &TypstFileId) -> &SpaceContext { let space_id = &self.get_source_context(id).space_id; self.space_context_map.get(space_id).unwrap() } pub fn get_space_context_mut(&mut self, id: &TypstFileId) -> &mut SpaceContext { let space_id = self.get_source_context(id).space_id.clone(); self.space_context_map.get_mut(&space_id).unwrap() } /// Splits the state into the two borrows a renderer needs: the world and /// this note's source context. Field-level, so the borrow checker keeps /// them disjoint and renderer code never sees fonts, other notes, or the /// revision counter. pub fn render_context(&mut self, id: &TypstFileId) -> Option> { let note = self.source_context_map.get_mut(id)?; let world = &mut self.world; Some(RenderContext { world, note }) } } /// The minimal borrow a render pass needs. Built by /// [`TypstState::render_context`]. The paged and HTML renderers take this /// instead of the whole state. pub struct RenderContext<'a> { pub world: &'a mut TypstWorld, /// The note being rendered: sources, maps, documents, page width. pub note: &'a mut SourceContext, } /// Result of `TypstState::check_index`: a self-test of the source maps. #[derive(Tsify, Serialize, Deserialize)] pub struct IndexCheckReport { /// True when every checked invariant passed. pub ok: bool, /// How many positions were sampled for each direction. pub checked: u32, /// Human-readable descriptions of failed invariants. pub mismatches: Vec, /// Every segment of the raw to pristine-synth map, for the debug lab. pub segments: Vec, } /// One segment in the check report, labelled for humans. #[derive(Tsify, Serialize, Deserialize)] pub struct CheckedSegment { pub kind: String, pub generated: bool, pub from: u32, pub from_end: u32, pub to: u32, pub to_end: u32, } #[derive(Tsify, Serialize, Deserialize)] pub struct TypstError(EcoString); #[derive(Tsify, Serialize, Deserialize)] pub struct Autocomplete { pub offset: usize, pub completions: Box<[TypstCompletion]>, }