diff --git a/.gitignore b/.gitignore index 68a25e9648..17ee0686fe 100644 --- a/.gitignore +++ b/.gitignore @@ -108,6 +108,7 @@ storageState.json /packages/frontend/artifacts/ /packages/frontend/hosts/web/assets/*.wasm /packages/frontend/hosts/web/assets/fonts/*.ttf +/blocksuite/crates/playground/web/assets/ /blocksuite/crates/playground/web/pkg/ /blocksuite/crates/playground/web/wasm-scalar-rpc.js /blocksuite/crates/playground/web/workers/ diff --git a/blocksuite/crates/AGENTS.md b/blocksuite/crates/AGENTS.md index 3d58304754..42ed2d9962 100644 --- a/blocksuite/crates/AGENTS.md +++ b/blocksuite/crates/AGENTS.md @@ -7,9 +7,9 @@ These crates belong to the client Cargo workspace rooted at `packages/frontend/C ### Workspace boundaries - `blocksuite/crates/doc` (`blocksuite-playground-doc`) & `bs-relay`: Pure CRDT document engine and binary room sync relay (`#![forbid(unsafe_code)]`, zero GUI/platform dependencies, `packages/frontend/scripts/check-invariants.sh` rejects `ui`, `wgpu`, `objc2`, and `web-sys` in `blocksuite/blocksuite/crates/doc/Cargo.toml`) built on `y-octo 0.4.0`. Preserves 53-bit `clientId` (`1..=2^53 - 1`), complete flavour schema defaults (`schema/`, 0 JS writeback updates on initial load), top-level Awareness `color` alongside `user` and `selectionV2`, deterministic `now_ms`-driven undo/awareness clocks (`session/`), WebSocket-only `seed-claim` / `seed-claim-result` single-winner arbitration (keyed by `seed:`), awareness refcounting across connections that forwards a removal (including the equal-clock live-to-`null` form `y-protocols` uses to expire a peer) once the last owner releases a client, `?ws=` relay origin forwarding with permissive blob CORS headers, and `wasm32-unknown-unknown` compatibility under `--no-default-features`. `read/` (`PageDocSession::read_page_snapshot`) is the typed read side: an ordered `PageSnapshot` tree of `BlockNode`s whose `BlockContent` covers every supported block flavour, keeps the normalized JSON of every `prop:*`, numbers `numbered` list runs, reads `prop:textAlign` and the note display modes by their BlockSuite wire values (`both` / `doc` / `edgeless`), reports blocks outside the root tree as `detached`, and reads any other flavour as `Unknown` instead of dropping it. -- `blocksuite/crates/preview` (`blocksuite-preview`): Pure-Rust offline preview kernel (`#![forbid(unsafe_code)]`, zero GUI/network/OS blocking I/O, zero host system font discovery or wall-clock calls). Provides `FontPool`, `SvgRasterizer`, `PinnedPixelCache`, `MermaidRenderer` (`merman` `resvg_safe`), pure in-memory RaTeX outline math rendering, `InMemoryTypstWorld`, `HayroPdfRenderer`, `PreviewEngine`, and `WasmPreviewEngine`. All four worker features (`mermaid`, `math`, `typst`, `pdf`) compile independently on `wasm32-unknown-unknown` with `wasm-worker`. -- `blocksuite/crates/editor` (`blocksuite-editor`): Reusable BlockSuite editor crate depending only on `blocksuite-playground-doc`, `blocksuite-preview`, `ui-kit`, `ui`, `ui-tokens`, and general utility crates (zero `affine-store` dependency and zero storage/network protocol leaks). Owns `theme` (backed by `ui-tokens` for colors, typography, icons, and `register_bundled_fonts`), `directory` (`WorkspaceDocDirectory` host port, `InMemoryDocDirectory`, and exact substring UTF-16 highlight matching), `block_flow/` (Page-mode renderer with LTR/RTL logical start/end placement), `rich_text/` (rich paragraph engine), `editor_session/` (selection and preedit core), `clipboard/`, `overlays/` (generic over `OverlayHost`), `surface/`, and `edgeless/` (generic over `EdgelessToolbarHost`). -- `blocksuite/crates/playground`: Standalone demonstration and verification host owning `PlaygroundView` (`lib.rs`, `chrome.rs`, `view_room.rs`), `room_client/` (live room sync), `showcase.rs` (deterministic `seed_showcase_doc` workspace), `PlaygroundView` glue for `editor_session/`, `overlays/`, and `edgeless/`, the native macOS desktop entry (`native-playground`), the WebAssembly canvas entry (`wasm_main`), and the deterministic headless verification CLI (`src/bin/bs_harness/`). It reuses the editor kernel and bundled fonts through `blocksuite-editor`, `ui-kit`, and `ui-tokens`. +- `blocksuite/crates/preview` (`blocksuite-preview`): Pure-Rust offline preview kernel (`#![forbid(unsafe_code)]`, zero GUI/network/OS blocking I/O, zero host system font discovery or wall-clock calls). Provides `FontPool`, `SvgRasterizer`, `PinnedPixelCache`, `MermaidRenderer` (`merman` `resvg_safe`), pure in-memory RaTeX outline math rendering, `InMemoryTypstWorld`, `HayroPdfRenderer`, and `PreviewEngine`. All four worker features (`mermaid`, `math`, `typst`, `pdf`) compile independently on `wasm32-unknown-unknown` with `wasm-worker`, whose only exports are the four scalar `affine_worker_*` functions in `wasm_worker.rs` (`reset_input`, `push_input_u32`, `invoke`, `output_u32`) that `packages/frontend/hosts/web/src/wasm-scalar-rpc.js` calls through a raw `WebAssembly.instantiate`. +- `blocksuite/crates/editor` (`blocksuite-editor`): Reusable BlockSuite editor crate depending only on `blocksuite-playground-doc`, `blocksuite-preview`, `ui-kit`, `ui`, `ui-tokens`, and general utility crates (zero `affine-store` dependency and zero storage/network protocol leaks). Owns `theme` (backed by `ui-tokens` for colors, typography, icons, and `register_bundled_fonts`; on `wasm32` the fonts come from `register_web_font_bytes` instead, which rejects data with zero usable faces (`validate_font_bytes`), so the Wasm bundle embeds zero font bytes), `directory` (`WorkspaceDocDirectory` host port, `InMemoryDocDirectory`, and exact substring UTF-16 highlight matching), `block_flow/` (Page-mode renderer with LTR/RTL logical start/end placement), `rich_text/` (rich paragraph engine), `editor_session/` (selection and preedit core), `clipboard/`, `overlays/` (generic over `OverlayHost`), `surface/`, and `edgeless/` (generic over `EdgelessToolbarHost`). +- `blocksuite/crates/playground`: Standalone demonstration and verification host owning `PlaygroundView` (`lib.rs`, `chrome.rs`, `view_room.rs`), `room_client/` (live room sync), `showcase.rs` (deterministic `seed_showcase_doc` workspace), `PlaygroundView` glue for `editor_session/`, `overlays/`, and `edgeless/`, the native macOS desktop entry (`native-playground`), the WebAssembly canvas entry (`wasm_main`, which `web/index.html` calls after it fetched the seven `ui-tokens` fonts from `assets/fonts/` and passed each to `register_web_font`; both throw, and the page never reports ready, when a font has zero usable faces or the set misses one of `REQUIRED_FONT_FAMILIES`), and the deterministic headless verification CLI (`src/bin/bs_harness/`). It reuses the editor kernel and bundled fonts through `blocksuite-editor`, `ui-kit`, and `ui-tokens`. - `unexpected_cfgs = "deny"` is enforced workspace-wide in `Cargo.toml`; dead upstream feature gates are forbidden. - `blocksuite/crates/oracle/`: Browser-captured style and surface geometry fixtures (`style-oracle.json`, `surface-oracle.json`, `surface-baselines.json`, `surface-metrics-test.ttf`), `surface-baselines.mjs`, `surface-oracle.spec.mjs`, `extract-style-oracle.spec.ts`, and browser-mode `vitest.config.ts` (`browser.enabled: true` so `scripts/ci/vitest-node-projects.mjs` skips it). @@ -72,5 +72,5 @@ These crates belong to the client Cargo workspace rooted at `packages/frontend/C - **Focused, table-driven tests**: Keep test-only imports and helpers inside `#[cfg(test)] mod tests`, placing unit tests in the file under test and cross-submodule tests in the lowest common `mod.rs`. Keep every test file and function name aligned with its actual assertion scope, and group similar scenarios into table-driven loops rather than proliferating near-identical `#[test]` functions. - **Sub-60-second verification loop**: Validate uncertain paths with minimal focused spikes first and remove scaffolding before landing. Keep routine edit-verify turns under **60 seconds** using targeted `cargo check --locked -p ...` / `cargo test --locked -p ... --lib ` and `./packages/frontend/scripts/check-invariants.sh` (which enforces `super::super` bans, `mod.rs` layout, orphan-file detection, and per-file LOC limits automatically alongside `rustfmt.toml`). -- **Standalone Web preview staging (`playground/scripts/stage-web.mjs`)**: Stages `wasm-scalar-rpc.js`, `workers/preview-worker-core.js`, `workers/{math,pdf,mermaid,typst}-worker.js`, built preview `.wasm` binaries, and `pkg/playground.{js,_bg.wasm}` into `blocksuite/crates/playground/web/` (`node blocksuite/crates/playground/scripts/stage-web.mjs [--out ]`) and validates relative ESM imports. +- **Standalone Web preview staging (`playground/scripts/stage-web.mjs`)**: Stages `wasm-scalar-rpc.js`, `workers/preview-worker-core.js`, `workers/{math,pdf,mermaid,typst}-worker.js`, built preview `.wasm` binaries, `pkg/playground.{js,_bg.wasm}`, and the `ui-tokens` fonts (`assets/fonts/*.ttf`) into `blocksuite/crates/playground/web/` (`node blocksuite/crates/playground/scripts/stage-web.mjs [--out ]`) and validates relative ESM imports. - **Whiteboard `mindmap` & `gfx/text` `RE_RTL_CHECK` compatibility**: `SurfaceElementKind::Mindmap` decodes `layoutType` (`Right`/`Left`/`Balance`), `style` (`1..=4` `0.27.5` `StrokeColorShortMap` medium palettes), and `children` (`{ index, parent?, collapsed? }`) with zero CRDT writeback, synthesizing `0.27.5` branch and `6px` collapsed-stub connectors (`surface/mindmap.rs`) beneath child shapes and falling back to deterministic `compute_mindmap_layout` when child shapes share an unpositioned origin (interactive Mindmap authoring/editing remains future work). Edgeless `SurfaceText`, `Shape` labels, and `Connector` labels evaluate `surface::is_gfx_text_rtl` (`0.27.5` non-`/u` UTF-16 `RE_RTL_CHECK`) per delta/line (`RichParagraphStyle::gfx_per_delta_rtl`), and mobile Edgeless read-only mode (`PlaygroundOptions::edgeless_readonly`, `?mobile=1` / `--edgeless-readonly`) hides `chrome.edgeless_toolbar`, suppresses mutating gestures/shortcuts, and supports 1-finger pan plus 2-finger centroid pinch-zoom. diff --git a/blocksuite/crates/editor/Cargo.toml b/blocksuite/crates/editor/Cargo.toml index e827afaf86..4101c7d06a 100644 --- a/blocksuite/crates/editor/Cargo.toml +++ b/blocksuite/crates/editor/Cargo.toml @@ -16,9 +16,11 @@ harness = ["ui/harness"] [dependencies] anyhow.workspace = true blocksuite-playground-doc = { path = "../doc", default-features = false } +fontdb.workspace = true image.workspace = true serde.workspace = true serde_json.workspace = true +ttf-parser.workspace = true ui = { path = "../../../packages/ui/ui" } ui-tokens = { path = "../../../packages/ui/tokens" } unicode-bidi.workspace = true diff --git a/blocksuite/crates/editor/src/theme.rs b/blocksuite/crates/editor/src/theme.rs index 4636da3dfb..2f5e637b23 100644 --- a/blocksuite/crates/editor/src/theme.rs +++ b/blocksuite/crates/editor/src/theme.rs @@ -22,6 +22,8 @@ pub use ui_tokens::{ /// and `Noto Sans Hebrew`) into the active `TextSystem`. /// /// Must be called before opening any window across macOS, Linux headless, and Web Wasm. +/// Native targets read the bytes that `ui-tokens` embeds. +#[cfg(not(target_arch = "wasm32"))] pub fn register_bundled_fonts(cx: &App) -> anyhow::Result<()> { let fonts: Vec> = bundled_font_bytes() .into_iter() @@ -31,6 +33,111 @@ pub fn register_bundled_fonts(cx: &App) -> anyhow::Result<()> { cx.text_system().add_fonts(fonts) } +/// Family names that the editor theme renders with. The Web page must supply a +/// font for each of them. +pub const REQUIRED_FONT_FAMILIES: [&str; 4] = + [FONT_SANS, FONT_CODE, "Noto Sans Arabic", "Noto Sans Hebrew"]; + +/// Number of fonts the Web page supplies, one per `ui-tokens` font file. +pub const WEB_FONT_COUNT: usize = bundled_font_bytes().len() + bundled_script_font_bytes().len(); + +/// Loads a TrueType or OpenType font (or collection) with the same `fontdb` +/// loader as the text system and returns the family names of its usable faces. +/// +/// A face is usable when `fontdb` accepts it and it has glyphs. Data with zero +/// usable faces is an error, so a server that answers a font request with an +/// empty body or an HTML page is caught before the font reaches the text +/// system, which skips such faces without an error. +pub fn validate_font_bytes(bytes: &[u8]) -> anyhow::Result> { + anyhow::ensure!(!bytes.is_empty(), "font data is empty"); + let mut db = fontdb::Database::new(); + db.load_font_source(fontdb::Source::Binary(Arc::new(bytes.to_vec()))); + let mut families: Vec = db + .faces() + .filter(|face| { + db.with_face_data(face.id, |data, index| { + ttf_parser::Face::parse(data, index).is_ok_and(|f| f.number_of_glyphs() > 0) + }) == Some(true) + }) + .flat_map(|face| face.families.iter().map(|(name, _)| name.clone())) + .filter(|name| !name.is_empty()) + .collect(); + anyhow::ensure!(!families.is_empty(), "font data contains 0 usable faces"); + families.sort_unstable(); + families.dedup(); + Ok(families) +} + +/// Checks that the Web page supplied [`WEB_FONT_COUNT`] fonts that together +/// cover [`REQUIRED_FONT_FAMILIES`]. `font_families` holds the families of +/// each font, as [`validate_font_bytes`] returns them. +pub fn check_web_font_set(font_families: &[Vec]) -> anyhow::Result<()> { + anyhow::ensure!( + font_families.len() == WEB_FONT_COUNT, + "expected {WEB_FONT_COUNT} web fonts, got {}", + font_families.len() + ); + let available: Vec<&String> = font_families.iter().flatten().collect(); + let missing: Vec<&str> = REQUIRED_FONT_FAMILIES + .into_iter() + .filter(|required| !available.iter().any(|family| family == required)) + .collect(); + anyhow::ensure!( + missing.is_empty(), + "web fonts do not contain the families {}", + missing.join(", ") + ); + Ok(()) +} + +std::thread_local! { + static WEB_FONTS: std::cell::RefCell, Vec)>> = + const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Validates and queues font bytes that the Web page fetched from its static +/// font assets. +/// +/// The page calls this for each font before it opens the window. The Wasm build +/// never references the `ui-tokens` font bytes, so the bundle carries no fonts. +/// A rejected font clears the queue, so the page starts the next attempt from an +/// empty queue. +pub fn register_web_font_bytes(bytes: Vec) -> anyhow::Result<()> { + let families = validate_font_bytes(&bytes).inspect_err(|_| clear_web_fonts())?; + WEB_FONTS.with(|fonts| fonts.borrow_mut().push((bytes, families))); + Ok(()) +} + +/// Checks the fonts queued by [`register_web_font_bytes`] with +/// [`check_web_font_set`], and clears the queue when they fail. +pub fn check_web_fonts() -> anyhow::Result<()> { + let font_families: Vec> = WEB_FONTS.with(|fonts| { + fonts + .borrow() + .iter() + .map(|(_, families)| families.clone()) + .collect() + }); + check_web_font_set(&font_families).inspect_err(|_| clear_web_fonts()) +} + +fn clear_web_fonts() { + WEB_FONTS.with(|fonts| fonts.borrow_mut().clear()); +} + +/// Registers the fonts queued by [`register_web_font_bytes`] into the active +/// `TextSystem`, in the order the page queued them. +#[cfg(target_arch = "wasm32")] +pub fn register_bundled_fonts(cx: &App) -> anyhow::Result<()> { + check_web_fonts()?; + let fonts: Vec> = WEB_FONTS + .with(|fonts| std::mem::take(&mut *fonts.borrow_mut())) + .into_iter() + .map(|(bytes, _)| Cow::Owned(bytes)) + .collect(); + cx.text_system().add_fonts(fonts) +} + /// Color theme of the playground chrome and document. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum PlaygroundTheme { @@ -437,6 +544,93 @@ impl IconPaint { mod tests { use super::*; + /// Returns `font` with every PostScript name record (name ID 6) renamed to an + /// unused name ID, keeping the glyphs and the family names. + fn without_post_script_name(font: &[u8]) -> Vec { + let mut out = font.to_vec(); + let be16 = |at: usize| usize::from(u16::from_be_bytes([font[at], font[at + 1]])); + let be32 = |at: usize| { + u32::from_be_bytes([font[at], font[at + 1], font[at + 2], font[at + 3]]) as usize + }; + let record = (0..be16(4)) + .map(|i| 12 + i * 16) + .find(|&at| &font[at..at + 4] == b"name") + .expect("name table"); + let name = be32(record + 8); + for i in 0..be16(name + 2) { + let name_id = name + 6 + i * 12 + 6; + if be16(name_id) == 6 { + out[name_id..name_id + 2].copy_from_slice(&0x7fff_u16.to_be_bytes()); + } + } + out + } + + #[test] + fn validate_font_bytes_accepts_bundled_fonts_and_rejects_broken_data() { + let [inter, plex_mono, ..] = bundled_font_bytes(); + let [arabic, hebrew] = bundled_script_font_bytes(); + let html: &[u8] = b""; + let no_post_script_name = without_post_script_name(hebrew); + let no_faces = "font data contains 0 usable faces"; + let cases: [(&str, &[u8], Result<&str, &str>); 8] = [ + ("inter", inter, Ok("Inter")), + ("plex mono", plex_mono, Ok("IBM Plex Mono")), + ("arabic", arabic, Ok("Noto Sans Arabic")), + ("hebrew", hebrew, Ok("Noto Sans Hebrew")), + ("empty", b"", Err("font data is empty")), + ("html", html, Err(no_faces)), + ("truncated", &inter[..1024], Err(no_faces)), + ("no postscript name", &no_post_script_name, Err(no_faces)), + ]; + for (name, bytes, expected) in cases { + match (validate_font_bytes(bytes), expected) { + (Ok(families), Ok(family)) => { + assert!(families.iter().any(|f| f == family), "{name}: {families:?}"); + } + (Err(err), Err(message)) => assert_eq!(err.to_string(), message, "{name}"), + (result, _) => panic!("{name}: unexpected {result:?}"), + } + } + } + + #[test] + fn web_font_queue_clears_on_failure_and_accepts_a_new_attempt() { + let bundled: Vec<&[u8]> = bundled_font_bytes() + .into_iter() + .chain(bundled_script_font_bytes()) + .collect(); + for bytes in &bundled[..3] { + register_web_font_bytes(bytes.to_vec()).unwrap(); + } + assert!(register_web_font_bytes(Vec::new()).is_err()); + for bytes in &bundled[..WEB_FONT_COUNT - 1] { + register_web_font_bytes(bytes.to_vec()).unwrap(); + } + assert!(check_web_fonts().is_err()); + for bytes in &bundled { + register_web_font_bytes(bytes.to_vec()).unwrap(); + } + check_web_fonts().unwrap(); + } + + #[test] + fn check_web_font_set_requires_every_font_and_family() { + let bundled: Vec> = bundled_font_bytes() + .into_iter() + .chain(bundled_script_font_bytes()) + .map(|bytes| validate_font_bytes(bytes).unwrap()) + .collect(); + check_web_font_set(&bundled).unwrap(); + + let without_hebrew = &bundled[..WEB_FONT_COUNT - 1]; + assert!(check_web_font_set(without_hebrew).is_err()); + let mut hebrew_replaced = bundled.clone(); + hebrew_replaced[WEB_FONT_COUNT - 1] = bundled[0].clone(); + let err = check_web_font_set(&hebrew_replaced).unwrap_err(); + assert!(err.to_string().contains("Noto Sans Hebrew"), "{err}"); + } + #[test] fn css_colors_resolve_variables_fallbacks_and_hex() { let light = PlaygroundTheme::Light; diff --git a/blocksuite/crates/playground/scripts/stage-web.mjs b/blocksuite/crates/playground/scripts/stage-web.mjs index 9eed83ff56..4f8836c26c 100755 --- a/blocksuite/crates/playground/scripts/stage-web.mjs +++ b/blocksuite/crates/playground/scripts/stage-web.mjs @@ -4,22 +4,25 @@ // Stages standalone `playground/web` (`pkg/playground.{js,_bg.wasm}`) // and shared Web Worker preview scripts (`wasm-scalar-rpc.js`, // `workers/preview-worker-core.js`, `workers/*-worker.js`) and built preview -// Wasm binaries (`workers/*-worker.wasm`), then verifies all relative ESM -// imports resolve inside the staged output directory. +// Wasm binaries (`workers/*-worker.wasm`) and the tracked `ui-tokens` fonts +// (`assets/fonts/*.ttf`, fetched by `index.html` before the window opens), then +// verifies all relative ESM imports resolve inside the staged output directory. import { copyFileSync, cpSync, existsSync, mkdirSync, + readdirSync, readFileSync, } from 'node:fs'; -import { dirname, join, resolve } from 'node:path'; +import { basename, dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; const PLAYGROUND_ROOT = resolve(fileURLToPath(new URL('..', import.meta.url))); const REPO_ROOT = resolve(PLAYGROUND_ROOT, '../../..'); const HOST_WEB_SRC = join(REPO_ROOT, 'packages/frontend/hosts/web/src'); +const FONTS_SRC = join(REPO_ROOT, 'packages/ui/tokens/fonts'); const args = process.argv.slice(2); let sourceDirArg = '/tmp/preview-wasm'; @@ -86,6 +89,15 @@ for (const kind of KINDS) { } } +const fontsDst = join(WEB_DIR, 'assets', 'fonts'); +mkdirSync(fontsDst, { recursive: true }); +const fontFiles = readdirSync(FONTS_SRC, { recursive: true }).filter(rel => + rel.endsWith('.ttf') +); +for (const rel of fontFiles) { + copyFileSync(join(FONTS_SRC, rel), join(fontsDst, basename(rel))); +} + const stagedJsFiles = [ join(WEB_DIR, 'wasm-scalar-rpc.js'), ...WORKER_FILES.map(f => join(workersDst, f)), @@ -105,5 +117,5 @@ for (const jsPath of stagedJsFiles) { } console.log( - `Staged worker scripts and ${stagedWasmCount} .wasm files into ${WEB_DIR}` + `Staged worker scripts, ${stagedWasmCount} .wasm files and ${fontFiles.length} fonts into ${WEB_DIR}` ); diff --git a/blocksuite/crates/playground/src/view_room.rs b/blocksuite/crates/playground/src/view_room.rs index be4284c863..3503e6fc07 100644 --- a/blocksuite/crates/playground/src/view_room.rs +++ b/blocksuite/crates/playground/src/view_room.rs @@ -471,23 +471,33 @@ fn web_options() -> PlaygroundOptions { #[cfg(target_family = "wasm")] #[wasm_bindgen::prelude::wasm_bindgen(start)] -pub fn wasm_main() { +pub fn install_panic_hook() { console_error_panic_hook::set_once(); - let Some(window) = web_sys::window() else { - // Node / headless Wasm test environment: skip DOM canvas bootstrap so callers can - // invoke exported CRDT helpers directly without side effects. - return; - }; - if js_sys::Reflect::get( - &window, - &wasm_bindgen::JsValue::from_str("__AFFINE_WEB_HOST__"), - ) - .ok() - .is_some_and(|v| v.is_truthy()) - { - // Web thin host (`/host/`): avoid mounting a second fullscreen playground window. - return; - } +} + +/// Validates and queues one font for the window that [`wasm_main`] opens. +/// +/// The page fetches the fonts from its static font assets, which the preview +/// workers share through the browser HTTP cache, and calls this once per font +/// before [`wasm_main`]. Data with zero usable font faces throws. +#[cfg(target_family = "wasm")] +#[wasm_bindgen::prelude::wasm_bindgen] +pub fn register_web_font(bytes: &[u8]) -> Result<(), wasm_bindgen::JsError> { + crate::theme::register_web_font_bytes(bytes.to_vec()) + .map_err(|err| wasm_bindgen::JsError::new(&format!("{err:#}"))) +} + +/// Opens the fullscreen playground window on the page canvas. +/// +/// The standalone playground page calls this after it registered its fonts with +/// [`register_web_font`]. It throws before it starts the application when the +/// fonts miss a required family. The Web thin host (`/host/`) loads the same +/// module only for its CRDT helpers and never calls it. +#[cfg(target_family = "wasm")] +#[wasm_bindgen::prelude::wasm_bindgen] +pub fn wasm_main() -> Result<(), wasm_bindgen::JsError> { + crate::theme::check_web_fonts() + .map_err(|err| wasm_bindgen::JsError::new(&format!("{err:#}")))?; let platform = std::rc::Rc::new(ui::WebPlatform::new(false)); ui::Application::with_platform(platform).run(|cx| { if let Err(err) = register_bundled_fonts(cx) { @@ -502,4 +512,5 @@ pub fn wasm_main() { panic!("failed to open playground web window: {err:#}"); } }); + Ok(()) } diff --git a/blocksuite/crates/playground/web/index.html b/blocksuite/crates/playground/web/index.html index 81c27f2168..d8facbd938 100644 --- a/blocksuite/crates/playground/web/index.html +++ b/blocksuite/crates/playground/web/index.html @@ -29,16 +29,64 @@ diff --git a/blocksuite/crates/preview/BENCHMARK.md b/blocksuite/crates/preview/BENCHMARK.md index fa840cf58a..f3cc288965 100644 --- a/blocksuite/crates/preview/BENCHMARK.md +++ b/blocksuite/crates/preview/BENCHMARK.md @@ -60,19 +60,21 @@ Each preview capability builds independently under the unified `packages/fronten Production web packaging strips DWARF debug info (`debug = 0`) and post-processes every `.wasm` with Binaryen `wasm-opt -Oz --strip-debug --strip-producers`, selecting `opt-level = 3` (`--profile wasm-release`) for latency-sensitive `math` (`svg-raster` outline-only) and `pdf` (pure `hayro`, zero `resvg`/`usvg`) and `opt-level = "s"` (`--profile wasm-release-size`) for `mermaid` and `typst` (`svg-text`) so `typst` keeps comfortable headroom under Cloudflare Workers' 25 MiB single-asset limit without `opt-level = "z"` runtime slowdowns: -| Worker Feature | Profile | Stripped + `wasm-opt -Oz` Raw Size | `gzip -9` Size | Unstripped `--release` Raw (`debug = "limited"`) | +| Worker Feature | Profile | Stripped + `wasm-opt -Oz` Raw Size | `gzip -9` Size | `brotli -q 11` Size | | --- | --- | ---: | ---: | ---: | -| `math,wasm-worker` (RaTeX + `svg-raster` outlines) | `wasm-release` (`opt-level = 3`) | ~3.72 MiB | ~1.40 MiB | 28.87 MiB | -| `pdf,wasm-worker` (`hayro 0.9.0`, zero `resvg`) | `wasm-release` (`opt-level = 3`) | ~3.99 MiB | ~1.74 MiB | 48.92 MiB | -| `mermaid,wasm-worker` (`merman 0.11.0` + `svg-text`) | `wasm-release-size` (`opt-level = "s"`) | ~15.53 MiB | ~5.79 MiB | 179.34 MiB | -| `typst,wasm-worker` (`typst 0.15.1` + `svg-text`) | `wasm-release-size` (`opt-level = "s"`) | ~21.08 MiB | ~7.96 MiB | 167.39 MiB | +| `math,wasm-worker` (RaTeX + `svg-raster` outlines) | `wasm-release` (`opt-level = 3`) | 3,891,848 B (3.71 MiB) | 1,494,340 B (1.43 MiB) | 1,118,553 B (1.07 MiB) | +| `pdf,wasm-worker` (`hayro 0.9.0`, zero `resvg`) | `wasm-release` (`opt-level = 3`) | 4,169,271 B (3.98 MiB) | 1,828,122 B (1.74 MiB) | 1,462,210 B (1.39 MiB) | +| `mermaid,wasm-worker` (`merman 0.11.0` + `svg-text`) | `wasm-release-size` (`opt-level = "s"`) | 15,509,926 B (14.79 MiB) | 5,859,601 B (5.59 MiB) | 4,269,645 B (4.07 MiB) | +| `typst,wasm-worker` (`typst 0.15.1` + `svg-text`) | `wasm-release-size` (`opt-level = "s"`) | 21,509,557 B (20.51 MiB) | 8,273,986 B (7.89 MiB) | 6,214,687 B (5.93 MiB) | + +Measured on Linux x86-64 with Rust `1.98.1` and Binaryen `version_123` (`wasm-opt -Oz --strip-debug --strip-producers --enable-bulk-memory --enable-nontrapping-float-to-int --enable-sign-ext --enable-mutable-globals`). ## 4. Native Build and Toolchain Audit - `math`, `mermaid`, and `pdf` are pure safe Rust with zero `cc` build scripts and zero native C or C++ libraries. - `typst` depends on `stacker` -> `psm`, which compiles a small stack-probe assembly stub via `cc` on native targets (`wasm32-unknown-unknown` builds do not invoke `psm`). - `blocksuite-preview` itself enforces `#![forbid(unsafe_code)]`, zero wall-clock calls, zero host font discovery, strict CSS color validation with XML attribute escaping, and zero external SVG `` filesystem or network resolution. -- Across the Wasm Worker boundary, Mermaid and Typst copy cached RGBA pixels once from the shared `Arc` (or move them via `Arc::try_unwrap` when unshared), while `take_pixels(&mut self)` eliminates a second clone on JS property access. +- The Wasm Worker boundary is four scalar exports (`affine_worker_reset_input`, `affine_worker_push_input_u32`, `affine_worker_invoke`, `affine_worker_output_u32`) that stream one binary request and response frame through 32-bit words. The workers export no `wasm-bindgen` classes, so `wasm-opt` removes every engine method that no opcode reaches. ## 5. S1 Release Probe Measurements and Verification Boundaries diff --git a/blocksuite/crates/preview/src/lib.rs b/blocksuite/crates/preview/src/lib.rs index 5f2dae4060..048c521344 100644 --- a/blocksuite/crates/preview/src/lib.rs +++ b/blocksuite/crates/preview/src/lib.rs @@ -27,8 +27,6 @@ pub mod typst_world; #[cfg(feature = "pdf")] pub mod pdf; -#[cfg(feature = "wasm-worker")] -pub mod wasm; #[cfg(feature = "wasm-worker")] pub mod wasm_worker; diff --git a/blocksuite/crates/preview/src/svg_raster.rs b/blocksuite/crates/preview/src/svg_raster.rs index f182036344..9d946d9f28 100644 --- a/blocksuite/crates/preview/src/svg_raster.rs +++ b/blocksuite/crates/preview/src/svg_raster.rs @@ -273,9 +273,10 @@ impl SvgRasterizer { usvg::roxmltree::Document::parse_with_options(svg, xml_opt).map_err(|err| { PreviewError::SvgParse(usvg::Error::ParsingFailed(err).to_string()) })?; - if xml_contains_svg_text_element(xml_doc.root()) { + if xml_requires_svg_text(xml_doc.root()) { return Err(PreviewError::SvgParse( - "SVG requires the `svg-text` feature".to_string(), + "SVG and inline `data:image/svg+xml` images require the `svg-text` feature" + .to_string(), )); } usvg::Tree::from_xmltree(&xml_doc, &self.options) @@ -625,29 +626,39 @@ fn build_minimal_probe_ttf() -> Vec { out } -/// Walks parsed XML elements (matching `usvg`'s SVG namespace and container rules) and returns -/// `true` when any SVG `` element (`http://www.w3.org/2000/svg` or unqualified) is present, -/// ignoring XML comments, CDATA, foreign namespaces, and non-rendered metadata/style subtrees. +/// Walks every parsed XML element and returns `true` when the SVG needs the `svg-text` +/// feature to render: an SVG `` element (`http://www.w3.org/2000/svg` or unqualified), +/// or an SVG `` whose `href` / `xlink:href` is an inline `data:image/svg+xml` document. +/// +/// The walk visits every element, inside ``, `` and foreign-namespace +/// containers too, because `usvg` indexes `id`s across the whole tree and a `` can +/// render text defined anywhere. XML comments, CDATA, and elements in foreign namespaces +/// are not SVG elements. #[cfg(all(feature = "svg-raster", not(feature = "svg-text")))] -fn xml_contains_svg_text_element(root: usvg::roxmltree::Node<'_, '_>) -> bool { - let mut stack = vec![root]; - while let Some(node) = stack.pop() { - for child in node.children() { - if !child.is_element() { - continue; - } - let tag = child.tag_name(); - if !matches!(tag.namespace(), None | Some("http://www.w3.org/2000/svg")) { - continue; - } - match tag.name() { - "text" => return true, - "metadata" | "title" | "desc" | "style" | "script" | "foreignObject" => {} - _ => stack.push(child), - } +fn xml_requires_svg_text(root: usvg::roxmltree::Node<'_, '_>) -> bool { + const XLINK_NS: &str = "http://www.w3.org/1999/xlink"; + let is_inline_svg = |href: &str| { + href.trim() + .get(..18) + .is_some_and(|scheme| scheme.eq_ignore_ascii_case("data:image/svg+xml")) + }; + root.descendants().any(|node| { + if !node.is_element() { + return false; } - } - false + let tag = node.tag_name(); + if !matches!(tag.namespace(), None | Some("http://www.w3.org/2000/svg")) { + return false; + } + match tag.name() { + "text" => true, + "image" => [node.attribute("href"), node.attribute((XLINK_NS, "href"))] + .into_iter() + .flatten() + .any(is_inline_svg), + _ => false, + } + }) } /// Returns true for whitespace, control characters, and Unicode `Default_Ignorable_Code_Point` @@ -740,31 +751,69 @@ mod tests { rasterizer.rasterize(valid, f32::NAN), Err(PreviewError::InvalidSize(_)) )); + } - let text_svg = r#"Hi"#; - let prefixed_text_svg = r#"Hi"#; - let mixed_prefixed_text_svg = r#"Hi"#; - for candidate in [text_svg, prefixed_text_svg, mixed_prefixed_text_svg] { + #[cfg(feature = "svg-raster")] + #[test] + fn enforces_svg_text_feature_gate_across_xml_constructs() { + let rasterizer = SvgRasterizer::new(&FontPool::new()); + let wrap = |body: &str| { + format!( + r#"{body}"# + ) + }; + let text_svgs = [ + wrap(r#"Hi"#), + r#"Hi"#.to_string(), + wrap(r#"Hi"#), + wrap(r##"Hi"##), + wrap(r##"Hi"##), + wrap( + r##"Hi"##, + ), + ]; + for candidate in &text_svgs { #[cfg(feature = "svg-text")] - assert!(matches!( - rasterizer.rasterize(candidate, 1.0), - Err(PreviewError::MissingGlyphFont(_)) - )); + assert!( + matches!( + rasterizer.rasterize(candidate, 1.0), + Err(PreviewError::MissingGlyphFont(_)) + ), + "{candidate}" + ); #[cfg(not(feature = "svg-text"))] match rasterizer.rasterize(candidate, 1.0) { Err(PreviewError::SvgParse(msg)) => assert!(msg.contains("svg-text"), "{msg}"), - other => panic!("expected SvgParse requiring svg-text, got {other:?}"), + other => { + panic!("expected SvgParse requiring svg-text for {candidate}, got {other:?}") + } } } - // Path-only SVG with ` legend` inside an XML comment and foreign-namespace metadata - // has 0 SVG text elements and must rasterize cleanly regardless of `svg-text`. - let commented_path_svg = r##" - - legend - - "##; - let rendered = rasterizer.rasterize(commented_path_svg, 1.0).unwrap(); + // An inline SVG image can carry `` of its own. + #[cfg(not(feature = "svg-text"))] + for candidate in [ + wrap( + r#""#, + ), + wrap( + r#""#, + ), + ] { + match rasterizer.rasterize(&candidate, 1.0) { + Err(PreviewError::SvgParse(msg)) => assert!(msg.contains("svg-text"), "{msg}"), + other => { + panic!("expected SvgParse requiring svg-text for {candidate}, got {other:?}") + } + } + } + + // `` inside an XML comment and in a foreign namespace is no SVG text element: + // the path renders with or without `svg-text`. + let commented_path_svg = wrap( + r##"legend"##, + ); + let rendered = rasterizer.rasterize(&commented_path_svg, 1.0).unwrap(); assert!(rendered.count_non_transparent_pixels() > 0); } diff --git a/blocksuite/crates/preview/src/wasm.rs b/blocksuite/crates/preview/src/wasm.rs deleted file mode 100644 index 41f8f5b132..0000000000 --- a/blocksuite/crates/preview/src/wasm.rs +++ /dev/null @@ -1,591 +0,0 @@ -use wasm_bindgen::prelude::*; - -use crate::cache::CacheLimits; -use crate::engine::PreviewEngine; - -#[cfg(any(feature = "mermaid", feature = "typst"))] -use crate::PreviewDate; -#[cfg(feature = "math")] -use crate::math::{MathDisplayMode, MathRenderOptions}; -#[cfg(feature = "mermaid")] -use crate::mermaid::{MermaidOptions, MermaidTheme}; -#[cfg(feature = "pdf")] -use crate::pdf::PdfRenderRequest; - -/// Structured SVG output with intrinsic logical pixel dimensions. -#[cfg(feature = "mermaid")] -#[wasm_bindgen(getter_with_clone)] -#[derive(Debug, Clone)] -pub struct WasmSvgOutput { - /// Standalone SVG string. - pub svg: String, - /// Intrinsic logical width in pixels (parsed from SVG root attributes). - pub width_px: f32, - /// Intrinsic logical height in pixels (parsed from SVG root attributes). - pub height_px: f32, -} - -/// Structured RGBA8 pixel buffer with physical and logical dimensions. -#[cfg(any(feature = "mermaid", feature = "typst"))] -#[wasm_bindgen] -#[derive(Debug, Clone)] -pub struct WasmRgbaOutput { - /// Physical pixel width. - pub width_px: u32, - /// Physical pixel height. - pub height_px: u32, - /// Logical width in CSS pixels or points. - pub logical_width: f32, - /// Logical height in CSS pixels or points. - pub logical_height: f32, - pixels: Vec, -} - -#[cfg(any(feature = "mermaid", feature = "typst"))] -#[wasm_bindgen] -impl WasmRgbaOutput { - /// Moves the tightly packed RGBA8 pixel buffer (`width_px * height_px * 4`) to JS. - /// - /// Note: Mermaid and Typst copy the buffer once from the engine's cached - /// `Arc` (or take it without copying when unshared), while - /// `take_pixels` eliminates a second clone on repeated JS property reads. - /// Subsequent calls return an empty buffer. - pub fn take_pixels(&mut self) -> Vec { - std::mem::take(&mut self.pixels) - } -} - -/// Math SVG output and baseline metrics returned across the Wasm Worker boundary. -#[cfg(feature = "math")] -#[wasm_bindgen(getter_with_clone)] -#[derive(Debug, Clone)] -pub struct WasmMathOutput { - /// Total box width in points. - pub width_pt: f64, - /// Distance from the top edge to the baseline in points. - pub ascent_pt: f64, - /// Distance from the baseline to the bottom edge in points. - pub descent_pt: f64, - /// Standalone pure-`` SVG string. - pub svg: String, -} - -/// Rasterized math RGBA8 output and baseline metrics. -#[cfg(feature = "math")] -#[wasm_bindgen] -#[derive(Debug, Clone)] -pub struct WasmMathRgbaOutput { - /// Total box width in points. - pub width_pt: f64, - /// Distance from the top edge to the baseline in points. - pub ascent_pt: f64, - /// Distance from the baseline to the bottom edge in points. - pub descent_pt: f64, - /// Physical pixel width. - pub width_px: u32, - /// Physical pixel height. - pub height_px: u32, - pixels: Vec, -} - -#[cfg(feature = "math")] -#[wasm_bindgen] -impl WasmMathRgbaOutput { - /// Moves the tightly packed RGBA8 pixel buffer (`width_px * height_px * 4`) to JS - /// without cloning. Subsequent calls return an empty buffer. - pub fn take_pixels(&mut self) -> Vec { - std::mem::take(&mut self.pixels) - } -} - -/// Multi-page Typst SVG output and first-page metrics returned across the Wasm Worker boundary. -#[cfg(feature = "typst")] -#[wasm_bindgen(getter_with_clone)] -#[derive(Debug, Clone)] -pub struct WasmTypstOutput { - /// First-page width in Typst points. - pub width_pt: f64, - /// First-page height in Typst points. - pub height_pt: f64, - /// First-page ascent in points. - pub ascent_pt: f64, - /// First-page descent in points. - pub descent_pt: f64, - /// Total compiled page count. - pub page_count: usize, - /// First-page SVG string (convenience alias for `pages_svg[0]`). - pub svg: String, - /// SVG string for every compiled page in order. - pub pages_svg: Vec, -} - -/// PDF page RGBA buffer and dimensions returned across the Wasm Worker boundary. -#[cfg(feature = "pdf")] -#[wasm_bindgen] -#[derive(Debug, Clone)] -pub struct WasmPdfPageOutput { - /// Physical pixel width. - pub width_px: u32, - /// Physical pixel height. - pub height_px: u32, - /// Logical page width in PDF points. - pub logical_width: f32, - /// Logical page height in PDF points. - pub logical_height: f32, - /// Total number of pages in the PDF document. - pub page_count: usize, - pixels: Vec, -} - -#[cfg(feature = "pdf")] -#[wasm_bindgen] -impl WasmPdfPageOutput { - /// Moves the tightly packed RGBA8 pixel buffer (`width_px * height_px * 4`) to JS - /// without cloning. Subsequent calls return an empty buffer. - pub fn take_pixels(&mut self) -> Vec { - std::mem::take(&mut self.pixels) - } -} - -/// Persistent WebAssembly Worker preview engine. -/// -/// Retains registered fonts, pixel cache, in-memory Typst files/packages, and -/// parsed PDF handles across Worker RPC calls. -#[wasm_bindgen] -pub struct WasmPreviewEngine { - inner: PreviewEngine, -} - -#[wasm_bindgen] -impl WasmPreviewEngine { - /// Creates a new persistent preview engine with the given cache limits. - #[wasm_bindgen(constructor)] - pub fn new(max_cache_entries: usize, max_cache_bytes: usize) -> Self { - let limits = if max_cache_entries == 0 && max_cache_bytes == 0 { - CacheLimits::MOBILE_DEFAULT - } else { - CacheLimits { - max_entries: max_cache_entries, - max_bytes: max_cache_bytes, - } - }; - Self { - inner: PreviewEngine::new(limits), - } - } - - /// Registers a TrueType/OpenType font byte buffer into the engine's `FontPool`. - pub fn register_font(&mut self, bytes: &[u8]) -> Result { - self.inner - .register_font(bytes.to_vec()) - .map_err(|err| JsValue::from_str(&err.to_string())) - } - - /// Returns the number of font faces registered in this engine. - pub fn font_face_count(&self) -> usize { - self.inner.font_face_count() - } - - /// Registers an in-memory Typst virtual file. - #[cfg(feature = "typst")] - pub fn register_typst_file(&mut self, path: &str, bytes: &[u8]) -> Result<(), JsValue> { - self.inner - .register_typst_file(path, bytes.to_vec()) - .map_err(|err| JsValue::from_str(&err.to_string())) - } - - /// Registers an in-memory Typst package file (such as `@preview/demo:0.1.0`). - #[cfg(feature = "typst")] - pub fn register_typst_package_file( - &mut self, - namespace: &str, - name: &str, - version: &str, - path: &str, - bytes: &[u8], - ) -> Result<(), JsValue> { - self.inner - .register_typst_package_file(namespace, name, version, path, bytes.to_vec()) - .map_err(|err| JsValue::from_str(&err.to_string())) - } - - /// Renders a Mermaid diagram to `resvg`-safe SVG with intrinsic dimensions. - #[cfg(feature = "mermaid")] - pub fn render_mermaid_svg( - &self, - source: &str, - year: i32, - month: u8, - day: u8, - tz_offset_minutes: i16, - theme: Option, - ) -> Result { - let parsed_theme = - parse_mermaid_theme(theme.as_deref()).map_err(|err| JsValue::from_str(&err))?; - let opts = MermaidOptions { - today: PreviewDate::new(year, month, day), - timezone_offset_minutes: tz_offset_minutes, - theme: parsed_theme, - ..MermaidOptions::default() - }; - let svg = self - .inner - .render_mermaid_svg(source, &opts) - .map_err(|err| JsValue::from_str(&err.to_string()))?; - let (width_px, height_px) = parse_svg_dimensions(&svg); - Ok(WasmSvgOutput { - svg, - width_px, - height_px, - }) - } - - /// Renders a Mermaid diagram to cached RGBA8 pixels at `scale`. - #[cfg(feature = "mermaid")] - pub fn render_mermaid_rgba( - &mut self, - source: &str, - year: i32, - month: u8, - day: u8, - tz_offset_minutes: i16, - scale: f32, - theme: Option, - ) -> Result { - self.render_mermaid_rgba_with_policy( - source, - year, - month, - day, - tz_offset_minutes, - scale, - theme, - false, - ) - } - - /// Renders a Mermaid diagram to cached RGBA8 pixels in lenient mode, allowing - /// missing glyphs to fall back when no additional script fonts are available. - #[cfg(feature = "mermaid")] - pub fn render_mermaid_rgba_lenient( - &mut self, - source: &str, - year: i32, - month: u8, - day: u8, - tz_offset_minutes: i16, - scale: f32, - theme: Option, - ) -> Result { - self.render_mermaid_rgba_with_policy( - source, - year, - month, - day, - tz_offset_minutes, - scale, - theme, - true, - ) - } - - #[cfg(feature = "mermaid")] - fn render_mermaid_rgba_with_policy( - &mut self, - source: &str, - year: i32, - month: u8, - day: u8, - tz_offset_minutes: i16, - scale: f32, - theme: Option, - lenient: bool, - ) -> Result { - let parsed_theme = - parse_mermaid_theme(theme.as_deref()).map_err(|err| JsValue::from_str(&err))?; - let opts = MermaidOptions { - today: PreviewDate::new(year, month, day), - timezone_offset_minutes: tz_offset_minutes, - theme: parsed_theme, - ..MermaidOptions::default() - }; - let buf = if lenient { - self.inner.render_mermaid_rgba_lenient(source, &opts, scale) - } else { - self.inner.render_mermaid_rgba(source, &opts, scale) - } - .map_err(|err| JsValue::from_str(&err.to_string()))?; - let width_px = buf.width_px; - let height_px = buf.height_px; - let logical_width = buf.logical_width; - let logical_height = buf.logical_height; - let pixels = std::sync::Arc::try_unwrap(buf) - .map(|owned| owned.pixels) - .unwrap_or_else(|shared| shared.pixels.clone()); - Ok(WasmRgbaOutput { - width_px, - height_px, - logical_width, - logical_height, - pixels, - }) - } - - /// Renders a LaTeX formula to pure-`` SVG with exact baseline metrics. - #[cfg(feature = "math")] - pub fn render_latex_svg( - &self, - latex: &str, - display_mode: bool, - font_size_pt: f64, - color_css: Option, - ) -> Result { - let opts = MathRenderOptions { - mode: if display_mode { - MathDisplayMode::Display - } else { - MathDisplayMode::Inline - }, - font_size_pt, - padding_pt: 0.0, - color_css: color_css.unwrap_or_else(|| "#000000".to_string()), - }; - let out = self - .inner - .render_latex_svg(latex, &opts) - .map_err(|err| JsValue::from_str(&err.to_string()))?; - Ok(WasmMathOutput { - width_pt: out.width_pt, - ascent_pt: out.ascent_pt, - descent_pt: out.descent_pt, - svg: out.svg, - }) - } - - /// Renders a LaTeX formula to RGBA8 pixels with exact baseline metrics. - #[cfg(feature = "math")] - pub fn render_latex_rgba( - &mut self, - latex: &str, - display_mode: bool, - font_size_pt: f64, - scale: f32, - color_css: Option, - ) -> Result { - let opts = MathRenderOptions { - mode: if display_mode { - MathDisplayMode::Display - } else { - MathDisplayMode::Inline - }, - font_size_pt, - padding_pt: 0.0, - color_css: color_css.unwrap_or_else(|| "#000000".to_string()), - }; - let out = self - .inner - .render_latex_rgba(latex, &opts, scale) - .map_err(|err| JsValue::from_str(&err.to_string()))?; - Ok(WasmMathRgbaOutput { - width_pt: out.width_pt, - ascent_pt: out.ascent_pt, - descent_pt: out.descent_pt, - width_px: out.image.width_px, - height_px: out.image.height_px, - pixels: out.image.pixels, - }) - } - - /// Compiles native Typst markup into all page SVGs using persistent fonts and packages. - #[cfg(feature = "typst")] - pub fn compile_typst_svg( - &mut self, - source: &str, - year: i32, - month: u8, - day: u8, - ) -> Result { - let pages = self - .inner - .compile_typst_pages(source, PreviewDate::new(year, month, day)) - .map_err(|err| JsValue::from_str(&err.to_string()))?; - let first = pages - .first() - .ok_or_else(|| JsValue::from_str("compiled typst document has zero pages"))?; - let pages_svg: Vec = pages.iter().map(|p| p.svg.clone()).collect(); - Ok(WasmTypstOutput { - width_pt: first.width_pt, - height_pt: first.height_pt, - ascent_pt: first.ascent_pt, - descent_pt: first.descent_pt, - page_count: pages.len(), - svg: first.svg.clone(), - pages_svg, - }) - } - - /// Compiles native Typst markup and rasterizes `page_index` to RGBA8. - #[cfg(feature = "typst")] - pub fn compile_typst_rgba( - &mut self, - source: &str, - year: i32, - month: u8, - day: u8, - page_index: usize, - scale: f32, - ) -> Result { - let buf = self - .inner - .compile_typst_page_rgba( - source, - PreviewDate::new(year, month, day), - page_index, - scale, - ) - .map_err(|err| JsValue::from_str(&err.to_string()))?; - let width_px = buf.width_px; - let height_px = buf.height_px; - let logical_width = buf.logical_width; - let logical_height = buf.logical_height; - let pixels = std::sync::Arc::try_unwrap(buf) - .map(|owned| owned.pixels) - .unwrap_or_else(|shared| shared.pixels.clone()); - Ok(WasmRgbaOutput { - width_px, - height_px, - logical_width, - logical_height, - pixels, - }) - } - - /// Parses and caches a PDF document, returning a handle for subsequent page renders. - #[cfg(feature = "pdf")] - pub fn load_pdf(&mut self, pdf_bytes: &[u8]) -> Result { - self.inner - .load_pdf(pdf_bytes.to_vec()) - .map_err(|err| JsValue::from_str(&err.to_string())) - } - - /// Releases a cached PDF document handle. - #[cfg(feature = "pdf")] - pub fn unload_pdf(&mut self, handle: u32) -> bool { - self.inner.unload_pdf(handle) - } - - /// Renders a page from a cached PDF document handle into RGBA8 pixels. - #[cfg(feature = "pdf")] - pub fn render_pdf_page_rgba( - &self, - handle: u32, - page_index: usize, - scale: f32, - max_edge_px: u32, - ) -> Result { - let req = PdfRenderRequest { - page_index, - scale, - max_edge_px, - ..PdfRenderRequest::default() - }; - let (page_count, buf) = self - .inner - .render_pdf_page(handle, req) - .map_err(|err| JsValue::from_str(&err.to_string()))?; - Ok(WasmPdfPageOutput { - width_px: buf.width_px, - height_px: buf.height_px, - logical_width: buf.logical_width, - logical_height: buf.logical_height, - page_count, - pixels: buf.pixels, - }) - } -} - -#[cfg(feature = "mermaid")] -fn parse_mermaid_theme(theme: Option<&str>) -> Result, String> { - let Some(raw) = theme.map(str::trim).filter(|s| !s.is_empty()) else { - return Ok(None); - }; - if raw.eq_ignore_ascii_case("light") { - Ok(Some(MermaidTheme::Light)) - } else if raw.eq_ignore_ascii_case("dark") { - Ok(Some(MermaidTheme::Dark)) - } else { - Err(format!( - "unsupported Mermaid theme '{raw}' (expected 'light' or 'dark')" - )) - } -} - -#[cfg(feature = "mermaid")] -fn parse_svg_dimensions(svg: &str) -> (f32, f32) { - if let Some(vb_pos) = svg.find("viewBox=\"") { - let after = &svg[vb_pos + 9..]; - if let Some(end) = after.find('"') { - let nums: Vec = after[..end] - .split(|c: char| c.is_whitespace() || c == ',') - .filter_map(|part| part.parse::().ok()) - .collect(); - if nums.len() == 4 { - return (nums[2], nums[3]); - } - } - } - (0.0, 0.0) -} - -pub use crate::wasm_worker::{ - affine_worker_invoke, affine_worker_output_u32, affine_worker_push_input_u32, - affine_worker_reset_input, -}; - -#[cfg(all(test, feature = "mermaid"))] -mod tests { - use super::*; - use crate::test_support::build_test_font_pool; - - #[test] - fn wasm_mermaid_theme_parser_and_distinct_light_dark_pixels() { - assert_eq!(parse_mermaid_theme(None), Ok(None)); - assert_eq!(parse_mermaid_theme(Some(" ")), Ok(None)); - assert_eq!( - parse_mermaid_theme(Some("light")), - Ok(Some(MermaidTheme::Light)) - ); - assert_eq!( - parse_mermaid_theme(Some("DARK")), - Ok(Some(MermaidTheme::Dark)) - ); - assert!(parse_mermaid_theme(Some("neon")).is_err()); - - let mut engine = PreviewEngine::default(); - for blob in build_test_font_pool().font_blobs() { - engine.register_font(blob.to_vec()).unwrap(); - } - let src = "flowchart TD\n A[Start] --> B[End]"; - let light = engine - .render_mermaid_rgba( - src, - &MermaidOptions { - theme: parse_mermaid_theme(Some("light")).unwrap(), - ..MermaidOptions::default() - }, - 2.0, - ) - .unwrap(); - let dark = engine - .render_mermaid_rgba( - src, - &MermaidOptions { - theme: parse_mermaid_theme(Some("dark")).unwrap(), - ..MermaidOptions::default() - }, - 2.0, - ) - .unwrap(); - assert_ne!(light.sha256(), dark.sha256()); - } -} diff --git a/blocksuite/crates/preview/src/wasm_worker.rs b/blocksuite/crates/preview/src/wasm_worker.rs index 247d6f58ee..a4c33e2ed0 100644 --- a/blocksuite/crates/preview/src/wasm_worker.rs +++ b/blocksuite/crates/preview/src/wasm_worker.rs @@ -340,3 +340,30 @@ pub fn affine_worker_output_u32(word_index: usize) -> u32 { u32::from_le_bytes(chunk) }) } + +#[cfg(all(test, feature = "mermaid"))] +mod tests { + use super::*; + use crate::test_support::build_test_font_pool; + + #[test] + fn mermaid_opcode_theme_tags_render_distinct_light_dark_svg() { + let mut state = RawWorkerState::new(); + for blob in build_test_font_pool().font_blobs() { + state.engine.register_font(blob.to_vec()).unwrap(); + } + let mut render = |theme_tag: u8| { + state.input = [&[2, theme_tag][..], b"flowchart TD\n A[Start] --> B[End]"].concat(); + state.dispatch() + }; + let default = render(0).unwrap(); + let light = render(1).unwrap(); + let dark = render(2).unwrap(); + assert_eq!(render(3), Err("invalid mermaid theme tag 3".to_string())); + for frame in [&default, &light, &dark] { + assert_eq!(frame[0], 1); + assert!(frame[1..].starts_with(b"