mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 11:15:01 +03:00
feat(web): mount the desktop workbench with worker previews
This commit is contained in:
1 parent
4bcbca66cb
commit
624e987d43
9 files changed
+215
-52
No files matched your search
@@ -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<ui::Task<()>>,
|
||||
cx: &mut ui::Context<PlaygroundView>,
|
||||
) {
|
||||
#[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(());
|
||||
|
||||
@@ -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}",
|
||||
|
||||
@@ -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:#}");
|
||||
|
||||
@@ -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<PlaygroundView>, ui::AsyncApp);
|
||||
|
||||
std::thread_local! {
|
||||
static STANDALONE_PDF_TARGET: RefCell<Option<MediaTarget>> = const { RefCell::new(None) };
|
||||
static PENDING_MEDIA_TARGETS: RefCell<HashMap<u64, MediaTarget>> = 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<PlaygroundView>, 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;
|
||||
|
||||
@@ -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<Option<(WeakEntity<PlaygroundView>, ui::AsyncApp)>> =
|
||||
const { RefCell::new(None) };
|
||||
pub(super) static PENDING_MEDIA_TARGETS: RefCell<
|
||||
HashMap<u64, (WeakEntity<PlaygroundView>, 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<PlaygroundView>, 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();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta
|
||||
http-equiv="Content-Security-Policy"
|
||||
content="default-src 'self'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' blob:; worker-src 'self' blob:; frame-src blob: about:; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; base-uri 'none'; object-src 'none'"
|
||||
/>
|
||||
<title>AFFiNE Desktop</title>
|
||||
<link rel="icon" href="data:," />
|
||||
<style>
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
canvas {
|
||||
display: block;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
}
|
||||
#embed-layer {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="embed-layer"></div>
|
||||
<script type="module">
|
||||
import { startDesktop } from '/desktop/start.js';
|
||||
import { installPlaygroundPreviewBridge } from '/preview-workers.js';
|
||||
|
||||
try {
|
||||
const wasm = await import('/pkg/affine_desktop.js');
|
||||
installPlaygroundPreviewBridge(wasm, location.origin + '/');
|
||||
await startDesktop(
|
||||
wasm,
|
||||
window.__AFFINE_FONT_ASSETS__,
|
||||
location.search,
|
||||
matchMedia('(prefers-color-scheme: dark)').matches,
|
||||
window.__playgroundPreview
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
const notice = document.createElement('p');
|
||||
notice.setAttribute('role', 'alert');
|
||||
notice.textContent = `AFFiNE Desktop could not start: ${error.message}`;
|
||||
document.body.append(notice);
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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');
|
||||
}
|
||||
@@ -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/
|
||||
);
|
||||
});
|
||||
Reference in new issue
Block a user