From 624e987d4345ffc0fe60e1813ec0dfd30fe09c37 Mon Sep 17 00:00:00 2001 From: DarkSky Date: Wed, 2 Dec 2026 01:30:08 +0900 Subject: [PATCH] feat(web): mount the desktop workbench with worker previews --- blocksuite/crates/playground/src/doc_panel.rs | 8 +- blocksuite/crates/playground/src/lib.rs | 3 +- blocksuite/crates/playground/src/view_room.rs | 2 +- .../src/wasm_preview/media_picker.rs | 16 +++- .../crates/playground/src/wasm_preview/mod.rs | 65 +++++----------- packages/frontend/hosts/web/AGENTS.md | 2 +- .../frontend/hosts/web/desktop/index.html | 57 ++++++++++++++ packages/frontend/hosts/web/desktop/start.js | 38 ++++++++++ .../frontend/hosts/web/tests/desktop.test.mjs | 76 +++++++++++++++++++ 9 files changed, 215 insertions(+), 52 deletions(-) create mode 100644 packages/frontend/hosts/web/desktop/index.html create mode 100644 packages/frontend/hosts/web/desktop/start.js create mode 100644 packages/frontend/hosts/web/tests/desktop.test.mjs diff --git a/blocksuite/crates/playground/src/doc_panel.rs b/blocksuite/crates/playground/src/doc_panel.rs index 3becc869cc..85db07128d 100644 --- a/blocksuite/crates/playground/src/doc_panel.rs +++ b/blocksuite/crates/playground/src/doc_panel.rs @@ -697,12 +697,16 @@ impl PlaygroundView { } } -#[cfg(not(target_arch = "wasm32"))] -pub(crate) fn install_native_preview_wakeup( +pub(crate) fn install_preview_wakeup( tasks: &mut Vec>, cx: &mut ui::Context, ) { + #[cfg(not(target_arch = "wasm32"))] crate::block_flow::ensure_native_preview_providers_installed(); + #[cfg(target_arch = "wasm32")] + if !crate::wasm_preview::install_worker_previews() { + return; + } let (wakeup_tx, wakeup_rx) = async_channel::bounded::<()>(1); let wakeup_sub = crate::block_flow::subscribe_preview_wakeup(std::sync::Arc::new(move || { let _ = wakeup_tx.try_send(()); diff --git a/blocksuite/crates/playground/src/lib.rs b/blocksuite/crates/playground/src/lib.rs index 814934b74b..acdfff6ee8 100644 --- a/blocksuite/crates/playground/src/lib.rs +++ b/blocksuite/crates/playground/src/lib.rs @@ -318,8 +318,7 @@ impl PlaygroundView { ), }; - #[cfg(not(target_arch = "wasm32"))] - doc_panel::install_native_preview_wakeup(&mut tasks, cx); + doc_panel::install_preview_wakeup(&mut tasks, cx); let default_doc_directory = directory::InMemoryDocDirectory::with_namespace(format!( "doc:{:x}", diff --git a/blocksuite/crates/playground/src/view_room.rs b/blocksuite/crates/playground/src/view_room.rs index 98c1694404..a7b68ce0e1 100644 --- a/blocksuite/crates/playground/src/view_room.rs +++ b/blocksuite/crates/playground/src/view_room.rs @@ -558,7 +558,7 @@ pub fn wasm_main() -> Result<(), wasm_bindgen::JsError> { let options = web_options(); if let Err(err) = cx.open_window(ui::WindowOptions::default(), |_, cx| { let view = cx.new(|cx| PlaygroundView::with_options(options, cx)); - crate::wasm_preview::install_wasm_preview_providers(view.downgrade(), cx); + crate::wasm_preview::set_standalone_pdf_target(view.downgrade(), cx); view }) { panic!("failed to open playground web window: {err:#}"); diff --git a/blocksuite/crates/playground/src/wasm_preview/media_picker.rs b/blocksuite/crates/playground/src/wasm_preview/media_picker.rs index 6209c7cec3..d7e5d51172 100644 --- a/blocksuite/crates/playground/src/wasm_preview/media_picker.rs +++ b/blocksuite/crates/playground/src/wasm_preview/media_picker.rs @@ -1,11 +1,23 @@ //! WebAssembly host media-picker callbacks and DOM `#embed-layer` iframe bridge. +use std::{cell::RefCell, collections::HashMap}; + use ui::WeakEntity; use wasm_bindgen::prelude::*; use crate::PlaygroundView; -use super::{ACTIVE_VIEW, PENDING_MEDIA_TARGETS}; +type MediaTarget = (WeakEntity, ui::AsyncApp); + +std::thread_local! { + static STANDALONE_PDF_TARGET: RefCell> = const { RefCell::new(None) }; + static PENDING_MEDIA_TARGETS: RefCell> = RefCell::new(HashMap::new()); +} + +/// Sets the standalone page that accepts PDF imports without a picker request. +pub(crate) fn set_standalone_pdf_target(view: WeakEntity, cx: &ui::App) { + STANDALONE_PDF_TARGET.with(|slot| *slot.borrow_mut() = Some((view, cx.to_async()))); +} #[wasm_bindgen] extern "C" { @@ -88,7 +100,7 @@ fn with_media_target( let target = if let Some(req_id) = request_id { PENDING_MEDIA_TARGETS.with(|slot| slot.borrow().get(&req_id).cloned()) } else { - ACTIVE_VIEW.with(|slot| slot.borrow().clone()) + STANDALONE_PDF_TARGET.with(|slot| slot.borrow().clone()) }; let Some((weak, app)) = target else { return; diff --git a/blocksuite/crates/playground/src/wasm_preview/mod.rs b/blocksuite/crates/playground/src/wasm_preview/mod.rs index 0cb15be649..425b0999b4 100644 --- a/blocksuite/crates/playground/src/wasm_preview/mod.rs +++ b/blocksuite/crates/playground/src/wasm_preview/mod.rs @@ -12,24 +12,22 @@ pub use media_picker::{ }; use std::{ - cell::RefCell, collections::{HashMap, HashSet, VecDeque}, hash::Hash, sync::{Arc, Mutex, OnceLock, RwLock}, }; -use ui::{Hsla, WeakEntity}; +use ui::Hsla; use wasm_bindgen::prelude::*; use crate::{ - PlaygroundView, block_flow::{ CodePreviewKind, CodePreviewProvider, CodePreviewResult, CodePreviewSlot, MAX_SINGLE_PDF_PAGE_RGBA_BYTES, MathPreviewProvider, MathRenderResult, MathRenderSlot, PdfAsyncPageResult, PdfPageCount, PdfPageProvider, PdfPreviewPage, bump_latex_formula_revision, bump_preview_revision, fast_pdf_content_hash, hsla_to_css_hex, - register_code_preview_provider, register_math_preview_provider, register_pdf_page_provider, - rgba_pixels_to_render_image, + notify_preview_wakeup, register_code_preview_provider, register_math_preview_provider, + register_pdf_page_provider, rgba_pixels_to_render_image, }, theme::PlaygroundTheme, wasm_pdf_state::{CountStep, PageStep, WasmPdfState, WorkerPlan}, @@ -174,33 +172,6 @@ impl CodePreviewProvider for WasmCodePreviewProvider { } } -std::thread_local! { - pub(super) static ACTIVE_VIEW: RefCell, ui::AsyncApp)>> = - const { RefCell::new(None) }; - pub(super) static PENDING_MEDIA_TARGETS: RefCell< - HashMap, ui::AsyncApp)>, - > = RefCell::new(HashMap::new()); -} - -fn notify_active_view(refresh_pdf: bool) { - ACTIVE_VIEW.with(|slot| { - if let Some((weak, app)) = slot.borrow().as_ref() { - let weak = weak.clone(); - let app = app.clone(); - let _ = app.update(|cx| { - let _ = weak.update(cx, |view, cx| { - if refresh_pdf { - let attachments = view.active_pdf_attachments(); - view.refresh_pdf_previews(&attachments); - view.refresh_pdf_viewer_pages(); - } - cx.notify(); - }); - }); - } - }); -} - struct WasmMathPreviewProvider; impl MathPreviewProvider for WasmMathPreviewProvider { @@ -338,14 +309,20 @@ impl PdfPageProvider for WasmPdfPageProvider { } } -/// Registers the Web Worker preview providers and binds `view` for automatic repaint wakeups. -pub(crate) fn install_wasm_preview_providers(view: WeakEntity, cx: &ui::App) { - ACTIVE_VIEW.with(|slot| { - *slot.borrow_mut() = Some((view, cx.to_async())); +/// Installs the providers once for a Web host that exposes the worker bridge. +pub(crate) fn install_worker_previews() -> bool { + if !js_sys::Reflect::get(&js_sys::global(), &"__playgroundPreview".into()) + .is_ok_and(|bridge| bridge.is_object()) + { + return false; + } + static INSTALL: std::sync::Once = std::sync::Once::new(); + INSTALL.call_once(|| { + register_math_preview_provider(Some(Arc::new(WasmMathPreviewProvider))); + register_pdf_page_provider(Some(Arc::new(WasmPdfPageProvider))); + register_code_preview_provider(Some(Arc::new(WasmCodePreviewProvider))); }); - register_math_preview_provider(Some(Arc::new(WasmMathPreviewProvider))); - register_pdf_page_provider(Some(Arc::new(WasmPdfPageProvider))); - register_code_preview_provider(Some(Arc::new(WasmCodePreviewProvider))); + true } #[wasm_bindgen] @@ -391,7 +368,7 @@ pub fn deliver_code_preview( fifo_insert(map, order, MAX_CODE_PREVIEW_CACHE_ENTRIES, key, result); } crate::block_flow::bump_code_preview_revision(kind_enum, &source_for_rev); - notify_active_view(false); + notify_preview_wakeup(); } #[wasm_bindgen] @@ -430,7 +407,7 @@ pub fn deliver_code_preview_error( ); } crate::block_flow::bump_code_preview_revision(kind_enum, &source_for_rev); - notify_active_view(false); + notify_preview_wakeup(); } /// Callback invoked by `preview-workers.js` when a RaTeX math formula finishes rasterizing. @@ -474,7 +451,7 @@ pub fn deliver_math_preview( fifo_insert(map, order, MAX_MATH_CACHE_ENTRIES, key, result); } bump_latex_formula_revision(&latex_for_rev); - notify_active_view(false); + notify_preview_wakeup(); } /// Callback invoked by `preview-workers.js` when RaTeX reports a definitive syntax/parse error @@ -509,13 +486,13 @@ pub fn deliver_math_error( ); } bump_latex_formula_revision(&latex_for_rev); - notify_active_view(false); + notify_preview_wakeup(); } fn wake_after_pdf_delivery(wake: bool) { if wake { bump_preview_revision(); - notify_active_view(true); + notify_preview_wakeup(); } } diff --git a/packages/frontend/hosts/web/AGENTS.md b/packages/frontend/hosts/web/AGENTS.md index f0331bffef..b7c107d6a1 100644 --- a/packages/frontend/hosts/web/AGENTS.md +++ b/packages/frontend/hosts/web/AGENTS.md @@ -1,6 +1,6 @@ # Working in `packages/frontend/hosts/web/` (for agents) -This directory holds the zero-build Web Mobile thin host for AFFiNE. +This directory holds the zero-build Web Mobile host and the `desktop/` Workbench entry for AFFiNE. It uses plain HTML and standard ES modules with JSDoc types. ## Hard boundaries diff --git a/packages/frontend/hosts/web/desktop/index.html b/packages/frontend/hosts/web/desktop/index.html new file mode 100644 index 0000000000..60baffd2ea --- /dev/null +++ b/packages/frontend/hosts/web/desktop/index.html @@ -0,0 +1,57 @@ + + + + + + + AFFiNE Desktop + + + + +
+ + + diff --git a/packages/frontend/hosts/web/desktop/start.js b/packages/frontend/hosts/web/desktop/start.js new file mode 100644 index 0000000000..3bfadf1b79 --- /dev/null +++ b/packages/frontend/hosts/web/desktop/start.js @@ -0,0 +1,38 @@ +const defaultFonts = [ + 'Inter-VariableFont_slnt,wght.ttf', + 'IBMPlexMono-Regular.ttf', + 'IBMPlexMono-Bold.ttf', + 'IBMPlexMono-Italic.ttf', + 'IBMPlexMono-BoldItalic.ttf', + 'NotoSansArabic-Regular.ttf', + 'NotoSansHebrew-Regular.ttf', +].map(name => '/assets/fonts/' + name); + +async function fetchFont(url) { + const response = await fetch(url); + if (!response.ok) + throw new Error(`Font ${url} returned HTTP ${response.status}`); + return new Uint8Array(await response.arrayBuffer()); +} + +export async function startDesktop( + wasm, + fontUrls = defaultFonts, + search, + prefersDark, + preview +) { + const [, fonts] = await Promise.all([ + wasm.default(), + Promise.all(fontUrls.map(fetchFont)), + ]); + for (const bytes of fonts) { + wasm.register_web_desktop_font(bytes); + preview.registerFont(bytes); + } + const params = new URLSearchParams(search); + const theme = params.get('theme'); + const dark = theme === 'dark' || (theme !== 'light' && prefersDark); + const split = params.get('split'); + wasm.wasm_desktop_main(dark, split === 'true' || split === '1'); +} diff --git a/packages/frontend/hosts/web/tests/desktop.test.mjs b/packages/frontend/hosts/web/tests/desktop.test.mjs new file mode 100644 index 0000000000..27be7069b6 --- /dev/null +++ b/packages/frontend/hosts/web/tests/desktop.test.mjs @@ -0,0 +1,76 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { test } from 'node:test'; + +import { startDesktop } from '../desktop/start.js'; + +void test('both desktop URLs load the desktop host and Wasm module from the same paths', async () => { + const html = await readFile( + new URL('../desktop/index.html', import.meta.url), + 'utf8' + ); + const imports = [...html.matchAll(/(?:from |import\()'([^']+)'/g)].map( + match => match[1] + ); + for (const path of ['/desktop', '/desktop/']) { + assert.deepEqual( + imports.map(url => new URL(url, 'https://example.org' + path).pathname), + ['/desktop/start.js', '/preview-workers.js', '/pkg/affine_desktop.js'] + ); + } +}); + +void test('the desktop registers fonts in order before mounting the selected theme and panes', async t => { + for (const [query, prefersDark, dark, split] of [ + ['', false, false, false], + ['', true, true, false], + ['?theme=light&split=1', true, false, true], + ['?theme=dark&split=true', false, true, true], + ['?theme=system&split=false', true, true, false], + ]) { + await t.test(query + ' system dark=' + prefersDark, async t => { + const requests = []; + const calls = []; + t.mock.method(globalThis, 'fetch', async url => { + requests.push(url); + return new Response(Uint8Array.of(url.endsWith('latin') ? 1 : 2)); + }); + const wasm = { + default: async () => calls.push('init'), + register_web_desktop_font: bytes => calls.push(['font', ...bytes]), + wasm_desktop_main: (...args) => calls.push(['mount', ...args]), + }; + const preview = { + registerFont: bytes => calls.push(['preview', ...bytes]), + }; + await startDesktop( + wasm, + ['/latin', '/mono'], + query, + prefersDark, + preview + ); + assert.deepEqual(requests, ['/latin', '/mono']); + assert.deepEqual(calls, [ + 'init', + ['font', 1], + ['preview', 1], + ['font', 2], + ['preview', 2], + ['mount', dark, split], + ]); + }); + } +}); + +void test('an unavailable font stops desktop startup', async t => { + t.mock.method( + globalThis, + 'fetch', + async () => new Response(null, { status: 404 }) + ); + await assert.rejects( + startDesktop({ default() {} }, ['/missing'], '', false, {}), + /Font \/missing returned HTTP 404/ + ); +});